Language Reference

Microsoft® Access

Relational Database Management System for Windows® 95

Microsoft Corporation

Information in this document is subject to change without notice. Companies, names, and data used in examples herein are fictitious unless otherwise noted. No part of this document may be reproduced or transmitted in any form or by any means, electronic or mechanical, for any purpose, without the express written permission of Microsoft Corporation.

© 1995 Microsoft Corporation. All rights reserved.

Microsoft, MS, MS-DOS, PowerPoint, Visual Basic, Win32, Windows, and Windows NT are either registered trademarks or trademarks of Microsoft Corporation in the United States and/or other countries.

dBASE, dBASE IV, and Paradox are registered trademarks of Borland International, Inc.

Hewlett-Packard and LaserJet are registered trademarks of Hewlett-Packard Company.

IBM is a registered trademark of International Business Machines Corporation.

Lotus is a registered trademark of Lotus Development Corporation.

Macintosh and TrueType are registered trademarks of Apple Computer, Inc.

Paintbrush is a trademark of Wordstar Atlanta Technology Center.

PostScript is a trademark of Adobe Systems, Inc.

Unicode is a trademark of Unicode, Incorporated.

Document No. DB65250-1095


Introduction

Welcome to Microsoft Access Language Reference, your reference for programming in Microsoft® Access. This book contains information on the Visual Basic® for Applications programming language and its use within Microsoft Access. It also contains information on Microsoft Access language elements that enhance the Visual Basic programming language and make it easier for you to create great database applications with Microsoft Access.

This book contains reference information on programming with Visual Basic in Microsoft Access only. It does not contain reference information on programming with data access objects. For more information, see online Help and the following two books:

  • Microsoft Office 95 Data Access Reference, available in the Microsoft Access Developer’s Toolkit, contains reference information on programming with data access objects and their methods and properties, and with Microsoft Jet Database Engine SQL.
  • Building Applications with Microsoft Access for Windows® 95, available with Microsoft Access 95, is a guide to designing and creating database applications with Microsoft Access.

The information included in this manual is the best available at the time of publication; in some cases, information in online Help may be more up-to-date.


Contents

This reference manual has four sections:

Language Summary

This section provides a quick reference for finding information about related functions, statements, objects, methods, properties, events, actions, operators, and keywords.

A-Z Reference

This section includes detailed descriptions of the functions, statements, objects, methods, properties, events, actions, operators, and keywords provided by Visual Basic and by Microsoft Access. It also provides code examples that show how to use selected elements in Visual Basic code.

If a method or property provided by Microsoft Access has the same name as one provided by Visual Basic, the topic title denotes whether the method or property is supplied by Microsoft Access or by Visual Basic. For example, the Microsoft Access Count property topic is titled “Count Property (Microsoft Access),” and the Visual Basic Count property is titled “Count Property (Visual Basic).”

Some Visual Basic topics include Microsoft Access-specific information in addition to general programming information. This information follows the general information in the topic.

In most cases you don’t need to know whether a language element is provided by Visual Basic or by Microsoft Access when you’re programming. This book distinguishes between the two because some objects and their methods and properties are provided by Microsoft Access, and some are provided by Visual Basic. If you look up these objects, methods, and properties in the Object Browser, you’ll need to know whether they are supplied by Visual Basic or by Microsoft Access. For more information on using the Object Browser, search the online index for “Object Browser,” or ask the Answer Wizard.

Appendixes

This section includes a graphical representation of the Microsoft Access object hierarchy and a table of ANSI values.

Index

This section provides a complete index of all reference topics in this book.


Document Conventions

This manual uses the following typographic conventions.

Example of convention | Description
Sub, If, ChDir, Recordset, Time, Fontsize | Words in bold with the initial letter capitalized are language-specific reserved words with special meaning to Visual Basic. These can be funtions, statements, objects, methods, properties, operators, or keywords.
DblClick, TransferText | Names of events and actions appear with the inital letter capitalized. Concatenated names may contain other capital letters.
expr, path | In syntax, text in italic indicates placeholders for information you supply.
[color] | In syntax, items inside brackets are optional.
{While|Until} | In syntax, braces and a vertical bar indicate a mandatory choice between two or more items. You must choose one of the items unless all of the items also are enclosed in brackets.
Dims dbs As Database "Illegal Function Call" | This Font is used for code and for error messages.
acNormal | Intrisic constants consist of a word or words beginning with an initial capital letter, preceded by a prefix that indicates which type library they reside in. The prefix "ac" indicates that the constant is a Microsoft Access constant; "vb" indicates that the constant is a Visual Basic Constant. Constants are shown in bold.
ENTER | Small capital letters are used for the names of keys, such as ENTER and CTRL. The key names correspond to the names on the IBMÒ Personal Computer Keyboard. Other computers may use different names for keys.
ALT+F1 | A plus sign (+) between key names indicates a combination of keys. For example, ALT+F1 means hold down the ALT key while pressing the F1 key.
varX= MSGBox(Concatenate "_ & "strings separated by "_ & "the line continuation "_ & character." | The line-continuation character (_) consists of a space and an undersocre. You can use this character to continue from one line of code to the next.
CreateForm ([database[, [image] formtemplate]]) | In syntax, an arrow indicates line continuation.


Programming Style

This manual follows the guidelines below in presenting Visual Basic code:

  • Reserved words are in lowercase with an initial capital letter.

    Dim intSomeValue As Integer, strTextValue As StringintStartNumber As Integer
' If, Then, and Str are reserved words.intSomeValue = 0 Then strTextValue = Str(intStartNumber)
  • Variable names begin with a lowercase prefix, followed by a lowercase word or words with an initial capital letter. Variables are declared at beginning of an example.

    Dim dblIncome As DoublestrFirstName As String * 30
  • Line labels are used instead of line numbers for error-handling routines and for On...GoSub and On...GoTo statements.

    On Error GoTo ErrorHandler
.
.
.:
    MsgBox Err.Description
  • An apostrophe ( ' ) introduces a comment.

    ' This is a comment; these two lines
' are ignored when the program is running.
  • Control-flow blocks and statements in Sub and Function procedures are indented.

    Sub SomeCode ( )
    If intX > 0 Then
        intP = intQ
    End IfSub


Objects, Methods, and Properties

Microsoft Access objects include the Application, Form, Report, Control, Screen, and DoCmd objects. For a graphical representation of the Microsoft Access object hierarchy, see Appendix A.

The methods and properties that apply to each object are listed in the Object Browser. To open the Object Browser, open a module and click Object Browser on the View menu. In the Libraries/Databases box, click the Microsoft Access For Windows 95 library, then click an object in the Modules/Classes box. The Methods/Properties box lists the methods and properties of the object you selected.

For more information on using the Object Browser, search the online index for “Object Browser,” or ask the Answer Wizard.

Visual Basic objects include the Collection, Debug, and Err objects. To see the methods and properties associated with these objects, search the online index for the name of the object, or ask the Answer Wizard.


Methods by Programming Task

The following table lists Microsoft Access and Visual Basic methods by programming task.

Table 1 Methods by Programming Task

Category | Task | Method
Combo box/list box | Force a combo box to drop down | Dropdown
 | Return data in the bound column of a combo box or list box | ItemData
Controls | Set default properties of a control | DefaultControl
 | Size a control to fit the text or image it displays | SizeToFit
 | Undo changes to a control or form | Undo
Filters | Build a criteria string for a filter | BuildCriteria
 | Apply an existing filter | ApplyFilter
Finding records | Find a record according to specified criteria | FindRecord
 | Find next matching record | FindNext

Table 1 Methods by Programming Task (continued)

Category | Task | Method
Graphics on printed reports | Change the coordinate system | Scale
 | Draw a shape | Circle, Line, PSet
 | Find the size of text | TextHeight, TextWidth
 | Print text | Print
Importing, exporting, or linking data | Import, export, or link data in a database | TransferDatabase
 | Import, export, or link data in a spreadsheet | TransferSpreadsheet
 | Import, export, or link data in a text file | TransferText
 | Export data from a database to a Microsoft Excel workbook, a rich-text file, or a text file. | OutputTo
Interacting with application and environment | Generate sound from the computer’s speaker | Beep
 | Cancel an event | CancelEvent
 | Carry out a menu command | DoMenuItem
 | Toggle mouse pointer to hourglass | Hourglass
 | Maximize window | Maximize
 | Minimize window | Minimize
 | Move or resize the active window | MoveSize
 | Refresh the application title bar | RefreshTitleBar
 | Rename a database object | Rename
 | Restore window to original size and position | Restore
 | Send an object in an electronic mail message | SendObject
 | Set the state for a menu item on a custom toolbar | SetMenuItem
 | Toggle warning messages | SetWarnings
 | Toggle built-in toolbar | ShowToolbar
Microsoft Access options | Set or return Microsoft Access options | GetOption, SetOption

Table 1 Methods by Programming Task (continued)

Category | Task | Method
Modules | Add text to a module | InsertText
Navigating through records | Move to a specified record | GoToRecord
Printing | Print to Debug window | Print
 | Print the active object | PrintOut
Quitting Microsoft Access | Quit Microsoft Access | Quit, Quit (DoCmd object)
Running code | Run a procedure in another database | Run
 | Run a macro | RunMacro
 | Run an SQL statement | RunSQL
Setting the focus | Move the focus to the specified control | GoToControl
 | Move the focus to a form or control | SetFocus
 | Move to a specified page on a form with page breaks | GoToPage, GoToPage (DoCmd object)
 | Select a database object | SelectObject
Updating data | Update calculated controls or requery data for a form or control | Recalc, Refresh, Requery, Requery (DoCmd object)
 | Specify whether Microsoft Access updates the screen | Echo
 | Update the screen | Repaint
 | Update the screen for a specified database object | RepaintObject
Working with a Collection object | Add a member to a Collection object | Add
 | Remove a member from a Collection object | Remove
 | Return a specific member of a Collection object either by position or by key | Item
Working with the Err object | Generate a run-time error | Raise
 | Clear all property settings of the Err object | Clear

Table 1 Methods by Programming Task (continued)

Category | Task | Method
Working with a database in the Microsoft Access window | Create a new database | NewCurrentDatabase
 | Open an existing database | OpenCurrentDatabase
 | Close a database | CloseCurrentDatabase
Working with database objects | Open a database object | OpenForm, OpenModule, OpenQuery, OpenReport, OpenTable
 | Save a database object | Save
 | Close a database object | Close
 | Copy a database object | CopyObject
 | Delete a database object | DeleteObject
Working with a Workspace object | Clone the default Workspace object | DefaultWorkspaceClone


Properties by Programming Task

The following table lists Microsoft Access and Visual Basic properties by programming task.

Table 2 Properties by Programming Task

Category | Task | Property
Application object | Determine the object in which a macro or Visual Basic code is running | CodeContextObject
 | Determine whether the current Microsoft Access application was started by user or through OLE Automation | UserControl
Collection object | Count the number of objects in a Collection object | Count (Visual Basic)
Combo box/list box | Bind a combo box or list box to a table field | BoundColumn
 | Determine the list index value of an item in a combo box or list box | ListIndex

Table 2 Properties by Programming Task (continued)

Category | Task | Property
 | Determine the number of rows in a combo box or list box | ListCount
 | Specify the width of the list box portion of a combo box | ListWidth
 | Refer to a column or row in a combo box or list box | Column
 | Specify whether to allow multiple selections in a list box | MultiSelect
 | Determine if an item in a list box is selected | Selected
 | Restrict text entry in a list | LimitToList
 | Specify the column widths or hide a column in a multiple-column combo box or list box | ColumnWidths
 | Specify the number of columns in a combo box or list box | ColumnCount
 | Specify the number of rows in a list box | ListRows
 | Specify the text contained in a text box or in the text box portion of a combo box | Specify the text contained in a text box or in the text box portion of a combo box
 | Specify whether values are automatically filled in when you type in a combo box | AutoExpand
 | Specify the source for a list box | RowSource,
 | Display a single row of column headings for list boxes, combo boxes, and OLE objects that accept column headings | ColumnHeads

Table 2 Properties by Programming Task (continued)

Category | Task | Property
Database properties | Set startup options | AppTitle, AppIcon, StartupForm, StartupShowDBWindow, StartupShowStatusBar, StartupMenuBar, StartupShortcutMenuBar, AllowFullMenus, AllowShortcutMenus, AllowBuiltInToolbars, AllowToolbarChanges, AllowBreakIntoCode, AllowSpecialKeys, AllowBypassKey
 | Set summary properties | Title, Subject, Author, Manager, Company, Category, Keywords, Comments
Data source | Specify the source of a control’s data | ControlSource
 | Specify underlying records for a form or report | RecordSource
 | Refer to underlying records | Bookmark, RecordsetClone
 | Specify a filter for a table, form, or query and apply the filter | Filter, FilterOn
 | Specify how to sort records in a table, form, report, or query and apply sort | OrderBy, OrderByOn
 | Set the name of a bitmap to load in a command button or toggle button, or as a background for a form or report | Picture
 | Specify whether an object’s picture is linked or embedded | PictureType
 | Specify a numeric value for controls included in an option group | OptionValue
 | Keep a running sum in a text box | RunningSum

Table 2 Properties by Programming Task (continued)

Category | Task | Property
 | Determine whether the current record has been modified since it was last saved | Dirty
Display | Specify form views | DefaultView, ViewsAllowed
 | Specify how to size a picture or other object | SizeMode
 | Specify gridline effects on a datasheet | DatasheetCellsEffect, DatasheetGridlinesBehavior, DatasheetGridlinesColor
 | Automatically center a form when it is displayed | AutoCenter
 | Specify the display of columns or rows in Datasheet view | ColumnHidden, ColumnWidth, FrozenColumns, RowHeight
 | Specify font characteristics | DatasheetFontHeight, , , , , FontBold, FontItalic, FontName, FontSize, FontUnderline, FontWeight
 | Specify text to display in title bar | Caption
 | Specify text to display in status bar | StatusBarText
 | Specify text, number, and date format | AddColon, DecimalPlaces,
 | Align text | LabelAlign, TextAlign
 | Automatically resize form window | AutoResize
 | Specify the order of fields in Datasheet view | ColumnOrder
 | Specify whether a form or report is repainted | Painting
Editing | Enable or disable editing | AllowAdditions, AllowDeletions, AllowEdits, DataEntry, RecordsetType
 | Specify whether data in a control can be changed | Locked, Enabled

Table 2 Properties by Programming Task (continued)

Category | Task | Property
 | Specify type of locking | LockEdits, RecordLocks
 | Specify how a linked OLE object is updated | UpdateOptions
 | Specify data entry | DefaultValue, InputMask, ValidationRule, ValidationText, DataEntry
 | Determine or specify the value of a control | Value
 | Determine the value of a bound control before it was edited | OldValue
 | Determine or specify characteristics of the selected text | SelLength, SelStart,
Error trapping | Return the number of an error | Number
 | Return a descriptive string associated with an error | Description
 | Return the name of the object or application that originally generated the error. | Source
 | Return a system error code produced by a call into a dynamic-link library (DLL) | LastDLLError
Events | Occurs when a user opens, resizes, or closes a form or report | OnClose, OnLoad, OnOpen, OnResize, OnUnload
 | Occurs when a user adds, changes, or deletes data | AfterDelConfirm, , AfterUpdate, , , , OnChange, , OnDelete, , OnUpdated
 | Occurs when a user creates or applies a filter | OnFilter, OnApplyFilter
 | Occurs when a user changes the focus | OnActivate, OnDeactivate, , OnExit, , OnLostFocus

Table 2 Properties by Programming Task (continued)

Category | Task | Property
 | Occurs when a user interacts with the keyboard or mouse | OnClick, OnDblClick, , OnKeyPress, , OnMouseDown, ,
 | Occurs when a user changes to Print Preview | OnFormat, OnPrint, , OnNoData, OnPage
 | Occurs when a Microsoft Access error is generated in a form or report | OnError
 | Occurs on an interval specified by the TimerInterval property | OnTimer
 | Specify the interval between Timer events | TimerInterval
 | Determine the prefix of an event procedure name | EventProcPrefix
Form/report design | Specify when an object is displayed or printed | DisplayWhen
 | Automatically add a label to new controls | AutoLabel
 | Generate an automatic tab when the last character permitted by a text box’s input mask is typed | AutoTab
 | Specify whether a tab moves to a new record or page | Cycle
 | Specify the effect of pressing the ENTER key in a text box | EnterKeyBehavior
 | Determine if a form or report is bound to an empty recordset | HasData
 | Specify whether a group header is repeated on the next page or column | RepeatSection
 | Determine if report section will continue on the next page | WillContinue
 | Determine if report section began on a previous page | HasContinued
 | Specify whether report groups are kept together by page or by column | GrpKeepTogether

Table 2 Properties by Programming Task (continued)

Category | Task | Property
 | Specify text that appears in a screen tip | ControlTipText
 | Specify whether the What’s This button is added to a form’s title bar | WhatsThisButton
 | Specify whether the Close button on a form is enabled | CloseButton
 | Specify the Cancel button | Cancel
 | Specify the Default button | Default
 | Specify whether lines separate sections or records on a form | DividingLines
 | Specify the text in the status bar | StatusBarText
 | Specify a control’s place in the tab order on a form | TabIndex
 | Specify whether a control can receive the focus in Form view | TabStop
 | Display record selectors or scroll bars | RecordSelectors, ScrollBars
 | Display the Control menu, Maximize button, or Minimize button | ControlBox, MinMaxButtons, BorderStyle
 | Specify a string expression that identifies the name of a form, report, section, or control | Name
 | Display navigation buttons and a record number box on a form | NavigationButtons
 | Specify grid alignment units | GridX, GridY
 | Specify whether to display shortcut menus on a form | ShortcutMenu
 | Determine whether a form or report uses printer or screen fonts | LayoutForPrint
 | Specify a palette for a form or report | PaintPalette, PaletteSource
 | Determine the palette used to create the bitmap for a command button or toggle button | ObjectPalette

Table 2 Properties by Programming Task (continued)

Category | Task | Property
 | Specify how records in a form or report are linked to records in a subform, subreport, or embedded object | LinkChildFields, LinkMasterFields
 | Hide or display an object or a section | Transparent, Visible, DisplayWhen
 | Specify the color of an object or a section | BackColor, BackStyle, FillColor, ForeColor, Transparent
 | Specify border appearance | BorderColor, , BorderWidth
 | Create special effects | SpecialEffect
 | Specify the placement and proportion of a picture | PictureAlignment, PicturePages, PictureTiling, PictureSizeMode, SizeMode
 | Specify the direction of a line | LineSlant
Graphics | Draw | CurrentX, CurrentY, DrawMode, DrawStyle, DrawWidth, FillColor, FillStyle, ScaleHeight, ScaleLeft, ScaleMode, ScaleTop, ScaleWidth
Help | Specify the name or identification number of a Help topic | HelpContext (Visual Basic), HelpContextID (Microsoft Access), HelpFile (Microsoft Access), HelpFile(Visual Basic)
Macros | Specify the name of a macro or an event procedure to run when an event occurs | See the Events category of this table
 | Specify whether a macro repeats while a button remains pressed | AutoRepeat
 | Specify the name of a menu bar macro | MenuBar, ShortcutMenuBar
Miscellaneous | Enable a control to receive the focus | Enabled
 | Determine the number of controls on a form or report | Count (Microsoft Access)
 | Determine the view you’re currently in | CurrentView

Table 2 Properties by Programming Task (continued)

Category | Task | Property
 | Determine if a control is selected in form Design view | InSelection
 | Determine which control last received the focus | PreviousControl
 | Refer to a stored string expression when a form is opened | OpenArgs
 | Store extra information about a form, report, section, or control needed by your database | Tag
Object linking and embedding (OLE) | Get a description of linked object data | Item
 | Determine the display and behavior of an OLE object | Action, AutoActivate, DisplayType, SizeMode
 | Determine the type of OLE object | Class, OLEClass, OLEType,
 | Link and update data | SourceDoc, SourceItem,
 | Specify a linked or embedded OLE Automation object in a control | Object
 | Specify an operation to perform | Action, ObjectVerbs, ObjectVerbsCount, Verb
 | Determine the address of an OLE object | lpOLEObject
 | Determine the palette used to create an OLE object | ObjectPalette
Object references | Refer to the active object | ActiveControl, , ActiveReport, ActiveDatasheet
 | Return the name or type of the active object | CurrentObjectName, CurrentObjectType
 | Refer to a section | Section
 | Refer to a form or report | Form, Me, Report
 | Refer to a form or report that contains a control or section | Parent
 | Refer to a subform, subreport, or linked object | SourceObject

Table 2 Properties by Programming Task (continued)

Category | Task | Property
 | Refer to a form module or report module | Module
 | Return the DAO DBEngine object | DBEngine
Printing | Count the number of times the current section in a report is formatted or printed | FormatCount, PrintCount
 | Specify the printing of sections | ForceNewPage, KeepTogether (Sections), , , , PageFooter, , PrintSection
 | Specify the printing of duplicate data | HideDuplicates
 | Specify a page number or the total number of pages | Page, Pages
 | Determine whether lines and rectangles are replaced by rules when using a laser printer | FastLaserPrinting
 | Specify printer driver and printer information | PrtDevMode, PrtDevNames, PrtMip
Query design | Customize column headings in a crosstab query | ColumnHeadings
 | Specify information for a make-table or append query | DestConnectStr, ,
 | Specify information for a pass-through query | LogMessages, ,
 | Specify information for a query using external data | Source, SourceConnectStr,
 | Specify a name for an input table or query | Alias
 | Specify records to return | TopValues, UniqueRecords,
 | Specify the number of seconds to wait before a timeout error occurs when a query is run on an Open Database Connectivity (ODBC) database | ODBCTimeout

Table 2 Properties by Programming Task (continued)

Category | Task | Property
 | Specify whether to show all fields from the underlying tables | OutputAllFields
 | Specify permissions to view or run a query | RunPermissions
Records | Move between records | Bookmark
 | Enable record filtering | AllowFilters
Size and position | Return the height and width of a form | WindowHeight, WindowWidth
 | Determine the height and width of a window containing a form | InsideHeight, InsideWidth
 | Specify position of a label or control | LabelX, LabelY, Left,
 | Specify size of control | Height, Width
 | Specify the position of the current section | CurrentSectionLeft,
 | Automatically size a section or control when it’s printed | CanGrow, CanShrink
Sorting and grouping | Create a group footer or header | GroupFooter,
 | Determine which settings to use for the first week of year and the first day of week when grouping dates in a report | DateGrouping
 | Specify an array for each field or expression you group on | GroupLevel
 | Specify how to group data | GroupInterval, GroupOn
 | Specify how to keep grouped data together on the same page | KeepTogether (Groups)
 | Print a report section all on one page | KeepTogether (Sections)
 | Specify the sort order for values in a report | SortOrder
Table design | Specify field attributes | Caption, DataType, , Description, , FieldSize,
 | Specify the primary key | Primary
 | Set a single-field index | Indexed

Table 2 Properties by Programming Task (continued)

Category | Task | Property
 | Ignore Null values in index fields | IgnoreNulls
 | Specify whether values in an index must be unique | Unique
 | Specify the default control you want to use for displaying a field on forms | DisplayControl
 | Place conditions on what values are allowed in a field or record | AllowZeroLength, , Required, ,
Windows | Specify whether a form is modal | Modal
 | Specify whether a form opens as a pop-up form | PopUp
 | Get the handle for the main Microsoft Access window | hWndAccessApp
 | Get the handle for a form or report window | hWnd


Functions and Statements by Programming Task

The following table lists Microsoft Access and Visual Basic functions and statements by programming task.

Table 3 Functions and Statements by Programming Task

Category | Task | Function or statement
Arrays | Verify an array | IsArray
 | Create an array | Array
 | Change default lower limit of an array | Option Base
 | Declare and initialize an array | Dim, Private, Public, ReDim, Static
 | Find the limits of an array | LBound, UBound
 | Reinitialize an array | Erase, ReDim

Table 3 Functions and Statements by Programming Task (continued)

Category | Task | Function or statement
Compiler directives | Define compiler constant | #Const
 | Compile selected blocks of code | #If...Then...#Else
Control flow | Branch | GoSub...Return, GoTo, On Error, On...GoSub, On...GoTo
 | Exit or pause the program | DoEvents, End, Exit, Stop
 | Loop | Do...Loop, For...Next, For Each...Next, While...Wend, With
 | Make decisions | Choose, If...Then...Else, Select Case, Switch
 | Indicate the beginning or end of a procedure | Function...End Function, Property Get...End Property, Property Let...End Property, Property Set...End Property, Sub...End Sub
Conversion | Convert ANSI value to string | Chr
 | Convert to lowercase or uppercase | Format, LCase, UCase
 | Convert decimal number to other bases | Hex, Oct
 | Convert number to string | Format, Str
 | Convert one data type to another | CBool, CByte, CCur, CDate, CDbl, CInt, CLng, CSng, CStr, CVar, CVErr, Fix, Int
 | Convert string to ASCII value | Asc
 | Convert string to number | Val
Date and time | Get the current date or time | Date, Now, Time functions
 | Convert serial number to date | Date, DateSerial, DateValue, Month, Weekday, Year
 | Convert serial number to time | Hour, Minute, Second, TimeSerial, TimeValue
 | Set the date or time | Date, Time statements

Table 3 Functions and Statements by Programming Task (continued)

Category | Task | Function or statement
 | Time a process | Timer
 | Perform date calculations | DateAdd, DateDiff, DatePart
Domain | Perform domain aggregate functions | DAvg, DCount, DMax, DMin, DStDev, DStDevP, DSum, DVar, DVarP
 | Return a field value from a domain | DLookup
Dynamic Data Exchange (DDE) | Use Microsoft Access as a DDE client | DDEExecute, DDEInitiate
 | Send data to another application | DDEPoke, DDESend
 | Request data from another application | DDE, DDERequest
 | Terminate a DDE conversation | DDETerminate, DDETerminateAll
Error handling | Get error messages | Error function
 | Provide error information | Err
 | Generate run-time errors | Error statement
 | Trap errors during run time | On Error, Resume
 | Verify type | IsError
 | Return a Variant of subtype Error | CVErr
File and directory navigation | Change a directory or folder | ChDir
 | Change the drive | ChDrive
 | Copy a file | FileCopy
 | Make a directory or folder | MkDir
 | Remove a directory or folder | RmDir
 | Return the current path | CurDir
 | Return file, directory, label attributes | GetAttr
 | Return a filename or volume label | Dir
 | Return a file date/time stamp | FileDateTime

Table 3 Functions and Statements by Programming Task (continued)

Category | Task | Function or statement
 | Return file length | FileLen
 | Rename a file, directory, or folder | Name
 | Set attribute information for a file | SetAttr
File input and output | Access or create a file | Open
 | Close files | Close, Reset
 | Control output appearance | Format, Print, Print #, Spc, Tab, Width #
 | Copy a file | FileCopy
 | Get information about a file | EOF, FileAttr, FileDateTime, FileLen, FreeFile, GetAttr, Loc, LOF, Seek
 | Manage files | Dir, Kill, Lock, Unlock, Name
 | Read from a file | Get, Input, Input #, Line Input #
 | Return length of a file | FileLen
 | Set or get file attributes | FileAttr, GetAttr, SetAttr
 | Set read-write position in a file | Seek
 | Write to a file | Print #, Put, Write #
Financial functions | Calculate depreciation | DDB, SLN, SYD
 | Calculate future value | FV
 | Calculate payments | IPmt, Pmt, PPmt
 | Calculate number of periods | NPer
 | Calculate internal rate of return | IRR, MIRR
 | Calculate present value | NPV, PV
 | Calculate interest rate | Rate
Math | Derive trigonometric functions | Atn, Cos, Sin, Tan
 | Perform general calculations | Exp, Log, Sqr
 | Generate random numbers | Randomize, Rnd
 | Get absolute value | Abs

Table 3 Functions and Statements by Programming Task (continued)

Category | Task | Function or statement
 | Get the sign of an expression | Sgn
 | Perform numeric conversions | Fix, Int
Miscellaneous | Returns an RGB color code | QBColor, RGB
 | Process pending events | DoEvents
 | Run other programs | AppActivate, Shell
 | Send keystrokes to an application | SendKeys
 | Generate sound from the computer’s speaker | Beep
 | Return a string associated with an operating system environment variable | Environ
 | Return a reference to an OLE Automation object | CreateObject, GetObject
Registry | Read program settings | GetSetting, GetAllSettings
 | Save program settings | SaveSetting
 | Delete program settings | DeleteSetting
String manipulation | Compare two strings | StrComp
 | Convert to lowercase or uppercase | Format, LCase, UCase
 | Create string of repeating characters | Space, String
 | Find length of a string | Len
 | Format a string | Format
 | Justify a string | LSet, RSet
 | Manipulate strings | InStr, Left, LTrim, Mid, Right, RTrim, Trim
 | Set string comparison rules | Option Compare
 | Work with ASCII and ANSI values | Asc, Chr
 | Convert strings | StrConv
Variables and constants | Assign values | Let
 | Declare variables or constants | Const, Dim, Private, Public, New, Static

Table 3 Functions and Statements by Programming Task (continued)

Category | Task | Function or statement
 | Declare a module as private | Option Private Module
 | Get information about a Variant | IsArray, IsDate, IsEmpty, IsError, IsMissing, IsNull, IsNumeric, IsObject, TypeName, VarType
 | Require explicit variable declarations | Option Explicit
 | Set default data type | DefBool, DefByte, DefCur, DefDate, DefDbl, DefInt, DefLng, DefObj, DefSng, DefStr, DefVar
 | Refer to current object | Me


Visual Basic Data Types

The following table lists the intrinsic Visual Basic data types, the functions used to convert one to another, and the functions used to check the data type of a variable.

Table 4 Visual Basic Data Types

Category | Data Type
Intrinsic data types | Boolean, Byte, Currency, Date, Double, Integer, Long, Object, Single, String, Variant (default)
Data type conversion functions | CBool, CByte, CCur, CDate, CDbl, CInt, CLng, CSng, CStr, CVar, CVErr, Fix, Int
Data type verification functions | IsArray, IsDate, IsEmpty, IsError, IsMissing, IsNull, IsNumeric, IsObject


Visual Basic Operators

The following table lists the arithmetic, comparison, and logical operators provided by Visual Basic.

Table 5 Visual Basic Operators

Category | Operator
Arithmetic | ^, -, *, /, \, Mod, +, &
Comparison | =, <>, <, >, <=, >=, Is, Like
Logical | And, Eqv, Imp, Not, Or, Xor


Events

The following table lists events by category and describes when each type of event occurs.

Table 6 Events

Category | Event | Occurs when
Data | AfterDelConfirm, AfterInsert, AfterUpdate, BeforeDelConfirm, BeforeInsert, BeforeUpdate, Change, Current, Delete, NotInList, Updated | Changes to records and occur.
Error | Error | Microsoft Access produces error.
Filter | ApplyFilter, Filter | A filter is created or applied.
Focus | Activate, Deactivate, Enter, Exit, GotFocus, LostFocus | Objects receive or lose the or become active or .
Keyboard | KeyDown, KeyPress, KeyUp | A user types on the , or keys are sent the SendKeys statement.
Mouse | Click, DblClick, MouseDown, MouseMove, MouseUp | A mouse action, such as a or double-click, occurs.

Table 6 Events (continued)

Category | Event | Occurs when
Print | Format, NoData, Page, Print, Retreat | A report is being printed orbeing formatted for .
Timing | Timer | A specified time interval .
Window | Close, Load, Open, Resize, Unload | A user carries out an action a form or report.


Actions

The following table groups actions into functional categories.

Table 7 - Actions

Category | Description | Action
Data in forms and reports | Restrict data | ApplyFilter
 | Move through data | FindNext, FindRecord, GoToControl, GoToPage, GoToRecord
 | Requery the source of a control | Requery
 | Remove an applied filter and display all records | ShowAllRecords
Execution | Carry out a command | DoMenuItem
 | Run a macro, procedure, or query | OpenQuery, RunCode, RunMacro, RunSQL
 | Run another application | RunApp
 | Stop execution | CancelEvent, Quit, StopAllMacros, StopMacro
Import/export | Send Microsoft Access objects to other applications | OutputTo, SendObject
 | Transfer data between Microsoft Access and other data formats | TransferDatabase, TransferSpreadsheet, TransferText
Category | Event | Occurs When
Object Manipulation | Copy or rename an object | CopyObject, Rename
 | Delete an object | DeleteObject
 | Move or resize a window | Maximize, Minimize, MoveSize, Restore
 | Open or close a database object | Close, OPenForm, OpenModule, OpenQuery, OpenReport, OpenTable
 | Print a database object | PrintOut
 | Save a database object | Save
 | Select a database object | SelectObject
 | Set the value of a field, control, or property | SetValue
 | Complete any pending screen updates for a specified database object | RepaintObject
Miscellaneous | Create and modify a custom menu bar or shortcut menu for a form | AddMenu, SetMenuItem
 | Display information on the screen | Echo, Hourglass, MsgBox, SetWarnings
 | Generate keystrokes | SendKeys
 | Display or hide the toolbar | ShowToolbar
 | Generate sound from the computer's speaker | Beep


#Const Directive

Description

Used to define conditional compiler constants for Visual Basic.

Syntax

#Const constname = expressionThe #Const compiler directive syntax has these parts:

Part | Description
constname | Name of the constant follows standard variable naming conventions.
expression | Literal, other conditional compiler constant, or any combination that includes all arithmetic or logical operators except Is.

Remarks

Conditional compiler constants are always Private to the module in which they appear. It is not possible to create Public compiler constants using the #Const directive. Public compiler constants can only be created in the user interface.

Only conditional compiler constants (and literals) can be used in expression. Using a standard constant (a constant defined with Const) or using a constant that is undefined causes an error to occur. Conversely, constants defined using the #Const keyword can’t be used for anything but conditional compilation.

Conditional compiler constants are always evaluated at the module level, regardless of their placement in code.

See Also

#If...Then...#Else Directive, Const Statement.

Specifics (Microsoft Access)

In Microsoft Access, you can define a public conditional compiler constant in the Declarations section of a module. A public compiler constant is applicable to all modules in the current database, but not in any other database.

You can also declare a public compiler constant by clicking Options on the Tools menu, then clicking the Module tab. Enter the constant in the Conditional Compilation Arguments box.

For example, you might enter the following expression into the Conditional Compilation Arguments box.

conDebug = 1

You can use a public compiler constant in code in any module. For example, you can create an #If...Then...#Else construct to optionally run debug code.

#If conDebug = 1 Then
    .        ' Run debug code.
    .
    .
#Else
    .        ' Run streamlined code.
    .
    .
#End If

To create multiple public conditional compilation constants, declare them on separate lines in the Declarations section. In the Conditional Compilation Arguments box, separate them with colons. For example, you can enter the following conditional compilation constants in the Conditional Compilation Arguments box.

conActiveLanguage = 0 : conDebug = 1

Using a logical operator, you can include both constants in an #If...Then...#Else construct. In the following example, you can run the first segment of code only if an expression containing both constants is true.

#If (conActiveLanguage = 0 And conDebug = 1) Then
    .        ' Run debug code for the active language version.
    .
    .
#Else
    .        ' Run another code segment.
    .
    .
#End If

Note A conditional compilation constant is always evaluated with a text-based string comparison method. This evaluation is equivalent to having an Option Compare Text statement in the module and occurs even if the module contains an Option Compare Database statement.

When writing code for conditional compilation, it may be less confusing to view one procedure at a time rather than all procedures in the module. To change how you view your code, click Options on the Tools menu, then click the Module tab. In the Code View section, clear the Full Module View check box.

Example

This example uses the #Const directive to declare conditional compiler constants for use in #If...#Else...#End If constructs.

#Const DebugVersion = 1    ' Will evaluate true in #If block.


#If...Then...#Else Directive

Description

Conditionally compiles selected blocks of Visual Basic code.

Syntax

#If expression Then statements[#ElseIf expression-n Then [elseifstatements]][#Else [elsestatements]]#End If

The #If...Then...#Else directive syntax has these parts:

Part | Description
expression | Any expression, consisting exclusively of one or more conditional compiler constants, literals, and operators, that evaluates to True or False.
statements | Visual Basic program lines or compiler directives that are evaluated if the associated expression is True.
expression-n | Same as expression.
elseifstatements | One or more program lines or compiler directives that are evaluated if expression-n is True.
elsestatements | One or more program lines or compiler directives that are evaluated if no previous expression or expression-n is True.

Remarks

The behavior of the #If...Then...#Else directive is the same as the If...Then...Else statement, except that there is no single-line form of the #If, #Else, #ElseIf, and #End If directives, that is, no other code can appear on the same line as any of the directives. Conditional compilation is typically used to compile the same program for different platforms. It is also used to prevent debugging code from appearing in an executable file. Code excluded during conditional compilation is completely omitted from the final executable file, so it has no size or performance effect.

Regardless of outcome of any evaluation, all expressions are evaluated. Therefore, all constants used in expressions must be defined — any undefined constant evaluates as Empty.

Note The Option Compare statement does not affect expressions in #If and #ElseIf statements. Expressions in a conditional-compiler directive are always evaluated with Option Compare Text.

See Also

#Const Directive, If...Then...Else Statement.

Example

This example references conditional compiler constants in a #If...Then...#Else construct to determine whether to compile certain statements.

' If Win16 evaluates as true, do the statements following the #If.
#If Win16 Then
    '. Place exclusively 16-bit Windows statements here.
    '.
    '.
' Otherwise, if it is a 32-bit Windows program, do this:
#ElseIf Win32 Then
    '. Place exclusively 32-bit Windows statements here.
    '.
    '.
' Otherwise, if it is neither, do this:
#Else
    '. Place other platform statements here.
    '.
    '.
#End If


& Operator

Description

Used to force string concatenation of two expressions.

Syntax

result = expression1 & expression2

The & operator syntax has these parts:

Part | Description
result | Any String or Variant variable.
expression1 | Any expression.
expression2 | Any expression.

Remarks

Whenever an expression is not a string, it is converted to a String variant. The data type of result is String if both expressions are String expressions; otherwise, result is a String variant. If both expressions are Null, result is also Null. However, if only one expression is Null, that expression is treated as a zero-length string when concatenated with the other expression. Any expression that is Empty is also treated as a zero-length string.

See Also

Operator Precedence.

Example

This example uses the & operator to force string concatenation.

MyStr = "Hello" & " World"            ' Returns "Hello World".= "Check " & 123 & " Check"    ' Returns "Check 123 Check".


* Operator

Description

Used to multiply two numbers.

Syntax

result = number1*number2

The * operator syntax has these parts:

Part | Description
result | Any numeric variable.
number1 | Any numeric expression.
number2 | Any numeric expression.

Remarks

The data type of result is usually the same as that of the most precise expression. The order of precision, from least to most precise, is Byte, Integer, Long, Single, Currency, Double. The following are exceptions to this order:

  • When multiplication involves a Single and a Long, the data type of result is converted to a Double.
  • When the data type of result is a Long, Single, or Date variant that overflows its legal range, result is converted to a Variant containing a Double.
  • When the data type of result is a Byte variant that overflows its legal range, result is converted to an Integer variant.
  • When the data type of result is an Integer variant that overflows its legal range, result is converted to a Long variant.

Note The order of precision used by multiplication is not the same as the order of precision used by addition and subtraction.

If one or both expressions are Null expressions, result is Null. If an expression is Empty, it is treated as if it were 0.

See Also

Operator Precedence.

Example

This example uses the * operator to multiply two numbers.

MyValue = 2 * 2                ' Returns 4.= 459.35 * 334.90     ' Returns 153836.315.


+ Operator

Description

Used to sum two numbers.

Syntax

result = expression1+expression2

The + operator syntax has these parts:

Part | Description
result | Any numeric variable.
expression1 | Any expression.
expression2 | Any expression.

Remarks

Although you can also use the + operator to concatenate two character strings, you should use the & operator for concatenation to eliminate ambiguity and provide self-documenting code.

When you use the + operator, you may not be able to determine whether addition or string concatenation will occur. If at least one expression is not a Variant, the following rules apply:

If | Then
Both expressions are numeric data types (Byte, Boolean, Integer, Long, Single, Double, Date, or Currency) | Add.
Both expressions are String | Concatenate.
One expression is a numeric data type and the other is any Variant (except Null) | Add.
One expression is a String and the other is any Variant (except Null) | Concatenate.
One expression is an Empty Variant | Return the remaining expression unchanged as result.
One expression is a numeric data type and the other is a String | A Type mismatch error occurs.
Either expression is Null | result is Null.

If both expressions are Variant expressions, the underlying type of the expressions determines the behavior of the + operator in the following way:

Both Variant expressions are numeric | Add.
Both Variant expressions are strings | Concatenate.
One Variant expression is numeric and the other is a string | Add.

For simple arithmetic addition involving only expressions of numeric data types, the data type of result is usually the same as that of the most precise expression. The order of precision, from least to most precise, is Byte, Integer, Long, Single, Double, and Currency. The following are exceptions to this order:

  • When a Single and a Long are added together, the data type of result is converted to a Double.
  • When the data type of result is a Long, Single, or Date variant that overflows its legal range, result is converted to a Double variant.
  • When the data type of result is a Byte variant that overflows its legal range, result is converted to an Integer variant.
  • When the data type of result is an Integer variant that overflows its legal range, result is converted to a Long variant.
  • When a Date is added to any data type, the data type of result is always a Date.

Note The order of precision used by addition and subtraction is not the same as the order of precision used by multiplication.

If one or both expressions are Null expressions, result is Null. If both expressions are Empty, result is an Integer. However, if only one expression is Empty, the other expression is returned unchanged as result.

See Also

Operator Precedence.

Example

This example uses the + operator to sum numbers. The + operator can also be used to concatenate strings, however, to eliminate ambiguity, you should use the & operator instead. If the components of an expression created with the + operator include both strings and numerics, the arithmetic result is assigned. If the components are exclusively strings, the strings are concatenated.

MyNumber = 2 + 2                ' Returns 4.= 4257.04 + 98112    ' Returns 102369.04.= "34": Var2 = 6        ' Initialize mixed variables.= Var1 + Var2        ' Returns 40.= "34": Var2 = "6"        ' Initialize variables with strings.= Var1 + Var2        ' Returns "346" (string concatenation).


-Operator

Description

Used to find the difference between two numbers or to indicate the negative value of a numeric expression.

Syntax 1

result = number1-number2

Syntax 2

-number

The - operator syntax has these parts:

Part | Description
result | Any numeric variable.
number | Any numeric expression.
number1 | Any numeric expression.
number2 | Any numeric expression.

Remarks

In Syntax 1, the - operator is the arithmetic subtraction operator used to find the difference between two numbers. In Syntax 2, the - operator is used as the unary negation operator to indicate the negative value of an expression.

The data type of result is usually the same as that of the most precise expression. The order of precision, from least to most precise, is Byte, Integer, Long, Single, Double, Currency. The following are exceptions to this order:

  • When subtraction involves a Single and a Long, the data type of result is converted to a Double.
  • When the data type of result is a Long, Single, or Date variant that overflows its legal range, result is converted to a Variant containing a Double.
  • When the data type of result is a Byte variant that overflows its legal range, result is converted to an Integer variant.
  • When the data type of result is an Integer variant that overflows its legal range, result is converted to a Long variant.
  • When subtraction involves a Date and any other data type, the data type of result is a Date.
  • When subtraction involves two Date expressions, the data type of result is Double.

Note The order of precision used by addition and subtraction is not the same as the order of precision used by multiplication.

If one or both expressions are Null expressions, result is Null. If an expression is Empty, it is treated as if it were 0.

See Also

Operator Precedence.

Example

This example uses the - operator to calculate the difference between two numbers.

MyResult = 4 - 2                    ' Returns 2.= 459.35 - 334.90        ' Returns 124.45.


/ Operator

Description

Used to divide two numbers and return a floating-point result.

Syntax

result = number1/number2

The / operator syntax has these parts:

Part | Description
result | Any numeric variable.
number1 | Any numeric expression.
number2 | Any numeric expression.

Remarks

The data type of result is usually a Double or a Double variant. The following are exceptions to this rule:

  • When both expressions are Byte, Integer, or Single expressions, result is a Single unless it overflows its legal range; in which case, an error occurs.
  • When both expressions are Byte, Integer, or Single variants, result is a Single variant unless it overflows its legal range; in which case, result is a Variant containing a Double.

If one or both expressions are Null expressions, result is Null. Any expression that is Empty is treated as 0.

See Also

Operator Precedence.

Example

This example uses the / operator to perform floating-point division.

MyValue = 10 / 4            ' Returns 2.5.= 10 / 3            ' Returns 3.333333.


\ Operator

Description

Used to divide two numbers and return an integer result.

Syntax

result = number1\number2

The \ operator syntax has these parts:

Part | Description
result | Any numeric variable.
number1 | Any numeric expression.
number2 | Any numeric expression.

Remarks

Before division is performed, the numeric expressions are rounded to Byte, Integer, or Long expressions.

Usually, the data type of result is a Byte, Byte variant, Integer, Integer variant, Long, or Long variant, regardless of whether result is a whole number. Any fractional portion is truncated. However, if any expression is Null, result is also Null. Any expression that is Empty is treated as 0.

See Also

Operator Precedence.

Example

This example uses the \ operator to perform integer division.

MyValue = 11 \ 4            ' Returns 2.= 9 \ 3            ' Returns 3.= 100 \ 3        ' Returns 33.


^ Operator

Description

Used to raise a number to the power of an exponent.

Syntax

result = number^exponent

The ^ operator syntax has these parts:

Part | Description
result | Any numeric variable.
number | Any numeric expression.
exponent | Any numeric expression.

Remarks

Number can be negative only if exponent is an integer value. When more than one exponentiation is performed in a single expression, the ^ operator is evaluated as it is encountered from left to right.

Usually, the data type of result is a Double or a Variant containing a Double. However, if either number or exponent is a Null expression, result is also Null.

See Also

Operator Precedence.

Example

This example uses the ^ operator to raise a number to the power of an exponent.

MyValue = 2 ^ 2                ' Returns 4.= 3 ^ 3 ^ 3            ' Returns 19683.= (-5) ^ 3            ' Returns -125.


Abs Function

Description

Returns the absolute value of a number.

Syntax

Abs(number)

The number argument can be any valid numeric expression. If number contains Null, Null is returned; if it is an uninitialized variable, zero is returned.

Remarks

The absolute value of a number is its unsigned magnitude. For example, Abs(-1) and Abs(1) both return 1.

See Also

Sgn Function.

Example

This example uses the Abs function to compute the absolute value of a number.

MyNumber = Abs(50.3)            ' Returns 50.3.= Abs(-50.3)        ' Returns 50.3.


Action Property

Applies To

Bound Object Frame Control, Chart Control, Unbound Object Frame Control.

Description

You can use the Action property in Visual Basic to specify the operation to perform on an OLE object.

Setting

The Action property uses the following settings.

Constant | Value | Description
acOLECreateEmbed | 0 | Creates an embedded object. To use this setting, you must first set the control’s OLETypeAllowed property to acOLEEmbedded or acOLEEither. Set the Class property to the type of OLE object you want to create. You can use the SourceDoc property to use an existing file as a template.
acOLECreateLink | 1 | Creates a linked OLE object from the contents of a file. To use this setting, you must first set the control’s OLETypeAllowed and SourceDoc properties. Set the OLETypeAllowed property to acOLELinked or acOLEEither. The SourceDoc property specifies the file used to create the OLE object. You can also set the control’s SourceItem property (for example, to specify a row-and-column range if the object you’re creating is a Microsoft Excel worksheet). When you create an OLE object using this setting, the control displays a metafile graphic image of the file specified by the control’s SourceDoc property. If you save the OLE object, only the link information, such as the name of the application that supplied the object and the name of the linked file, is saved because the control contains an image of the data but no source data.
acOLECopy | 4 | Copies the object to the Clipboard. When you copy an OLE object to the Clipboard, all the data and link information associated with the object is placed on the Clipboard as well. You can copy both linked and embedded objects onto the Clipboard. Using this setting is equivalent to clicking Copy on the Edit menu.
acOLEPaste | 5 | Pastes data from the Clipboard to the control. If the paste operation is successful, the control’s OLEType property is set to acOLELinked or acOLEEmbedded. If the paste operation isn’t successful, the OLEType property is set to acOLENone. Using this setting is equivalent to clicking Paste on the Edit menu.
acOLEUpdate | 6 | Retrieves the current data from the application that supplied the object and displays that data as a metafile graphic in the control.
acOLEActivate | 7 | Opens an OLE object for an operation, such as editing. To use this setting, you must first set the control’s Verb property. The Verb property specifies the operation to perform when the OLE object is activated.
acOLEClose | 9 | Closes an OLE object and ends the connection with the application that supplied the object. This setting applies to embedded objects only. Using this setting is equivalent to clicking Close on the object’s Control menu.
acOLEDelete | 10 | Deletes the specified OLE object and frees the associated memory. This setting enables you to explicitly delete an OLE object. Objects are automatically deleted when a form is closed or when the object is updated to a new object. You can’t use the Action property to delete a bound OLE object from its underlying table or query.
acOLEInsertObjDlg | 14 | Displays the Insert Object dialog box. In Form view or Datasheet view, you display this dialog box to enable the user to create a new object or to link or embed an existing object. You can use the control’s OLETypeAllowed property to determine the type of object the user can create (with the constant acOLELinked, acOLEEmbedded, or acOLEEither) using this dialog box.
acOLEPasteSpecialDlg | 15 | Displays the Paste Special dialog box. In Form View or Datasheet view, you display this dialog box to enable the user to paste an object from the Clipboard. The dialog box provides several options, including pasting either a linked or embedded object. You can use the control’s OLETypeAllowed property to determine the type of object that can be pasted (with the constant acOLELinked, acOLEEmbedded, or acOLEEither) using this dialog box.
acOLEFetchVerbs | 17 | Updates the list of verbs an OLE object supports. To display the list of verbs, use the ObjectVerbs and ObjectVerbsCount properties.

You can set the Action property only using Visual Basic. The Action property setting has an Integer data type value.

The Action property isn’t available in Design view but can be read or set in other views.

Remarks

When a control is disabled or locked, you can use some Action property settings. The following table indicates which settings are allowed or not allowed under these conditions.

Setting | Disabled | Locked
acOLECreateEmbed | Not allowed | Not allowed
acOLECreateLink | Not allowed | Not allowed
acOLECopy | Allowed | Allowed
acOLEPaste | Not allowed | Not allowed
acOLEUpdate | Not allowed | Not allowed
acOLEActivate | Allowed | Allowed
acOLEClose | Not allowed | Allowed
acOLEDelete | Not allowed | Not allowed
acOLEInsertObjDlg | Not allowed | Not allowed
acOLEPasteSpecialDlg | Not allowed | Not allowed
acOLEFetchVerbs | Not allowed | Allowed

See Also

AutoActivate Property; Class Property; Enabled, Locked Properties; ObjectVerbs Property; ObjectVerbsCount Property; OLEType Property; OLETypeAllowed Property; SourceDoc Property; SourceItem Property; UpdateOptions Property; Verb Property.

Example

The following example creates a linked OLE object and sizes the control to display the object’s entire contents when the user clicks a command button.

Sub Command1_Click
    OLE1.Class = "Excel.Sheet"                ' Set class name.
    OLE1.OLETypeAllowed = acOLELinked        ' Specify type of object.
    OLE1.SourceDoc = "C:\Excel\Oletext.xls"    ' Specify source file.
    OLE1.SourceItem = "R1C1:R5C5"            ' Specify data to link.
    OLE1.Action = acOLECreateLink            ' Create linked object.
    OLE1.SizeMode = acOLESizeZoom            ' Adjust control size.Sub


Activate, Deactivate Events

Applies To

Form, Report.

Description

These events occur:

  • Activate — When a form or report receives the focus and becomes the active window.
  • Deactivate — When a form or report loses the focus to a Table, Query, Form, Report, Macro, or Module window, or to the Database window.

Note The Deactivate event doesn’t occur when a form or report loses the focus to a dialog box, to a form for which the PopUp property is set to Yes, or to a window in another application.

Remarks

You can make a form or report active by opening it, clicking it or a control on it, or by using the SetFocus method in Visual Basic (for forms only).

The Activate event can occur only when a form or report is visible.

The Activate event occurs before the GotFocus event; the Deactivate event occurs after the LostFocus event.

When you switch between two open forms, the Deactivate event occurs for the form being switched from, and the Activate event occurs for the form being switched to. If the forms contain no visible, enabled controls, the LostFocus event occurs for the first form before the Deactivate event, and the GotFocus event occurs for the second form after the Activate event.

When you first open a form, the following events occur in this order:

Open [image] Load [image] Resize [image] Activate [image] Current

When you close a form, the following events occur in this order:

Unload [image] Deactivate [image] Close

When you close a report, the following events occur in this order:

Unload [image] Close [image] Deactivate

See Also

Current Event; GotFocus, LostFocus Events; GoToRecord Action; Load, Unload Events; Open, Close Events; Resize Event; SetFocus Method.


Activate, Deactivate Events -- Event Procedures

Description

To create an event procedure that is executed when the Activate or Deactivate event occurs, set the OnActivate or OnDeactivate property to [Event Procedure], and click the Build button.

Syntax

Private Sub Form_Activate( )Private Sub Report_Activate( )Private Sub Form_Deactivate( )Private Sub Report_Deactivate( )

Remarks

You can use Activate and Deactivate event procedures to display and hide custom toolbars. If you use a Deactivate event procedure to hide a custom toolbar, also make sure to hide the toolbar in response to the Unload event for the form or report, because the Deactivate event doesn’t occur when a form or report is unloaded. Don’t use the GotFocus or LostFocus event to hide a toolbar, because these events aren’t triggered on forms or reports that contain enabled controls.

You can’t cancel the Activate or Deactivate event.

See Also

Activate, Deactivate Events — Macros.

Example

The following example shows how to display a custom toolbar named CustomToolbar when a form receives the focus and to hide it when the focus moves to a different window.

Private Sub Form_Activate()
    DoCmd.ShowToolbar "CustomToolBar", acToolbarYes    ' Display toolbar.Sub
Sub Form_Deactivate()
    DoCmd.ShowToolbar "CustomToolBar", acToolbarNo    ' Hide toolbar.Sub


Activate, Deactivate Events -- Macros

Description

To run a macro when the Activate or Deactivate event occurs, set the OnActivate or OnDeactivate property to the name of the macro.

Remarks

You can use the ShowToolbar action in an Activate or Deactivate macro to display or hide a custom toolbar. Use the Activate or Deactivate event to display or hide custom toolbars when you have more than one form loaded at a time. If you have only one form loaded at a time, you can use the Open and Close events.

If you use a Deactivate macro to hide a custom toolbar, also make sure to hide the toolbar in response to the Unload event for the form or report, because the Deactivate event doesn’t occur when a form or report is unloaded. Don’t use the GotFocus or LostFocus event to hide a custom toolbar, because these events aren’t triggered on forms or reports that contain enabled controls.

You can’t use the CancelEvent action in an Activate or Deactivate macro.

See Also

Activate, Deactivate Events — Event Procedures.


ActiveControl Property

Applies To

Screen Object.

Description

You can use the ActiveControl property together with the Screen object to identify or refer to the control that has the focus.

Setting

This property setting contains the control object that has the focus at run time.

This property is available only in Visual Basic and is read-only in all views.

Remarks

You can use the ActiveControl property to refer to the control that has the focus at runtime together with one of its properties or methods. The following example assigns the name of the control with the focus to the strControlName variable.

Dim CurrentControl As ControlstrControlName As StringCurrentControl = Screen.ActiveControl= CurrentControl.Name

If no control has the focus when you use the ActiveControl property, or if all of the active form’s controls are hidden or disabled, an error occurs.

See Also

ActiveDatasheet Property, ActiveForm Property, ActiveReport Property, Me Property, Screen Object.

Example

The following code assigns the active control to the CurrentControl variable and then takes different actions depending on the value of the control’s Name property.

Dim CurrentControl As ControlCurrentControl = Screen.ActiveControlCurrentControl.Name = "txtCustomerID" Then
    .    ' Do this.
    .
    .CurrentControl.Name = "btnCustomerDetails" Then
    .    ' Do this.
    .
    .If


ActiveDatasheet Property

Applies To

Screen Object.

Description

You can use the ActiveDatasheet property together with the Screen object to identify or refer to the Datasheet that has the focus.

Setting

The ActiveDatasheet property setting contains the datasheet object that has the focus at run time.

This property is available only in Visual Basic and is read-only in all views.

Remarks

You can use the ActiveDatasheet property to refer to an active datasheet together with one of its properties or methods. For example, the following code uses the ActiveDatasheet property to reference the top row of the selection in the active datasheet.

TopRow = Screen.ActiveDatasheet.SelTop

See Also

ActiveControl Property; ActiveForm Property; ActiveReport Property; Screen Object; SelHeight, SelWidth Properties; SelTop, SelLeft Properties.

Example

The following example uses the ActiveDatasheet property to identify the datasheet cell with the focus, or if more than one cell is selected, the location of the first row and column in the selection.

Sub GetSelection()
    Dim obj As Object
    Dim lngFirstRow As Long, lngFirstColumn As Long
    Const conNoActiveDatasheet = 2484
    On Error GoTo GetSelection_Err
    Set obj = Screen.ActiveDatasheet
    lngFirstRow = obj.SelTop
    lngFirstColumn = obj.SelLeft
    MsgBox "The first item in this selection is located at " _
        & "Row " & lngFirstRow & ", Column " & lngFirstColumn_Bye:
    Exit Sub_Err:
    If Err = conNoActiveDatasheet Then
        Resume GetSelection_Bye
    End IfSub


ActiveForm Property

Applies To

Screen Object.

Description

You can use the ActiveForm property together with the Screen object to identify or refer to the form that has the focus.

Setting

This property setting contains the form object that has the focus at run time.

This property is available only in Visual Basic and is read-only in all views.

Remarks

You can use the ActiveForm property to refer to an active form together with one of its properties or methods. The following example displays the Name property setting of the active form.

Dim CurrentForm As FormCurrentForm = Screen.ActiveForm"Current form is " & CurrentForm.Name

If a subform has the focus, ActiveForm refers to the main form. If no form or subform has the focus when you use the ActiveForm property, an error occurs.

See Also

ActiveControl Property, ActiveDatasheet Property, ActiveReport Property, Me Property, Screen Object.


ActiveReport Property

Applies To

Screen Object.

Description

You can use the ActiveReport property together with the Screen object to identify or refer to the report that has the focus.

Setting

This property setting contains the report object that has the focus at run time.

This property is available only in Visual Basic and is read-only in all views.

Remarks

You can use the ActiveReport property to refer to an active report together with one of its properties or methods. The following example displays the Name property setting of the active report.

Dim CurrentReport As ReportCurrentReport = Screen.ActiveReport"Current report is " & CurrentReport.Name

If no report has the focus when you use the ActiveReport property, an error occurs.

See Also

ActiveControl Property, ActiveDatasheet Property, ActiveForm Property, Me Property, Screen Object.


Add Method

Applies To

Collection Object.

Description

Adds a member to a Collection object.

Syntax

object.Add(item, [key], [before], [after])

The Add method syntax has the following object qualifier and named-arguments:

Part | Description
object | Required. An object expression that evaluates to an object in the Applies To list.
item | Required. An expression of any type that specifies the member to add to the collection.
key | Optional. A unique string expression that specifies a key string that can be used, instead of a positional index, to access a member of the collection.
before | Optional. An expression that specifies a relative position in the collection. The member to be added is placed in the collection before the member identified by the before argument. If a numeric expression, before must be a number from 1 to the value of the collection’s Count property. If a string expression, before must correspond to the key specified when the member being referred to was added to the collection. You can specify before or after positions but not both.
after | Optional. An expression that specifies a relative position in the collection. The member to be added is placed in the collection after the member identified by the after argument. If numeric, after must be a number from 1 to the value of the collection’s Count property. If a string, after must correspond to the key specified when the member being referred to was added to the collection. You can specify before or after positions but not both.

Remarks

An error occurs if a value provided for before or after would not return a member of the collection when provided to the Item method as the index. In other words, whether the before or after argument is a string or numeric expression, it must refer to an existing member of the collection.

An error also occurs if a specified key duplicates the key for an existing member of the collection.

See Also

Item Method, Remove Method.

Specifics (Microsoft Access)

Items added to a user-defined collection are automatically indexed. You can refer to an individual item by this index. For example, if you have a collection colThings that contains four objects, you can refer to the third item in the collection with the expression colThings(3).

Note When you add items to a Collection object, they are automatically indexed beginning with the number 1. Therefore, when you enumerate a Collection object, keep in mind that the index begins at 1. This may be different from built-in collections, which usually are indexed beginning with 0.

When you add an object to a user-defined collection, you can specify a custom key for that object in addition to the automatic index. In subsequent references to the object, you can refer to the custom key. For example, you can add an object objMine with the following key.

colThings.Add Item := objMine, key := ("A")

Subsequently you can refer to this particular object in the collection either as colThings(A), or by its numeric index.

Example

This example uses the Add method to add Inst objects (instances of a class called Class1 containing a Public variable InstanceName) to a collection called MyClasses. To see how this works, choose the Class Module command from the Insert menu and declare a public variable called InstanceName at module level of Class1 (type Public InstanceName) to hold the names of each instance. Leave the default name as Class1. Copy and paste the following code into the Form_Load event procedure. (If your host application doesn’t have forms, paste the code at module-level and enclose it in a Sub...End Sub block.)

Dim MyClasses As New Collection    ' Create a Collection object.Num As Integer                ' Counter for individualizing keys.TheName                        ' Holder for names user enters.
    Dim Inst As New Class1        ' Create a new instance of Class1.
    Num = Num + 1                ' Increment Num, then get a name.
    Msg = "Please enter a name for this object." & Chr(13) _
         & "Press Cancel to see names in collection."
    TheName = InputBox(Msg, "Name the Collection Items")
    Inst.InstanceName = TheName    ' Put name in object instance.
    ' If user entered name, add it to the collection.
    If Inst.InstanceName <> "" Then
        ' Add the named object to the collection.
        MyClasses.Add item := Inst, key := CStr(Num)
    End If
    ' Clear the current reference in preparation for next one.
    Set Inst = NothingUntil TheName = ""

The following example creates a user-defined collection and uses the Add method to add new objects to it. To test this example, create a new form and save it as Form1. In the form’s module, declare a public variable varInstName. Your new user-defined objects will be derived from this form and its module.

You can manipulate individual objects within the collection by calling the methods or setting the properties that you have defined for them. In the module of Form1, enter the following code.

' Declare public variable in Declarations section of form module.varInstName As Variant
Sub ChangeCaption (strCaption As String)
    Me.Visible = True
    Me.Caption = strCaptionSub

This Sub procedure becomes a method that you can perform on your user-defined object, once you have created a new instance of the object.

With these steps completed, enter the following procedure in a standard module. When you run this procedure, it will create new instances of your user-defined object and add them to the collection defined by the Collection object. Then it will display the objects (forms in this case) with their changed captions.

Function MakeCollection()
    ' Create new Collection object using New keyword.
    Dim colFormObjects As New Collection
    ' Declare other variables.
    Dim strObjName As String, strList As String
    Dim strMsg As String, strCRLF As String
    Dim intI As Integer

    strCRLF = Chr(13) & Chr(10)

    ' Create objects and add them to collection.
    Do
        ' Create new instance of user-defined object.
        Dim frmObject As New Form_Form1
        strMsg = ("Please enter a name for this new object." & strCRLF _
            & "Press Cancel to see the items in the collection.")
        ' Get name for this instance of object.
        strObjName = InputBox(strMsg, "Name the collection item:")
        ' Store name in public variable you declared in form module.
        frmObject.varInstName = strObjName
        ' If user entered name, add object to collection.
        If frmObject.varInstName <> "" Then
            colFormObjects.Add Item := frmObject
        End If
        ' Clear object variable so it can be set to next instance.
        Set frmObject = Nothing
    Loop Until strObjName = ""

    ' Enumerate and display items in collection.
    ' Note that items in Collection object are indexed beginning with 1.
    intI = 1
    For Each frmObject In colFormObjects
        strList = strList & frmObject.varInstName & strCRLF
        frmObject.ChangeCaption ("New Form #" & intI)
        intI = intI + 1
    Next frmObject
    ' Display list of object names.
    MsgBox strList, , "Objects in colFormObjects collection"Function


AddColon, AutoLabel Properties

Applies To

Bound Object Frame Control, Check Box Control, Combo Box Control, Command Button Control, List Box Control, Option Button Control, Option Group Control, Subform/Subreport Control, Text Box Control, Toggle Button Control.

Description

  • AddColon — You can use this property to specify whether a colon follows the text in labels for new controls.
  • AutoLabel — You can use this property to specify whether labels are attached to new controls.

Setting

The AddColon property uses the following settings.

Setting | Description
Yes | A colon follows the text in labels for new controls.
No | A colon doesn’t follow the text in labels for new controls.

The AutoLabel property uses the following settings.

Setting | Description
Yes | A label is attached to new controls.
No | A label isn’t attached to new controls.

You can set these properties only using a control’s default control style.

Remarks

Changes to the default control style setting affect only controls created on the current form or report. To change the default control style for all new forms or reports that you create without using a Microsoft Access wizard.


AddMenu Action

Description

The AddMenu action can be used to:

  • Create a custom menu bar for a form or report. The custom menu bar replaces the built-in menu bar for the form or report.
  • Create a custom shortcut menu for a form, form control, or report. The custom shortcut menu replaces the built-in shortcut menu for the form, form control, or report.
  • Create a global menu bar. The global menu bar replaces the built-in menu bar for all Microsoft Access windows, except where you have added a custom menu bar for a form or report.
  • Create a global shortcut menu. The global shortcut menu replaces the built-in shortcut menu for all Microsoft Access windows, except where you have added a custom shortcut menu for a form, form control, or report.

Setting

The AddMenu action uses the following arguments.

Action argument | Description
Menu Name | The name of the drop-down menu to add to the custom menu bar or global menu bar. This is a required argument for custom menu bars and global menu bars. This argument is ignored for custom shortcut menus and global shortcut menus.
Menu Macro Name | The name of the macro group that contains the macros for the menu’s commands. This is a required argument.
If you run a macro containing the AddMenu action in a library database, Microsoft Access looks for the macro group with this name in the current database only.
Status Bar Text | The text to display in the status bar when the menu is selected. This argument is ignored for custom shortcut menus and global shortcut menus.

Remarks

To create a custom menu bar, a custom shortcut menu, a global menu bar, or a global shortcut menu, you must do the following:

  1. Create a menu bar macro that contains an AddMenu action for each drop-down menu you want on the custom menu bar or global menu bar. For custom shortcut menus and global shortcut menus, the menu bar macro should contain just one AddMenu action.
  2. Assign commands to each drop-down menu by creating a macro group for each menu. Each command runs the set of actions defined by a macro in this macro group. For custom shortcut menus and global shortcut menus, create just one macro group, in which each macro contains the set of actions for one of the commands in the shortcut menu.
  3. Attach the menu bar macro to the appropriate Microsoft Access object:
    • For custom menu bars, enter the name of the menu bar macro in the MenuBar property for the form or report.
    • For custom shortcut menus, enter the name of the menu bar macro in the ShortcutMenuBar property for the form, form control, or report.
    • For global menu bars, click Startup on the Tools menu, then in the Startup dialog box enter the name of the menu bar macro in the Shortcut Menu Bar box.
    • For global shortcut menus, click Startup on the Tools menu, then in the Startup dialog box enter the name of the menu bar macro in the Shortcut Menu Bar box.

Tip You can use the Menu Builder to create any of the custom or global menu bars and shortcut menus by clicking the Build button next to the property box or Startup dialog option box where you specify the menu bar macro. The Menu Builder creates and names the menu bar macro and the macro groups containing the actions for the menu commands and subcommands on the menu you create. If you use the Menu Builder to create the menu bar macro and the macro groups for the menus, you can also use the Menu Builder to edit these macros and macro groups.

However, if you create the custom menu bar or custom shortcut menu in the Macro window, you can’t use the Menu Builder to edit the menu bar macro and macro groups because the Menu Builder places restrictions on the names it uses for the menu bar macro and macro groups, and on the kinds of actions it uses in the macros.

For global shortcut menus and custom shortcut menus, add only one menu in the Menu Builder. Any additional menus are ignored.

Each menu on the menu bar requires a separate AddMenu action.

The custom and global menu bars and shortcut menus replace the built-in menu bars and shortcut menus for the objects they’re attached to. If you want to retain certain Microsoft Access commands to use on these menus, use the DoMenuItem action to put the commands into the macro groups for the desired menus.

You can run a macro from a menu command by using the RunMacro action in the macro for the command.

Note AddMenu actions can be used only in a menu bar macro specified by the MenuBar or ShortcutMenuBar property of a form, form control, or report, or by the Menu Bar box or Shortcut Menu Bar box in the Startup dialog box, available by clicking Startup on the Tools menu. Menu bar macros should contain only AddMenu actions.

You can create a submenu for a custom menu or a custom shortcut menu by using the AddMenu action in a macro group specified by the Menu Macro Name argument. If you put an AddMenu action in such a macro group, Microsoft Access creates a submenu with the menu name and status bar text specified by the Menu Name and Status Bar Text arguments for this AddMenu action. The submenu contains the commands defined by the macros in the macro group specified by the Menu Macro Name argument for the AddMenu action. The Menu Name and Status Bar Text columns of such an AddMenu action are ignored, since this action defines a submenu, not a command on the top-level menu. You can create multiple levels of submenus by using AddMenu actions in the macro groups for each level of menu.

Macro conditions are supported in the top-level menu bar macro only. In other words, you can use a condition in a menu bar macro to determine if a particular menu will be displayed on the custom menu bar or global menu bar, but only for the menus on the top level of the menu bar. You can’t use conditions to display or hide commands or submenus on the menus. You can also use a condition to hide or show a custom shortcut menu or global shortcut menu.

Note In Microsoft Access version 2.0, if you used the AddMenu action to put the Add-Ins submenu on the File menu of a custom menu bar, Microsoft Access automatically added the appropriate Add-Ins submenu items to your custom menu. In Microsoft Access for Windows 95, the Add-Ins submenu has moved to the Tools menu. Microsoft Access adds the submenu items to this menu as before. However, it will not add the submenu items to an Add-Ins submenu on the File menu of a custom menu bar or global menu bar. If you had an Add-Ins submenu on one or more of your custom menu bars in version 2.0, you may want to rewrite your macros and move the Add-Ins submenu to the Tools menu.

The AddMenu action isn’t available in Visual Basic. You can, however, set the MenuBar or ShortcutMenuBar property in Visual Basic to attach a custom menu bar or custom shortcut menu to a form, form control, or report. You can set the StartupMenuBar property (the programmatic equivalent of setting the Menu Bar box) to create a global menu bar. You can also set the MenuBar property of the Application object to create a global menu bar. Similarly, you can set the StartupShortcutMenuBar property (the programmatic equivalent of setting the Shortcut Menu Bar box) or the ShortcutMenuBar property of the Application object to create a global shortcut menu.

See Also

Application Object, Event Properties, MenuBar Property, ShortcutMenuBar Property, StartupMenuBar Property, StartupShortcutMenuBar Property.


AfterDelConfirm Event

See Delete, BeforeDelConfirm, AfterDelConfirm Events.


AfterInsert Event

See BeforeInsert, AfterInsert Events.


AfterUpdate Event

See BeforeUpdate, AfterUpdate Events.


Alias Property

Applies To

Query.

Description

You can use the Alias property to specify a custom name for an input table or query when you use the same table or query more than once in the same query.

Note The Alias property applies only to tables or queries when used as the source of data in a query.

Setting

You can set the Alias property using a string expression to any name not currently being used in the database. You set this property in query design view by right clicking on the field list in the query design grid and choosing Properties.

You can set the Alias property in SQL view of the Query window by using an AS clause in the SQL statement.

Remarks

You must use an alias when creating self-join in an SQL statement.

When you add a table or query to a query, Microsoft Access automatically sets the Alias property to the name of the table or query. If a second instance of the same table or query is added, Microsoft Access sets the Alias as the object name plus an underscore and a one (“_1”).

Creating an alias doesn’t change the name of the table or query — it only specifies another name that can also be used to refer to the table or query. For example, in a query containing a self-join that shows employees and their managers, you would use two copies of the Employees table. Microsoft Access automatically calls the duplicate table Employees_1. To give this table a more meaningful name, you could set its Alias property to Managers.

Example

The following example sets the RecordSource property for a form to an SQL statement that uses the AS clause to specify Managers as the alias for the Employees table.

Dim strGetSQL AS String= "SELECT DISTINCTROW Employees.[FirstName]," _
    & "Employees.[LastName], Employees.Title," _
    & "Managers.[FirstName], Managers.[LastName] FROM Employees" _
    & "INNER JOIN Employees AS Managers ON Employees.[ReportsTo] = " _
    & "Managers.[EmployeeID];"!Form1.RecordSource = strGetSQL

This example uses a self-join to show employees and their managers. It uses the AS clause to set the Alias property of the duplicate Employees table to Managers. You can enter this SQL statement in SQL view of the Query window.

SELECT DISTINCTROW Employees.[FirstName], Employees.[LastName], .Title, Managers.[FirstName], Managers.[LastName] Employees INNER JOIN Employees AS Managers ON Employees.[ReportsTo] = Managers.[EmployeeID];


AllowAdditions Property

Applies To

Form.

Description

You can use the AllowAdditions property to specify whether a user can add a record using a form.

Setting

The AllowAdditions property uses the following settings.

Setting | Description | Visual Basic
Yes | (Default) The user can add new records. | True (-1)
No | The user can’t add new records | False (0)

You can set the AllowAdditions property in the form’s property sheet, a macro, or using Visual Basic.

Remarks

Set the AllowAdditions property to No to allow users to view or edit existing records but not add new records.

If you want to prevent changes to existing records (make a form read-only), set the AllowAdditions, AllowDeletions, and AllowEdits properties to No. You can also make records read-only by setting the RecordsetType property to Snapshot.

If you want to open a form for data entry only, set the form’s DataEntry property to Yes.

When AllowAdditions is set to No, the Data Entry command on the Records menu is not available.

See Also

AllowDeletions Property, AllowEdits Property, DataEntry Property, RecordsetType Property.

Example

The following example examines the ControlType property for all controls on a form. For each label and text box control, the procedure toggles the SpecialEffect property for those controls. When the label controls’ SpecialEffect property is set to Shadowed and the Text box controls’ SpecialEffect property is set to Normal and the AllowAdditions, AllowDeletions, and AllowEdits properties are all set to True.

Sub ToggleControl(frm As Form)ctlCurrentControl As ControlintI As Integer, intCanEdit As IntegerconTransparent = 0conWhite = 16777215intI = 0 To frm.Count - 1
    Set ctlCurrentControl = frm(intI)
    Select Case ctlCurrentControl.ControlType
        Case acLabel
            If ctlCurrentControl.SpecialEffect = acEffectShadow Then
                ctlCurrentControl.SpecialEffect = acEffectNormal
                ctlCurrentControl.BorderStyle = conTransparent
                intCanEdit = True
            Else
                ctlCurrentControl.SpecialEffect = acEffectShadow
                intCanEdit = False
            End If
        Case acTextBox
            If ctlCurrentControl.SpecialEffect = acEffectNormal Then
                ctlCurrentControl.SpecialEffect = acEffectSunken
                ctlCurrentControl.BackColor = conWhite
            Else
                ctlCurrentControl.SpecialEffect = acEffectNormal
                ctlCurrentControl.BackColor = frm.Detail.BackColor
            End If
    End SelectintI
    If intCanEdit = False Then
        frm.AllowAdditions = False
        frm.AllowDeletions = False
        frm.AllowEdits = False
    Else
        frm.AllowAdditions = True
        frm.AllowDeletions = True
        frm.AllowEdits = True
    End IfSub


AllowAutoCorrect Property

Applies To

Combo Box Control, Text Box Control.

Description

You can use the AllowAutoCorrect property to specify whether a text box or a combo box control will automatically correct entries made by the user.

Setting

The AllowAutoCorrect property uses the following settings.

Setting | Description | Visual Basic
Yes | (Default) Entries are automatically corrected according to the settings in the AutoCorrect dialog box. | True (-1)
No | Entries are not corrected. | False (0)

You can set the AllowAutoCorrect property in a control’s property sheet, a macro, or using Visual Basic. You can also set this property in the control’s default control style.

Remarks

The AutoCorrect dialog box is available by clicking AutoCorrect on the Tools menu.


AllowBreakIntoCode Property

Applies To

Database Object.

Description

You can use the AllowBreakIntoCode property to specify whether or not the user can view Visual Basic code after a run-time error occurs in a module.

Setting

The AllowBreakIntoCode property uses the following settings.

Setting | Description
True (-1) | Enable the Debug button on the dialog box that appears when a error occurs.
False (0) | Disable the Debug button.

You can set this property by using a macro or Visual Basic. You can also set this property using the Allow Viewing Code After Error option in the Advanced section of the Startup dialog box, available by clicking Startup on the Tools menu. This is the easiest way to set this property.

Remarks

You should not disable the AllowBreakIntoCode property when debugging application or macros.

This property’s setting does not take effect until the next time the application database opens.

Example

This example shows procedure named SetStartupProperties that passes the name of the property to be set, its data type, and its desired setting. The general purpose procedure ChangeProperty attempts to set the startup property and, if the property is not found, uses the CreateProperty method to append it to the database properties collection. This is necessary because these properties do not appear in the properties collection until they have been set or changed at least once.

Sub SetStartupProperties()
    ChangeProperty "StartupForm", dbText, "Customers"
    ChangeProperty "StartupShowDBWindow", dbBoolean, False
    ChangeProperty "StartupShowStatusBar", dbBoolean, False
    ChangeProperty "AllowBuiltinToolbars", dbBoolean, False
    ChangeProperty "AllowFullMenus", dbBoolean, True
    ChangeProperty "AllowBreakIntoCode", dbBoolean, False
    ChangeProperty "AllowSpecialKeys", dbBoolean, True
    ChangeProperty "AllowBypassKey", dbBoolean, TrueSub
ChangeProperty(strPropName As String, varPropType As Variant, _            varPropValue As Variant) As Integer
        Dim dbs As Database, prp As Property
        Const conPropNotFoundError = 3270
        Set dbs = CurrentDb
        On Error GoTo Change_Err
        dbs.Properties(strPropName) = varPropValue
        ChangeProperty = True
    Change_Bye:
        Exit Function
    Change_Err:
        If Err = conPropNotFoundError Then  ' prop not found.
            Set prp = dbs.CreateProperty(strPropName, _
                varPropType, varPropValue)
            dbs.Properties.Append prp
            Resume Next
    Else
            ' unknown error.
            ChangeProperty = False
            Resume Change_Bye
        End IfFunction


AllowBuiltInToolbars Property

Applies To

Database Object.

Description

You can use the AllowBuiltInToolbars property to specify whether or not the user can display Microsoft Access built-in toolbars. For example, you can use the AllowBuiltInToolbars property to prevent a user from seeing a Microsoft Access built-in toolbar within a database application.

Setting

The AllowBuiltInToolbars property has the following settings.

Setting | Description
True (-1) | Allow built-in toolbars to be displayed.
False (0) | Don’t allow built-in toolbars to be displayed.

You can set this property by using a macro or Visual Basic. You can also set this property using the Allow Default Toolbars option in the Startup dialog box, available by clicking Startup on the Tools menu. This is the easiest way to set this property.

Remarks

If the AllowBuiltInToolbars property is set to False, clicking Toolbars on the View menu will not display any built-in toolbars.

The user can modify built-in toolbars only when the AllowToolbarChanges property is set to True and the AllowBuiltInToolbars property is set to True.

This property setting has no effect on the ShowToolbar action. If the AllowBuiltInToolbars property is set to False, no toolbar is displayed.

This property’s setting does not take effect until the next time the application database opens.

See Also

AllowBreakIntoCode Property, AllowToolbarChanges Property, ShowToolbar Action.

Example

See the AllowBreakIntoCode property example.


AllowBypassKey Property

Applies To

Database Object.

Description

You can use the AllowBypassKey property to specify whether or not the SHIFT key is enabled for bypassing the startup properties or the AutoExec macro. For example, you can set the AllowBypassKey property to False to prevent a user from bypassing the startup properties and the AutoExec macro.

Setting

The AllowBypassKey property uses the following settings.

Setting | Description
True (-1) | Enable the SHIFT key to allow the user to bypass the startup properties or the AutoExec macro.
False (0) | Disable the SHIFT key to prevent the user from bypassing the startup properties or the AutoExec macro.

You can set this property by using a macro or Visual Basic.

Remarks

You should enable the AllowBypassKey property when debugging your database.

This property’s setting does not take effect until the next time the application database opens.

See Also

AllowBreakIntoCode Property, AllowSpecialKeys Property.

Example

See the AllowBreakIntoCode property example.


AllowDeletions Property

Applies To

Form.

Description

You can use the AllowDeletions property to specify whether a user can delete a record using a form.

Setting

The AllowDeletions property uses the following settings.

Setting | Description | Visual Basic
Yes | (Default) The user can delete records. | True (-1)
No | The user can’t delete records. | False (0)

You can set the AllowDeletions property in the form’s property sheet, a macro, or using Visual Basic.

Remarks

You can set this property to No to allow users to view and edit existing records but not to delete them. When AllowDeletions is set to Yes, records may be deleted so long as existing referential integrity rules are not violated.

If you want to prevent changes to existing records (make a form read-only), set the AllowAdditions, AllowDeletions, and AllowEdits properties to No. You can also make records read-only by setting the RecordsetType property to Snapshot.

When AllowDeletions is set to No, the Delete Record command on the Edit menu is not available.

See Also

AllowAdditions Property, AllowEdits Property, DataEntry Property, RecordsetType Property.

Example

See the AllowAdditions property example.


AllowEditing, DefaultEditing Properties

Applies To

Form.

Description

  • AllowEditing — determines whether the Allow Editing command on the Records menu is enabled when you open a form in Form view or Datasheet view.
  • DefaultEditing — determines whether a form opens to allow editing, read-only access, data entry (you can only enter new records), or editing of existing records only (you can’t enter any new records).

Note The AllowEditing and DefaultEditing properties are included in this version of Microsoft Access only for compatibility with previous versions. It is recommended that you use the AllowEdits, AllowAdditions, and DataEntry properties instead.

Setting

The AllowEditing property uses the following settings.

Setting | Description
Available | (Default) The Allow Editing command on the Records menu is enabled.
Unavailable | The Allow Editing command is disabled.

The DefaultEditing property uses the following settings.

Setting | Description
Allow Edits | (Default) You can edit, add, or delete records in the form’s table or query.
Read Only | You can’t edit, add, or delete records until you choose the Allow Editing command.
Data Entry | You can add new records. Existing records aren’t available.
Can’t Add Records | You can edit or delete existing records. You can’t add new records.

You can set these properties in the form’s property sheet, a macro, or Visual Basic.

Remarks

Use these properties to design forms for data entry or for read-only access. You can combine them to establish the following conditions.

DefaultEditing | AllowEditing | Description
Allow Edits | Available or Unavailable | All records are available. You can edit, add, or delete records.
Read Only | Available | All records are available. You must choose the Allow Editing command to edit, add, or delete records.
Unavailable | All records are available. You can’t edit, add, or delete records.
Data Entry | Available | No existing records are available. You can add new records.
Unavailable | No existing records are available. You can’t edit, add, or delete records.
Can’t Add Records | Available or Unavailable | All existing records are available, and you can edit or delete them. You can’t add new records.

Note The Data Entry setting doesn’t completely prevent you from viewing records when using the form. If the AllowFilters property is set to Yes, you can click Remove Filter/Sort on the Records menu to display all records.

See Also

AllowAdditions Property, AllowEdits Property, DataEntry Property.

Example

The following example disables the Records menu’s Allow Editing command and specifies that the form open in data entry mode.

Sub Form_Open(Cancel As Integer)
    Const conDataEntry = 3
        Me.AllowEditing = False      ' Disable Records menu option.
        Me.DefaultEditing = conDataEntrySub


AllowEdits Property

Applies To

Form.

Description

You can use the AllowEdits property to specify whether a user can edit saved records using a form.

Setting

The AllowEdits property uses the following settings.

Setting | Description | Visual Basic
Yes | (Default) The user can edit saved records. | True (-1)
No | The user can’t edit saved records. | False (0)

You can set the AllowEdits property in the form’s property sheet, a macro, or using Visual Basic.

Remarks

You can use the AllowEdits property to prevent changes to all data displayed by a form. If you want to prevent changes to data in a specific control, use the Enabled or Locked properties.

If you want to prevent changes to existing records (make a form read-only), set the AllowAdditions, AllowDeletions, and AllowEdits properties to No. You can also make records read-only by setting the RecordsetType property to Snapshot.

See Also

AllowAdditions Property; AllowDeletions Property; DataEntry Property; Enabled, Locked Properties; RecordsetType Property.

Example

See the AllowAdditions property example.


AllowFilters Property

Applies To

Form.

Description

You can use the AllowFilters property to specify whether records can be filtered.

Settings

The AllowFilters property uses the following settings.

Setting | Description | Visual Basic
Yes | (Default) Records can be filtered. | True (-1)
No | Records can’t be filtered. | False (0)

You can set this property using the form’s property sheet, a macro, or Visual Basic.

Remarks

Filters are commonly used to view a temporary subset of the records in a database. When you use a filter, you apply criteria to display only records that meet specific conditions. In an Employees table, for example, you can use a filter to display only records of employees with over 5 years of service. You can also use a filter to restrict access to records containing sensitive information, such as financial or medical data.

When the AllowFilters property is set to No, all of the filter options on the Records menu and the shortcut menu are disabled.

See Also

Filter Property, ShortcutMenu Property.

Example

The following example shows a function that toggles a form’s AllowFilters property on and off.

Function ToggleAllowFilters() As Integer
    Forms!Customers.AllowFilters = Not Forms!Customers.AllowFiltersFunction


AllowFullMenus Property

Applies To

Database Object.

Description

You can use the AllowFullMenus property to specify whether or not full Microsoft Access built-in menus will be available when the application database opens. For example, you can use the AllowFullMenus property to disable menu items that give users the ability to modify table, form, query, or report structures.

Setting

The AllowFullMenus property uses the following settings.

Setting | Description
True (-1) | Display the full built-in menus at startup.
False (0) | Don’t display full built-in menus at startup.

You can set this property by using a macro or Visual Basic. You can also set this property using the Allow Full Menus option in the Startup dialog box, available by clicking Startup on the Tools menu. This is the easiest way to set this property.

Remarks

This property’s setting does not take effect until the next time the database opens.

See Also

AllowBreakIntoCode Property, AllowShortcutMenus Property, StartupMenuBar Property, StartupShortcutMenuBar Property.

Example

See the AllowBreakIntoCode property example.


AllowShortcutMenus Property

Applies To

Database Object.

Description

You can use the AllowShortcutMenus property to specify whether or not your application allows Microsoft Access to display shortcut menus. For example, you can use the AllowShortcutMenus property to prevent the user from using any shortcut menu within your application.

Setting

The AllowShortcutMenus property uses the following settings.

Setting | Description
True (-1) | Allow Microsoft Access shortcut menus to be displayed.
False (0) | Don’t allow Microsoft Access shortcut menus to be displayed.

You can set this property by using a macro or Visual Basic. You can also set this property using the Allow Default Shortcut Menus option in the Startup dialog box, available by clicking Startup on the Tools menu. This is the easiest way to set this property.

Remarks

This property’s setting does not take effect until the next time the database opens.

See Also

AllowBreakIntoCode Property, AllowFullMenus Property.


AllowSpecialKeys Property

Applies To

Database Object.

Description

You can use the AllowSpecialKeys property to specify whether or not special key sequences (ALT+F1 (F11), CTRL+F11, CTRL+BREAK, and CTRL+G) are disabled or enabled. For example, you can use the AllowSpecialKeys property to prevent a user from displaying the Database window using F11, entering break mode within a Visual Basic module using CTRL+BREAK, or displaying the Debug window using CTRL+G.

Setting

The AllowSpecialKeys property uses the following settings.

Setting | Description
True (-1) | Enable the special key sequences.
False (0) | Disable the special key sequences.

You can set this property by using a macro or Visual Basic. You can also set this property by selecting Use Access Special Keys in the Advanced section of the Startup dialog box, available by clicking Startup on the Tools menu. This is the easiest way to set this property.

Remarks

You should enable the AllowSpecialKeys property when debugging your database.

The AllowSpecialKeys property affects the following key sequences.

Key sequences | Effect
ALT+F1 (F11) | Bring the Database window to the front.
CTRL+G | Display the Debug window.

Key sequences | Effect
CTRL+F11 | Toggle between the custom menu bar and the built-in menu bar.
CTRL+BREAK | Enter break mode.

This property’s setting does not take effect until the next time the application database opens

See Also

AllowBreakIntoCode Property, AllowBypassKey Property.

Example

See the AllowBreakIntoCode property example.


AllowToolbarChanges Property

Applies To

Database Object.

Description

You can use the AllowToolbarChanges property to specify whether or not your database allows users to customize toolbars. For example, you can use the AllowToolbarChanges property to prevent users from deleting a toolbar button or an entire toolbar from your application.

Setting

The AllowToolbarChanges property uses the following settings.

Setting | Description
True (-1) | Allow changes to toolbars.
False (0) | Don’t allow changes to toolbars.

You can set this property by using a macro or Visual Basic. You can also set this property using the Allow Toolbar Changes option in the Startup dialog box, available by clicking Startup on the Tools menu. This is the easiest way to set this property.

Remarks

Setting the AllowToolbarChanges property to False prevents users from modifying any toolbars. It disables the Toolbars command on the View menu, the right-click menu feature on toolbars, and all Close buttons on toolbars displayed in the Microsoft Access window.

The user can modify built-in toolbars only when the AllowToolbarChanges property is True and the AllowBuiltInToolbars is True.

This property’s setting does not take effect until the next time the database opens.

See Also

AllowBreakIntoCode Property, AllowBuiltInToolbars Property, ShowToolbar Action.

Example

See the AllowBreakIntoCode property example.


AllowZeroLength Property

Applies To

Table Fields.

Description

You can use the AllowZeroLength property to specify whether a zero-length string (" ") is a valid entry in a field.

Note The AllowZeroLength property applies only to text and Memo table fields.

Setting

The AllowZeroLength property uses the following settings.

Setting | Description | Visual Basic
Yes | A zero-length string is a valid entry. | True (-1)
No | (Default) A zero-length string is an invalid entry. | False (0)

You can set this property in the table’s property sheet or Visual Basic.

Note To access a field’s AllowZeroLength property using Visual Basic, use the Data Access Object’s AllowZeroLength property.

Remarks

You can use the settings of the AllowZeroLength and Required properties to differentiate between information that doesn’t exist (stored as a zero-length string in the field) and information that may exist but is unknown (stored as a Null value in the field). For example, you might have customers in your database who don’t have a fax number. If the AllowZeroLength property is set to Yes and the Required property is set to No, you can enter a zero-length string to indicate that a customer doesn’t have a fax number. If you leave the Fax field blank (you don’t type a number or you delete the existing number), it can indicate that the customer may have a fax number, but you don’t know what it is.

Note You need to use an input mask when data is entered in a field to distinguish between the display of a Null value and a zero-length string. For example, the string “None” can be displayed when a zero-length string is entered.

The AllowZeroLength property works independently of the Required property. The Required property determines only whether a Null value is valid for the field. If the AllowZeroLength property is set to Yes, then a zero-length string will be a valid value for the field regardless of the setting of the Required property.

The following table shows the results of combining the settings of the AllowZeroLength and Required properties.

AllowZeroLength | Required | User’s action | Value stored
No | No | Presses ENTER Presses SPACEBAR Enters a zero-length string | Null Null (not allowed)
Yes | No | Presses ENTER Presses SPACEBAR Enters a zero-length string | Null Nullstring
No | Yes | Presses ENTER Presses SPACEBAR Enters a zero-length string | (not allowed) (not allowed) (not allowed)
Yes | Yes | Presses ENTER Presses SPACEBAR Enters a zero-length string | (not allowed)stringstring

See Also

DefaultValue Property, Required Property, Microsoft Office 95 Data Access Reference topics: AllowZeroLength Property, Required Property.


And Operator

Description

Used to perform a logical conjunction on two expressions.

Syntax

result = expression1 And expression2

The And operator syntax has these parts:

Part | Description
result | Any numeric variable.
expression1 | Any expression.
expression2 | Any expression.

Remarks

If, and only if, both expressions evaluate to True, result is True. If either expression evaluates to False, result is False. The following table illustrates how result is determined:

If expression1 is | And expression2 is | The result is
True | True | True
True | False | False
True | Null | Null
False | True | False
False | False | False
False | Null | False
Null | True | Null
Null | False | False
Null | Null | Null

The And operator also performs a bit-wise comparison of identically positioned bits in two numeric expressions and sets the corresponding bit in result according to the following truth table:

If bit in expression1 is | And bit in expression2 is | The result is
0 | 0 | 0
0 | 1 | 0
1 | 0 | 0
1 | 1 | 1

See Also

Operator Precedence.

Example

This example uses the And operator to perform a logical conjunction on two expressions.

A = 10: B = 8: C = 6: D = Null    ' Initialize variables.= A > B And B > C        ' Returns True.= B > A And B > C        ' Returns False.= A > B And B > D        ' Returns Null.= A And B                ' Returns 8 (bit-wise comparison).


AppActivate Statement

Description

Activates an application window.

Syntax

AppActivate title[, wait]

The AppActivate statement syntax has these named arguments:

Part | Description
title | The title argument is the string expression in the title bar of the application window you want to activate.
In addition, the task ID returned by the Shell function can be used, in place of title, to activate an application.
wait | Boolean value specifying whether the calling application has the focus before activating another. If False (default), the specified application is immediately activated, even if the calling application does not have the focus. If True, the calling application waits until it has the focus, then activates the specified application.

Remarks

The AppActivate statement changes the focus to the named application or window but does not affect whether it is maximized or minimized. Focus moves from the activated application window when the user takes some action to change the focus or close the window. Use the Shell function to start an application and set the window style.

In determining which application to activate, title is compared to the title string of each running application. If there is no exact match, any application whose title string begins with title is activated. In Microsoft Windows, if there is more than one instance of the application named by title, one is arbitrarily activated.

See Also

SendKeys Statement, Shell Function.

Example

This example illustrates various uses of the AppActivate statement to activate an application window. The Shell statements assume the applications are in the paths specified.

AppActivate "Microsoft Word"                    ' Activate Microsoft
                                            ' Word.
' AppActivate can also use the return value of the Shell function.= Shell("C:\WORD\WINWORD.EXE", 1)    ' Run Microsoft Word.MyAppID                            ' Activate Microsoft
                                            ' Word.
' You can also use the return value of the Shell function.= Shell("c:\EXCEL\EXCEL.EXE",1)    ' Run Microsoft Excel.ReturnValue                        ' Activate Microsoft
                                            ' Excel.


AppIcon Property

Applies To

Database Object.

Description

You can use the AppIcon property to specify the name of the bitmap (.bmp) or icon (.ico) file that contains the application’s icon. For example, you can use the AppIcon property to specify a .bmp file that contains an picture of an automobile to represent an automotive parts application.

Setting

The AppIcon property is a string expression that is a bitmap or icon filename.

You can set this property by using a macro or Visual Basic. You can also set this property using the Application Icon option in the Startup dialog box, available by clicking Startup on the Tools menu. This is the easiest way to set this property.

To set the AppIcon property using Visual Basic you must first create the property using the CreateProperty method and append it to the Database properties collection.

Remarks

This property setting takes effect immediately after it is set in code or the Startup dialog box is closed.

If you are distributing your application, it is recommended that the .bmp or .ico file containing the icon reside in the same directory as your Microsoft Access application.

If the AppIcon property is not set or is invalid, the Microsoft Access icon is displayed.

See Also

AppTitle Property.

Example

The following example shows how to change the AppIcon and AppTitle properties. If the properties have not already been set or created, you must create them and append them to the Database object using the CreateProperty method.

Sub cmdAddProp_Click()
    Dim x As Integer
    x = AddAppProperty("AppTitle", dbText, "My Custom Application")
    x = AddAppProperty("AppIcon", dbText, "C:\Windows\Cars.bmp")Sub
AddAppProperty(prpName As String, prpType As Variant, _
        prpValue As Variant) As Integer
    Dim dbs As Database, prp As Property
    Const conPropNotFoundError = 3270
    Set dbs = CurrentDb
    On Error GoTo AddProp_Err
    dbs.Properties(prpName) = prpValue
    AddAppProperty = True_Bye:
    Exit Function_Err:
    If Err = conPropNotFoundError Then
        Set prp = dbs.CreateProperty(prpName, prpType, prpValue)
        dbs.Properties.Append prp
        Resume
    Else
        AddAppProperty = False
        Resume AddProp_Bye
    End IfFunction


Application Object

Description

The Application object refers to the active Microsoft Access application.

Remarks

The Application object contains all Microsoft Access objects and collections, including the Forms collection, the Reports collection, the Screen object, and the DoCmd object.

You can use the Application object to apply methods or property settings to the entire Microsoft Access application. For example, you can use the SetOption method of the Application object to set database options from Visual Basic. The following example shows how you can set the Show Status Bar option.

Application.SetOption "Show Status Bar", True

Microsoft Access is an OLE Automation server. You can manipulate Microsoft Access objects from another application that is an OLE Automation controller. To do this, you use the Application object.

For example, Microsoft Visual Basic is an OLE Automation controller. You can open a Microsoft Access database from Microsoft Visual Basic and work with its objects. From Microsoft Visual Basic, first create a reference to Microsoft Access. Then create a new instance of the Application object and point an object variable to it, as in the following example.

Dim appAccess As Access.ApplicationappAccess = CreateObject("Access.Application.7")

Once you have created a new instance of the Microsoft Access Application object, you can open a database or create a new database, using either the OpenCurrentDatabase method or the NewCurrentDatabase method. You can then set the properties of the Application object and call its methods.

Note If you are creating an instance of the Microsoft Access Application object from Microsoft Excel, you must declare the object variable as type Object, as in the following example.

Dim appAccess As ObjectappAccess = CreateObject("Access.Application.7")

You can also manipulate other Microsoft Access objects through the Application object. For example, using the OpenForm method of the Microsoft Access DoCmd object, you can open a Microsoft Access form from Microsoft Excel.

appAccess.DoCmd.OpenForm "OrderForm"

For more information on creating a reference and controlling objects by OLE Automation, see the documentation for the application that is acting as the OLE Automation controller.

Properties
DBEngine Property.

Methods
BuildCriteria Method; CloseCurrentDatabase Method; DefaultWorkspaceClone Method; Echo Method; GetOption, SetOption Methods; NewCurrentDatabase Method; OpenCurrentDatabase Method; Quit Method; RefreshTitleBar Method; Run Method.

See Also
CreateObject Function, DBEngine Object, DoCmd Object, Forms Collection, GetObject Function, Reports Collection, Screen Object.

Example
The following example prints some current property settings of the Application object, sets an option, and then quits the application, saving all objects.

Sub ApplicationInformation()
    ' Print name and type of current object.
    Debug.Print Application.CurrentObjectName
    Debug.Print Application.CurrentObjectType
    ' Set Show Hidden Objects option.
    Application.SetOption "Show Hidden Objects", True
    ' Quit Microsoft Access, saving all objects.
    Application.Quit acSaveYesSub

The next example shows how to use Microsoft Access as an OLE Automation server. From Microsoft Visual Basic or another application that acts as an OLE Automation controller, create a reference to Microsoft Access by clicking References on the Tools menu. Select the check box next to Microsoft Access For Windows 95. Then enter the following code in a Visual Basic module within that application.

This procedure creates a new instance of the Application object and opens a new database in the Microsoft Access Database window. It then creates a new form in that database.

Note that an instance of Microsoft Access will close when the variable pointing to the Application object goes out of scope. To prevent Microsoft Access from closing when the procedure has finished running, the variable representing the Application object is declared at the module level in the example below.

' Declare object variable in Declarations section of module.appAccess As Access.Application

NewAccessDB()
    ' Declare Database variable and Microsoft Access Form variable.
    Dim dbs As Database, frm As Access.Form

    ' Return instance of Application object.

    Set appAccess = CreateObject("Access.Application.7")
    ' Create new database in Microsoft Access window.
    appAccess.NewCurrentDatabase("Newdb.mdb")
    ' Create new Microsoft Access form in Design view.
    set frm = appAccess.CreateForm
    ' Restore form window.
    appAccess.DoCmd.RestoreSub


Application Property

Applies To

Bound Object Frame Control, Chart Control, Check Box Control, Combo Box Control, Command Button Control, Controls Collection, Form, Form Section, Forms Collection, Image Control, Label Control, Line Control, List Box Control, Option Button Control, Option Group Control, Page Break Control, Properties Collection, Rectangle Control, Report, Report Section, Reports Collection, Screen Object, Subform/Subreport Control, Text Box Control, Toggle Button Control, Unbound Object Frame Control.

Description

You can use the Application property in Visual Basic to access the active Microsoft Access Application object and its related properties.

Setting

The Application property is set by Microsoft Access and is read-only.

Remarks

Each Microsoft Access object has an Application property that returns the current Application object. You can use this property to access any of the Application object properties. For example, you could refer to the menu bar for the Application object from the current form using the following syntax:

Me.Application.MenuBar

See Also

Application Object.

Example

This example demonstrates the use of the Application and DBEngine properties to display the DBEngine properties in a message box.

Private Sub Command1_Click()
    Dim x As Integer
    x = DisplayApplicationInfo(Me) Sub
DisplayApplicationInfo(obj As Object) As Integer
    Dim apl As Object, intI As Integer, strProps As String
    On Error Resume Next
    ' Form application property.
        Set apl = obj.Application
        MsgBox "Application visible Property = " & apl.Visible
        If apl.UserControl = True Then
        For intI = 0 To apl.DBEngine.Properties.Count - 1
    strProps = strProps & apl.DBEngine.Properties(intI).Name & ", "
        Next intI
        End If
    MsgBox Left(strProps, Len(strProps) - 2) & ".", vbOK, _
        "DBEngine Properties"Function


ApplyFilter Action

Description

You can use the ApplyFilter action to apply a filter, a query, or an SQL WHERE clause to a table, form, or report to restrict or sort the records in the table, or the records from the underlying table or query of the form or report. For reports, you can use this action only in a macro specified by the report’s OnOpen event property.

Setting

The ApplyFilter action uses the following arguments.

Action argument | Description
Filter Name | The name of a filter or query that restricts or sorts the records of the table, form, or report. You can enter the name of either an existing query or a filter that has been saved as a query.
Where Condition | A valid SQL WHERE clause (without the word WHERE) or an expression that restricts the records of the table, form or report.

Note In the Where Condition expression, the left side of the expression typically contains a field name from the underlying table or query for the form or report. The right side of the expression typically contains the criteria you want to apply to this field in order to restrict or sort the records. For example, the criteria can be the name of a control on another form that contains the value you want the records in the first form to match. The name of the control should be fully qualified: Forms!formname!controlname.

The maximum length of the Where Condition argument is 256 characters. If you need to enter a longer SQL WHERE clause, use the ApplyFilter method of the DoCmd object in Visual Basic. You can enter SQL WHERE clause statements of up to 32,768 characters in Visual Basic.

Note You must use one or both arguments. You can use the Filter Name argument if you’ve already defined a filter that provides the appropriate data. You can use the Where Condition argument to enter the restriction criteria directly. If you use both arguments, Microsoft Access applies the WHERE clause to the results of the filter.

Remarks

You can apply a filter or query to a form in Form view or Datasheet view.

For tables and forms, this action is similar to clicking Apply Filter/Sort on the Records menu or clicking the Apply Filter button on the toolbar. The menu command or button applies the most recently created filter to the table or form, whereas the ApplyFilter action applies a specified filter or query.

If you point to Filters on the Records menu and then click Advanced Filter/Sort after running the ApplyFilter action, the Advanced Filter/Sort window shows the filter criteria you have selected with this action.

To remove a filter and display all of the records for a table or form, you can use the ShowAllRecords action, the Remove Filter/Sort command on the Records menu, or the Remove Filter button on the toolbar.

When you save a table or form, Microsoft Access saves any filter currently defined in that object, but won’t apply the filter automatically the next time the object is opened (although it will automatically apply any sort you applied to the object before it was saved). If you want to apply a filter automatically when a form is first opened, specify a macro using the ApplyFilter action or an event procedure using the ApplyFilter method of the DoCmd object as the OnOpen event property setting of the form. You can also apply a filter using the OpenForm or OpenReport action, or their corresponding methods. To apply a filter automatically when a table is first opened, you can open the table using a macro containing the OpenTable action, followed immediately by an ApplyFilter action.

See Also

ApplyFilter Method, Filter Property, FilterOn Property, OpenForm Action, OpenQuery Action, ShowAllRecords Action, WHERE Clause (Microsoft Office 95 Data Access Reference).


ApplyFilter Event

Applies To

Form.

Description

The ApplyFilter event occurs when the user does one of the following:

  • Clicks the Apply Filter/Sort command on the Filter menu, or clicks the Apply Filter button on the toolbar. This applies the most recently created filter (created using either the Filter By Form feature or the Advanced Filter/Sort window).
  • Clicks the Filter By Selection subcommand of the Filter command on the Records menu, or clicks the Filter By Selection button on the toolbar. This applies a filter based on the current selection in the form.
  • Clicks the Remove Filter/Sort command on the Records menu, or clicks the Remove Filter button on the toolbar. This removes any filter (or sort) currently applied to the form.
  • Closes the Advanced Filter/Sort window or the Filter By Form window.

Remarks

You can use the ApplyFilter event to:

  • Make sure the filter that is being applied is correct. For example, you may want to be sure that any filter applied to an Orders form includes criteria restricting the OrderDate field. To do this, check the value of the Filter property for the form to make sure this criteria is included in the WHERE clause expression in this property.
  • Change the display of the form before the filter is applied. For example, when you apply a certain filter, you may want to disable or hide some fields that are not appropriate for the records displayed by this filter.
  • Undo or change actions you took when the Filter event occurred. For example, you can disable or hide some controls on the form when the user is creating the filter, because you do not want these controls to be included in the filter criteria. You can then enable or show these controls after the filter is applied.

The actions in the ApplyFilter macro or event procedure occur before the filter is applied or removed; or after the Advanced Filter/Sort or Filter By Form window is closed, but before the form is redisplayed. The criteria you’ve entered in the newly created filter are available to the ApplyFilter macro or event procedure (as the setting of the Filter property).

Note The ApplyFilter event does not occur when you apply or remove a filter using the ApplyFilter, OpenForm, or ShowAllRecords actions in a macro, or their corresponding methods of the DoCmd object in Visual Basic. It also does not occur if you use the Close action or the Close method of the DoCmd object to close the Advanced Filter/Sort window or the Filter By Form window. The ApplyFilter event also does not occur if you set the Filter property or FilterOn property in a macro or Visual Basic (although you can set these properties in an ApplyFilter macro or event procedure).

See Also

Filter Property, FilterLookup Property, FilterOn Property, OrderBy Property, OrderByOn Property.


ApplyFilter Event -- Event Procedures

Description

To create an event procedure that is executed when the ApplyFilter event occurs, set the OnApplyFilter property to [Event Procedure], and click the Build button.

Syntax

Private Sub Form_ApplyFilter(Cancel As Integer, ApplyType As Integer)

The ApplyFilter event procedure uses the following arguments.

Argument | Description
Cancel | The setting determining whether to apply the filter. Setting Cancel to True (-1) prevents the filter from being applied. You can also use the CancelEvent method of the DoCmd object to cancel applying the filter.
ApplyType | The action you took that caused the ApplyFilter event to occur. The ApplyType argument can be one of the following intrinsic constants:
Constant

acShowAllRecords
acApplyFilter
acCloseFilterWindow

 Value

0

Remarks

You can use the ApplyFilter event procedure to show or hide, enable or disable certain controls on the form when the filter is applied or removed. For example, when a filter is applied to an Orders form to show only orders that have been paid for, you can hide the AmountDue, Tax, and TotalDue fields when the ApplyType argument is acApplyFilter, and show them again when the ApplyType argument is acShowAllRecords.

You can also use the ApplyFilter event procedure to undo actions you took when the Filter event occurred. This is especially useful if the user closed the filter window without creating a filter (the ApplyType argument is acCloseFilterWindow).

See Also

ApplyFilter Event — Macros.

Example

The following example shows how to hide the AmountDue, Tax, and TotalDue controls on an Orders form when the applied filter restricts the records to only those orders that have been paid for.

Private Sub Form_ApplyFilter(Cancel As Integer, ApplyType As Integer)
    If Not IsNull(Me.Filter) And (InStr(Me.Filter, "Orders.Paid=-1")>0 _
            Or InStr(Me.Filter, "Orders.Paid=True")>0)Then
        If ApplyType = acApplyFilter Then
            Forms!Orders!AmountDue.Visible = False
            Forms!Orders!Tax.Visible = False
            Forms!Orders!TotalDue.Visible = False
        ElseIf ApplyType = acShowAllRecords Then
            Forms!Orders!AmountDue.Visible = True
            Forms!Orders!Tax.Visible = True
            Forms!Orders!TotalDue.Visible = True
        End If
    End IfSub


ApplyFilter Event -- Macros

Description

To run a macro when the ApplyFilter event occurs, set the OnApplyFilter property to the name of the macro.

Remarks

You can check a filter, or even change the criteria the user has entered, by reading the value of the Filter property in a macro condition, or setting the value of the property using the SetValue action in an ApplyFilter macro.

You can use the CancelEvent action in an ApplyFilter macro to cancel applying the filter. You can use a condition to check the value of one or more controls on the form, and apply a filter only when appropriate. For example, if a HasOutstandingOrders check box is selected in an Orders form, you could apply a filter to show these outstanding orders in the records on the form. Otherwise, you can cancel applying the filter, and display a message saying there are no outstanding orders to display.

See Also

ApplyFilter Event — Event Procedures.


ApplyFilter Method

Applies To

DoCmd Object.

Description

The ApplyFilter method carries out the ApplyFilter action in Visual Basic. For more information on how the action and its arguments work, see the action topic.

Syntax

DoCmd.ApplyFilter [filtername] [, wherecondition]

The ApplyFilter method uses the following arguments.

Argument | Description
filtername | A string expression that is the valid name of a query in the current database.
wherecondition | A string expression that is a valid SQL WHERE clause without the word WHERE.

Remarks

You must include at least one of the two ApplyFilter arguments. If you enter a value for both arguments, wherecondition is applied to the filter.

The maximum length of the wherecondition argument is 32,768 characters (unlike the Where Condition action argument in the Macro window, whose maximum length is 256 characters).

If you specify the wherecondition argument and leave the filtername argument blank, you must include the filtername argument’s comma.

See Also

ApplyFilter Action, DoCmd Object, Filter Property, FilterOn Property, OpenForm Method, OpenQuery Method, OpenReport Method, ShowAllRecords Method.

Example

This example uses the ApplyFilter method to display only records that contain the name King in the LastName field.

DoCmd.ApplyFilter , "[LastName] = 'King'"


AppTitle Property

Applies To

Database Object.

Description

You can use the AppTitle property to specify the text that appears in the application database’s title bar. For example, you can use the AppTitle property to specify that the string “Inventory Control” appear in the title bar of your Inventory Control database application.

Setting

The AppTitle property is a string expression containing the text to appear in the title bar.

You can set this property by using a macro or Visual Basic. You can also set this property using the Application Title option in the Startup dialog box, available by clicking Startup on the Tools menu. This is the easiest way to set this property.

To set the AppTitle property using Visual Basic you must first create the property using the CreateProperty method and append it to the Database properties collection. You must also use the RefreshTitleBar method to make any changes visible.

Remarks

If this property is not set, the string “Microsoft Access” appears in the title bar.

This property’s setting takes effect immediately after setting the property in code or closing the Startup dialog box.

See Also

AppIcon Property.

Example

See the AppTitle property example.


Array Function

Description

Returns a Variant containing an array.

Syntax

Array(arglist)

The arglist consists of a comma-delimited list of an arbitrary number of values that are assigned to the elements of the array contained within the Variant. If no arguments are specified, an array of zero-length is created.

Remarks

Although a Variant containing an array is conceptually different from an array whose elements are of type Variant, the way the array elements are accessed is the same. The notation used to refer to an element of an array consists of the variable name followed by parentheses containing an index number indicating the desired element. In the following example, the first statement creates a variable A as a Variant. The second statement assigns an array to variable A. The final statement illustrates how to assign the value contained in the second array element to another variable.

Dim A As Variant= Array(10,20,30)= A(2)

The lower bound of an array created using the Array function is determined by the lower bound specified with the Option Base statement.

Note A Variant not declared as an array can still contain an array. A Variant variable can contain an array of any type, except fixed-length strings and user-defined types.

See Also

Def type Statements, Dim Statement, Let Statement, Option Base Statement, Variant Data Type.

Example

This example uses the Array function to return a Variant containing an array.

MyWeek = Array("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun")
' Return values assume lower bound set to 1 (using Option Base
' statement).= MyWeek(2)    ' MyDay contains "Tue".= MyWeek(4)    ' MyDay contains "Thu".


Asc Function

Description

Returns the character code corresponding to the first letter in a string.

Syntax

Asc(string)

The string argument is any valid string expression. If the string contains no characters, a run-time error occurs.

Note Another function (AscB) is provided for use with byte data contained in a string. Instead of returning the character code for the first character, AscB returns the first byte.

See Also

Chr Function.

Example

This example uses the Asc function to return a character code corresponding to the first letter in the string.

MyNumber = Asc("A")        ' Returns 65.= Asc("a")        ' Returns 97.= Asc("Apple")    ' Returns 65.


Atn Function

Description

Returns the arctangent of a number.

Syntax

Atn(number)

The number argument can be any valid numeric expression.

Remarks

The Atn function takes the ratio of two sides of a right triangle (number) and returns the corresponding angle in radians. The ratio is the length of the side opposite the angle divided by the length of the side adjacent to the angle.

The range of the result is -pi/2 to pi/2 radians.

To convert degrees to radians, multiply degrees by pi/180. To convert radians to degrees, multiply radians by 180/pi.

Note Atn is the inverse trigonometric function of Tan, which takes an angle as its argument and returns the ratio of two sides of a right triangle. Do not confuse Atn with the cotangent, which is the simple inverse of a tangent (1/tangent).

See Also

Cos Function, Derived Math Functions, Sin Function, Tan Function.

Example

This example uses the Atn function to calculate the value of pi.

pi = 4 * Atn(1)        ' Calculate the value of pi.


AutoActivate Property

Applies To

Bound Object Frame Control, Chart Control, Unbound Object Frame Control.

Description

You can use the AutoActivate property to specify how the user can activate an OLE object.

Setting

The AutoActivate property uses the following settings.

Setting | Description | Visual Basic
Manual | The OLE object isn’t activated when it receives the focus or when the user double-clicks the control. You can activate an OLE object only using Visual Basic by setting the control’s Action property to acOLEActivate. | 0
GetFocus | (For unbound object frame and chart controls only) If the control contains an OLE object, the application that supplied the object is activated when the control receives the focus. | 1
Double-Click | (Default) If the control contains an OLE object, the application that supplied the object is activated when the user double-clicks the control or presses CTRL+ENTER when the control has the focus. | 2

You can set this property using the property sheet, a macro, or Visual Basic. You can also set this property in a control’s default control style.

The AutoActivate property can be set only in Design view.

Remarks

Some OLE objects can be activated from within the control. When such an object is activated, the object can be edited (or some other operation can be performed) from inside the boundaries of the control. This feature is called in-place activation. If an object supports in-place activation, see the documentation for the application that created the object for information about using this feature.

Using Visual Basic, you can determine if a control contains an object by checking the setting of its OLEType property.

Note If you set a control’s AutoActivate property to Double-Click and specify a DblClick event for the control, the DblClick event occurs before the object is activated.

See Also

Action Property, OLEType Property.


AutoCenter Property

Applies To

Form.

Description

You can use the AutoCenter property to specify whether a form will be centered automatically in the application window when the form is opened.

Setting

The AutoCenter property uses the following settings.

Setting | Description | Visual Basic
Yes | The form will be centered automatically on opening. | True (-1)
No | (Default) The form won’t be centered automatically on opening. | False (0)

You can set this property in the form’s property sheet, a macro, or Visual Basic.

You can set this property only in Design view.

Remarks

Depending on the size and placement of the application window, forms can appear off to one side of the application window, hiding part of the form. Centering the form automatically when it’s opened makes it easier to view and use.

See Also

Form Object.


AutoExpand Property

Applies To

Combo Box Control.

Description

You can use the AutoExpand property to specify whether Microsoft Access automatically fills the text box portion of a combo box with a value that matches the characters as you type in the combo box. This lets you quickly enter an existing value in a combo box without displaying the list box portion of the combo box.

Setting

The AutoExpand property has the following settings.

Setting | Description | Visual Basic
Yes | (Default) Microsoft Access fills in the combo box from the list with the first value matching the first character that you type. As you type additional characters, Microsoft Access changes the value displayed to match all the characters typed. | True (-1)
No | You must select a value from the list or type the entire value. | False (0)

You can set the AutoExpand property using the combo box’s property sheet, a macro, or Visual Basic.

Remarks

When you enter characters in the text box portion of a combo box, Microsoft Access searches the values in the list to find those that match the characters you have typed. If the AutoExpand property is set to Yes, Microsoft Access automatically displays the first underlying value that matches the characters entered so far.


AutoLabel Property

See AddColon, AutoLabel Properties.


AutoRepeat Property

Applies To

Command Button Control.

Description

You can use the AutoRepeat property to specify whether an event procedure or macro runs repeatedly while a command button on a form remains pressed.

Setting

The AutoRepeat property uses the following settings.

Setting | Description | Visual Basic
Yes | The macro or event procedure in the Click event runs repeatedly while the command button remains pressed. | True (-1)
No | (Default) The macro or event procedure runs once. | False (0)

You can set this property using the property sheet, a macro, or Visual Basic.

Remarks

The initial repeat of the event procedure or macro occurs 0.5 second after it first runs. Subsequent repeats occur either 0.25 second apart or the duration of the event procedure or macro, whichever is longer.


AutoResize Property

Applies To

Form.

Description

You can use the AutoResize property to specify whether a Form window opens automatically sized to display complete records.

Setting

The AutoResize property uses the following settings.

Setting | Description | Visual Basic
Yes | (Default) The Form window is automatically sized to display a complete record. | True (-1)
No | When opened, the Form window has the last saved size. To save a form window’s size, open the form, size the window, save the form by clicking Save on the File menu, and close the form. When you next open the form, it will be the saved window size. | False (0)

You can set this property in the form’s property sheet, a macro, or Visual Basic.

This property can be set only in Design view.

Remarks

The Form window resizes only if opened in Form view. If you open the form first in Design view or Datasheet view and then change to Form view, the Form window won’t resize.

If a form’s AutoResize property is set to No and its AutoCenter property is set to Yes, and if you make any changes in Design view and don’t switch to Form view before saving the form, Microsoft Access clips the form on the right and bottom edges the next time you open the form.

If the AutoCenter property is set to No, a Form window opens with its upper-left corner in the same location as when it was closed.

See Also

AutoCenter Property, MoveSize Action.


AutoTab Property

Applies To

Text Box Control.

Description

You can use the AutoTab property to specify whether an automatic tab occurs when the last character permitted by a text box control’s input mask is entered. An automatic tab moves the focus to the next control in the form’s tab order.

Setting

The AutoTab property uses the following settings.

Setting | Description | Visual Basic
Yes | Generates a tab when the last allowable character in a text box is entered. | True (-1)
No | (Default) Doesn’t generate a tab when the last allowable character in a text box is entered. | False (0)

You can set this property using the control’s property sheet, a macro, or Visual Basic.

You can also set this property using the control’s default control style.

The AutoTab property affects tab behavior in both Form view and Datasheet view.

Remarks

You create an input mask for a control using the InputMask property.

You can also create an input mask for a text box control bound to a field by setting the InputMask property for the field in the form’s underlying table or query. If the field is dragged to a form from the field list, the field’s input mask is inherited by the text box control.

You could use the AutoTab property if you have a text box on a form for which you usually enter the maximum number of characters for each record. Once the maximum number of characters are entered, focus automatically moves to the next control in the tab order. For example, you could use this property for a CategoryType field that must always be five characters long.

See Also

Cycle Property, InputMask Property, TabIndex Property, TabStop Property.


BackColor Property

Applies To

Bound Object Frame Control, Chart Control, Combo Box Control, Image Control, Label Control, List Box Control, Option Group Control, Rectangle Control, Text Box Control, Unbound Object Frame Control.

Description

You can use the BackColor property to specify the color for the interior of a control or section.

Setting

The BackColor property contains a numeric expression that corresponds to the color used to fill a control or section’s interior.

You can set the BackColor property using the Formatting toolbar, a control’s property sheet, a macro, or Visual Basic.

You can also use the Color Builder to set this property by clicking the Build button to the right of the property in the property sheet. Using the Color Builder enables you to define custom back colors for controls.

In Visual Basic, use a numeric expression to set this property. This property setting has a data type of Long.

For controls, you can set the default for this property using a control’s default control style.

Remarks

To use the BackColor property, the BackStyle property, if available, must be set to Normal.

See Also

BackStyle Property, BorderColor Property, DrawMode Property, DrawStyle Property, DrawWidth Property, FillColor Property, ForeColor Property, PSet Method, QBColor Function, RGB Function.

Example

The following example uses the RGB function to set the BorderColor, BackColor, and ForeColor properties depending on the value of the txtPastDue text box. You can also use the QBColor function to set these properties. Putting the following code in the Form_Current( ) event sets the control display characteristics as soon as the user opens a form or moves to a new record.

Sub Form_Current()
    Dim curAmntDue As Currency, lngBlack As Long
    Dim lngRed As Long, lngYellow As Long, lngWhite As Long
    If Not IsNull(Me!txtPastDue.Value) Then
        curAmntDue =Me!txtPastDue.Value
    Else
        Exit Sub
    End If
    lngRed = RGB(255, 0, 0)
    lngBlack = RGB(0, 0, 0)
    lngYellow = RGB(255, 255, 0)
    lngWhite = RGB(255, 255, 255)
    If curAmntDue > 100 Then
        Me!txtPastDue.BorderColor = lngRed
        Me!txtPastDue.ForeColor = lngRed
        Me!txtPastDue.BackColor = lngYellow
    Else
        Me!txtPastDue.BorderColor = lngBlack
        Me!txtPastDue.ForeColor = lngBlack
        Me!txtPastDue.BackColor = lngWhite
    End IfSub


BackStyle Property

Applies To

Bound Object Frame Control, Chart Control, Combo Box Control, Image Control, Label Control, Option Group Control, Rectangle Control, Text Box Control, Unbound Object Frame Control.

Description

You can use the BackStyle property to specify whether the control will be transparent.

Setting

The BackStyle property uses the following settings.

Setting | Description | Visual Basic
Normal | (Default for all controls except option group) The control has its interior color set by the BackColor property. | 1
Transparent | (Default for option group) The control is transparent. The color of the form or report behind the control is visible. | 0

You can set this property using the Formatting toolbar, a control’s property sheet, a macro, or Visual Basic.

You can set the default for this property using a control’s default control style.

Remarks

If the Transparent button on the BackColor toolbar palette is selected, the BackStyle property is set to Transparent; otherwise the BackStyle property is set to Normal.

Tip To make a command button invisible, set its Transparent property to Yes.

See Also

BackColor Property, SpecialEffect Property.


Beep Action

Description

You can use the Beep action to sound a beep tone through the computer’s speaker.

Setting

The Beep action doesn’t use any arguments.

Remarks

You can use the Beep action to signal the following occurrences:

  • Important screen changes have occurred.
  • The wrong kind of data has been entered in a control. For example, the user has entered numeric data in a Text control.
  • A macro has reached a specified point or has completed its actions.

The frequency and duration of the beep depend on hardware, which may vary between computers.

To run the Beep action in Visual Basic, use the Beep method of the DoCmd object.

See Also

Beep Method; MsgBox Action; ValidationRule, ValidationText Properties.


Beep Method

Applies To

DoCmd Object.

Description

The Beep method carries out the Beep action in Visual Basic. For more information on how the action works, see the action topic.

Syntax

DoCmd.Beep

This method uses no arguments.

Remarks

You can also use the Visual Basic Beep statement to cause your computer to sound a tone through its speaker.

See Also

Beep Action, DoCmd Object, MsgBox Action.


Beep Statement

Description

Sounds a tone through the computer’s speaker.

Syntax

Beep

Remarks

The frequency and duration of the beep depend on your hardware and system software and vary among computers.

Example

This example uses the Beep statement to sound three consecutive tones through the computer’s speaker.

For I = 1 To 3        ' Loop 3 times.
    Beep                ' Sound a tone.I


BeforeDelConfirm Event

See Delete, BeforeDelConfirm, AfterDelConfirm Events.


BeforeInsert, AfterInsert Events

Applies To

Form.

Description

These events occur:

  • BeforeInsert — when the user types the first character in a new record, but before the record is actually created.
  • AfterInsert — after a new record is added.

Note Setting the value of a control using a macro or Visual Basic doesn’t trigger these events.

Remarks

You can use an AfterInsert event procedure or macro to requery a recordset whenever a new record is added.

The BeforeInsert and AfterInsert events are similar to the BeforeUpdate and AfterUpdate events. These events occur in the following order:

BeforeInsert [image] BeforeUpdate [image] AfterUpdate [image] AfterInsert

The following table summarizes the interaction between these events.

Event | Occurs when
BeforeInsert | User types the first character in a new record.
BeforeUpdate | User updates the record.
AfterUpdate | Record is updated.
AfterInsert | Record updated is a new record.

If the first character in a new record is typed into a text box or combo box, the BeforeInsert event occurs before the Change event.

See Also

BeforeUpdate, AfterUpdate Events; Change Event; Current Event; Delete, BeforeDelConfirm, AfterDelConfirm Events; GoToRecord Action; Open, Close Events.


BeforeInsert, AfterInsert Events -- Event Procedures

Description

To create an event procedure that is executed when the BeforeInsert or AfterInsert event occurs, set the BeforeInsert or AfterInsert property to [Event Procedure], and click the Build button.

Syntax

Private Sub Form_BeforeInsert (Cancel As Integer)Private Sub Form_AfterInsert ( )

The BeforeInsert event procedure uses the following argument.

Argument | Description
Cancel | The setting determines if the BeforeInsert event occurs. Setting Cancel to True (-1) cancels the BeforeInsert event.

Remarks

You can’t cancel the AfterInsert event.

See Also

BeforeInsert, AfterInsert Events — Macros.

Example

This example shows how you can use a BeforeInsert event procedure to verify that the user wants to create a new record, and an AfterInsert event procedure to requery the record source for the Employees form after a record has been added.

To try this example, add the following code to the Declarations section of a form named Employees that is based on a table or query. Switch to the form’s Datasheet view and try to insert a record.

Private Sub Form_BeforeInsert (Cancel As Integer)
    If MsgBox("Insert new record here?", vbOKCancel) = vbCancel Then
        Cancel = True
    End IfSub
Sub Form_AfterInsert ()
    Forms!Employees.Requery    Sub


BeforeInsert, AfterInsert Events -- Macros

Description

To run a macro when the BeforeInsert or AfterInsert event occurs, set the BeforeInsert or AfterInsert property to the name of the macro.

Remarks

You can use these macros to display messages or useful information. For example, you can have the BeforeInsert macro display data the user needs when entering a new record.

You can use the CancelEvent action in a BeforeInsert macro to cancel the creation of the new record. When you use the CancelEvent action in a BeforeInsert macro, the focus returns to the new record, which is blank (the character that the user typed is deleted).

You can’t use the CancelEvent action in an AfterInsert macro.

See Also

BeforeInsert, After Insert Events — Event Procedures.


BeforeUpdate, AfterUpdate Events

Applies To

Bound Object Frame Control, Check Box Control, Combo Box Control, List Box Control, Option Button Control, Option Group Control, Text Box Control, Toggle Button Control.

Description

These events occur:

  • BeforeUpdate — before changed data in a control or record is updated.
  • AfterUpdate — after changed data in a control or record is updated.

Notes

  • Changing data in a control using a macro or Visual Basic doesn’t trigger these events for the control. However, if you then move to another record or save the record, the form’s BeforeUpdate and AfterUpdate events do occur.
  • The BeforeUpdate and AfterUpdate events apply only to controls on a form, not controls on a report.
  • These events don’t apply to option buttons, check boxes, or toggle buttons in an option group. They apply only to the option group itself.

Remarks

The BeforeUpdate and AfterUpdate events are triggered when a control or record is updated. Within a record, changed data in each control is updated when the control loses the focus or when the user presses ENTER or TAB. When the focus leaves the record or if the user chooses the Save Record command from the File menu, the entire record is updated, and the data is saved in the database.

When you enter new or changed data in a control on a form and then move to another record or save the record by choosing Save Record from the File menu, the BeforeUpdate and AfterUpdate events for the form occur immediately after the BeforeUpdate and AfterUpdate events for the control. If you moved to a different record, the Exit and LostFocus events for the control then occur, followed by the Current event for the record you moved to, and the Enter and GotFocus events for the first control in this record. To run the BeforeUpdate and AfterUpdate macros or event procedures without running the Exit and LostFocus macros or event procedures, save the record using the Save Record command on the File menu.

BeforeUpdate and AfterUpdate macros and event procedures run only if you change the data in a control. These events don’t occur when a value changes in a calculated control. BeforeUpdate and AfterUpdate macros and event procedures for a form run only if you change the data in a record (the data in one or more controls in the record).

For forms, you can use the BeforeUpdate event to cancel updating of a record before moving to another record.

For bound controls, the OldValue property isn’t set to the updated value until after the AfterUpdate event occurs. Even if the user enters a new value in the control, the OldValue property setting isn’t changed until the data is saved. If you cancel an update, the value of the OldValue property replaces the existing value in the control.

You often use the BeforeUpdate event to validate data, especially when you perform complex validations, such as those that:

  • Involve conditions for more than one value on a form.
  • Display different error messages for different data entered.
  • Can be overridden by the user.
  • Contain references to controls on other forms or contain user-defined functions.

Note To perform simple validations or more complex validations, such as requiring a value in a field or validating more than one control on a form, you can use the ValidationRule property for controls and the ValidationRule and Required properties for fields and records in tables.

See Also

Enter, Exit Events.


BeforeUpdate, AfterUpdate Events -- Event Procedures

Description

To create an event procedure that is run when the BeforeUpdate or AfterUpdate event occurs, set the BeforeUpdate or AfterUpdate property to [Event Procedure], and click the Build button.

Syntax

Private Sub Form_BeforeUpdate (Cancel As Integer)Private Sub controlname_BeforeUpdate (Cancel As Integer)Private Sub Form_AfterUpdate ( )Private Sub controlname_AfterUpdate ( )

The BeforeUpdate event procedure uses the following argument.

Argument | Description
controlname | A string that is the name of the control affected by the BeforeUpdate event procedure.
Cancel | The setting determines if the BeforeUpdate event occurs. Setting Cancel to True (-1) cancels the BeforeUpdate event

The AfterUpdate event procedure uses the following argument.

Argument | Description
controlname | A string that is the name of the control affected by the AfterUpdate event procedure.

Remarks

You can’t cancel the AfterUpdate event.

You can use an AfterUpdate event procedure to display a different page in the form or move the focus to a particular control or record. For example, when the user enters a value in a Category control on a form, you can use the GoToPage method in the AfterUpdate event procedure for the form to move the focus to the page of the form that contains the controls for that category.

See Also

BeforeUpdate, AfterUpdate Events — Macros.

Example

This example shows how you can use a BeforeUpdate event procedure to check whether a product name has already been entered. After the user types a product name in the ProductName box, the value is compared to the ProductName field in the Products table. If there is a matching value in the Products table, a message is displayed that informs the user that the product has already been entered in the database.

To try the following example, add the following code to the Declarations section of a form named Products that contains a text box called ProductName.

Private Sub ProductName_BeforeUpdate(Cancel As Integer)
    If (Not IsNull(DLookup("[ProductName]", "Products", _
        "[ProductName] ='" & Forms!Products!ProductName & "'"))) Then
        MsgBox "Product has already been entered in the database."
        Cancel = True
        Me!ProductName.Undo
    End IfSub


BeforeUpdate, AfterUpdate Events -- Macros

Description

To run a macro when the BeforeUpdate or AfterUpdate event occurs, set the BeforeUpdate or AfterUpdate property to the name of the macro. Microsoft Access runs the macro specified by the BeforeUpdate or AfterUpdate property for a control or form before or after the data in the control or in the current record on the form is updated. If the data in the control or record isn’t updated, the macro doesn’t run.

Remarks

You can use BeforeUpdate macros if you want to store all the validations for a form in one macro group or if you use a validation expression on several forms.

For example, suppose you have a form on which the user enters the name of a country in a Country control and its corresponding postal code in a Postal Code control. You use conditional expressions in the macro to make sure that the data entered in the Country control corresponds to the data entered in the Postal Code control and to display a message if invalid data is entered in the Postal Code control.

You can use an AfterUpdate macro to display a different page in the form or move the focus to a particular control or record. For example, when the user enters a value in a Category control on a form, you can use the GoToPage action in an AfterUpdate macro to move the focus to the page of the form that contains the controls for that category.

You can use the CancelEvent action in a BeforeUpdate macro to cancel the update. If the BeforeUpdate macro is attached to a control, the CancelEvent action returns the focus to the control, and the data the user entered remains in the control.

If a BeforeUpdate macro is attached to a form (in which it runs each time a record is changed), the CancelEvent action returns the focus to the record.

You can’t use the CancelEvent action in an AfterUpdate macro.

See Also

BeforeUpdate, AfterUpdate Events — Event Procedures.


Bookmark Property

Applies To

Form.

Description

You can use the Bookmark property with forms to set a bookmark that uniquely identifies a particular record in the form’s underlying table, query, or SQL statement.

Setting

The Bookmark property contains a string expression created by Microsoft Access.

You can access this property using Visual Basic or a macro.

Note You get or set the form’s Bookmark property separately from the underlying table or query data access Bookmark property.

Remarks

When a bound form is opened in Form view, each record is assigned a unique bookmark. In Visual Basic, you can save the bookmark for the current record by assigning the value of the form’s Bookmark property to a string variable. To return to a saved record after moving to a different record, set the form’s Bookmark property to the value of the saved string variable.

Note Bookmarks are not saved with the records they represent. They are re-created by Microsoft Access each time a bound form is opened.

There is no limit to the number of bookmarks you can save if each is saved with a unique string variable.

The Bookmark property is only available for the form’s current record. To save a bookmark for a record other than the current record, move to the desired record and assign the value of the Bookmark property with a string variable that identifies this record.

You can use bookmarks in any form that is based entirely on Microsoft Access tables. However, other database products may not support bookmarks. For example, you can’t use bookmarks in a form based on a linked table that has no primary index.

Requerying a form invalidates any bookmarks set on records in the form. However, clicking Refresh on the Records menu doesn’t affect bookmarks.

Since Microsoft Access creates a unique bookmark for each record in a form’s recordset when a form is opened, a form’s bookmark will not work on another recordset, even when the two recordsets are based on the same table, query or SQL statement. For example, suppose you open a form bound to the Customers table. If you then open the Customers table using Visual Basic and use the Seek method to locate a specific record in the table, you can’t set the form’s Bookmark property to the current table record. To perform this kind of operation you use the form’s RecordsetClone property.

A trappable error occurs if you save the Bookmark property with a string variable and then try to return to that record after the record has been deleted.

The value of the Bookmark property isn’t the same as a record number.

See Also

Bookmark Property (Microsoft Office 95 Data Access Reference), RecordsetClone Property.

Example

The following example determines the Bookmark property for the current record in the Customers form.

Dim strLocation As String= Forms![Customers].Bookmark


Boolean Data Type

Description

Boolean variables are stored as 16-bit (2-byte) numbers, but they can only be True or False. Boolean variables display as either True or False (when Print is used) or #TRUE# or #FALSE# (when Write # is used). Use the keywords True and False to assign one of the two states to Boolean variables.

When other numeric data types are converted to Boolean values, 0 becomes False while all other values become True. When Boolean values are converted to other data types, False becomes 0 while True becomes -1.

See Also

CBool Function, Data Type Summary, Def type Statements, Integer Data Type.


BorderColor Property

Applies To

Bound Object Frame Control, Chart Control, Combo Box Control, Image Control, Label Control, Line Control, Option Group Control, Rectangle Control, Text Box Control, Unbound Object Frame Control.

Description

You can use the BorderColor property to specify the color of a control’s border.

Setting

The BorderColor property setting is a numeric expression that corresponds to the color you want to use for a control’s border.

You can use the Color Builder to set this property by clicking the Build button to the right of the property in the property sheet. Using the Color Builder enables you to define custom border colors for controls.

You can also set this property using the Formatting toolbar, a macro, or Visual Basic.

You can set the default for this property using a control’s default control style.

Remarks

A control’s border color is visible only when its SpecialEffect property is set to Flat or Shadowed. If the SpecialEffect property is set to something other than Flat or Shadowed, setting the BorderColor property changes the SpecialEffect property setting to Flat.

See Also

BorderStyle Property, BorderWidth Property, ForeColor Property, QBColor Function, RGB Function, SpecialEffect Property.

Example

See the BackColor property example.


BorderLineStyle Property

Applies To

Bound Object Frame Control, Chart Control, Combo Box Control, Label Control, Line Control, Option Group Control, Rectangle Control, Text Box Control, Unbound Object Frame Control.

Description

You use the BorderLineStyle property to specify the line style of a control’s border.

Note The BorderLineStyle property is included in this version of Microsoft Access only for compatibility with previous versions. Use the BorderStyle property to specify how a control’s border will appear.

Setting

The BorderLineStyle property uses the following settings.

Setting | Description | Visual Basic
Solid | (Default) Solid line | 0
Dashes | Dashed line | 1
Short Dashes | Dashed line with short dashes | 2
Dots | Dotted line | 3
Sparse Dots | Dotted line with dots spaced far apart | 4
Dash Dot | Line with a dash-dot combination | 5
Dash Dot Dot | Line with a dash-dot-dot combination | 6

You can set this property using the control’s property sheet, a macro, or Visual Basic.

Remarks

You can use this property to customize the look of your controls.

Note The BorderLineStyle property isn’t the same as the BorderStyle property, which determines whether a control’s border is transparent or visible.

See Also

BorderColor Property, BorderStyle Property, BorderWidth Property.

Example

You can use the following code to create a dotted border for a text box.

conDots = 3![frmCustomers]![txtLastName].BorderLineStyle = conDots


BorderStyle Property

Applies To

Bound Object Frame Control, Chart Control, Check Box Control, Combo Box Control, Form, Image Control, Label Control, Line Control, List Box Control, Option Button Control, Option Group Control, Rectangle Control, Text Box Control, Unbound Object Frame Control.

Description

  • Forms — You can use the BorderStyle property to specify the type of border and border elements (title bar, Control menu, Minimize and Maximize buttons) to use for the form. You typically use different border styles for normal forms, pop-up forms, and custom dialog boxes.
  • Controls — You can use the BorderStyle property to specify how a control’s border appears.

Setting

For forms, the BorderStyle property uses the following settings.

Setting | Description | Visual Basic
None | The form has no border or related border elements. | 0
Thin | The form has a thin border and can include any of the border elements. The form isn’t resizable (the Size command on the Control menu isn’t available). You often use this setting for pop-up forms. (If you want a form to remain on top of all Microsoft Access windows, you must also set its PopUp property to Yes.) | 1

Setting | Description | Visual Basic
Sizable | (Default) The form has the default border for Microsoft Access forms, can include any of the border elements, and can be resized. You often use this setting for normal Microsoft Access forms. | 2
Dialog | The form has a thick border and can include only a title bar and a Control menu. The form can’t be maximized, minimized, or resized (the Maximize, Minimize, and Size commands aren’t available on the Control menu). You often use this setting for custom dialog boxes. (If you want a form to be modal, however, you must also set its Modal property to Yes. If you want it to be a modal pop-up form, which dialog boxes typically are, you must set both its PopUp and Modal properties to Yes.) | 3

You can set the BorderStyle property only in form Design view using the form’s property sheet, a macro, or Visual Basic.

For controls, the BorderStyle property uses the following settings.

Setting | Description | Visual Basic
Transparent | (Default only for label, graph, and subreport) Transparent | 0
Solid | (Default) Solid line | 1
Dashes | Dashed line | 2
Short Dashes | Dashed line with short dashes | 3
Dots | Dotted line | 4
Sparse Dots | Dotted line with dots spaced far apart | 5
Dash Dot | Line with a dash-dot combination | 6
Dash Dot Dot | Line with a dash-dot-dot combination | 7

You can set the BorderStyle property using the control’s property sheet, the Formatting toolbar, a macro, or Visual Basic.

You can also set this property using the controls default control style.

A control’s border style is visible only when its SpecialEffect property is set to Flat or Shadowed. If the SpecialEffect property is set to something other than Flat or Shadowed, setting the BorderStyle property changes the SpecialEffect property setting to Flat.

Remarks

For a form, the BorderStyle property establishes the characteristics that visually identify the form as a normal form, a pop-up form, or a custom dialog box. You may also set the Modal and PopUp properties to further define the form’s characteristics.

You may also want to set the form’s ControlBox, MinMaxButtons, ScrollBars, NavigationButtons, and RecordSelectors properties. These properties interact in the following ways:

  • If the BorderStyle property is set to None or Dialog, the form doesn’t have Maximize or Minimize buttons, regardless of its MinMaxButtons property setting.
  • If the BorderStyle property is set to None, the form doesn’t have a Control menu, regardless of its ControlBox property setting.
  • If the PopUp property is set to No, the BorderStyle property normally wouldn’t be set to Dialog. If you set the PopUp property to No and the BorderStyle property to Dialog, the form doesn’t have Maximize and Minimize buttons and can’t be resized, but it does have a thin border. If the PopUp property is set to Yes, the BorderStyle property can be any of the four settings.
  • · The BorderStyle property setting doesn’t affect the display of the scroll bars, navigation buttons, the record number box, or record selectors.

If you open the form in Form view and then switch to another view, the BorderStyle property setting will be in effect in the other view.

If you set the BorderStyle property of a pop-up form to None, you won’t be able to close the form unless you put a Close button on it that runs a macro containing the Close action or an event procedure that uses the Close method.

Pop-up forms are typically fixed in size, but you can make a pop-up form sizable by setting its PopUp property to Yes and its BorderStyle property to Sizable.

You can also use the Dialog setting of the Window Mode argument of the OpenForm action to open a form with its Modal and PopUp properties set to Yes.

See Also

BackStyle Property, BorderColor Property, BorderWidth Property, ControlBox Property, ForeColor Property, MinMaxButtons Property, Modal Property, PopUp Property, SpecialEffect Property.


BorderWidth Property

Applies To

Bound Object Frame Control, Chart Control, Check Box Control, Combo Box Control, Image Control, Label Control, Line Control, Option Button Control, Option Group Control, Rectangle Control, Subform/Subreport Control, Text Box Control, Unbound Object Frame Control.

Description

You can use the BorderWidth property to specify the width of a control’s border.

Setting

The BorderWidth property uses the following settings.

Setting | Description | Visual Basic
Hairline | (Default) The narrowest border possible on your system | 0
1 pt to 6 pt | The width as indicated in points | 1 to 6

You can set this property using the Formatting toolbar, a macro, or Visual Basic.

You can set the default for this property using the control’s default control style.

Remarks

To use the BorderWidth property, the SpecialEffect property must be set to Flat or Shadowed and the BorderStyle property must not be set to Transparent.

The exact border width depends on your computer and printer. On some systems, the Hairline and 1-point widths appear the same.

See Also

BackStyle Property, BorderColor Property, BorderStyle Property, SpecialEffect Property.


BoundColumn Property

Applies To

Combo Box Control, List Box Control, Table Fields.

Description

When you make a selection from a list box or combo box, the BoundColumn property tells Microsoft Access which column’s values to use as the value of the control. If the control is bound to a field, the value in the column specified by the BoundColumn property is stored in the field named in the ControlSource property.

Setting

The BoundColumn property has the following settings.

Setting | Description
0 | The ListIndex property value, rather than the column value, is stored in the current record. The ListIndex property value of the first row is 0, the second row is 1, and so on. Microsoft Access sets the ListIndex property when an item is selected from a list box or the list box portion of a combo box. Setting the BoundColumn property to 0 and using the ListIndex property value of the control might be useful if, for example, you are only interested in storing a sequence of numbers.
1 or greater | (Default) If the setting is 1 or greater, then the corresponding column value becomes the control’s value. If the control is bound to a field, then this value is stored in the current record.

You can set the BoundColumn property in the object’s property sheet, a macro, or Visual Basic.

For table fields, you can set this property in table Design view for fields with the DisplayControl property set to Combo Box or List Box.

Note Microsoft Access sets this property automatically when you select Lookup Wizard as the data type for a field in table Design view.

In Visual Basic, set the BoundColumn property using a number or a numeric expression equal to a value from 0 to the number set by the ColumnCount property.

Remarks

The leftmost visible column in a combo box contains the data that appears in the text box part of the combo box in Form view or in a report. The BoundColumn property determines which column in the control will be stored when you make a selection. This allows you to display different data than you store as the value of the control.

Note If the bound column is not the same as the leftmost visible column in the control, the LimitToList property is set to Yes.

Microsoft Access uses zero-based numbers to refer to columns in the Column property. This means that if the BoundColumn property is set to 1, you could access the value stored in that column using the expression Column(0).

If the AutoExpand property is set to Yes, Microsoft Access automatically fills in a value that matches the data in the text box.

See Also

AutoExpand Property, Column Property, ColumnHeads Property, ColumnWidths Property, ControlSource Property, ListRows Property, ListWidth Property, MultiSelect Property, Selected Property, Value Property.


BuildCriteria Method

Applies To

Application Object.

Description

The BuildCriteria method returns a parsed criteria string as it would appear in the query design grid or in Filter By Form mode. For example, you may want to set a form’s Filter property based on varying criteria from the user. You can use the BuildCriteria method to construct the criteria string argument for the Filter property.

Syntax

BuildCriteria(field, fieldtype, expression)

The BuildCriteria method uses the following arguments.

Argument | Description
field | A string expression identifying the field for which you wish to define criteria.
fieldtype | An intrinsic constant denoting the data type of the field. For a list of possible field data types, see the data access Type property.
expression | A string expression identifying the criteria to be parsed.

The BuildCriteria method returns a string.

Remarks

The BuildCriteria method enables you to easily construct criteria for a filter based on user input. It parses the expression argument in the same way that the expression would be parsed had it been entered in the query design grid or in Filter By Form mode.

For example, a user creating a query on an Orders table might restrict the result set to orders placed after January 1, 1995, by setting criteria on an OrderDate field. The user might enter an expression such as the following one in the criteria cell beneath the OrderDate field.

>1-1-95

Microsoft Access automatically parses this expression and returns the following expression.

>#1/1/95#

The BuildCriteria method provides the same parsing from Visual Basic code. For example, to return the correctly parsed string shown above, you can supply the following arguments to the BuildCriteria method.

Dim strCriteria As String= BuildCriteria("OrderDate", dbDate, ">1-1-95")

Since you need to supply criteria for the Filter property in correctly parsed form, you can use the BuildCriteria method to construct a correctly parsed string.

You can use the BuildCriteria method to construct a string with multiple criteria if those criteria refer to the same field. For example, you can use the BuildCriteria method with the following arguments to construct a string with multiple criteria relating to the OrderDate field.

strCriteria = BuildCriteria("OrderDate", dbDate, ">1-1-95 and <5-1-95")

This example returns the following criteria string.

OrderDate>#1/1/95# And OrderDate<#5/1/95#

However, if you wish to construct a criteria string referring to multiple fields, you must create the strings and concatenate them yourself. For example, if you wish to construct criteria for a filter to show records for orders placed after 1-1-95 and for which freight is less than $50, you would need to use the BuildCriteria method twice and concatenate the resulting strings.

Example

The following example prompts the user to enter the first few letters of a product’s name, then uses the BuildCriteria method to construct a criteria string based on the user’s input. Next, the procedure provides this string as an argument to the Filter property of a Products form. Finally, the FilterOn property is set to apply the filter.

Sub SetFilter()
    Dim frm As Form, strMsg As String
    Dim strInput As String, strFilter As String

    ' Open Products form in Form view.
    DoCmd.OpenForm "Products"
    ' Return Form variable pointing to Products form.
    Set frm = Forms!Products
    strMsg = "Enter one or more letters of product name " _
        & "followed by an asterisk."
    ' Prompt user for input.
    strInput = InputBox(strMsg)
    ' Build criteria string.
    strFilter = BuildCriteria("ProductName", dbText, strInput)
    ' Set Filter property to apply filter.
    frm.Filter = strFilter
    ' Set FilterOn property; form now shows filtered records.
    frm.FilterOn = TrueSub


Byte Data Type

Description

Byte variables are stored as single, unsigned, 8-bit (1-byte) ranging in value from 0 to 255.

The Byte data type is useful for containing binary data that can be passed to and from dynamic link libraries (DLL) and OLE Automation objects.

See Also

CByte Function, Data Type Summary, Def type Statements, Integer Data Type.


Call Statement

Description

Transfers control to a Sub procedure, Function procedure, dynamic-link library (DLL) procedure, or a Macintosh® code resource procedure.

Syntax

[Call] name [argumentlist]

The Call statement syntax has these parts:

Part | Description
Call | Optional keyword; if specified, you must enclose argumentlist in parentheses. For example:
Call MyProc(0)
name | Name of the procedure to call.
argumentlist | Comma-delimited list of variables, arrays, or expressions to pass to the procedure. Components of argumentlist may include the keywords ByVal or ByRef to describe how the arguments are to be treated by the called procedure. However, ByVal and ByRef can be used with Call only when making a call to a DLL procedure or a Macintosh code resource.

Remarks

You are not required to use the Call keyword when calling a procedure. However, if you use the Call keyword to call a procedure that requires arguments, argumentlist must be enclosed in parentheses. If you omit the Call keyword, you also must omit the parentheses around argumentlist. If you use either Call syntax to call any intrinsic or user-defined function, the function’s return value is discarded.

To pass a whole array to a procedure, use the array name followed by empty parentheses.

See Also

Declare Statement.

Example

This example illustrates how the Call statement is used to transfer control to a Sub procedure, an intrinsic function, a dynamic-link library (DLL) procedure, and a procedure in a Macintosh code resource.

' Call a Sub procedure.PrintToDebugWindow("Hello World")
' The above statement causes control to be passed to the following
' Sub procedure.PrintToDebugWindow(AnyString)
    Debug.Print AnyString            ' Print to Debug window.Sub
' Call an intrinsic function. The return value of the function is
' discarded.Shell(AppName, 1)                ' AppName contains the path of the
                                    ' executable file.
' Call a Microsoft Windows DLL procedure. The Declare statement must be
' Private in a Class Module, but not in a standard Module.Declare Sub MessageBeep Lib "User" (ByVal N As Integer)CallMyDll()
    Call MessageBeep(0)                ' Call Windows DLL procedure.
    MessageBeep 0                    ' Call again without Call keyword.Sub
' Call a Macintosh code resource.Sub MessageAlert Lib "MyHd:MyAlert" Alias "MyAlert" (ByVal N _
    As Integer)CallMyCodeResource()
    Call MessageAlert(0)                ' Call Macintosh code resource.
    MessageAlert 0                    ' Call again without Call keyword.Sub


Cancel Property

Applies To

Command Button Control.

Description

You can use the Cancel property to specify whether a command button is also the Cancel button on a form.

Setting

The Cancel property has the following settings.

Setting | Description | Visual Basic
Yes | The command button is the Cancel button. | True (-1)
No | (Default) The command button isn’t the Cancel button. | False (0)

You can set this property using the command button’s property sheet, a macro, or Visual Basic.

Remarks

When a command button’s Cancel property setting is Yes and the form is in the active window, the user can choose the command button by pressing ESC, or pressing ENTER when the command button has the focus, or by clicking the command button.

Note If a text box has the focus when the user presses ESC, any changes made to the data in the text box will be lost, and the original data is restored.

When the Cancel property is set to Yes for one command button, it is automatically set to No for all other command buttons.

Tip For a form that supports irreversible operations, such as deletions, it’s a good idea to make the Cancel button the default command button. To do this, set both the Cancel property and the Default property to Yes.

See Also

Default Property.


CancelEvent Action

Description

You can use the CancelEvent action to cancel the event that caused Microsoft Access to run the macro containing this action. The macro name is the setting of an event property such as BeforeUpdate, OnOpen, OnUnload, or OnPrint.

Setting

The CancelEvent action doesn’t use any arguments.

Remarks

In a form, you typically use the CancelEvent action in a validation macro with the BeforeUpdate event property. When a user enters data in a control or record, Microsoft Access runs the macro before adding the data to the database. If the data fails the validation conditions in the macro, the CancelEvent action cancels the update process before it starts.

Often, you can use this action with the MsgBox action to indicate that the data has failed the validation conditions and to provide helpful information about the kind of data that should be entered.

The following events can be canceled by the CancelEvent action:

ApplyFilter | Delete | MouseDown
BeforeDelConfirm | Exit | NoData
BeforeInsert | Filter | Open
BeforeUpdate | Format | Print
DblClick | KeyPress | Unload

Note You can use the CancelEvent action with the MouseDown event only to cancel the event that occurs when you click the right mouse button.

If a control’s OnDblClick event property setting specifies a macro containing the CancelEvent action, the action cancels the double-click event.

For events that can be canceled, the default behavior for the event (that is, what Microsoft Access typically does when the event occurs) occurs after the macro for the event runs. This enables you to cancel the default behavior. For example, when you double-click a word that the insertion point is on in a text box, Microsoft Access normally selects the word. You can cancel this default behavior in the macro for the DblClick event and perform some other action, such as opening a form containing information about the data in the text box. For events that can’t be canceled, the default behavior occurs before the macro runs.

Note If a form’s OnUnload event property specifies a macro that carries out a CancelEvent action, you won’t be able to close the form. You must either correct the condition that caused the CancelEvent action or open the macro and delete the CancelEvent action to close the form. If the form is a modal form, you won’t be able to open the macro.

To carry out the CancelEvent action in Visual Basic, use the CancelEvent method of the DoCmd object.

See Also

CancelEvent Method, StopMacro Action.


CancelEvent Method

Applies To

DoCmd Object.

Description

The CancelEvent method carries out the CancelEvent action in Visual Basic. For more information on how the action works, see the action topic.

Syntax

DoCmd.CancelEvent

This method uses no arguments.

Remarks

The CancelEvent method has an effect only when it is run as the result of an event. This method cancels the event.

All events that can be canceled in Visual Basic have a Cancel argument. You can use this argument instead of the CancelEvent method to cancel the event. The KeyPress event and MouseDown event (for clicking the right mouse button only) can be canceled only in macros, not event procedures, so you must use the CancelEvent action in a macro to cancel these events.

See Also

CancelEvent Action, DoCmd Object.


CanGrow, CanShrink Properties

Applies To

Form Section, Report Section, Subform/Subreport Control, Text Box Control.

Description

You can use the CanGrow and CanShrink properties to control the appearance of sections on reports and controls on forms that are printed. For example, if you set both properties to Yes, a section or control automatically adjusts vertically to print or display all the data the report or form contains.

Note The CanGrow and CanShrink properties do not apply to form or report header and footer sections.

Setting

The CanGrow property uses the following settings.

Setting | Description | Visual Basic
Yes | The section or control grows vertically so that Microsoft Access can print all the data it contains. | True (-1)
No | (Default) The section or control doesn’t grow. Data that can’t be seen won’t be printed. | False (0)

The CanShrink property uses the following settings.

Setting | Description | Visual Basic
Yes | The section or control shrinks vertically so that Microsoft Access can print the data it contains without leaving blank lines. | True (-1)
No | (Default) The section or control doesn’t shrink. | False (0)

You can set these properties only in the property sheet.

For controls, you can set the default for these properties using the default control style.

These property settings are read-only in Visual Basic.

Remarks

If you set a control’s CanGrow property to Yes, Microsoft Access automatically sets the CanGrow property of the section containing the control to Yes.

Sections grow and shrink vertically across their entire width. However, report header and footer sections will not grow, even if the CanGrow property of a control is set to Yes.

When you use the CanGrow and CanShrink properties, remember that:

  • The property settings don’t affect the horizontal spacing between controls; they affect only the vertical space the controls themselves occupy.
  • Overlapping controls can’t grow or shrink.
  • The size of a large control can prevent controls beside it from shrinking. For example, if several small controls are on the left side of a report’s detail section and one large control, such as an unbound object frame, is on the right side, the controls on the left will not shrink, even if they contain no data.

See Also

Format Event, Retreat Event.


Caption Property

Applies To

Command Button Control, Form, Label Control, Query Fields, Report, Table Fields, Toggle Button Control.

Description

You can use the Caption property to provide helpful information to the user through captions on objects in various views:

  • Fields — Specifies the text for labels attached to controls created by dragging a field from the field list and serves as the column heading for the field in table or query Datasheet view.
  • Forms — Specifies the text that appears in the title bar in Form view.
  • Reports — Specifies the title of the report in Print Preview.
  • Buttons and labels — Specifies the text that appears in the control.

Setting

Enter the caption text. Captions can have up to 2,048 characters. Captions for forms and reports that are too long to display on the title bar are truncated.

For controls, you can set this property in the property sheet. For fields, you can set this property in the property sheet in table Design view or in the Query window (in the Field Properties property sheet). You can also use a macro or Visual Basic. In Visual Basic, use a string expression to set the value of this property for forms, reports, and controls.

Remarks

If you don’t specify a caption for a table field, the field’s FieldName property setting will be used as the caption of a control or as the column heading. If you don’t specify the caption for a query field, the one for the underlying table field will be used. If you don’t set a caption for a form, button, or label, Microsoft Access will assign the object a unique name based on the object, such as “Form1”. If you create a control by dragging a field from the field list and haven’t specified a Caption property setting for the field, the field’s FieldName property setting will be copied to the control’s Name property box and will also appear in the label of the control created.

You can use the Caption property to assign an access key to a control. In the caption, include an ampersand (&) immediately preceding the character you want for an access key. The character will be underlined. When browsing the form, press ALT plus the underlined character to move the focus to that control.

Tip Include two ampersands (&&) in the setting for a control’s caption if you want to display an ampersand itself in the caption text. For example, to display “Save & Exit”, you should type Save && Exit in the Caption property box.

See Also

Description Property, Description Property (Microsoft Office 95 Data Access Reference).


CBool Function

Description

Converts an expression to a Boolean.

Syntax

CBool(expression)

The expression argument is any valid numeric or string expression.

Remarks

If expression is zero, False is returned; otherwise, True is returned. If expression can’t be interpreted as a numeric value, a run-time error occurs.

See Also

Data Type Summary.

Example

This example uses the CBool function to convert an expression to a Boolean. If the expression evaluates to a nonzero value, CBool returns True; otherwise, it returns False.

A = 5: B = 5                ' Initialize variables.= CBool(A = B)        ' Check contains True.= 0                    ' Define variable.= CBool(A)            ' Check contains False.


CByte Function

Description

Converts an expression to a Byte.

Syntax

CByte(expression)

The expression argument is any valid numeric or string expression.

Remarks

In general, you can document your code using the data type conversion functions to show that the result of some operation should be expressed as a particular data type rather than the default data type. For example, use CByte to force byte arithmetic in cases where currency, single-precision, double-precision, or integer arithmetic normally would occur.

You should use the CByte function instead of Val to provide internationally-aware conversions from any other data type to a Byte. For example, different decimal separators are properly recognized depending on the locale setting of your system, as are different thousand separators.

If expression lies outside the acceptable range for the Byte data type, an error occurs.

See Also

Data Type Summary.

Example

This example uses the CByte function to convert an expression to a Byte.

MyDouble = 125.5678            ' MyDouble is a Double.= CByte(MyDouble)        ' MyByte contains 126.


CCur Function

Description

Converts an expression to a Currency.

Syntax

CCur(expression)

The expression argument is any valid numeric or string expression.

Remarks

In general, you can document your code using the data type conversion functions to show that the result of some operation should be expressed as a particular data type rather than the default data type. For example, use CCur to force currency arithmetic in cases where single-precision, double-precision, or integer arithmetic normally would occur.

You should use the CCur function instead of Val to provide internationally-aware conversions from any other data type to a Currency. For example, different decimal separators are properly recognized depending on the locale setting of your computer, as are different thousand separators and various currency options.

If expression lies outside the acceptable range for the Currency data type, an error occurs.

See Also

Data Type Summary.

Example

This example uses the CCur function to convert an expression to a Currency.

MyDouble = 543.214588            ' MyDouble is a Double.= CCur(MyDouble * 2)        ' Convert result of MyDouble * 2
                                ' (1086.429176) to a
                                ' Currency (1086.4292).


CDate Function

Description

Converts an expression to a Date.

Syntax

CDate(date)

The date argument is any valid date expression.

Remarks

Use the IsDate function to determine if date can be converted to a date or time. CDate recognizes date and time literals as well as some numbers that fall within the range of acceptable dates. When converting a number to a date, the whole number portion is converted to a date. Any fractional part of the number is converted to a time of day, starting at midnight.

CDate recognizes date formats according to the locale setting of your system. The correct order of day, month, and year may not be determined if it is provided in a format other than one of the recognized date settings. In addition, a long date format is not recognized if it also contains the day-of-the-week string.

Note A CVDate function is also provided for compatibility with previous versions of Visual Basic. However, since there is now an intrinsic Date type, there is no further need for CVDate. The syntax of the CVDate function is identical to the CDate function. The difference is that it returns a Variant whose subtype is Date instead of an actual Date type. The same effect can be achieved by converting an expression to a Date and then assigning it to a Variant. This technique is consistent with the conversion of all other intrinsic types to their equivalent Variant subtypes.

See Also

Data Type Summary, IsDate Function.

Example

This example uses the CDate function to convert a string to a Date. In general, hard coding dates and times as strings (as shown in this example) is not recommended. Use date and time literals (such as #2/12/1969#, #4:45:23 PM#) instead.

MyDate = "February 12, 1969"            ' Define date.= CDate(MyDate)            ' Convert to Date data type.= "4:35:47 PM"                ' Define time.= CDate(MyTime)            ' Convert to Date data type.


CDbl Function

Description

Converts an expression to a Double.

Syntax

CDbl(expression)

The expression argument is any valid numeric or string expression.

Remarks

In general, you can document your code using the data type conversion functions to show that the result of some operation should be expressed as a particular data type rather than the default data type. For example, use CDbl or CSng to force double- or single-precision arithmetic in cases where currency or integer arithmetic normally would occur.

You should use the CDbl function instead of Val to provide internationally aware conversions from any other data type to a Double. For example, different decimal separators and thousands separators are properly recognized depending on the locale setting of your system.

See Also

Data Type Summary.

Example

This example uses the CDbl function to convert an expression to a Double.

MyCurr = CCur(234.456784)                ' MyCurr is a Currency.= CDbl(MyCurr * 8.2 * 0.01)        ' Convert result to a Double.


Change Event

Applies To

Combo Box Control, Text Box Control.

Description

The Change event occurs when the contents of a text box or the text portion of a combo box changes. Examples of this event include entering a character directly in the text box or combo box or changing the control’s Text property setting using a macro or Visual Basic.

Notes

  • Setting the value of a control using a macro or Visual Basic doesn’t trigger this event for the control. You must type the data directly into the control, or set the control’s Text property.
  • This event applies only to controls on a form.

Remarks

By running a macro or executing an event procedure when a Change event occurs, you can coordinate data display among controls. You can also display data or a formula in one control and the results in another control.

The Change event doesn’t occur when a value changes in a calculated control or when you select an item from the combo box list.

Note

Note A Change event can cause a cascading event. This occurs when a macro or event procedure that runs in response to the control’s Change event alters the control’s contents — for example, by changing a property setting that determines the control’s value, such as the Text property for a text box. To prevent a cascading event:

  • If possible, avoid attaching a Change macro or event procedure to a control that alters the control’s contents.
  • Avoid creating two or more controls having Change events that affect each other — for example, two text boxes that update each other.

Changing the data in a text box or combo box using the keyboard causes keyboard events to occur in addition to control events like the Change event. For example, if you move to a new record and type an ANSI character in a text box in the record, the following events occur in this order:

KeyDown [image] KeyPress [image] BeforeInsert [image] Change [image] KeyUp

The BeforeUpdate and AfterUpdate events for the text box or combo box control occur after you have entered the new or changed data in the control and moved to another control (or clicked Save Record on the Records menu), and thus after all of the Change events for the control.

The NotInList event occurs for combo boxes for which the LimitToList property is set to Yes after you enter a value that is not in the list and attempt to move to another control or save the record. It occurs after all the Change events for the combo box. In this case, the BeforeUpdate and AfterUpdate events for the combo box don’t occur, because Microsoft Access doesn’t accept a value that is not in the list.

See Also

BeforeUpdate, AfterUpdate Events; Enter, Exit Events; GotFocus, LostFocus Events; KeyDown, KeyUp Events; KeyPress Event; NotInList Event; Open, Close Events; Text Property.


Change Event -- Event Procedures

Description

To create an event procedure that is executed when the Change event occurs, set the OnChange property to [Event Procedure], and click the Build button.

Syntax

Private Sub controlname_Change( )

The Change event procedure uses the following argument.

Argument | Description
controlname | A string that is the name of the control affected by the Change event procedure.

Remarks

You can’t cancel the Change event.

To prevent a cascading event, avoid creating a Change event procedure for a control that alters the control’s contents. If you do create such an event procedure, be sure to set a variable that prevents further changes while the current change is in progress.

See Also

Change Event — Macros.

Example

The following example counts the number of characters entered in a text box. If more than three characters are entered, a message is displayed and the count is reset to 0.

To try this example, add the following code to the Declarations section of a module for a form named Orders that contains a text box called ShipRegion.

Private Sub ShipRegion_Change()
    ' Declare variable as static to preserve value between calls.
    Static intLetter As Integer

    ' Check to see how many letters have been entered.
    If intLetter < 3 Then
        intLetter = intLetter + 1
    ' If more than three, reset value of text box.
    Else
        MsgBox "Only three characters are allowed."
        intLetter = 0
        Forms!Orders!ShipRegion.Undo
    End IfSub


Change Event -- Macros

Description

To run a macro when the Change event occurs, set the OnChange property to the name of the macro.

Remarks

You can use a Change macro to synchronize data in two controls; when a change occurs in one control, it can be reflected in the other control.

You can’t use the CancelEvent action in a Change macro.

See Also

Change Event — Event Procedures.


ChDir Statement

Description

Changes the current directory or folder.

Syntax

ChDir path

The path argument is a string expression that identifies which directory or folder becomes the new default directory or folder. The path may include the drive. If no drive is specified, ChDir changes the default directory or folder on the current drive.

Remarks

The ChDir statement changes the default directory but not the default drive. For example, if the default drive is C, the following statement changes the default directory on drive D, but C remains the default drive:

ChDir "D:\TMP"

See Also

ChDrive Statement, CurDir Function, Dir Function, MkDir Statement, RmDir Statement.

Example

This example uses the ChDir statement to change the current directory or folder.

' Change current directory or folder to "MYDIR"."MYDIR"
' Assume "C:" is the current drive. The following statement changes
' the default directory on drive "D:". "C:" remains the current drive."D:\WINDOWS\SYSTEM"


ChDrive Statement

Description

Changes the current drive.

Syntax

ChDrive drive

The drive argument is a string expression that specifies an existing drive. If you supply a zero-length argument (""), the current drive doesn’t change. If the argument drive is a multiple-character string, ChDrive uses only the first letter.

See Also

ChDir Statement, CurDir Function, MkDir Statement, RmDir Statement.

Example

This example uses the ChDrive statement to change the current drive.

ChDrive "D"            ' Make "D" the current drive.


Choose Function

Description

Selects and returns a value from a list of arguments.

Syntax

Choose(index, choice-1[, choice-2, ... [,choice-n]])

The Choose function syntax has these parts:

Part | Description
index | Numeric expression or field that results in a value between 1 and the number of available choices.
choice | Variant expression containing one of the possible choices.

Remarks

Choose returns a value from the list of choices based on the value of index. If index is 1, Choose returns the first choice in the list; if index is 2, it returns the second choice, and so on.

You can use Choose to look up a value in a list of possibilities. For example, if index evaluates to 3 and choice-1 = “one”, choice-2 = “two”, and choice-3 = “three”, Choose returns “three”. This capability is particularly useful if index represents the value in an option group.

Choose evaluates every choice in the list, even though it returns only one. For this reason, you should watch for undesirable side effects. For example, if you use the MsgBox function as part of an expression in all the choices, a message box will be displayed for each choice as it is evaluated, even though Choose returns the value of only one of them.

The Choose function returns a #Null# if index is less than 1 or greater than the number of choices listed.

If index is not a whole number, it is rounded to the nearest whole number before being evaluated.

See Also

IIf Function.

Specifics (Microsoft Access)

The Choose function is most useful in a calculated control on a form or report. For example, you can use the Choose function to set the value of a control based on the value of another field. Set the ControlSource property of the control to an expression containing the Choose function.

= Choose([ShipVia], "Speedy", "United", "Federal")

In the preceding example, if ShipVia contains 1, the Choose function returns the first string, “Speedy”. If it contains 2, the function returns the second string, “United”, and so on. If ShipVia contains 0, the Choose function returns a Null.

The next example shows how you can ensure that a string is returned even if the field contains 0.

= Choose([ShipVia] + 1, "none", "Speedy", "United", "Federal")

Note In a Visual Basic module, you may want to use the more full-featured Select Case statement to return a value from a set of several choices.

Example

This example uses the Choose function to display a name in response to an index passed into the procedure in the Ind parameter.

Function  GetChoice(Ind As Integer)
    GetChoice =  Choose(Ind, "Speedy", "United", "Federal")Function

You can use the Choose function to set the value of one field based on the value of another field. For example, suppose you have an Orders table that contains a field called OrderDate. You could create a calculated control on a form to display the day of the week on which an order was placed. The following example uses the Weekday function to return the numeric representation of the day of the week corresponding to the order date. The Choose function returns a string containing the name of the day of the week based on that numeric value.

= Choose(Weekday([OrderDate]) - 1, "Monday", "Tuesday", "Wednesday", _     "Thursday", "Friday")


Chr Function

Description

Returns the character associated with the specified character code.

Syntax

Chr(charcode)

The charcode argument is a number that identifies a character.

Remarks

Numbers from 0 to 31 are the same as standard, nonprintable ASCII codes. For example, Chr(10) returns a linefeed character.

Note Another function (ChrB) is provided for use with byte data contained in a string. Instead of returning a character, which may be one or two bytes, ChrB always returns a single byte.

See Also

Asc Function, Str Function.

Example

This example uses the Chr function to return the character associated with the specified character code.

MyChar = Chr(65)            ' Returns A.= Chr(97)            ' Returns a.= Chr(62)            ' Returns >.= Chr(37)            ' Returns %.


CInt Function

Description

Converts an expression to an Integer.

Syntax

CInt(expression)

The expression argument is any valid numeric or string expression.

Remarks

In general, you can document your code using the data type conversion functions to show that the result of some operation should be expressed as a particular data type rather than the default data type. For example, use CInt or CLng to force integer arithmetic in cases where currency, single-precision, or double-precision arithmetic normally would occur.

You should use the CInt function instead of Val to provide internationally-aware conversions from any other data type to an Integer. For example, different decimal separators are properly recognized depending on the locale setting of your system, as are different thousand separators.

If expression lies outside the acceptable range for the Integer data type, an error occurs.

Note CInt differs from the Fix and Int functions, which truncate, rather than round, the fractional part of a number. When the fractional part is exactly 0.5, the CInt function always rounds it to the nearest even number. For example, 0.5 rounds to 0, and 1.5 rounds to 2.

See Also

Data Type Summary; Int, Fix Functions.

Example

This example uses the CInt function to convert a value to an Integer.

MyDouble = 2345.5678            ' MyDouble is a Double.= CInt(MyDouble)        ' MyInt contains 2346.


Circle Method

Applies To

Report Object.

Description

The Circle method draws a circle, an ellipse, or an arc on a Report object when the Print event occurs.

Syntax

object.Circle [Step](x, y), radius[, [color][, [start][, [end][, aspect]]]]

You can use this method only in an event procedure or a macro specified by the event properties OnPrint or OnFormat for a report section, or OnPage for a report.

The Circle method uses the following arguments.

Argument | Description
object | Report object on which the circle is drawn.
Step | A key word that specifies that the center of the circle, ellipse, or arc is relative to the current coordinates given by the current settings for the CurrentX and CurrentY properties of object.
x, y | Single values indicating the coordinates of the center point of the circle, ellipse, or arc. The scale properties (ScaleMode, ScaleLeft, ScaleTop, ScaleHeight, and ScaleWidth) of object determine the unit of measure used.
radius | A Single value indicating the radius of the circle, ellipse, or arc. The scale properties (ScaleMode, ScaleLeft, ScaleTop, ScaleHeight, and ScaleWidth) of object determine the unit of measure used. By default distances are measured in twips.

Argument | Description
color | A Long value indicating the RGB (red-green-blue) color of the circle outline. If this argument is omitted, the value of the ForeColor property is used. You can also use the RGB function or QBColor function to specify the color.
start, end | Single values. When a partial circle or ellipse is drawn, start and end specify (in radians) the beginning and end positions of the arc. The default value for start is 0 radians; the default for end is 2 pi radians. The range for both is -2 pi radians to 2 pi radians.
aspect | Single value indicating the aspect ratio of the circle. The default value is 1.0, which yields a perfect (nonelliptical) circle on any screen.

Remarks

When drawing a partial circle or ellipse, if start is negative, the Circle method draws a radius to start and treats the angle as positive. If end is negative, the Circle method draws a radius to end and again treats the angle as positive. The Circle method always draws in a counterclockwise (positive) direction.

To fill a circle, set the FillColor and FillStyle properties of the report. Only a closed figure can be filled. Closed figures include circles, ellipses, and pie slices, which are arcs with radius lines drawn at both ends.

When drawing pie slices, if you need to draw a radius to angle 0 to form a horizontal line segment to the right, specify a very small negative value for start rather than 0. For example, you might specify -.00000001 for start.

You can omit an argument in the middle of the syntax, but you must include the argument’s comma before including the next argument. If you omit a trailing argument, don’t use any commas following the last argument you specify.

The width of the line used to draw the circle, ellipse, or arc depends on the DrawWidth property setting. The way the circle is drawn on the background depends on the settings of the DrawMode and DrawStyle properties.

When you apply the Circle method, the CurrentX and CurrentY properties are set to the center point specified by the arguments x and y.

See Also

CurrentX, CurrentY Properties; DrawMode Property; DrawStyle Property; DrawWidth Property; Event Properties; FillColor Property; FillStyle Property; ForeColor Property; QBColor Function; RGB Function; ScaleHeight, ScaleWidth Properties; ScaleLeft, ScaleTop Properties; ScaleMode Property.

Example

The following example uses the Circle method to draw a circle, and then create a pie slice within the circle and color it red.

To try this example in Microsoft Access, create a new report by clicking the New button on the Reports tab of the Database window. Set the OnPrint property of the Detail section to [Event Procedure]. Enter the following code in the report’s module, then switch to Print Preview.

Private Sub Detail_Print(Cancel As Integer, PrintCount As Integer)
    Const conPI = 3.14159265359

    Dim sngHCtr As Single, sngVCtr As Single, sngRadius As Single
    Dim sngStart As Single, sngEnd As Single

    sngHCtr = Me.ScaleWidth / 2                ' Horizontal center.
    sngVCtr = Me.ScaleHeight / 2                ' Vertical center.
    sngRadius = Me.ScaleHeight / 3            ' Circle radius.
    Me.Circle(sngHCtr, sngVCtr), sngRadius    ' Draw circle.
    sngStart = -0.00000001                    ' Start of pie slice.
    sngEnd = -2 * conPI / 3                    ' End of pie slice.
    Me.FillColor = RGB(255,0,0)                ' Color pie slice red.
    Me.FillStyle = 0    ' Fill pie slice.
    ' Draw Pie slice within circle
    Me.Circle(sngHCtr, sngVCtr), sngRadius, , sngStart, sngEndSub


Class Property

Applies To

Bound Object Frame Control, Chart Control, Unbound Object Frame Control.

Description

You can use the Class property to specify or determine the class name of an embedded OLE object.

Setting

The Class property setting is a string expression that you or Microsoft Access supplies when you create or paste an OLE object.

You can set the Class property using the property sheet, a macro, or Visual Basic.

Remarks

A class name defines the type of OLE object. For example, Microsoft Excel version 5.0 supports several types of OLE objects, including worksheets and charts. Their class names are “Excel.Sheet” and “Excel.Chart” respectively. When you create an OLE object in Design view using the Paste Special command on the Edit menu or the Object command on the Insert menu, Microsoft Access enters the class name of the new object in the property sheet.

Note To determine the class name of an OLE object, see the documentation for the application supplying the object.

The Class property setting is updated when you copy an object from the Clipboard. For example, if you paste a Microsoft Excel chart from the Clipboard into an OLE object that previously contained a Microsoft Excel worksheet, the Class property setting changes from “Excel.Sheet” to “Excel.Chart”. You can paste an object from the Clipboard using Visual Basic by setting the control’s Action property to acOLEPaste or acOLEPasteSpecialDlg.

See Also

Action Property, OLEClass Property.

Example

See the Action property example.


Clear Method

Applies To

Err Object.

Description

Clears all property settings of the Err object.

Syntax

object.Clear

The object is always the Err object.

Remarks

Use Clear to explicitly clear the Err object after an error has been handled. This is necessary, for example, when you use deferred error handling with On Error Resume Next. Visual Basic for applications calls the Clear method automatically whenever any of the following statements is executed:

  • Any type of Resume statement.
  • Exit Sub, Exit Function, Exit Property.
  • Any On Error statement.

Clear is equivalent to Err = 0 in previous Basic products.

Note The On Error Resume Next construct may be preferable to On Error GoTo when dealing with errors generated during access to other objects. Checking Err after each interaction with an object removes ambiguity about which object your code was accessing when the error occurred. Thus, you can be sure which object placed the error code in Err.Number, as well as which object originally generated the error (the one specified in Err.Source).

See Also

Description Property, Err Object, HelpContext Property (Visual Basic), HelpFile Property (Visual Basic), LastDLLError Property, Number Property, On Error Statement, Raise Method, Source Property.

Example

This example uses the Err object’s Clear method to reset the numeric properties of the Err object to zero and its string properties to zero-length strings. If Clear were omitted from the following code, the error message dialog box would be displayed on every iteration of the loop (after an error occurs) whether or not a successive calculation generated an error.

Dim Result(10) As Integer            ' Declare array whose elements
                                    ' will overflow easily.Error Resume Next                    ' Defer error trapping.
Until indx = 10
    ' Generate an occasional error or store result if no error.
    Result(indx) = Rnd * indx * 20000
    If Err.Number <> 0 Then
        MsgBox Err, , "Error Generated: ", Err.HelpFile, Err.HelpContext
        Err.Clear                    ' Clear Err object properties.
    Else
        indx = indx + 1
    End If


Click Event

Applies To

Bound Object Frame Control, Chart Control, Check Box Control, Combo Box Control, Command Button Control, Form, Form Section, Image Control, Label Control, List Box Control, Option Button Control, Option Group Control, Rectangle Control, Subform/Subreport Control, Text Box Control, Toggle Button Control, Unbound Object Frame Control.

Description

The Click event occurs when the user presses and then releases a mouse button over an object.

Notes

  • The Click event applies only to forms, form sections, and controls on a form.
  • This event doesn’t apply to check boxes, option buttons, or toggle buttons in an option group. It applies only to the option group itself.
  • This event doesn’t apply to a label attached to another control, such as the label for a text box. It applies only to “freestanding” labels. Clicking an attached label has the same effect as clicking the associated control. The normal events for the control occur, not any events for the attached label.

Remarks

On a form, this event occurs when the user clicks a blank area of the form or a disabled control on the form.

For a control, this event occurs when the user:

  • Clicks a control with the left mouse button. Clicking a control with the right or middle mouse button does not trigger this event.
  • Selects an item in a combo box or list box, either by pressing the arrow keys and then pressing the ENTER key or by clicking the mouse button.
  • Presses the SPACEBAR when a command button, check box, option button, or toggle button has the focus.
  • Presses the ENTER key on a form that has a command button whose Default property is set to Yes.
  • Presses the ESC key on a form that has a command button whose Cancel property is set to Yes.
  • Presses a control’s access key. For example, if a command button’s Caption property is set to &Go, pressing ALT+G triggers the event.

Typically, you attach a Click event procedure or macro to a command button to carry out commands and command-like actions. For the other applicable controls, use this event to trigger actions in response to one of the occurrences discussed earlier in this topic.

The Click event for an option group occurs after you change the value of one of the controls in the option group by clicking the control. For example, if you click a toggle button, option button, or check box in an option group, the Click event for the option group occurs after the BeforeUpdate and AfterUpdate events for the option group.

The Click event for a command button occurs when you choose the command button. In addition, if the command button doesn’t already have the focus when you choose it, the Enter and GotFocus events for the command button occur before the Click event.

When a Click event occurs for a list box, the following related events also occur, in this order:

MouseDown [image] MouseUp [image] Click

Other controls have a similar order of events.

Double-clicking a control causes both DblClick and Click events to occur. For command buttons, double-clicking triggers the following events, in this order:

Click [image] DblClick [image] Click

You can use a CancelEvent action in a DblClick macro to cancel the second Click event. For more information, see the DblClick event topic.

Tip To distinguish between the left, right, and middle mouse buttons, use the MouseDown and MouseUp events.

See Also

DblClick Event; MouseDown, MouseUp Events.


Click Event -- Event Procedures

Description

To create an event procedure that is run when the Click event occurs, set the OnClick property to [Event Procedure], and click the Build button.

Syntax

Private Sub Form_Click ( )Private Sub controlname_Click ( )

The Click event procedure uses the following argument.

Argument | Description
controlname | A string that is the name of the control affected by the Click event procedure.

Remarks

When the user double-clicks a list box, the following events occur, in this order:

MouseDown [image] MouseUp [image] Click [image] DblClick

Other controls have a similar order of events. When you’re creating event procedures for these related events, be sure that their event procedure code doesn’t conflict. (For example, the DblClick event procedure shouldn’t contain code that cancels actions carried out in the Click event procedure.)

For a command button only, Microsoft Access runs the event procedure when the user chooses the command button by pressing the ENTER key or an access key. The event procedure is run once. If you want the event procedure to be run repeatedly while the command button is pressed, set its AutoRepeat property to Yes. For other types of controls, you must click the control using the mouse button to trigger the Click event.

You can’t cancel the Click event.

See Also

Click Event — Macros.

Example

In this example, the Click event procedure is attached to the ReadOnly check box. The event procedure sets the Enabled and Locked properties of another control on the form, the Amount text box. When the check box is clicked, the event procedure checks whether the check box is being selected or cleared and then sets the text box’s properties to enable or disable editing accordingly.

To try the following example, add the code to the Declarations section of a form named Sales that contains a check box called ReadOnly and a text box named Amount.

Private Sub ReadOnly_Click ()
    Dim ctl As Control
    Set ctl = Forms!Sales!Amount
    If Forms!Sales!ReadOnly = True Then    ' If checked.
        ctl.Enabled = False    ' Disable editing.
        ctl.Locked = True
    Else        ' If cleared.
        ctl.Enabled = True    ' Enable editing.
        ctl.Locked = False
    End IfSub


Click Event -- Macros

Description

To run a macro when the Click event occurs, set the OnClick property to the name of the macro.

Remarks

You often use Click macros to carry out the actions for each command button on a form. For example, by clicking one command button on a form, users can print a report showing the form’s records. By clicking another, they can open a related form.

For a command button only, Microsoft Access runs the macro specified by the OnClick property when the user chooses the command button by pressing the Enter key or an access key. The macro runs once. If you want the macro to run repeatedly while the command button is pressed, set its AutoRepeat property to Yes. For other types of controls, you must click the control using the mouse button to trigger the Click event.

You can’t use the CancelEvent action in a Click macro.

See Also

Click Event — Event Procedures.


CLng Function

Description

Converts an expression to a Long.

Syntax

CLng(expression)

The expression argument is any valid numeric or string expression.

Remarks

In general, you can document your code using the data type conversion functions to show that the result of some operation should be expressed as a particular data type rather than the default data type. For example, use CInt or CLng to force integer arithmetic in cases where currency, single-precision, or double-precision arithmetic normally would occur.

You should use the CLng function instead of Val to provide internationally-aware conversions from any other data type to a Long. For example, different decimal separators are properly recognized depending on the locale setting of your system, as are different thousand separators.

If expression lies outside the acceptable range for the Long data type, an error occurs.

Note CLng differs from the Fix and Int functions, which truncate, rather than round, the fractional part of a number. When the fractional part is exactly 0.5, the CLng function always rounds it to the nearest even number. For example, 0.5 rounds to 0, and 1.5 rounds to 2.

See Also

Data Type Summary; Int, Fix Functions.

Example

This example uses the CLng function to convert a value to a Long.

MyVal1 = 25427.45: MyVal2 = 25427.55    ' MyVal1, MyVal2 are Doubles.= CLng(MyVal1)    ' MyLong1 contains 25427.= CLng(MyVal2)    ' MyLong2 contains 25428.


Close Action

Description

You can use the Close action to close either a specified Microsoft Access window or the active window if none is specified.

Setting

The Close action uses the following arguments.

Action argument | Description
Object Type | The type of object whose window you want to close. Click Table, Query, Form, Report, Macro, or Module in the drop-down list in the Action Arguments section of the Macro window. To select the active window, leave this argument blank.
Object Name | The name of the object to be closed. The Object Name box shows all objects in the database of the type selected with the Object Type argument. Click the object to close. If you left the Object Type box blank, leave this box blank also.
Save | Whether to save changes to the object when it’s closed. You can click Yes to save the object, No to close the object without saving it, and Prompt to prompt the user whether or not to save the object. The default is Prompt.

Remarks

The Close action works on all database objects that the user can explicitly open or close. This action has the same effect as selecting an object and then closing it by clicking Close on the File menu, clicking Close on the Control menu for the object’s window, or clicking the Close button for the object.

If the Save argument is set to Prompt and the object hasn’t already been saved before the Close action is carried out, a dialog box prompts the user to save the object before the macro closes it. If you’ve set the Warnings On argument of the SetWarnings action to No, the dialog box isn’t displayed and the object is automatically saved.

To run the Close action in Visual Basic, use the Close method of the DoCmd object.

See Also

Close Method; Event Properties; Open, Close Events; Quit Action.


Close Event

See Open, Close Events.


Close Method

Applies To

DoCmd Object.

Description

The Close method carries out the Close action in Visual Basic. For more information on how the action and its arguments work, see the action topic.

Syntax

DoCmd.Close [objecttype, objectname], [save]

The Close method uses the following arguments.

Argument

Description

objecttype | One of the following intrinsic constants: acTable acQuery acForm acReport acMacro acModule
objectname | A string expression that is the valid name of an object of the type selected with the objecttype argument.
save | One of the following intrinsic constants: acPrompt acSaveYes acSaveNo
 | If you leave this argument blank, the default (acPrompt) is assumed.

Remarks

If you leave the objecttype and objectname arguments blank, Microsoft Access closes the active window. If you specify the save argument and leave the objecttype and objectname arguments blank, you must include the objecttype and objectname arguments’ commas.

See Also

Close Action; DoCmd Object; Open, Close Events; Quit Method (DoCmd Object); Save Method.

Example

This example uses the Close method to close the form Order Review, saving any changes to the form without prompting.

DoCmd.Close acForm, "Order Review", acSaveYes


Close Statement

Description

Concludes input/output (I/O) to a file opened using the Open statement.

Syntax

Close [filenumberlist]

The filenumberlist argument can be one or more file numbers using the following syntax, where filenumber is any valid file number:

[[#]filenumber][, [#]filenumber] . . .

Remarks

If you omit filenumberlist, all active files opened by the Open statement are closed.

When you close files that were opened for Output or Append, the final buffer of output is written to the operating system buffer for that file. All buffer space associated with the closed file is released.

When the Close statement is executed, the association of a file with its file number ends.

See Also

End Statement, Open Statement, Reset Statement, Stop Statement.

Example

This example uses the Close statement to close all three files opened for Output.

For I = 1 To 3    ' Loop 3 times.
    FileName = "TEST" & I    ' Create filename.
    Open FileName For Output As #I    ' Open file.
    Print #I, "This is a test."    ' Write string to file.I    ' Close all 3 open files.


CloseButton Property

Applies To

Form.

Description

You can use the CloseButton property to specify whether the Close button on a form is enabled.

Setting

The CloseButton property uses the following settings.

Setting | Description | Visual Basic
Yes | (Default) The Close button is enabled. | True (-1)
No | The Close button is disabled and the Close command isn’t available on the Control menu. | False (0)

You can set the CloseButton property in the form or report’s property sheet, a macro, or using Visual Basic.

You can set the CloseButton property only in form Design view.

Remarks

If you set the CloseButton property to No, the Close button remains visible but is dimmed, and you must provide some other way to close the form — for example, a command button or custom menu command that runs a macro or event procedure that closes the form.

See Also

BorderStyle Property, ControlBox Property, MinMaxButtons Property.


CloseCurrentDatabase Method

Applies To

Application Object.

Description

You can use the CloseCurrentDatabase method to close the current database from another application that has opened a database through OLE Automation. For example, you might use this method from Microsoft Excel to close the database currently open in the Microsoft Access window before opening another database.

Syntax

application.CloseCurrentDatabase

The CloseCurrentDatabase method uses the following argument.

Argument | Description
application | The Application object.

Remarks

The CloseCurrentDatabase method is useful when you have opened a Microsoft Access database from another application through OLE Automation. Once you have created an instance of Microsoft Access from another application, you must also create a new database or specify an existing database to open. This database opens in the Microsoft Access window.

If you use the CloseCurrentDatabase method to close the database that is open in the current instance of Microsoft Access, you can then open a different database without having to create another instance of Microsoft Access.

Note Don’t confuse the CloseCurrentDatabase method with the data access Close method. The Close method closes a Database object variable, causing the variable to go out of scope, but it doesn’t actually close the database open in the Microsoft Access window. The CloseCurrentDatabase method closes the database that is open in the Microsoft Access window.

See Also

NewCurrentDatabase Method, OpenCurrentDatabase Method.

Example

The following example opens a Microsoft Access database from another application through OLE Automation, creates a new form and saves it, then closes the database.

You can enter this code in a Visual Basic module in any application that can act as an OLE Automation controller. For example, you might run the following code from Microsoft Excel or Microsoft Visual Basic.

When the variable pointing to the Application object goes out of scope, the instance of Microsoft Access that it represents closes as well. Therefore, you should declare this variable at the module level.

' Enter following in Declarations section of module.
' From Microsoft Excel, use "Dim appAccess As Object".appAccess As Access.Application
GetTableNames()
    Dim dbs As Database, frm As Form, strDB As String

    ' Initialize string to database path.
    strDB = "C:\MSOffice\Access\Samples\Northwind.mdb"
    ' Create new instance of Microsoft Access.
    Set appAccess = CreateObject("Access.Application.7")
    ' Open database in Microsoft Access window.
    appAccess.OpenCurrentDatabase strDB
    ' Create new form.
    Set frm = appAccess.CreateForm
    ' Save new form.
    appAccess.DoCmd.Save , "NewForm1"
    ' Close currently open database.
    appAccess.CloseCurrentDatabaseSub


CodeContextObject Property

Applies To

Application Object.

Description

You can use the CodeContextObject property to determine the object in which a macro or Visual Basic code is executing.

Setting

The CodeContextObject property is set by Microsoft Access and is read only.

Remarks

The ActiveForm and ActiveReport properties of the Screen object always return the object that currently has the focus. The object with the focus may or may not be the object where a macro or Visual Basic code is currently running, for example, when Visual Basic code runs in the Timer event on a hidden form.

See Also

ActiveForm Property, ActiveReport Property, Application Object, Me Property, Screen Object.

Example

In this example the CodeContextObject property is used in a function to identify the name of the object in which an error occurred. The object name is then used in the message box title as well as in the body of the error message. The Error statement is used in the Command1_Click() event to generate the error for this example.

Private Sub Command1_Click()
    On Error GoTo Command1_Err
    Error 11            ' Generate divide by zero error.
    Exit Sub_Err:
    If ErrorMessage("Command1_Click() Event", vbYesNo + _
    vbInformation, Err) = vbYes Then
        Exit Sub
    Else
        Resume
    End IfSub
ErrorMessage(strText As String, intType As Integer, _
        intErrVal As Integer) As Integer
    Dim objCurrent As Object
    Dim strMsgboxTitle As String
    Set objCurrent = CodeContextObject
    strMsgboxTitle = "Error in " & objCurrent.Name
    strText = strText & "Error #" & intErrVal & _
        " occurred in " &     objCurrent.Name
    ErrorMessage = MsgBox(strText, intType, strMsgboxTitle)
    Err = 0Function


CodeDb Function

Description

You can use the CodeDb function in a module to determine the name of the Database object that refers to the database in which code is currently executing. Use the CodeDb function to access data access objects that are part of a library database.

For example, you can use the CodeDb function in a module in a library database to create a Database object referring to the library database. You can then open a recordset based on a table in the library database.

Syntax

Set database = CodeDbThe CodeDb function has the following argument.

Argument | Description
database | A Database object variable.

Remarks

The CodeDb function returns a Database object for which the Name property is the full path name of the database from which it is called. This function can be useful when you need to manipulate the data access objects in your library database.

When you call a function in a library database, the database from which you have called the function remains the current database, even while code is executing in a module in the library database. In order to refer to the data access objects in the library database, you need to know the name of the Database object that represents the library database.

For instance, suppose you have a table in a library database that lists error messages. To manipulate data in the table from code, you could use the CodeDb function to determine the name of the Database object that refers to the library database that contains the table.

If the CodeDb function is executed from the current database, it returns the name of the current database, which is the same value returned by the CurrentDb function.

See Also

CurrentDb Function.

Example

The following example uses the CodeDb function to return a Database object that refers to a library database. The library database contains both a table named Errors and the code that is currently executing. After the CodeDb function determines this information, the GetErrorString function opens a table-type recordset based on the Errors table. It then extracts an error message from a field named ErrorData based on the integer value passed to the function.

Function GetErrorString (ByVal intError As Integer) As String

    Dim dbs As Database, rst As Recordset

    ' Variable refers to database where code is executing.
    Set dbs = CodeDb

    ' Create table-type Recordset.

    Set rst = dbs.OpenRecordSet("Errors", dbOpenTable)
    ' Set index to primary key (ErrorID field).
    rst.Index = "PrimaryKey"
    ' Find error number passed into GetErrorString.

    rst.Seek "=", intError
    ' Return associated error message.

    GetErrorString = rst.Fields!ErrorData.Value

    rst.Close

End Function


Collection Object

Description

A Collection object is an ordered set of items that can be referred to as a unit.

Syntax

Collection

Remarks

The Collection object provides a convenient way to refer to a related group of items as a single object. The items in a Collection, known as members, need only be related by the fact that they are in the Collection. It is not necessary that members of a Collection be of the same data type.

A Collection can be created in the same way as other objects. For example:

Dim X As New Collection

Once created, members can be added to the Collection using the Add method and removed using the Remove method. Specific members can be returned from the Collection using the Item method, while the entire collection can be iterated using the For Each...Next statement.

Properties

Count Property.

Methods

Add Method, Item Method, Remove Method.

See Also

Add Method, For Each...Next Statement, Item Method, Remove Method.

Specifics (Microsoft Access)

In Microsoft Access, a Collection object can consist of a set of objects of any type. You can create a Collection object that consists of several objects of the same type or objects of different types.

The collection defined by a Collection object can contain any combination of Microsoft Access objects, data access objects, and objects from any other application that exposes its objects to Microsoft Access. You can also add a Collection object to a collection defined by a Collection object.

The collection can also contain user-defined objects that you create in Microsoft Access. For example, you can create user-defined objects with custom methods and properties from a form module or report module. Then you can add these objects to a collection defined by a Collection object, and manipulate them as a set.

Example

This example creates a Collection object (MyClasses), then creates a dialog box in which users can add objects to the collection. To see how this works, choose the Class Module command from the Insert menu and declare a public variable called InstanceName at module level of Class1 ( type Public InstanceName) to hold the names of each instance. Leave the default name as Class1. Copy and paste the code into the General section of another module, then start it with the statement ClassNamer in another procedure. (This example only works with host applications that support classes.)

Sub ClassNamer()
    Dim MyClasses As New Collection        ' Create a Collection object.
    Dim Num                ' Counter for individualizing keys.
    Dim Msg As String        ' Variable to hold prompt string.
    Dim TheName, MyObject, NameList        ' Variants to hold information.
    Do
        Dim Inst As New Class1        ' Create a new instance of Class1.
        Num = Num + 1        ' Increment Num, then get a name.
        Msg = "Please enter a name for this object." & Chr(13) _
             & "Press Cancel to see names in collection."
        TheName = InputBox(Msg, "Name the Collection Items")
        Inst.InstanceName = TheName        ' Put name in object instance.
        ' If user entered name, add it to the collection.
        If Inst.InstanceName <> "" Then
            ' Add the named object to the collection.
            MyClasses.Add item := Inst, key := CStr(Num)
        End If
        ' Clear the current reference in preparation for next one.
        Set Inst = Nothing
    Loop Until TheName = ""
    For Each MyObject In MyClasses        ' Create list of names.
        NameList = NameList & MyObject.InstanceName & Chr(13)
    Next MyObject
    ' Display the list of names in a message box.
    MsgBox NameList, , "Instance Names In MyClasses Collection"
    For Num = 1 To MyClasses.Count        ' Remove name from the collection.
        MyClasses.Remove 1        ' Since collections are reindexed
                        ' automatically, remove the first
    Next                    ' member on each iteration.Sub

The following example creates a Collection object, and then creates a dialog box in which users can add user-defined objects to the collection. To test this example, create a new form and save it as Form1. In the form’s module, declare a public variable varInstName. Your new user-defined objects will be derived from this form and its module.

You can manipulate individual objects within the collection by calling the methods or setting the properties that you have defined for them. In the module of Form1, enter the following code.

' Declare public variable in Declarations section of form module.varInstName As Variant
Sub ChangeCaption (strCaption As String)
    Me.Visible = True
    Me.Caption = strCaptionSub

This Sub procedure becomes a method which you can perform on your user-defined object, once you have created a new instance of the object.

Once you have completed these steps, enter the following procedure in a standard module. When you run this procedure, it will create new instances of your user-defined object and add them to the collection defined by the Collection object. Then it will display the objects (forms in this case) with their changed captions.

Function MakeCollection()
    ' Create new Collection object using New keyword.
    Dim colFormObjects As New Collection
    ' Declare other variables.
    Dim strObjName As String, strList As String
    Dim strMsg As String, strCRLF As String
    Dim intI As Integer

    strCRLF = Chr(13) & Chr(10)

    ' Create objects and add them to collection.
    Do
        ' Create new instance of user-defined object.
        Dim frmObject As New Form_Form1
        strMsg = ("Please enter a name for this new object." & strCRLF _
            & "Press Cancel to see the items in the collection.")
        ' Get name for this instance of object.
        strObjName = InputBox(strMsg, "Name the collection item:")
        ' Store name in public variable you declared in form module.
        frmObject.varInstName = strObjName
        ' If user entered name, add object to collection.
        If frmObject.varInstName <> "" Then
            colFormObjects.Add Item := frmObject
        End If
        ' Clear object variable so it can be set to next instance.
        Set frmObject = Nothing
    Loop Until strObjName = ""

    ' Enumerate and display items in collection.
    ' Note that items in Collection object are indexed beginning with 1.
    intI = 1
    For Each frmObject In colFormObjects
        strList = strList & frmObject.varInstName & strCRLF
        frmObject.ChangeCaption ("New Form #" & intI)
        intI = intI + 1
    Next frmObject
    ' Display list of object names.
    MsgBox strList, , "Objects in colFormObjects collection"Function


Column Property

Applies To

Combo Box Control, List Box Control.

Description

You can use the Column property to refer to a specific column, or column and row combination, in a multiple-column combo box or list box. Use 0 to refer to the first column, 1 to refer to the second column, and so on. Use 0 to refer to the first row, 1 to refer to the second row, and so on. For example, in a list box containing a column of customer IDs and a column of customer names, you could refer to the customer name in the second column and fifth row as:

Forms![Contacts]![Customers].Column(1, 4)

Setting

The Column property uses the following settings.

Setting | Description
controlname | A string expression identifying the name of the combo box or list box control.
column | An Integer value that can range from 0 to the value of the ColumnCount property minus one.
row | Optional. An Integer value that can range from 0 to the value of the ListCount property minus one.

This property setting is only available in a macro or Visual Basic.

Remarks

You can use the Column property to assign the contents of a combo box or list box to another control, such as a text box. For example, to set the ControlSource property of a text box to the value in the second column of a list box, you could use the following expression:

= Forms![Customers]![CompanyName].Column(1)

If the user has made no selection when you refer to a column in a combo box or list box, the Column property setting will be Null. You can use the IsNull function to determine if a selection has been made as in the following example.

If IsNull(Forms![Customers]![Country]) Then MsgBox "No selection."

Note To determine how many columns a combo box or list box has, you can inspect the ColumnCount property setting.

The Column property returns a Variant of VarType 8 (String).

See Also

BoundColumn Property, ColumnCount Property, ColumnHeads Property, ColumnWidths Property, ListCount Property, MultiSelect Property, Nz Function, Selected Property.

Example

The following example uses the Column property and the ColumnCount property to print the values of a list box selection. Notice that if there is no selection, the value of lstCustomerNames will be Null.

Sub Read_ListBox()
    Dim intNumColumns As Integer, i As Integer
    Dim frmCust As Form
    Set frmCust = Forms![frmCustomers]
    If Not IsNull(frmCust![lstCustomerNames]) Then      ' Any selection?
        intNumColumns = frmCust![lstCustomerNames].ColumnCount
        Debug.Print "The list box contains "; intNumColumns; _
            IIf(intNumColumns = 1, " column", " columns"); " of data."
        Debug.Print "The current selection contains:"
        For i = 0 To intNumColumns - 1
            ' Print column data.
            Debug.Print frmCust![lstCustomerNames].Column(i)
        Next i
    Else
        Debug.Print "You haven't selected an entry in the list box."
    End IfSub


ColumnCount Property

Applies To

Chart Control, Combo Box Control, List Box Control, Table Fields, Unbound Object Frame Control.

Description

You can use the ColumnCount property to specify the number of columns displayed in a list box, or in the drop-down portion of a combo box, or sent to OLE objects in a chart or object frame. For example, if you set the ColumnCount property for a list box on an Employees form to 3, one column can list last names, another can list first names, and the third can list employee ID numbers.

Setting

The ColumnCount property holds an Integer between 1 and the maximum number of fields in the table, query, or SQL statement specified in the RowSource property of the control.

You can set the ColumnCount property in the control’s property sheet, a macro, or Visual Basic.

For table fields, you can set this property in table Design view for fields with the DisplayControl property set to Combo Box or List Box.

Note Microsoft Access sets this property automatically when you select Lookup Wizard as the data type for a field in table Design view.

Remarks

A combo box or list box can have multiple columns. If the control’s RowSource property contains the name of a table, query, or SQL statement, a combo box or list box will display the fields from that source, from left to right, up to the number specified by the ColumnCount property.

To display a different combination of fields, create either a new query or a new SQL statement for the RowSource property, specifying the fields and the order you want.

You can use the ColumnWidths property to set the width of the columns displayed in the control.

See Also

BoundColumn Property, Column Property, ColumnHeads Property, ColumnWidths Property, ControlSource Property.

Example

See the Column property example.


ColumnHeadings Property

Applies To

Query.

Description

You can use the ColumnHeadings property to specify the order or limit the number of columns displayed in a crosstab query. For example, in a query that displays the names of countries, you may want to show them in a specific order, such as United States first, Canada second, and the United Kingdom third.

Note The ColumnHeadings property applies only to crosstab queries.

Setting

Enter the data values from the column headings field as a string expression in the order you want them displayed in the datasheet for the crosstab query, separated by a comma (or the list separator set in the Regional Settings section of the Windows Control Panel). The following table shows sample ColumnHeadings settings and the result in the crosstab query’s datasheet.

Sample setting | Result
“Qtr 1”, “Qtr 2”, “Qtr 3”, “Qtr 4” | Displays column headings for each quarter
“Mexico”, “Canada”, “USA” | Displays column headings for each country

You can set this property using the query property sheet or Visual Basic. You can also set it in SQL view of the Query window by using a PIVOT clause in the SQL statement.

Note The column headings you specify for the ColumnHeadings property must exactly match the data values in the column headings field in the query design grid.

Remarks

You use the ColumnHeadings property to obtain more control over the appearance of column headings in a crosstab query. By default, Microsoft Access displays all data values as column headings in ascending order. For example, if your column heading field name is Month, the default column headings displayed will be April, August, December, February, and so on. You can use the ColumnHeadings property to display the data in the correct order with the appropriate setting: “January”, “February”, “March”, and so on.

If you include a column heading in the ColumnHeadings property setting, the column is always displayed in query Datasheet view, even if the column contains no data. This is useful for a report based on a crosstab query, for example, when you always want to display the same column headings in the report.

Tip You can use the ColumnHeadings property to improve the speed of some crosstab queries by limiting the number of columns displayed.

See Also

ColumnHeads Property.

Example

This example creates four column headings (Qtr 1, Qtr 2, Qtr 3, Qtr 4) in Datasheet view of the crosstab query listing the quarterly orders by product. You can enter this statement in SQL view of the Query window.

TRANSFORM Sum(CCur([Order Details].[UnitPrice]* _
    [Order Details].[Quantity]*(1-[Discount])/100)*100) [Product Amount] Products.ProductName FROM Products JOIN (Orders INNER JOIN [Order Details] Orders.OrderID = [Order Details].OrderID) ON Products.ProductID _
    = [Order Details].ProductID (((Orders.ShippedDate) Between #1/1/94# And #12/31/94#))BY Products.ProductName "Qtr " & DatePart("q",[ShippedDate],1,0);


ColumnHeads Property

Applies To

Chart Control, Combo Box Control, List Box Control, Table Fields, Unbound Object Frame Control.

Description

You can use the ColumnHeads property to display a single row of column headings for list boxes, combo boxes, and OLE objects that accept column headings. You can also use this property to create a label for each entry in a chart. What is actually displayed as the first-row column heading depends on the object’s RowSourceType property.

Setting

The ColumnHeads property has the following settings.

Setting | Description | Visual Basic
Yes | Column headings are enabled and either field captions, field names, or the first row of data items are used as column headings or graph labels. | True (-1)
No | (Default) Column headings are not enabled. | False (0)

You can set the ColumnHeads property in the control’s property sheet, a macro, or Visual Basic.

For table fields, you can set this property in table Design view for fields with the DisplayControl property set to Combo Box or List Box.

Note Microsoft Access sets this property automatically when you select Lookup Wizard as the data type for a field in table Design view.

Remarks

The RowSourceType property specifies whether field names or the first row of data items are used to create column headings. If the RowSourceType property is set to Table/Query, the field names are used as column headings. If the field has a caption, then the caption is displayed. For example, if a list box has three columns and the RowSourceType property is set to Table/Query, the first three field names are used as headings. If the RowSourceType property is set to Value List, the first row of data items entered in the Value List will be column headings.

When the first row of data items are used as column headings, they can’t be selected.

Headings in combo boxes appear only when the list drops down.

See Also

BoundColumn Property, ColumnCount Property, ColumnHeadings Property, ColumnWidths Property, ControlSource Property, ListRows Property, ListWidth Property.


ColumnHidden Property

Applies To

Table Fields.

Description

You can use the ColumnHidden property to show or hide a specified column in Datasheet view. For example, you might want to hide a CustomerAddress field that’s too wide so you can view the CustomerName and PhoneNumber fields.

Note The ColumnHidden property applies to all fields in Datasheet view and to form controls when the form is in Datasheet view.

Setting

The ColumnHidden property uses the following settings.

Setting | Description | Visual Basic
Hide | The column is hidden. | True (-1)
Unhide | (Default) The column is visible. | False (0)

You can set this property by clicking Hide Columns or Unhide Columns on the Format menu in Datasheet view.

You can also set this property in Visual Basic using a Long value.

To set or change this property for a table or query using Visual Basic, you must use a field’s Properties collection.

Note The ColumnHidden property is not available in form Design view.

Remarks

Hiding a column in Datasheet view does not hide fields from the same column in Form view. Similarly, setting a control’s Visible property to False in Form view doesn’t hide the corresponding column in Datasheet view.

You can display a field in a query even though the column for the field is hidden in table Datasheet view.

You can use values from a hidden column as the criteria for a filter even though the column remains hidden after the filter is applied.

You can’t use the Copy, Paste, Find, and Replace commands on the Edit menu to affect hidden columns.

Setting a field’s ColumnWidth property to 0, or resizing the field to a zero width in Datasheet view, causes Microsoft Access to set the corresponding ColumnHidden property to True. Unhiding a column restores the ColumnWidth property to the value it had before the field was hidden.

See Also

ColumnOrder Property, ColumnWidth Property, RowHeight Property.

Example

The following example hides the ProductID field in Datasheet view of the Products form.

Forms![Products]![ProductID].ColumnHidden = -1

The next example also hides the ProductID field in Datasheet view of the Products table. To set the ColumnHidden property, the example uses the ShowColumn and SetFieldProperty procedures, which are in the database’s standard module.

Dim db As Databasedb = CurrentDbdb.TableDefs![Products].Fields![ProductID], False
ShowColumn (FieldObj As Field, Show As Integer)
    ' Set ColumnHidden property.
    SetFieldProperty FieldObj, "ColumnHidden", dbLong, Not ShowSub
SetFieldProperty (fldField As Field, strPropertyName As String, _
        intPropertyType As Integer, varPropertyValue As Variant)
    ' Set field property without producing nonrecoverable run-time
    ' error.
    Const conErrPropertyNotFound = 3270
    Dim proProperty As Property
    On Error Resume Next        ' Don't trap errors.
    fldField.Properties(strPropertyName) = varPropertyValue
    If Err <> 0 Then            ' Error occurred when value set.
        If Err <> conErrPropertyNotFound Then
            On Error GoTo 0
            MsgBox "Couldn't set property '" & strPropertyName _
                & "' on field '" & fldField.name & "'", 48, _
                "SetFieldProperty"
        Else
            On Error GoTo 0
            Set proProperty = fldField.CreateProperty(strPropertyName, _
                intPropertyType, varPropertyValue)
            fldField.Properties.Append proProperty
        End If
    End IfSub


ColumnOrder Property

Applies To

Table Fields.

Description

You can use the ColumnOrder property to specify the order of the columns in Datasheet view.

Note The ColumnOrder property applies to all fields in Datasheet view and to form controls when the form is in Datasheet view.

Setting

You set this property by selecting a column in Datasheet view and dragging it to a new position.

You set the ColumnOrder property in Visual Basic using a Long value.

To set or change this property for a table or query using Visual Basic, you must use a field’s Properties collection.

Note The ColumnOrder property is not available in form Design view.

Remarks

In Datasheet view, a field’s ColumnOrder property setting is determined by the field’s position. For example, the field in the leftmost column in Datasheet view has a ColumnOrder property setting of 1, the next field has a setting of 2, and so on. Changing a field’s ColumnOrder property resets the ColumnOrder property for that field and every field to the left of its original position in Datasheet view.

In other views, the ColumnOrder property setting is 0 unless you explicitly change the order of one or more fields in Datasheet view (either by dragging the fields to new positions or by changing their ColumnOrder property settings). Fields to the right of the moved field’s new position will have a ColumnOrder property setting of 0 in views other than Datasheet view.

The order of the fields in Datasheet view doesn’t affect the order of the fields in table Design view or Form view.

See Also

ColumnHidden Property, ColumnWidth Property, FrozenColumns Property, RowHeight Property.

Example

The following example displays the ProductName and QuantityPerUnit fields in the first two columns in Datasheet view of the Products form.

Forms![Products]![ProductName].ColumnOrder = 1![Products]![QuantityPerUnit].ColumnOrder = 2

The next example displays the ProductName and QuantityPerUnit fields in the first two columns of the Products table in Datasheet view. To set the ColumnOrder property, the example uses the SetFieldProperty procedure.

Dim db As Database, tdProducts As TableDefdb = CurrentDbtdProducts = db![Products]tdProducts![ProductName], "ColumnOrder", dbLong, 2tdProducts![QuantityPerUnit], "ColumnOrder", dbLong, 3
SetFieldProperty (fldField As Field, strPropertyName As String, _
        intPropertyType As Integer, varPropertyValue As Variant)
    ' Set field property without producing nonrecoverable run-time
    ' error.
    Const conErrPropertyNotFound = 3270
    Dim proProperty As Property
    On Error Resume Next        ' Don't trap errors.
    fldField.Properties(strPropertyName) = varPropertyValue
    If Err <> 0 Then            ' Error occurred when value set.
        If Err <> conErrPropertyNotFound Then
            On Error GoTo 0
            MsgBox "Couldn't set property '" & strPropertyName _
                & "' on field '" & fldField.name & "'", 48, _
                "SetFieldProperty"
        Else
            On Error GoTo 0
            Set proProperty = fldField.CreateProperty(strPropertyName, _
                intPropertyType, varPropertyValue)
            fldField.Properties.Append proProperty
        End If
    End IfSub


ColumnWidth Property

Applies To

Table Fields.

Description

You can use the ColumnWidth property to specify the width of a column in Datasheet view.

Note The ColumnWidth property applies to all fields in Datasheet view and to form controls when the form is in Datasheet view.

Setting

You can set this property by clicking the Column Width command on the Format menu in Datasheet view and entering the desired value.

In Visual Basic, the ColumnWidth property setting is an Integer value that represents the column width in twips. You can specify a width or use one of the following predefined settings.

Setting | Description
0 | Hides the column.
-1 | (Default) Sizes the column to the default width.
-2 | Sizes the column to fit the visible text.

Remarks

Setting the ColumnWidth property to 0, or resizing the field to a zero width in Datasheet view, sets the field’s ColumnHidden property to True and hides the field in Datasheet view.

Setting a field’s ColumnHidden property to False restores the field’s ColumnWidth property to the value it had before the field was hidden. For example, if the ColumnWidth property was -1 prior to the field being hidden by setting its ColumnWidth property to 0, changing the field’s ColumnHidden property to False resets the ColumnWidth to -1.

The ColumnWidth property for a field isn’t available when the field’s ColumnHidden property is set to True.

See Also

ColumnHidden Property, ColumnOrder Property, RowHeight Property.

Example

The following example changes the row height in Datasheet view of the Customers table to display two lines of data (450 twips) and sets the width of the Address column to 1.5 inches (2160 twips). These property settings will take effect the next time the Customers table is opened in Datasheet view.

To set the RowHeight and ColumnWidth properties, the example uses the SetTableProperty procedure, which is shown in the example for the DatasheetFontItalic and DatasheetFontUnderline properties, and the SetFieldProperty procedure, which is shown in the example for the ColumnHidden property.

Dim db As Database, tdCustomers As TableDefdb = CurrentDbtdCustomers = db![Customers]tdCustomers, "RowHeight", dbLong, 450tdCustomers![Address], "ColumnWidth", dbInteger, 2160

The next example takes effect in Datasheet view of the open Customers form. It sets the row height to 450 twips and sizes the column to fit the size of the visible text.

Forms![Customers].RowHeight = 450![Customers]![Address].ColumnWidth = -2


ColumnWidths Property

Applies To

Combo Box Control, List Box Control, Table Fields.

Description

You can use the ColumnWidths property to specify the width of each column in a multiple-column combo box or list box.

Setting

The ColumnWidths property holds a value specifying the width of each column in inches or centimeters, depending on the measurement system selected in the Regional Settings section of the Windows Control Panel. The default setting is 1 inch or 2.54 centimeters.

To separate your column entries, use semicolons (;) as list separators (or the list separator selected in the Regional Settings section of the Windows Control Panel).

A width of 0 hides a column. Any or all of the ColumnWidths property settings can be blank. You create a blank setting by typing a list separator without a preceding value. Blank values result in Microsoft Access automatically setting a default column width that varies depending on the number of columns and the width of the combo box or list box.

Note In a combo box, the first visible column is displayed in the text box portion of the control.

You can set the ColumnWidths property in a combo box or list box’s property sheet, a macro, or Visual Basic.

For table fields, you can set this property in table Design view for fields with the DisplayControl property set to Combo Box or List Box.

Note Microsoft Access sets this property automatically when you select Lookup Wizard as the data type for a field in table Design view.

In Visual Basic, use a string expression to set the column width value in twips. Column widths are separated by semicolons. To specify a different unit of measurement include the unit of measure. For example, the following string expression specifies three column widths in centimeters.

"6 cm;0;6 cm"

Remarks

If you leave the ColumnWidths property setting blank, Microsoft Access uses the default width. If the width of the control is greater than the width of the displayed columns, Microsoft Access sets the width of each column as the overall width of the list box or combo box divided by the number of columns. If the column widths you set are too wide to be fully displayed within the combo box or list box, the rightmost columns are hidden and a horizontal scroll bar appears.

If you specify the width for some columns but leave the setting for others blank, Microsoft Access divides the remaining width by the number of columns for which you haven’t specified a width. The minimum calculated column width is 1,440 twips (1 inch).

For example, the following settings are applied to a 4-inch list box.

Setting | Description
1.5 in;0;2.5 in | The first column is 1.5 inches, the second column is hidden, and the third column is 2.5 inches.
2 in;;2 in | The first column is 2 inches, the second column is 1 inch (default), and the third column is 2 inches. Because only half of the third column is visible, a horizontal scroll bar appears.
(Blank) | The three columns are the same width (1.33 inches).

Note This property is different than the ColumnWidth property, which specifies the width of a specified column in a datasheet.

See Also

BoundColumn Property, ColumnCount Property, ColumnHeads Property, ColumnWidth Property, ControlSource Property, ListRows Property, ListWidth Property.


Command Function

Description

You can use the Command function to return the argument portion of the command line used to launch Microsoft Access.

Syntax

Command

Remarks

When Microsoft Access is launched from the command line, any portion of the command line that follows the /Cmd option is passed to the program as the command-line argument. You can use the Command function to return the argument that has been passed.

To change a command-line argument once a database has been opened, click Options on the Tools menu. On the Module tab of the Options dialog box, enter a new argument in the Command Line Arguments box. The Command function will now return the new argument you have entered.

When the Command function is used anywhere other than in Visual Basic code in a module, you must include empty parentheses after the function. For example, to use the Command function in a text box on a form, you would set the ControlSource property to an expression like the following.

= Command()

Example

The following example shows how to launch Microsoft Access with a command-line argument, then shows how to return the value of this argument using the Command function.

To test this example, click the Windows Start Menu and choose Run. Type the following in the Run dialog box, on a single line.

C:\Msoffice\Access\Msaccess.exe C:\Msoffice\Access\Samples\Northwind.mdb å/cmd "Orders"

Next, open a new module in the Northwind sample database and add the following function.

Function CheckCommandLine()
    ' Check value returned by Command function.
    If Command = "Orders" Then
        DoCmd.OpenForm "Orders"
    ElseIf Command = "Employees" Then
        DoCmd.OpenForm "Employees"
    Else
        Exit Function
    End IfFunction

When you call this function, Microsoft Access will open the Orders form.

You can create a macro named AutoExec to call this function automatically when the database is opened.


Comparison Operators

Description

Used to compare expressions.

Syntax

result = expression1 comparisonoperator expression2result = object1 Is object2result = string Like pattern

Comparison operators have these parts:

Part | Description
result | Any numeric variable.
expression | Any expression.
comparisonoperator | Any comparison operator.
object | Any object name.
string | Any string expression.
pattern | Any string expression or range of characters.

Remarks

The Is and Like operators have specific comparison functionality that differs from the operators in the following table. The following table contains a list of the comparison operators and the conditions that determine whether result is True, False, or Null.

Operator | Description | True if | False if | Null if
< | Less than | expression1 < expression2 | expression1 >= expression2 | expression1 or expression2 = Null
<= | Less than or equal to | expression1 <= expression2 | expression1 > expression2 | expression1 or expression2 = Null
> | Greater than | expression1 > expression2 | expression1 <= expression2 | expression1 or expression2 = Null
>= | Greater than or equal to | expression1 >= expression2 | expression1 < expression2 | expression1 or expression2 = Null
= | Equal to | expression1 = expression2 | expression1 <> expression2 | expression1 or expression2 = Null
<> | Not equal to | expression1 <> expression2 | expression1 = expression2 | expression1 or expression2 = Null

When comparing two expressions, you may not be able to easily determine whether the expressions are being compared as numbers or as strings. The following table shows how the expressions are compared or what results when either expression is not a Variant.

If | Then
Both expressions are numeric data types (Byte, Boolean, Integer, Long, Single, Double, Date, or Currency) | Perform a numeric comparison.
Both expressions are String | Perform a string comparison.
One expression is a numeric data type and the other is a Variant that is, or can be, a number | Perform a numeric comparison.

If | Then
One expression is a numeric data type and the other is a string Variant that can’t be converted to a number | A Type Mismatch error occurs.
One expression is a String and the other is any Variant (except a Null) | Perform a string comparison.
One expression is Empty and the other is a numeric data type | Perform a numeric comparison, using 0 as the Empty expression.
One expression is Empty and the other is a String | Perform a string comparison, using a zero-length string as the Empty expression.

If expression1 and expression2 are both Variant expressions, their underlying type determines how they are compared. The following table shows how the expressions are compared or what results from the comparison, depending on the underlying type of the Variant.

If | Then
Both Variant expressions are numeric | Perform a numeric comparison.
Both Variant expressions are strings | Perform a string comparison.
One Variant expression is numeric and the other is a string | The numeric expression is less than the string expression.
One Variant expression is Empty and the other is numeric | Perform a numeric comparison, using 0 as the Empty expression.
One Variant expression is Empty and the other is a string | Perform a string comparison, using a zero-length string as the Empty expression.
Both Variant expressions are Empty | The expressions are equal.

Note If a Currency is compared with a Single or Double, the Single or Double is converted to a Currency. This causes any fractional part of the Single or Double value less than 0.0001 to be lost and may cause two values to compare as equal when they are not. When a Single is compared to a Double, the Double is rounded to the precision of the Single.

See Also

Is Operator, Like Operator, Operator Precedence, Option Compare Statement.

Example

This example shows various uses of comparison operators, which you use to compare expressions.

MyResult = (45 < 35)    ' Returns False.= (45 = 45)    ' Returns True.= (4 <> 3)    ' Returns True.= ("5" > "4")    ' Returns True.= "5": Var2 = 4    ' Initialize variables.= (Var1 > Var2)    ' Returns True.= 5: Var2 = Empty= (Var1 > Var2)    ' Returns True.= 0: Var2 = Empty= (Var1 = Var2)    ' Returns True.


Const Statement

Description

Declares constants for use in place of literal values.

Syntax

[Public | Private] Const constname [As type] = expression

The Const statement syntax has these parts:

Part | Description
Public | Used at module level to declare constants that are available to all procedures in all modules. Not allowed in procedures.
Private | Used at module level to declare constants that are available only within the module where the declaration is made. Not allowed in procedures.
constname | Name of the constant; follows standard variable naming conventions.
type | Data type of the constant; may be Byte, Boolean, Integer, Long, Currency, Single, Double, Date, String, or Variant. Use a separate As type clause for each constant being declared.
expression | Literal, other constant, or any combination that includes all arithmetic or logical operators except Is.

Remarks

Constants are private by default. Within procedures, constants are always private; their visibility can’t be changed. In standard modules, the default visibility of module-level constants can be changed using the Public keyword. In class modules, however, constants can only be private and their visibility can’t be changed using the Public keyword.

You can combine several constant declarations on the same line by separating each constant assignment with a comma. If constant declarations are combined in this way, the Public or Private keyword, if used, applies to all of them.

You can’t use variables, user-defined functions, or intrinsic Visual Basic functions (such as Chr) in expressions assigned to constants.

Tip Constants can make your programs self-documenting and easy to modify. Unlike variables, constants can’t be inadvertently changed while your program is running.

If you don’t explicitly declare the constant type (using As type), the constant is given the data type that is most appropriate for the expression provided.

Constants declared in Sub, Function, or Property procedures are local to that procedure. A constant declared outside a procedure is defined throughout the module in which it is declared. You can use constants anywhere you can use an expression.

See Also

#Const Directive, Def type Statements, Function Statement, Let Statement, Property Get Statement, Property Let Statement, Property Set Statement, Sub Statement.

Specifics (Microsoft Access)

A constant in a Microsoft Access standard module is private by default. If you precede a constant with the keyword Public, however, it is then available to other modules in the current database. It is also available to modules that reference the current database. A constant defined in a form module or report module is always private to that module, and can’t be made public using the Public keyword.

Example

This example uses the Const statement to declare constants for use in place of literal values. Public constants occur in a the General section of a standard module, rather than a Class Module. Private constants can go in the General section of any type of module.

' Constants are Private by default.MyVar = 459
' Declare Public constant. Const MyString = "HELP"
' Declare Private Integer constant.Const MyInt As Integer = 5
' Declare multiple constants on same line.MyStr = "Hello", MyDouble As Double = 3.4567

In Microsoft Access, you can declare only private constants in the Declarations section of a form module, report module, or standard module. However, you can declare both public and private constants in the General section of a standard module.

' In form or report module.conCommission = .08

' In standard module.conInterest = .054Const conAddress = "8421 58th Avenue, College Park, MD"


Control Object

Description

The Control object represents a control on a form or report.

Remarks

All controls on a form or report belong to the Controls collection for that Form or Report object. When you refer to an individual Control object in the Controls collection, you can refer to the Controls collection either implicitly or explicitly.

Me!NewData                    ' Implicitly refer to Controls collection.

Me![New Data]                ' Use if control name contains space.

Me("NewData")                ' Performance slightly slower.
(0)                        ' Refer to control's index in collection.

Me.Controls!NewData            ' Explicitly refer to Controls collection.
.Controls[New Data]
.Controls("NewData")
.Controls(0)

Note You can use the Me keyword to represent a form or report within code only if you’re referring to the form or report from code within the form module or report module. If you’re referring to a form or report from a standard module or a different form or report’s module, you must use the full reference to the form or report.

Each Control object is denoted by a particular intrinsic constant. For example, the intrinsic constant acTextBox is associated with a text box control, and acCommandButton is associated with a command button. To determine the type of an existing control, use the ControlType property. However, you don’t need to know the specific type of a control in order to use it in code. You can simply represent it with a variable of data type Control. You can see these constants in the Object Browser by clicking Modules on the Modules/Classes list, and then looking up the constants in the Methods/Properties list.

Properties

ControlType Property.

See Also

Controls Collection; CreateControl, CreateReportControl Functions; Form Object; Me; Report Object.

Example

The following example enumerates all controls in the Controls collection of a form called OrderForm and sets certain properties if the control is a text box.

Sub SetTextBoxProperties()

    Dim frm As Form, ctl As Control

    Set frm = Forms!OrderForm
    ' Enumerate Controls collection.

    For Each ctl In frm.Controls
        ' Check to see if control is text box.
        If ctl.ControlType = acTextBox Then
            ' Set control properties.
            With ctl
                .SetFocus
                .Enabled = True
                .Height = 400
                .SpecialEffect = 0
            End With
        End If
    Next ctlSub


ControlBox Property

Applies To

Form.

Description

You can use the ControlBox property to specify whether a form has a Control menu in Form view.

Setting

The ControlBox property uses the following settings.

Setting | Description | Visual Basic
Yes | (Default) The form has a Control menu in Form view. | True (-1)
No | The form doesn’t have a Control menu in Form view. | False (0)

You can set this property using the form’s property sheet, a macro, or Visual Basic.

You can set this property only in form Design view.

Note Setting the ControlBox property to No removes the Minimize, Maximize, and Close buttons on a form.

Remarks

To display a Control menu on a form, the ControlBox property must be Yes and the form’s BorderStyle property must be set to Thin, Sizable, or Dialog.

Even when a form’s ControlBox property is set to No, the form always has a Control menu when opened in Design view.

Setting the ControlBox property to No suppresses the Control menu when you open the form in Form view from the Database window, using a macro, or Visual Basic. The Control menu is also suppressed when you switch to another view from Form view.

See Also

BorderStyle Property, CloseButton Property, MinMaxButtons Property, Modal Property, PopUp Property.

Example

The following example sets the ControlBox property on the WarningBox form to False.

Forms!WarningBox.ControlBox = False


Controls Collection

Description

The Controls collection contains all of the controls on a form or report. The Controls collection is a member of a Form or Report object.

Remarks

You can enumerate individual controls, count them, and set their properties in the Controls collection. For example, you can enumerate the Controls collection of a particular form and set the Height property of each control to a specified value.

Tip The For Each...Next statement is useful for enumerating a collection.

It is faster to refer to the Controls collection implicitly, as in the following examples, which refer to a control called NewData on a form named OrderForm. Of the following syntax examples, Me!NewData is the fastest way to refer to the control.

Me!NewData    ' Or Forms!OrderForm!NewData.![New Data]    ' Use if control name contains space.("NewData")    ' Performance slightly slower.

You can also refer to an individual control by referring explicitly to the Controls collection.

Me.Controls!NewData    ' Or Forms!OrderForm.Controls!NewData..Controls![New Data].Controls("NewData")

Additionally, you can refer to a control by its index in the collection. The Controls collection is indexed beginning with zero.

Me(0)    ' Refer to first item in collection..Controls(0)

Note You can use the Me keyword to represent a form or report within code only if you’re referring to the form or report from code within the form module or report module. If you’re referring to a form or report from a standard module or a different form or report’s module, you must use the full reference to the form or report.

Properties

Count Property (Microsoft Access).

See Also

Control Object, For Each...Next Statement, Form Object, Me, Report Object.

Example

See the Control object example.


ControlSource Property

Applies To

Bound Object Frame Control, Check Box Control, Combo Box Control, List Box Control, Option Button Control, Option Group Control, Text Box Control, Toggle Button Control.

Description

You can use the ControlSource property to specify what data appears in a control. You can display and edit data bound to a field in a table, query, or SQL statement. You can also display the result of an expression. For a report group level, the ControlSource property determines the field or expression to group on.

Note The ControlSource property doesn’t apply to check box, option button, or toggle button controls in an option group. It applies only to the option group itself.

For reports, the ControlSource property applies only to report group levels.

Setting

The ControlSource property has the following settings.

Setting | Description
A field name | The control is bound to a field in a table, query, or SQL statement. Data from the field is displayed in the control. Changes to the data inside the control change the corresponding data in the field. (To make the control read-only, set the Locked property to Yes.)
An expression | The expression generates data for the control. This data is read-only and is not saved in the database.

You can set the ControlSource property for a control using the control’s property sheet, a macro, or Visual Basic. You can also set the ControlSource property for a text box by typing a field name or expression directly in the text box in form or report Design view.

For a report, you can set this property by selecting a field or typing an expression in the Field/Expression column of the Sorting And Grouping box. For details, see the GroupLevel property.

In Visual Basic, use a string expression to set the value of this property.

Remarks

Forms and reports act as “windows” into your database. You specify the primary source of data for a form or report by setting its RecordSource property to a table, query, or SQL statement. You can then set the ControlSource property to a field in the source of data or to an expression. If the ControlSource property setting is an expression, the value displayed is read-only and not saved in the database. For example:

Example Setting | Description
LastName | A field name in the source specified by the RecordSource property of a form or report. For a control, data from the LastName field is displayed in the control. For a report group level, Microsoft Access groups the data on last name.
= Date( ) + 7 | An expression. For a control, this expression displays a date seven days from today in the control.
= DatePart(“q”,[ShippedDate]) | An expression. For a control, this expression displays the quarter of the shipped date. For a report group level, Microsoft Access groups the data on the quarter of the shipped date.

See Also

Load, Unload Events; RecordSource Property; RowSourceType, RowSource Properties.

Example

The following example sets the ControlSource property for a text box named AddressPart to a field named City.

Forms![Customers]![AddressPart].ControlSource = "City"

The next example sets the ControlSource property for a text box named Expected to the expression = Date() + 7.

Forms![Invoice]![Expected].ControlSource = "= Date() + 7"


ControlTipText Property

Applies To

Bound Object Frame Control, Chart Control, Check Box Control, Combo Box Control, Command Button Control, Image Control, Label Control, List Box Control, Option Button Control, Option Group Control, Toggle Button Control, Unbound Object Frame Control.

Description

You can use the ControlTipText property to specify the text that appears in a screen tip when you hold the mouse pointer over a control.

Setting

You set the ControlTipText property using a string expression up to 255 characters long.

You can set the ControlTipText property in the control’s property sheet, a macro, or using Visual Basic.

You can set the ControlTipText property in any view.

Remarks

The ControlTipText property provides an easy way to provide helpful information about controls on a form.

There are other ways to provide on-line assistance for a form or a control on a form. You can use the StatusBarText property to display information in the status bar about a control. To provide more extensive help for a form or control, use the HelpFile and HelpContextID properties.

See Also

HelpButton Property; HelpContextID, HelpFile Properties (Microsoft Access); StatusBarText Property.


ControlType Property

Applies To

Bound Object Frame Control, Chart Control, Check Box Control, Color Builder, Combo Box Control, Command Button Control, Image Control, Label Control, List Box Control, Option Button Control, Page Break Control, Subform/Subreport Control, Text Box Control, Toggle Button Control, Unbound Object Frame Control.

Description

You can use the ControlType property in Visual Basic to determine the type of a control on a form.

Note The ControlType property applies only to controls on a form.

Setting

The ControlType property setting is a constant corresponding to an Integer value that specifies the control type.

Constant | Value | Control
acLabel | 100 | Label
acRectangle | 101 | Rectangle
acLine | 102 | Line
acImage | 103 | Image
acCommandButton | 104 | Command button
acOptionButton | 105 | Option button
acCheckBox | 106 | Check box
acOptionGroup | 107 | Option group
acBoundObjectFrame | 108 | Bound object frame
acTextBox | 109 | Text box
acListBox | 110 | List box
acComboBox | 111 | Combo box
acSubform | 112 | Subform
acObjectFrame | 114 | Unbound object frame
acPageBreak | 118 | Page break
acCustomControl | 119 | Custom control
acToggleButton | 122 | Toggle button

The ControlType property can only be set using Visual Basic in form Design view but can be read in all views.

Remarks

The ControlType property is useful not only for checking for a specific control type in code, but also for changing the type of control to another type. For example, you can change a text box to a combo box by setting the ControlType property for the text box to acComboBox while in form Design view.

You can use the ControlType property to change characteristics of similar controls on a form according to certain conditions. For example, if you don’t want certain users to edit existing data in text boxes, you can set the SpecialEffect property for all text boxes to Flat and set the form’s AllowEdits property to No. The SpecialEffect property does not affect whether data can be edited; it is used here to provide a visual clue that the control behavior has changed.

The ControlType property is also used to specify the type of control to create using the CreateControl function.

See Also

CreateControl, CreateReportControl Functions.

Example

See the AllowAdditions property example.


CopyObject Action

Description

You can use the CopyObject action to copy the specified database object to a different Microsoft Access database or to the same database under a new name. For example, you can copy or save an existing object in another database or quickly create a similar object with changes.

Setting

The CopyObject action uses the following arguments.

Action argument | Description
Destination Database | A valid path and filename for the destination database. Leave this argument blank if you want to select the current database.
If you run a macro containing the CopyObject action in a library database and leave this argument blank, Microsoft Access will copy the object into the library database.
New Name | A new name for the object. When copying to a different database, leave this argument blank to keep the same name.
Source Object Type | The object type you want to copy. Click Table, Query, Form, Report, Macro, or Module in the Source Object Type box in the Action Arguments section of the Macro window. To copy the object selected in the Database window, leave this box blank.
Source Object Name | The name of the object to be copied. The Source Object Name box shows all objects in the database of the type selected by the Source Object Type argument. In the Source Object Type box, click the object to copy. If you left the Source Object Type blank, leave this box blank also.
If you run a macro containing the CopyObject action in a library database, Microsoft Access looks for the object with this name first in the library database, then in the current database.

Remarks

You must enter a value for either one or both of the Destination Database and New Name arguments for this action.

If you leave the Source Object Type and Source Object Name arguments blank, Microsoft Access copies the object selected in the Database window. To select an object in the Database window, you can use the SelectObject action with the In Database Window argument set to Yes.

The CopyObject action is similar to selecting an object in the Database window, clicking Copy on the Edit menu, and then clicking Paste on the Edit menu. The Paste As dialog box appears so you can give the object a new name. The CopyObject action performs all of these steps automatically.

You can also copy an object selected in the Database window, or an open object in the Table window, Query window, Form window, Report window, Macro window, or Module window by clicking Save As/Export on the File menu. The Save As dialog box gives you the option of saving a copy of the object in the current database with a new name, or saving the object in another database. If this object has already been saved and you save it in the current database with a new name, the original version still exists with its old name.

The path and filename of the destination database must exist before the macro runs the CopyObject action. If they don’t exist, Microsoft Access displays an error message.

To run the CopyObject action in Visual Basic, use the CopyObject method of the DoCmd object.

See Also

CopyObject Method, Rename Action, TransferDatabase Action.


CopyObject Method

Applies To

DoCmd Object.

Description

The CopyObject method carries out the CopyObject action in Visual Basic. For more information on how the action and its arguments work, see the action topic.

Syntax

DoCmd.CopyObject [destinationdatabase] [, newname] [, sourceobjecttype, åsourceobjectname]

The CopyObject method uses the following arguments.

Argument | Description
destinationdatabase | A string expression that is the valid path and file name for the database you want to copy the object into. To select the current database, leave this argument blank.
If you execute Visual Basic code containing the CopyObject method in a library database and leave this argument blank, Microsoft Access copies the object into the library database.
newname | A string expression that is the new name for the object you want to copy. To use the same name if you are copying into another database, leave this argument blank.
sourceobjecttype | One of the following intrinsic constants: acTable acQuery acForm acReport acMacro acModule
sourceobjectname | A string expression that is the valid name of an object of the type selected with the sourceobjecttype argument.
If you execute Visual Basic code containing the CopyObject method in a library database, Microsoft Access looks for the object with this name first in the library database, then in the current database.

Remarks

You must include either the destinationdatabase or newname argument or both for this method.

If you leave the sourceobjecttype and sourceobjectname arguments blank, Microsoft Access copies the object selected in the Database window. To select an object in the Database window, you can use the SelectObject action or SelectObject method with the In Database Window argument set to Yes (True).

If you specify the sourceobjecttype and sourceobjectname arguments but leave either the newname argument or the destinationdatabase argument blank, you must include the newname or destinationdatabase argument’s comma. If you leave a trailing argument blank, don’t use a comma following the last argument you specify.

See Also

CopyObject Action, DoCmd Object, Rename Method, SelectObject Method, TransferDatabase Method.

Example

This example uses the CopyObject method to copy the Employees table and give it a new name in the current database.

DoCmd.CopyObject , "Employees Copy", acTable, "Employees"


Cos Function

Description

Returns the cosine of an angle.

Syntax

Cos(number)

The number argument can be any valid numeric expression that expresses an angle in radians.

Remarks

The Cos function takes an angle and returns the ratio of two sides of a right triangle. The ratio is the length of the side adjacent to the angle divided by the length of the hypotenuse.

The result lies in the range -1 to 1.

To convert degrees to radians, multiply degrees by p/180. To convert radians to degrees, multiply radians by 180/p.

See Also

Atn Function, Derived Math Functions, Sin Function, Tan Function.

Example

This example uses the Cos function to return the cosine of an angle.

MyAngle = 1.3    ' Define angle in radians.= 1 / Cos(MyAngle)    ' Calculate secant.


Count Property (Microsoft Access)

Applies To

Form, Report.

Description

You can use the Count property to determine the number of open forms or reports, or the number of controls on an open form or report.

Setting

The Count property setting is an Integer and is read-only in all views.

You can determine the Count property using a macro or Visual Basic.

If no forms or reports are open, the Count property setting is 0.

See Also

Count Property (Visual Basic), Count Property (Microsoft Office 95 Data Access Reference).

Example

The following example uses the Collection object’s Count property to specify how many iterations are required to remove all elements of the Collection object colThings. User-defined collections are indexed numerically. For a user-defined collection, the default base index is 1. Since collections are automatically reindexed when an item is removed, the following code removes the first member on each iteration.

Note that you can also use the For Each...Next statement to manipulate items in a collection.

Dim intIintI = 1 to colThings.Count
    colThings.Remove 1

The following example uses the Count property to control a loop that prints information about all open forms.

Sub Print_Form_Controls()
    Dim frm As Form, intI As Integer, intJ As Integer, strTab As String
    Dim intControls As Integer, intForms As Integer
    strTab = Chr(9)            ' Tab character.
    intForms = Forms.Count        ' Number of open forms.
    If intForms > 0 Then
        For intI = 0 To intForms - 1
            Set frm = Forms(intI)
            Debug.Print frm.Name        ' Print form name.
            intControls = frm.Count
            If intControls > 0 Then
                For intJ = 0 To intControls - 1
                    ' Print control name.
                    Debug.Print strTab; frm(intJ).Name
                Next intJ
            Else
                Debug.Print strTab; "(no controls)"
            End If
        Next intI
    Else
        MsgBox "No open forms.", vbExclamation, "Form Controls"
    End IfSub

The next example determines the number of controls on a form or report and assigns this number to a variable.

Dim intFormControls As IntegerintReportControls As Integer= Forms![Employees].Count= Reports![FreightCharges].Count


Count Property (Visual Basic)

Applies To

Collection Object.

Description

Returns the number of members in a collection. Not available at design time; read-only at run time.

Syntax

object.Count

The object qualifier is an object expression that evaluates to an object in the Applies To list.

See Also

Add Method, Item Method, Remove Method.

Example

This example uses the Collection object’s Count property to specify how many iterations are required to remove all the elements of the collection called MyClasses. When collections are numerically indexed, the base is 1 by default. Since collections are reindexed automatically when a removal is made, the following code removes the first member on each iteration.

Dim NumNum = 1 To MyClasses.Count    ' Remove name from the collection.
    MyClasses.Remove 1    ' Default collection numeric indexes    ' begin at 1.

See also the Count property (Microsoft Access) example.


CreateControl, CreateReportControl Functions

Description

You can use the CreateControl function to create a control on a specified open form. You can use the CreateReportControl function to create a control on a specified open report.

For example, suppose you are building a custom wizard that allows users to easily construct a particular form. You can use the CreateControl function in your wizard to add the appropriate controls to the form.

Syntax

CreateControl(formname, controltype[, section[, parent[, columnname[, left[, åtop[, width[, height]]]]]]])CreateReportControl(reportname, controltype[, section[, parent[, åcolumnname[, left[, top[, width[, height]]]]]]])

The CreateControl and CreateReportControl functions take the following arguments.

Argument | Description
formname, reportname | A string expression identifying the name of the open form or report on which you want to create the control.
controltype | One of the following intrinsic constants identifying the type of control you want to create. You can view these constants and paste them into your code from the Object Browser. Click the Object Browser button. Then click Access in the Libraries/Databases box, and click Constants in the Modules/Classes box.

Constant | Value | Control
acLabel | 100 | Label
acRectangle | 101 | Rectangle
acLine | 102 | Line
acImage | 103 | Image
acCommandButton | 104 | Command button
acOptionButton | 105 | Option button
acCheckBox | 106 | Check box
acOptionGroup | 107 | Option group
acBoundObjectFrame | 108 | Bound object frame
acTextBox | 109 | Text box
acListBox | 110 | List box
acComboBox | 111 | Combo box
acSubform | 112 | Subform
acObjectFrame | 114 | Unbound object frame
acPageBreak | 118 | Page break
acCustomControl | 119 | Custom control
acToggleButton | 122 | Toggle button

Argument | Description
section | One of the following intrinsic constants identifying the section that will contain the new control.

Constant | Section
acDetail | (Default) Detail section
acHeader | Form or report header
acFooter | Form or report footer
acPageHeader | Page header
acPageFooter | Page footer
acGroupLevel1Header | Group-level 1 header (reports only)
acGroupLevel1Footer | Group-level 1 footer (reports only)
acGroupLevel2Header | Group-level 2 header (reports only)
acGroupLevel2Footer | Group-level 2 footer (reports only)
If a report has additional group levels, the header/footer pairs are numbered consecutively, beginning with 9.
parent | String expression identifying the name of the parent control of an attached control. For controls that have no parent control, use a zero-length string for this argument.
columnname | Name of the field to which the control will be bound, if it is to be a data-bound control.
If you are creating a control that will not be bound to a field, use a zero-length string for this argument.
left, top | Numeric expressions indicating the coordinates for the upper-left corner of the control in twips.
width, height | Numeric expressions indicating the width and height of the control in twips.

Remarks

Use the CreateControl and CreateReportControl functions in a custom wizard to create controls on a form or report. Both functions return a Control object.

You can use the CreateControl and CreateReportControl functions only in form Design view or report Design view, respectively.

You use the parent argument to identify the relationship between a main control and a subordinate control. For example, if a text box has an attached label, the text box is the main (or parent) control and the label is the subordinate (or child) control. When you create the label control, set its parent argument to a string identifying the name of the parent control. When you create the text box, set its parent argument to a zero-length string.

You also set the parent argument when you create check boxes, option buttons, or toggle buttons. An option group is the parent control of any check boxes, option buttons, or toggle buttons that it contains. The only controls that can have a parent control are a label, check box, option button, or toggle button. All of these controls can also be created independently, without a parent control.

Set the columnname argument according to the type of control you are creating and whether or not it will be bound to a field in a table. The controls that may be bound to a field include the text box, list box, combo box, option group, and bound object frame. Additionally, the toggle button, option button, and check box controls may be bound to a field if they are not contained in an option group.

If you specify the name of a field for the columnname argument, you create a control that is bound to that field. All of the control’s properties are then automatically set to the settings of any corresponding field properties. For example, the value of the control’s ValidationRule property will be the same as the value of that property for the field.

Tip If your wizard creates controls on a new or existing form or report, it must first open the form or report in Design view.

To remove a control from a form or report, use the DeleteControl and DeleteReportControl statements.

See Also

CreateForm, CreateReport Functions; DeleteControl, DeleteReportControl Statements; Section Property.

Example

The following example first creates a new form based on an Orders table. It then uses the CreateControl function to create a text box control and an attached label control on the form.

Sub NewControls()
    Dim frm As Form

    Dim ctlLabel As Control, ctlText As Control

    Dim intDataX As Integer, intDataY As Integer

    Dim intLabelX As Integer, intLabelY As Integer

    ' Create new form with Orders table as its record source.

    Set frm = CreateForm
    frm.RecordSource = "Orders"

    ' Set positioning values for new controls.

    intLabelX = 100
    intLabelY = 100
    intDataX = 1000

    intDataY = 100
    ' Create unbound default-size text box in detail section.

    Set ctlText = CreateControl(frm.Name, acTextBox, , "", "", _
        intDataX, intDataY)
    ' Create child label control for text box.

    Set ctlLabel = CreateControl(frm.Name, acLabel, , ctlText.Name, _
        "NewLabel", intLabelX, intLabelY)
    ' Restore form.

    DoCmd.RestoreSub


CreateForm, CreateReport Functions

Description

The CreateForm function creates a form and returns a Form object. The CreateReport function creates a report and returns a Report object.

For example, suppose you are building a custom wizard to create a sales report. You can use the CreateReport function in your wizard to create a new report based on a specified report template.

Syntax

CreateForm([database[, formtemplate]])CreateReport([database[, reporttemplate]])

The CreateForm and CreateReport functions take the following arguments.

Argument | Description
database | A string expression identifying the name of the database that contains the form or report template you want to use to create a form or report. If you omit this argument, the current database (the value returned by the CurrentDb function) is used.
formtemplate, reporttemplate | A string expression identifying the name of the form or report you want to use as a template to create a new form or report. To create a form or report based on the default template, set this argument to Normal. If you omit this argument, Microsoft Access bases the new form or report on the template specified by the Forms/Reports tab of the Options dialog box, available by clicking Options on the Tools menu.

Remarks

Use the CreateForm and CreateReport functions when designing a wizard that creates a new form or report.

The CreateForm and CreateReport functions open a new, minimized form or report in form Design view or report Design view, respectively.

The form or report you specify for formtemplate or reporttemplate can be a form or report that you have created specifically to be used as a template, or any other form or report in the database identified by the database argument.

If the name you use for the formtemplate or reporttemplate argument isn’t valid, Visual Basic uses the form or report template specified by the Form Template or Report Template setting in the Forms/Reports tab of the Options dialog box, available by clicking Options on the Tools menu.

CreateForm and CreateReport create minimized forms and reports.

Note If you have created a form or report template in another database, the name of that template will be displayed in the Form Template or Report Template options in the Forms/Reports tab of the Options dialog box for every database created in Microsoft Access. In order to create a form or report based on a template that is not in your current database, however, you must either specify the other database in the database argument, or specifically import the template into the current database.

See Also

CreateControl, CreateReportControl Functions.

Example

The following example creates a report in the current database using the template specified by the Report Template setting in the Forms/Reports tab of the Options dialog box.

Sub NormalReport()
    Dim rpt As Report

    Set rpt = CreateReport    ' Create minimized report.
    DoCmd.Restore    ' Restore report.

End Sub

The next example creates a form in the current database that is based on the Customers form in the Northwind sample database, and sets its RecordSource property to the Customers table in the current database. If the currently open database is the Northwind sample database, then you could set the first argument to a zero-length string.

Sub NewForm()

    Dim frm As Form

    ' Create form based on Customers form in Northwind sample database.

    Set frm = CreateForm("Northwind.mdb", "Customers")

    DoCmd.Restore
    ' Set RecordSource to Customers table.
    frm.RecordSource = "Customers"Sub


CreateGroupLevel Function

Description

You can use the CreateGroupLevel function to specify a field or expression on which to group or sort data in a report.

For example, suppose you are building a custom wizard that provides the user with a choice of fields on which to group data when designing a report. Call the CreateGroupLevel function from your wizard to create the appropriate groups according to the user’s choice.

Syntax

CreateGroupLevel(report, expression, header, footer)

The CreateGroupLevel function syntax has the following arguments.

Argument | Description
report | A string expression identifying the name of the report that will contain the new group level.
expression | A string expression identifying the field or expression to sort or group on.
header, footer | An integer value that indicates whether a field or expression will have an associated group header and/or footer. If header and/or footer is True (-1), the field or expression will have a group header and/or footer. If header and/or footer is False (0), it won’t.

Remarks

Use the CreateGroupLevel function when designing a wizard that creates a report with groups or totals. CreateGroupLevel will group or sort data on the specified field or expression and create a header and/or footer for the group level.

The CreateGroupLevel function is available only in report Design view.

Microsoft Access uses an array, the GroupLevel property array, to keep track of the group levels created for a report. CreateGroupLevel adds a new group level to the array, based on the expression argument. CreateGroupLevel then returns an index value that represents the new group level’s position in the array. The first field or expression you sort or group on is level 0, the second is level 1, and so on. You can have up to ten group levels in a report (0 to 9).

When you specify that either header or footer argument, or both, is True, the GroupHeader and GroupFooter properties in a report are set to Yes, and a header and/or footer is created for the group level.

Once a header or footer is created, you can set other GroupLevel properties: GroupOn, GroupInterval, and KeepTogether. You can set these properties in Visual Basic, or you can set them in the report’s Sorting and Grouping Box.

Tip If your wizard creates group levels in a new or existing report, it must open the report in Design view.

See Also

GroupHeader, GroupFooter Properties; GroupInterval Property; GroupLevel Property; GroupOn Property; KeepTogether Property — Groups; SortOrder Property.

Example

The following example function creates a group level on an OrderDate field on a report called OrderReport. The report on which the group level is to be created must be open in Design view. Since the header and footer arguments are set to True, the function creates both the header and footer for the group level. The header and footer are then sized.

Sub CreateGL()

    Dim varGroupLevel As Variant

    ' Create new group level on OrderDate field.
    varGroupLevel = CreateGroupLevel("OrderReport", "OrderDate", _
        True, True)
    ' Set height of header/footer sections.
    Reports!OrderReport.Section(acGroupLevel1Header).Height = 400
    Reports!OrderReport.Section(acGroupLevel1Footer).Height = 400Sub


CreateObject Function

Description

Creates an OLE Automation object.

Syntax

CreateObject(class)

The class argument uses the syntax “appname.objecttype” and has these parts:

Part | Description
appname | The name of the application providing the object.
objecttype | The type or class of object to create.

Remarks

Every application that supports OLE Automation provides at least one type of object. For example, a word processing application may provide an application object, a document object, and a toolbar object.

To create an OLE Automation object, assign the object returned by CreateObject to an object variable:

Dim WordBasicObject As ObjectWordBasicObject = CreateObject("Word.Basic")

When this code is executed, the application creating the object is started (Microsoft Word in this example). If it is already running, a new instance of the application is started, and an object of the specified type is created. Once an object is created, you reference it in code using the object variable you defined. In the above example, you access properties and methods of the new object using the object variable, WordBasicObject. For example:

WordBasicObject.Insert "Hello, world.".FilePrint.FileSaveAs "C:\DOCS\TEST.DOC"

Similarly, you can pass the object returned by the CreateObject function to a function expecting an object as an argument. For example:

Call MySub (CreateObject("Word.Basic"))

Note Use CreateObject when there is no current instance of the object. If there is a current instance, or if you want to start the application and have it load a file, you can use the GetObject function.

If an object has registered itself as a single-instance object (for example, the Word.Basic object in Microsoft Word 6.0), only one instance of the object is created, no matter how many times CreateObject is executed.

See Also

GetObject Function, Set Statement.

Example

This example uses the CreateObject function to set a reference (xlApp) to Microsoft Excel. It uses the reference to access the Visible property of Microsoft Excel, then uses the Quit method of Microsoft Excel to close it. Finally, the reference itself is released.

Dim xlApp As Object    ' Declare variable to hold the reference.
    xlApp = CreateObject("excel.application").Visible = True    ' You may have to set Visible property to True
        ' if you want to see the application.
        ' Use xlApp to access Microsoft Excel's
        ' other objects..Quit    ' When you finish, use the Quit method to close xlApp = Nothing    ' the application, then release the reference.


CreateReport Function

See CreateForm, CreateReport Functions.


CreateReportControl Function

See CreateControl, CreateReportControl Functions.


CSng Function

Description

Converts an expression to a Single.

Syntax

CSng(expression)

The expression argument is any valid numeric or string expression.

Remarks

In general, you can document your code using the data type conversion functions to show that the result of some operation should be expressed as a particular data type rather than the default data type. For example, use CDbl or CSng to force double- or single-precision arithmetic in cases where currency or integer arithmetic normally would occur.

You should use the CSng function instead of Val to provide internationally-aware conversions from any other data type to a Single. For example, different decimal separators are properly recognized depending on the locale setting of your system, as are different thousand separators.

If expression lies outside the acceptable range for the Single data type, an error occurs.

See Also

Data Type Summary.

Example

This example uses the CSng function to convert a value to a Single.

' MyDouble1, MyDouble2 are Doubles.= 75.3421115: MyDouble2 = 75.3421555= CSng(MyDouble1)    ' MySingle1 contains 75.34211.= CSng(MyDouble2)    ' MySingle2 contains 75.34216.


CStr Function

Description

Converts an expression to a String.

Syntax

CStr(expression)

The expression argument is any valid numeric or string expression.

Remarks

In general, you can document your code using the data type conversion functions to show that the result of some operation should be expressed as a particular data type rather than the default data type. For example, use CStr to force the result to be expressed as a String.

You should use the CStr function instead of Str to provide internationally-aware conversions from any other data type to a String. For example, different decimal separators are properly recognized depending on the locale setting of your system.

The data in expression determines what is returned according to the following table:

If expression is | CStr returns
Boolean | A String containing True or False.
Date | A String containing a date in the short-date format of your system.
Null | A run-time error.
Empty | A zero-length String ("").
Error | A String containing the word Error followed by the error number.
Other numeric | A String containing the number.

See Also

Data Type Summary, Str Function.

Example

This example uses the CStr function to convert a numeric value to a String.

MyDouble = 437.324    ' MyDouble is a Double.= CStr(MyDouble)    ' MyString contains "437.324".


CurDir Function

Description

Returns the current path.

Syntax

CurDir[(drive)]

The drive argument is a string expression that specifies an existing drive. If no drive is specified or if drive is a zero-length string (""), CurDir returns the path for the current drive.

See Also

ChDir Statement, ChDrive Statement, MkDir Statement, RmDir Statement.

Example

This example uses the CurDir function to return the current path.

' Assume current path on C drive is "C:\WINDOWS\SYSTEM".
' Assume current path on D drive is "D:\EXCEL".
' Assume C is the current drive.= CurDir    ' Returns "C:\WINDOWS\SYSTEM".= CurDir("C")    ' Returns "C:\WINDOWS\SYSTEM".= CurDir("D")    ' Returns "D:\EXCEL".


Currency Data Type

Description

Currency variables are stored as 64-bit (8-byte) numbers in an integer format, scaled by 10,000 to give a fixed-point number with 15 digits to the left of the decimal point and 4 digits to the right. This representation provides a range of -922,337,203,685,477.5808 to 922,337,203,685,477.5807. The type-declaration character for Currency is @.

The Currency data type is useful for calculations involving money and for fixed-point calculations in which accuracy is particularly important.

See Also

CCur Function, Data Type Summary, Def type Statements, Long Data Type.


Current Event

Applies To

Form.

Description

The Current event occurs when the focus moves to a record, making it the current record, or when the form is requeried.

Remarks

This event occurs both when a form is opened and whenever the focus leaves one record and moves to another. Microsoft Access runs the Current macro or event procedure before the first or next record is displayed.

By running a macro or executing an event procedure when a form’s Current event occurs, you can display a message or synchronize records in another form related to the current record. For example, when a customer record becomes current, you can display the customer’s previous order. When a supplier record becomes current, you can display the products manufactured by the supplier in a Suppliers form. You can also perform calculations based on the current record or change the form in response to data in the current record.

If your macro or event procedure performs a GoToControl or GoToRecord action in response to an Open event, the Current event occurs.

The Current event also occurs when you refresh a form or requery the form’s underlying table or query — for example, when you choose Remove Filter/Sort from the Records menu or use the Requery action in a macro or the Requery method in Visual Basic code.

When you first open a form, the following events occur in this order:

Open [image] Load [image] Resize [image] Activate [image] Current

See Also

Activate, Deactivate Events; GotFocus, LostFocus Events; GoToRecord Action; Load, Unload Events; Open, Close Events.


Current Event -- Event Procedures

Description

To create an event procedure that is run when the Current event occurs, set the OnCurrent property to [Event Procedure], and click the Build button.

Syntax

Private Sub Form_Current ( )

Remarks

You can’t cancel this event using the CancelEvent method of the DoCmd object. However, you can use the GoToRecord method of the DoCmd object to move to a different record.

See Also

Current Event — Macros.

Example

In the following example, a Current event procedure checks the status of an option button called Discontinued. If the user selects the button, the example runs a query to determine substitute products.

Private Sub Form_Current ()
    If Me!Discontinued.Value = True Then
        .
        .    ' Code to run query.
        .
    End IfSub

The following example sets a form’s Caption property to the SupplierName field. As the focus moves from record to record, the title bar displays the current supplier name.

Private Sub Form_Current ()
    Me.Caption = Me!SupplierName.ValueSub


Current Event -- Macros

Description

To run a macro when the Current event occurs, set the OnCurrent property to the name of the macro.

Remarks

You can use a Current macro to display a message or synchronize records in another form related to the current record. For example, when a customer record becomes current, a macro can display the customer’s previous order. When a supplier record is current, the macro can display the products manufactured by the supplier in a Suppliers form.

You can’t use the CancelEvent action in a Current macro. However, you can use the GoToRecord action to move the focus to a different record.

See Also

Current Event — Event Procedures.


CurrentDb Function

Description

The CurrentDb function returns an object variable of type Database that represents the database currently open in the Microsoft Access window.

Syntax

CurrentDb

Remarks

In order to manipulate the structure of your database and its data from Visual Basic, you must use data access objects. The CurrentDb function provides a way to access the current database from Visual Basic code without having to know the name of the database. Once you have a variable that points to the current database, you can also access and manipulate other objects and collections in the data access object hierarchy.

You can use the CurrentDb function to create multiple object variables that refer to the current database. In the following example, the variables dbsA and dbsB both refer to the current database.

Dim dbsA As Database, dbsB As DatabasedbsA = CurrentDbdbsB = CurrentDb

Note In previous versions of Microsoft Access, you may have used the syntax DBEngine.Workspaces(0).Databases(0) or DBEngine(0)(0) to return a pointer to the current database. In Microsoft Access for Windows 95, you should use the CurrentDb function instead. The CurrentDb function creates another instance of the current database, while the DBEngine(0)(0) syntax refers to the open copy of the current database. Using the CurrentDb function enables you to create more than one variable of type Database that refer to the current database. Microsoft Access still supports the DBEngine(0)(0) syntax, but you should consider making this modification to your code in order to avoid possible conflicts in a multiuser database.

If you need to work with another database at the same time that the current database is open in the Microsoft Access window, use the OpenDatabase method of a Workspace object. The OpenDatabase method doesn’t actually open the second database in the Microsoft Access window; it simply returns a Database variable representing the second database. The following example returns a pointer to the current database and to a database called Contacts.mdb.

Dim dbsCurrent As Database, dbsContacts As DatabasedbsCurrent = CurrentDbdbsContacts = DBEngine.Workspaces(0).OpenDatabase("Contacts.mdb")

Example

The following example uses the CurrentDb function to return a Database object variable pointing to the current database. It then enumerates all the fields in the Employees table in that database.

Sub ListFields()
    Dim dbs As Database, tdf As TableDef, fld As Field

    ' Return Database object variable pointing to current database.
    Set dbs = CurrentDb
    ' Return TableDef object variable pointing to Employees table.
    Set tdf = dbs.TableDefs!Employees
    ' Enumerate fields in Employees table.
    For Each fld In tdf.Fields
        Debug.Print fld.Name
    Next fldSub


CurrentObjectType, CurrentObjectName Properties

Applies To

Application Object.

Description

You can use the CurrentObjectType and CurrentObjectName properties together with the Application object to determine the type of the active database object (table, query, form, report, macro, or module) and the name of the active database object.

Setting

The CurrentObjectType property is set by Microsoft Access to one of the following Microsoft Access intrinsic constants.

Setting | Description
acTable | The active object is a table.
acQuery | The active object is a query.
acForm | The active object is a form.
acReport | The active object is a report.
acMacro | The active object is a macro.
acModule | The active object is a module.

The CurrentObjectName property is set by Microsoft Access to a string expression containing the name of the active object.

These property settings are available only in Visual Basic and are read-only in all views.

Remarks

The following conditions determine which object is considered the active object:

  • If the user chooses the property sheet, toolbar, menu, palette, or the field list of an object, the CurrentObjectType and CurrentObjectName properties return the type and name of the underlying object.
  • If the user chooses a pop-up form, the CurrentObjectType and CurrentObjectName properties refer to the pop-up form itself, not the form from which it was opened.
  • If the active object is the Database window, the CurrentObjectType and CurrentObjectName properties return the item selected in the Database window.
  • If no object is selected, the CurrentObjectType property returns True (-1), and the CurrentObjectName property returns a zero-length string (" ").
  • If the current state is ambiguous (the active object isn’t a table, query, form, report, macro, or module) — for example, if a dialog box has the focus — the CurrentObjectType property returns True, and the CurrentObjectName property returns the dialog box name.

You can use these properties with the SysCmd function to determine the active object and its state (for example, if the object is open, new, or has been changed but not saved).

See Also

Application Object, SysCmd Function.

Example

The following example uses the CurrentObjectType and CurrentObjectName properties with the SysCmd function to determine if the active object is the Products form and if this form is open and has been changed but not saved. If these conditions are true, the form is saved and then closed.

Sub CheckProducts()
    Dim intState As Integer
    Dim intCurrentType As Integer
    Dim strCurrentName As String
    intCurrentType = Application.CurrentObjectType
    strCurrentName = Application.CurrentObjectName
    If intCurrentType = acForm And strCurrentName = "Products" Then
        intState = SysCmd(acSysCmdGetObjectState, intCurrentType, _
                strCurrentName)
        ' Products form changed but not saved.
        If intState = acObjStateDirty + acObjStateOpen Then
            ' Close Products form and save changes.
            DoCmd.Close intCurrentType, strCurrentName, acYes
        End If
    End IfSub


CurrentRecord Property

Applies To

Form.

Description

Use the CurrentRecord property to identify the current record in the recordset being viewed on a form.

Setting

Microsoft Access sets this property to a Long Integer value that represents the current record number displayed on a form.

The CurrentRecord property is read-only in Form view and Datasheet view. It is not available in Design view. This property is available only in Visual Basic.

Remarks

The value specified by this property corresponds to the value shown in the record number box found in the lower-left corner of the form.

See Also

NewRecord Property.

Example

The following example shows how to use the CurrentRecord property to determine the record number of the current record being displayed. The general-purpose CurrentFormRecord procedure assigns the value of the current record to the variable recordnum.

Sub CurrentFormRecord(frm As Form)
    Dim recordnum As Long
    recordnum = frm.CurrentRecordSub


CurrentSectionLeft, CurrentSection Top Properties

Description

You can use these properties to determine the distance in twips from the top edge and left side of the current section to the top edge and left side of the form.

Setting

  • CurrentSectionLeft — An Integer value that represents the distance from the left side of the current section to the left edge of the form.
  • CurrentSectionTop — An Integer value that represents the distance from the top edge of the current section from the top edge of the form.

These property settings are read-only and are available only in a macro or Visual Basic.

Remarks

The CurrentSectionLeft and CurrentSectionTop property settings change whenever a user scrolls through a form.

In single form view, if the user scrolls above the upper-left corner of the section or to the right of the left edge of the form, the property settings are negative values. If a section isn’t visible in the Form window, these properties are set to Null.

In continuous form view, if a section isn’t visible the CurrentSectionTop property is equal to the InsideHeight property of the form.

These properties are useful for finding the position of detail sections displayed in Form view as continuous forms. Each detail section has a different CurrentSectionTop property setting, depending on the section’s position on the form.

See Also

InsideHeight, InsideWidth Properties; Left, Top Properties; WindowHeight, WindowWidth Properties.

Example

The following example displays the CurrentSectionLeft and CurrentSectionTop property settings for a control on a continuous form. Whenever the user moves to a new record, the property settings for the current section are displayed in the lblStatus label in the form’s header.

Private Sub Form_Current()
    Dim intCurTop As Integer, intCurLeft As Integer
    intCurTop = Me.CurrentSectionTop
    intCurLeft = Me.CurrentSectionLeft
    Me!lblStatus.Caption = intCurLeft & " , " & intCurTopSub


CurrentUser Function

Description

You can use the CurrentUser function to return the name of the current user of the database.

For example, use the CurrentUser function in a procedure that keeps track of the users who modify the database.

Syntax

CurrentUser

Remarks

The CurrentUser function returns a string that contains the name of the current user account.

If you haven’t established a secure workgroup, the CurrentUser function returns the name of the default user account, Admin. The Admin user account gives the user full permissions to all database objects.

If you have enabled workgroup security, then the CurrentUser function returns the name of the current user account. User accounts other than Admin may specify permissions that restrict the users’ access to database objects.

The following example obtains the name of the current user and displays it in a dialog box.

MsgBox("The current user is: " & CurrentUser)


CurrentView Property

Applies To

Form.

Description

You can use the CurrentView property to determine how a form is currently displayed. For example, you might need to know whether a form is in Form view or Datasheet view before you attempt to place controls on the form using Visual Basic.

Settings

The CurrentView property uses the following settings.

Setting | Description
0 | The form is displayed in Design view.
1 | The form is displayed in Form view.
2 | The form is displayed in Datasheet view.

This property is available only in a macro or Visual Basic and is read-only in all views.

Remarks

You can also use this property to perform different tasks depending on the view. For example, a menu command running code can determine which view the form is displayed in and perform one task if the form is displayed in Form view or another task if it’s displayed in Datasheet view.

See Also

DefaultView, ViewsAllowed Properties.

Example

The following example determines whether a form is in Form or Datasheet view. If it’s in Form view, a message is displayed in a text box on the form; if it’s in Datasheet view, the same message is displayed in a message box.

Function GetCurrentView(frm As Form, strDisplayMsg As String)
    Const conFormView = 1
    Const conDataSheet = 2
    Dim intView As Integer
    intView = frm.CurrentView
    Select Case intView
        Case conFormView
            frm!MessageTextBox.SetFocus        ' Set focus to text box.
            ' Display message in text box.
            frm!MessageTextBox = strDisplayMsg
        Case conDataSheet
            ' Display message in message box.
            MsgBox strDisplayMsg
    End SelectFunction


CurrentX, CurrentY Properties

Applies To

Report.

Description

You can use the CurrentX and CurrentY properties to specify the horizontal and vertical coordinates for the starting position of the next printing and drawing method on a report. For example, you use these properties to determine where the center point of a circle is drawn on a report section.

Setting

  • CurrentX — A Single data type value used in a numeric expression to set the horizontal coordinate of the next printing drawing method.
  • CurrentY — A Single data type value used in a numeric expression to set the vertical coordinate of the next printing drawing method.

The coordinates are measured from the upper-left corner of the report section that contains the reference to the CurrentX or CurrentY property. The CurrentX property setting is 0 at the section’s left edge, and the CurrentY property setting is 0 at its top edge.

You can set the CurrentX and CurrentY properties only in a macro or a Visual Basic event procedure specified by the OnPrint property setting of a report section.

Remarks

Use the ScaleMode property to define the unit of measure, such as points, pixels, characters, inches, millimeters, or centimeters, that the coordinates will be based on.

When you use the following graphics methods, the CurrentX and CurrentY property settings are changed as indicated.

Method | Sets CurrentX, CurrentY to
Circle | The center of the object.
Line | The end point of the line (the x2, y2 coordinates).
Print | The next print position.

See Also

Circle Method; DrawMode Property; DrawStyle Property; Event Properties; Left, Top Properties; Line Method; Print Event; PrintOut Method; Scale Method; ScaleHeight, ScaleWidth Properties; ScaleLeft, ScaleTop Properties; ScaleMode Property.


CVar Function

Description

Converts an expression to a Variant.

Syntax

CVar(expression)

The expression argument is any valid numeric or string expression.

Remarks

In general, you can document your code using the data type conversion functions to show that the result of some operation should be expressed as a particular data type rather than the default data type. For example, use CVar to force the result to be expressed as a Variant.

See Also

Data Type Summary.

Example

This example uses the CVar function to convert an expression to a Variant.

MyInt = 4534                                ' MyInt is an Integer.= CVar(MyInt & "000")                ' MyVar contains the string
                                        ' 4534000.


CVErr Function

Description

Returns a Variant of subtype Error containing an error number specified by the user.

Syntax

CVErr(errornumber)

The errornumber argument is any valid error number.

Remarks

Use the CVErr function to create user-defined errors in user-created procedures. For example, if you create a function that accepts several arguments and normally returns a string, you can have your function evaluate the input arguments to ensure they are within acceptable range. If they are not, it is likely that your function will not return what you expect. In this event, CVErr allows you to return an error number that tells you what action to take.

Note that implicit conversion of an Error is not allowed. For example, you can’t directly assign the return value of CVErr to a non-Variant variable. However, you can perform an explicit conversion (using CInt, CDbl, and so on) of the value returned by CVErr and assign that to a variable of the appropriate data type.

See Also

Data Type Summary, IsError Function.

Example

This example uses the CVErr function to return a Variant whose VarType is vbError (10). The user-defined function CalculateDouble returns an error if the argument passed to it isn’t a number. You can use CVErr to return user-defined errors from user-defined procedures or to defer handling of a run-time error. Use the IsError function to test if the value represents an error.

' Call CalculateDouble with an error-producing argument.Test()
    Debug.Print CalculateDouble("345.45robert")Sub
' Define CalculateDouble Function procedure.CalculateDouble(Number)
    If IsNumeric(Number) Then
        CalculateDouble = Number * 2          ' Return result.
    Else
        CalculateDouble = CVErr(2001)      ' Return a user-defined error
    End If                                  ' number.Function


Cycle Property

Applies To

Form.

Description

You can use the Cycle property to specify what happens when you press the TAB key when the focus is in the last control on a bound form.

Setting

The Cycle property uses the following settings.

Setting | Description | Visual Basic
All Records | (Default) Pressing the TAB key from the last control on a form moves the focus to the first field in the next record in the underlying source of data. | 0
Current Record | Pressing the TAB key from the last control on a form moves the focus to the first control in the tab order on the form in the same record. | 1
Current Page | Pressing the TAB key from the last control on a page moves the focus back to the first control in the tab order on the page. | 2

You can set the Cycle property in the form’s property sheet, a macro, or using Visual Basic.

You can set the Cycle property in any view.

Remarks

When you press the TAB key on a form the focus moves through the controls on the form according to the control’s place in the tab order.

You can set the Cycle property to All Records for forms designed for data entry. This allows the user to move to a new record by pressing the TAB key.


Data Type Summary

Description

The following table shows the supported data types, including their storage sizes and ranges.

Data type | Storage size | Range
Byte | 1 byte | 0 to 255
Boolean | 2 bytes | True or False
Integer | 2 bytes | -32,768 to 32,767
Long (long integer) | 4 bytes | -2,147,483,648 to 2,147,483,647
Single (single-precision floating-point) | 4 bytes | -3.402823E38 to -1.401298E-45 for negative values; 1.401298E-45 to 3.402823E38 for positive values
Double (double-precision floating-point) | 8 bytes | -1.79769313486232E308 to .94065645841247E-324 for negative values; 4.94065645841247E-324 to 1.79769313486232E308 for positive values
Currency (scaled integer) | 8 bytes | -922,337,203,685,477.5808 to 922,337,203,685,477.5807
Date | 8 bytes | January 1, 100 to December 31, 9999
Object | 4 bytes | Any Object reference
String (variable-length) | 10 bytes + string length | 0 to approximately 2 billion (approximately 65,400 for Microsoft Windows version 3.1 and earlier)
String (fixed-length) | Length of string | 1 to approximately 65,400
Variant (with numbers) | 16 bytes | Any numeric value up to the range of a Double
Variant (with characters) | 22 bytes + string length | Same range as for variable-length String
User-defined (using Type) | Number required by elements | The range of each element is the same as the range of its data type

Note Arrays of any data type require 20 bytes of memory plus four bytes for each array dimension plus the number of bytes occupied by the data itself. The memory occupied by the data can be calculated by multiplying the number of data elements by the size of each element. For example, the data in a single-dimension array consisting of four Integer data elements of two bytes each occupies eight bytes. The eight bytes the data requires plus the 24 bytes of overhead brings the total memory requirement for the array to 32 bytes.

A Variant containing an array requires 12 bytes more than the array alone.

See Also

Boolean Data Type, Byte Data Type, Currency Data Type, Date Data Type, Def type Statements, Double Data Type, Integer Data Type, Long Data Type, Object Data Type, Single Data Type, String Data Type, Type Statement, User-Defined Data Type, Variant Data Type.


DataEntry Property

Applies To

Form.

Description

You can use the DataEntry property to specify whether a bound form opens to allow data entry only.

Setting

The DataEntry property uses the following settings.

Setting | Description | Visual Basic
Yes | The form opens showing only a blank record. | True (-1)
No | (Default) The form opens showing existing records. | False (0)

You can set the DataEntry property in a form’s property sheet, a macro, or using Visual Basic.

This property can be set in any view.

Remarks

The DataEntry property is effective only when a form has a valid RecordSource property setting and the AllowAdditions property is set to Yes.

Setting the DataEntry property to Yes using Visual Basic has the same effect as clicking Data Entry on the Records menu. Setting it to No using Visual Basic is equivalent to clicking Remove Filter/Sort on the Records menu.

See Also

AllowAdditions Property; AllowDeletions Property; AllowEdits Property; Enabled, Locked Properties; RecordsetType Property.


DatasheetCellsEffect Property

Applies To

Form, Query, Table.

Description

You can use the DatasheetCellsEffect property to specify whether special effects are applied to cells in a datasheet.

Note The DatasheetCellsEffect property applies only to objects in Datasheet view.

Setting

The DatasheetCellsEffect property uses the following settings.

Setting | Description | Visual Basic | Value
Flat | (Default) No special effects are applied to the cells in the datasheet. | acEffectNormal | 0
Raised | Cells in the datasheet appear raised. | acEffectRaised | 1
Sunken | Cells in the datasheet appear sunken. | acEffectSunken | 2

You can set this property using the Formatting toolbar (in Datasheet view), a macro, or Visual Basic.

You can also set this property by choosing Cells from the Format menu.

You can set the default DatasheetCellsEffect property using the Datasheet tab of the Options dialog on the Tools menu.

Remarks

The DatasheetCellsEffect property applies the selected effect to the entire datasheet.

When the DatasheetCellsEffect property is set to Raised or Sunken, grid lines will be visible on the datasheet regardless of the DatasheetGridLinesBehavior property setting.

See Also

DatasheetGridLinesBehavior Property, DatasheetGridLinesColor Property.


Database Properties

Applies To

Database Object.

Description

The Database properties allow you to provide additional information about your database. To view the Database properties click the Database Properties command on the File menu.

Setting

You can set these properties by entering information in the Summary or Custom tabs in the Database properties dialog box or using Visual Basic.

In Visual Basic, if a Database property has not already been set in the Database Properties dialog box, you must create the property using the CreateProperty method and append it to the Properties collection of a Document object. You set properties in the Summary tab using the SummaryInfo Document in the Documents collection. You set properties in the Custom tab using the UserDefined Document in the Documents collection. You must supply a name, data type, and default value for a custom property before you can add it to your database.

Note You can only enter or edit the properties that appear under the Summary or Custom tabs. The other Database properties are read-only.

Remarks

The Database properties appear in the Database Properties dialog box under the following tabs:

General

This is the same information that is displayed when you right-click on a filename using the Windows Explorer and choose the Properties command. The only difference is that when viewed in Microsoft Access, the Attributes settings are read-only.

Summary

Choose the Summary tab to add summary information about your database. The information you enter is added to the SummaryInfo Document in the Documents collection. This information is similar to the summary information you can provide in other Microsoft Office applications. Summary information allows the user to better identify a database both from within Microsoft Access and to outside programs such as the Windows 95 FindFile program.

Statistics

Choose the Statistics tab to view information about your database. This information includes the date and time the active database was created, the last date and time it was modified, accessed, and printed.

Contents

Choose the Contents tab to see a list of the names of the objects contained in your database.

Custom

Choose the Custom tab to view, add, or modify custom database properties. The custom properties you enter become properties of the UserDefined Document in the Documents collection.

Example

In the following example you can set or create a custom user-defined property that will appear on the Custom tab of the Database Properties dialog box. For example, you could call the SetCustomProperty function to add a new property called UserName to the UserDefined Document in the database. The arguments passed to the SetCustomProperty function are those required to execute the CreateProperty method.

Dim strName As String, strValue As String
' Set property name variable.= "LastUserName"
' Set property value variable.= InputBox("Please enter your full name")SetCustomProperty(strName, dbText, strValue) = True Then
    ' Property was successfully set.
    ' Error occurred trying to set property.If
SetCustomProperty(strPropName As String, intPropType _
        As Integer, strPropValue As String) As Integer
    Dim dbs As Database, cnt As Container
    Dim doc As Document, prp As Property
    Const conPropertyNotFound = 3270           ' Property not found error.
    Set dbs = CurrentDb()                   ' Define Database object.
    Set cnt = dbs.Containers!Databases       ' Define Container object.
    Set doc = cnt.Documents!UserDefined       ' Define Document object.
    On Error GoTo SetCustom_Err
    doc.Properties.Refresh
    ' Set custom property name. If an error occurs here it means the
    ' property does not exist and needs to be created and appended
    ' to the properties collection of the document object.
    Set prp = doc.Properties(strPropName)
    prp = strPropValue                       ' Set custom property value.
    SetCustomProperty = True_Bye:
    Exit Function_Err:
    If Err = conPropertyNotFound Then
        Set prp = doc.CreateProperty(strPropName, _
            intPropType, strPropValue)
        doc.Properties.Append prp           ' Append to collection.
        Resume Next
    Else                                       ' Unknown error.
        SetCustomProperty = False
        Resume SetCustom_Bye
    End IfFunction

The next example demonstrates how to display information from the Summary tab of the Database Properties dialog box. The application title, subject, and author are displayed in text box controls on a form. In this example, if the property has not already been set then “None” is returned from the procedure. If an unknown error occurs then a zero length string (" ") is returned.

Private Sub Form_Open(Cancel As Integer)
    Dim strTitle As String, strSubject As String, strAuthor As String
    strTitle = "Title"
    strSubject = "Subject"
    strAuthor = "Author"

    Me!txtTitle = GetSummaryInfo(strTitle)
    Me!txtSubject = GetSummaryInfo(strSubject)
    Me!txtAuthor = GetSummaryInfo(strAuthor)
Sub
GetSummaryInfo(strPropName As String) As String
    Dim dbs As Database, cnt As Container
    Dim doc As Document, prp As Property
    Const conPropertyNotFound = 3270            ' Property not found error.
    On Error GoTo GetSummary_Err
    Set dbs = CurrentDb()                    ' Define Database object.
    Set cnt = dbs.Containers!Databases        ' Define Container object.
    Set doc = cnt.Documents!SummaryInfo        ' Define Document object.
    doc.Properties.Refresh
    GetSummaryInfo = doc.Properties(strPropName)_Bye:
    Exit Function_Err:
    If Err = conPropertyNotFound Then
        Set prp = doc.CreateProperty(strPropName, dbText, "None")
        doc.Properties.Append prp            ' Append to collection.
        Resume
    Else                                        ' Unknown error.
        GetSummaryInfo = ""
        Resume GetSummary_Bye
    End IfFunction


DatasheetFontHeight Property

See DatasheetFontName, DatasheetFontHeight Properties.


DatasheetFontItalic, DatasheetFontUnderline Properties

Applies To

Form, Query, Table.

Description

You can use the DatasheetFontItalic and DatasheetFontUnderline properties to specify an italic or underlined appearance for field names and data in Datasheet view.

Note The DatasheetFontItalic and DatasheetFontUnderline properties apply to all fields in Datasheet view and to form controls when the form is in Datasheet view.

Setting

You can set these properties by clicking the Italic or Underline button on the Datasheet Formatting toolbar.

You can also set these properties by clicking Font on the Format menu in Datasheet view.

In Visual Basic, the DatasheetFontItalic property uses the following settings.

Setting | Description
True | The text is italic.
False | (Default) The text isn’t italic.

In Visual Basic, the DatasheetFontUnderline property uses the following settings.

Setting | Description
True | The text is underlined.
False | (Default) The text isn’t underlined.

In Visual Basic, these properties have a data type of Boolean.

See Also

DatasheetFontName, DatasheetFontHeight Properties; DatasheetFontWeight Property.

Example

The following example displays the data and field names in Datasheet view of the Products form as italic and underlined.

Forms![Products].DatasheetFontItalic = True![Products].DatasheetFontUnderline = True

The next example displays the data and field names in Datasheet view of the Products table as italic and underlined.

To set the DatasheetFontItalic and DatasheetFontUnderline properties, the example uses the SetTableProperty procedure, which is in the database’s standard module.

Dim db As Database, tdProducts As TableDefdb = CurrentDbtdProducts = db![Products]tdProducts, "DatasheetFontItalic", dbBoolean, TruetdProducts, "DatasheetFontUnderline", dbBoolean, True
SetTableProperty (TableObj As TableDef, strPropertyName As String, _
        intPropertyType As Integer, varPropertyValue As Variant)
    ' Set Microsoft Access-defined table property without causing
    ' nonrecoverable run-time error.
    Const conErrPropertyNotFound = 3270
    Dim proProperty As Property
    On Error Resume Next                ' Don't trap errors.
    TableObj.Properties(strPropertyName) = varPropertyValue
    If Err <> 0 Then                    ' Error occurred when value set.
        If Err <> conErrPropertyNotFound Then
            On Error GoTo 0
            MsgBox "Couldn't set property '" & strPropertyName _
                & "' on table '" & TableObj.name & "'", 48, _
                & "SetTableProperty"
        Else
            On Error GoTo 0
            Set proProperty = TableObj.CreateProperty(strPropertyName, _
                intPropertyType, varPropertyValue)
            TableObj.Properties.Append proProperty
        End If
    End If
    TableObj.Properties.RefreshSub


DatasheetFontName, DatasheetFontHeight Properties

Applies To

Form, Query, Table.

Description

You can use the DatasheetFontName and DatasheetFontHeight properties to specify the font and the font point size used to display field names and data.

Note The DatasheetFontName and DatasheetFontHeight properties apply to all fields in Datasheet view and to form controls when the form is in Datasheet view.

Setting

  • DatasheetFontName — In Visual Basic, you set this property using a string expression equal to the name of the font.
  • DatasheetFontHeight — In Visual Basic, this property setting is an Integer value between 1 and 127 representing the font height in points.

You can set these properties by choosing the font name or font height on the Datasheet Formatting toolbar.

You can also set these properties by clicking Font on the Format menu in Datasheet view.

Remarks

For the DatasheetFontName property, the font names you can specify depend on the fonts installed on your system and for your printer. If you specify a font that your system can’t display or that isn’t installed, Microsoft Windows will substitute a similar font.

For the DatasheetFontHeight property, the point size you specify must be valid for the font specified by the DatasheetFontName property. For example, MS Sans Serif is available in point sizes 8, 10, 12, 14, 18, and 24.

See Also

DatasheetFontItalic, DatasheetFontUnderline Properties; DatasheetFontWeight Property.

Example

The following example sets the font to MS Serif, the point size to 10, and the font weight to medium (500) in Datasheet view of the Products table.

To set these properties, the example uses the SetTableProperty procedure, which is shown in the DatasheetFontItalic, DatasheetFontUnderline properties example.

Dim db As Database, tdProducts As TableDefdb = CurrentDbtdProducts = db![Products]tdProducts, "DatasheetFontName", vbString, "MS Serif"tdProducts, "DatasheetFontHeight", vbInteger, 10tdProducts, "DatasheetFontWeight", vbInteger, 500

The next example makes the same changes as the preceding example in Datasheet view of the open Products form.

Forms![Products].DatasheetFontName = "MS Serif"![Products].DatasheetFontHeight = 10![Products].DatasheetFontWeight = 500


DatasheetFontUnderline Property

See DatasheetFontItalic, DatasheetFontUnderline Properties.


DatasheetFontWeight Property

Applies To

Form, Query, Table.

Description

You can use the DatasheetFontWeight property to specify the line width of the font used to display and print characters for field names and data in Datasheet view.

Note The DatasheetFontWeight property applies to all fields in Datasheet view and to form controls when the form is in Datasheet view.

Setting

In Visual Basic, the DatasheetFontWeight property setting uses the following Integer values.

Setting | Description
100 | Thin
200 | Extra Light
300 | Light
400 | (Default) Normal
500 | Medium
600 | Semi-bold
700 | Bold
800 | Extra Bold
900 | Heavy

You can also set Normal and Bold for this property by clicking Font on the Format menu in Datasheet view. In the Font dialog box, the only available font weight settings are Regular (identical to Normal) and Bold.

Another method of setting only the Regular and Bold properties is to use the Datasheet Formatting toolbar.

See Also

DatasheetFontItalic, DatasheetFontUnderline Properties; DatasheetFontName, DatasheetFontHeight Properties.

Example

See the DatasheetFontName, DatasheetFontHeight properties example.


DatasheetGridLinesBehavior Property

Applies To

Form, Query, Table.

Description

You can use the DatasheetGridLinesBehavior property to specify which grid lines will appear in Datasheet view.

Note This DatasheetGridLinesBehavior property applies only to objects in Datasheet view.

Setting

The DatasheetGridLinesBehavior property uses the following settings.

Setting | Description | Visual Basic | Value
Both | (Default) Horizontal and vertical grid lines are displayed. | acGridLinesBoth | 0
Horizontal | Only horizontal grid lines are displayed. | acGridLinesHoriz | 1
Vertical | Only vertical grid lines are displayed. | acGridLinesVert | 2
None | No grid lines are displayed. | acGridLinesNone | 3

You can set this property using the Formatting toolbar (in Datasheet view), a macro, or Visual Basic.

You can also set this property by choosing Cells from the Format menu.

You can set the default DatasheetGridLinesBehavior property using the Datasheet tab of the Options dialog on the Tools menu.

Remarks

Changes to the DatasheetGridLinesBehavior property will only be visible if the DatasheetCellsEffect property is set to Flat.

See Also

DatasheetCellsEffect Property, DatasheetGridLinesColor Property.


DatasheetGridLinesColor Property

Applies To

Form, Query, Table.

Description

You can use the DatasheetGridLinesColor property to specify the color of grid lines in a datasheet.

Note The DatasheetGridLinesColor property applies only to objects in Datasheet view.

Setting

The DatasheetGridLinesColor property setting is a numeric expression using a Long Integer data type. In Visual Basic, you can also use the RGB or QBColor functions to set this property.

You can set this property using the Formatting toolbar (in Datasheet view), a macro, or Visual Basic.

You can also set this property by choosing Cells from the Format menu.

You can set the default DatasheetGridLinesColor property using the Datasheet tab of the Options dialog on the Tools menu.

Remarks

This property setting affects the grid line color for the entire datasheet. It’s not possible to set the grid line color of individual cells in Datasheet view.

See Also

DatasheetCellsEffect Property, DatasheetGridLinesBehavior Property.


DataType Property

Applies To

Table Fields.

Description

You can use the DataType property to specify the type of data stored in a table field. Each field can store data only of a single data type.

Setting

The DataType property uses the following settings.

Setting | Type of data | Size
Text | (Default) Text or combinations of text and numbers, as well as numbers that don’t require calculations, such as phone numbers. | Up to 255 characters or the length set by the FieldSize property, whichever is less. Microsoft Access does not reserve space for unused portions of a text field.
Memo | Lengthy text or combinations of text and numbers. | Up to 64,000 characters.
Number | Numeric data used in mathematical calculations. For more information on how to set the specific Number type, see the FieldSize property topic. | 1, 2, 4, or 8 bytes (16 bytes for ReplicationID only).
Date/Time | Date and time values for the years 100 through 9999. | 8 bytes.
Currency | Currency values and numeric data used in mathematical calculations involving data with one to four decimal places. Accurate to 15 digits on the left side of the decimal separator. | 8 bytes.
AutoNumber | A unique sequential (incremented by 1) number or random number assigned by Microsoft Access whenever a new record is added to a table. AutoNumber fields can’t be updated. For more information, see the NewValues property topic. | 4 bytes (16 bytes for ReplicationID only).
Yes/No | Yes and No values and fields that contain only one of two values (True/False, On/Off). | 1 bit.

Setting | Type of data | Size
OLE Object | An object (such as a Microsoft Excel spreadsheet, a Microsoft Word document, graphics, sounds, or other binary data) linked to or embedded in a Microsoft Access table. | Up to 1 gigabyte (limited by available disk space)
Lookup Wizard... | Creates a field that allows you to choose a value from another table or from a list of values using a combo box. Choosing this option in the Data Type list starts the Lookup Wizard to define the data type. | The same size as the primary key field used to perform the lookup, typically 4 bytes.

You can set this property only in the upper portion of table Design view.

In Visual Basic, use the Data Access Objects Type property to read and set an object’s data type.

Remarks

Memo fields and OLE Object fields can’t be indexed.

Tip Use the Currency data type for a field requiring many calculations involving data with one to four decimal places. Single and Double data type fields require floating-point calculation. The Currency data type uses a faster fixed-point calculation.

Caution Changing a field’s data type after you enter data in a table causes a potentially lengthy process of data conversion when you save the table. If the data type in a field conflicts with a changed DataType property setting, you may lose some data.

Set the Format property to specify a custom or one of the predefined display formats for Number, Date/Time, Currency, and Yes/No data types.

See Also

FieldSize Property, Format Property, InputMask Property, NewValues Property.


Date Data Type

Description

Date variables are stored as IEEE 64-bit (8-byte) floating-point numbers that represent dates ranging from 1 January 100 to 31 December 9999 and times from 0:00:00 to 23:59:59. Any recognizable literal date values can be assigned to Date variables. Literal dates must be enclosed within number sign characters (#), for example, #January 1, 1993# or #1 Jan 93#.

Date variables display dates according to the short date format recognized by your computer. Times display according to the time format (either 12- or 24-hour) recognized by your computer.

When other numeric data types are converted to Date, values to the left of the decimal represent date information while values to the right of the decimal represent time. Midnight is 0 and midday is .5. Negative whole numbers represent dates before 30 December 1899.

See Also

CDate Function, Data Type Summary, Def type Statements, Double Data Type, Variant Data Type.


Date Function

Description

Returns the current system date.

Syntax

Date

Remarks

To set the system date, use the Date statement.

See Also

CDate Function, Date Statement, Format Function, Now Function, Time Function, Time Statement.

Specifics (Microsoft Access)

You can insert the current date on a form or report by clicking Date And Time on the Insert menu. This command creates a text box on a form or report and sets the ControlSource property of the text box to the expression =Date(). The command is available only in form Design view and report Design view.

You can also use the Date function in a query expression or in a macro. However, you must include the parentheses after the function when you use it anywhere other than a Visual Basic module, as in the expression Date().

Example

This example uses the Date function to return the current system date.

MyDate = Date                ' MyDate contains the current system date.

You can use the Date function in a calculated control by setting the ControlSource property of the control as in the following example.

= Date()

You can also use the Date function to set criteria for a query. For example, if you have an Orders table that contains an OrderDate field, you can create a query on the Orders table to return all records that have an OrderDate between 4-1-95 and today’s date. Enter the following in the Criteria cell under the OrderDate field.

Between #4-1-95# and Date()


Date Statement

Description

Sets the current system date.

Syntax

Date = date

For MS-DOS® computers, the date argument must be a date from January 1, 1980 through December 31, 2099, or an error occurs. For Microsoft Windows NT™ computers, date must be a date from January 1, 1980 through December 31, 2079.

Remarks

If you use the Date statement to set the date on computers using versions of MS-DOS earlier than version 3.3, the change remains in effect only until you change it again or turn off your computer. Many computers have a battery-powered CMOS RAM that retains date and time information when the computer is turned off. However, to permanently change the date on computers running earlier versions of MS-DOS, you may have to use your Setup disk or perform some equivalent action. Refer to the documentation for your particular system.

See Also

Date Function, Time Function, Time Statement.

Example

This example uses the Date statement to set the computer system date. In the development environment, the date literal is displayed in short date format using the locale settings of your code.

MyDate = #February 12, 1985#                    ' Assign a date.= MyDate                                ' Change system date.


DateAdd Function

Description

Returns a Variant containing a date to which a specified time interval has been added.

Syntax

DateAdd(interval, number, date)

The DateAdd function syntax has these named arguments:

Part | Description
interval | String expression, as described in Settings, that is the interval of time you want to add.
number | Numeric expression that is the number of intervals you want to add. It can be positive (to get dates in the future) or negative (to get dates in the past).
date | Date being added to, or the name of a Variant containing a valid date.

Settings

The interval argument has these settings:

Setting | Description
yyyy | Year
q | Quarter
m | Month
y | Day of year
d | Day
w | Weekday
ww | Week
h | Hour
n | Minute
s | Second

Remarks

You can use the DateAdd function to add or subtract a specified time interval from a date. For example, you could use DateAdd to calculate a date 30 days from today or a time that is 45 minutes from now.

If you want to add days to date, you can use Day of Year (“y”), Day (“d”), or Weekday (“w”).

The DateAdd function won’t return an invalid date. The following example adds one month to January 31:

DateAdd("m", 1, "31-Jan-95")

In this case, DateAdd returns 28-Feb-95, not 31-Feb-95. If date is 31-Jan-96, it returns 29-Feb-96 because 1996 is a leap year.

If the calculated date would precede the year 100 (that is, you subtract more years than are in date), an error occurs.

If number isn’t a Long value, it is rounded to the nearest whole number before being evaluated.

See Also

DateDiff Function, DatePart Function, Day Function, Format Function, Now Function, Weekday Function, Year Function.

Example

This example takes a date and, using the DateAdd function, displays a corresponding date a specified number of months in the future.

Dim FirstDate As Date                ' Declare variables.IntervalType As StringNumber As IntegerMsg= "m"                    ' "m" specifies months as interval.= InputBox("Enter a date")= InputBox("Enter number of months to add")= "New date: " & DateAdd(IntervalType, Number, FirstDate)Msg

The following example uses DateAdd to find the number of days in a month. The function DaysInMonth takes an argument of type Date.

Function DaysInMonth(dteAny As Date) As Integer
    Dim dteNextMonth, dteEndOfMonth
    dteNextMonth = DateAdd("m", 1, dteAny)
    dteEndOfMonth = dteNextMonth - DatePart("d", dteNextMonth)
    DaysInMonth = DatePart("d", dteEndOfMonth)Function

The next example shows how you can create a calculated control using the DateAdd function to display the date by which a particular order must be shipped — in this case, thirty days after the OrderDate. Suppose you have a form based on an Orders table, with a field called OrderDate. You can create another text box on the form to display the shipping date by setting the ControlSource property of this text box as in the following example.

= DateAdd("d", 30, [OrderDate])


DateDiff Function

Description

Returns the number of time intervals between two specified dates.

Syntax

DateDiff(interval, date1, date2[, firstdayofweek[, firstweekofyear]])

The DateDiff function syntax has these named arguments:

Part | Description
interval | String expression, as described in Settings, that is the interval of time you use to calculate the difference between date1 and date2.
date1, date2 | Two dates you want to use in the calculation.
firstdayofweek | A constant, as described in Settings, that specifies the first day of the week. If not specified, Sunday is assumed.
firstweekofyear | A constant, as described in Settings, that specifies the first week of the year. If not specified, the first week is assumed to be the week in which January 1 occurs.

Settings

The interval argument has these settings:

interval | Time interval
yyyy | Year
q | Quarter
m | Month
y | Day of year
d | Day
w | Weekday
ww | Week
h | Hour
n | Minute
s | Second

The firstdayofweek argument has these settings:

Constant | Value | Description
vbUseSystem | 0 | Use application setting if one exists; otherwise use NLS API setting.
vbSunday | 1 | Sunday (default)
vbMonday | 2 | Monday
vbTuesday | 3 | Tuesday
vbWednesday | 4 | Wednesday
vbThursday | 5 | Thursday
vbFriday | 6 | Friday
vbSaturday | 7 | Saturday

The firstweekofyear argument has these settings:

Constant | Value | Description
vbUseSystem | 0 | Use application setting if one exists; otherwise use NLS API setting.
vbFirstJan1 | 1 | Start with week in which January 1 occurs (default).
vbFirstFourDays | 2 | Start with the first week that has at least four days in the new year.
vbFirstFullWeek | 3 | Start with first full week of the year.

Remarks

You can use the DateDiff function to determine how many specified time intervals exist between two dates. For example, you might use DateDiff to calculate the number of days between two dates, or the number of weeks between today and the end of the year.

If you want to know the number of days between date1 and date2, you can use either Day of Year (“y”) or Day (“d”).

When interval is Weekday (“w”), DateDiff returns the number of weeks between the two dates. If date1 falls on a Monday, DateDiff counts the number of Mondays until date2. It counts date2 but not date1. If interval is Week (“ww”), however, the DateDiff function returns the number of calendar weeks between the two dates. It counts the number of Sundays between date1 and date2. DateDiff counts date2 if it falls on a Sunday; but it doesn’t count date1, even if it does fall on a Sunday.

If date1 refers to a later point in time than date2, the DateDiff function returns a negative number.

The firstdayofweek argument affects calculations that use the “w” and “ww” interval symbols.

If date is a date literal (a date enclosed by number signs (#)), the year, if specified, becomes a permanent part of that date. However, if date is enclosed in double quotation marks (""), and you omit the year, the current year is inserted in your code each time the date expression is evaluated. This makes it possible to write code that can be used in different years.

See Also

DateAdd Function, DatePart Function, Day Function, Format Function, Now Function, Weekday Function, Year Function.

Example

This example uses the DateDiff function to display the number of days between a given date and today.

Dim TheDate As Date                        ' Declare variables.Msg= InputBox("Enter a date")= "Days from today: " & DateDiff("d", Now, TheDate)Msg

The following examples use the DateDiff function to calculate the number of calendar weeks between the first of the year and today, and the number of days since February 1, 1995 respectively.

Debug.Print DateDiff("ww", "1-1", Now()).Print DateDiff("y", #1-Feb-1995#, Now())

The next example shows how to use the DateDiff function in a query expression. Suppose you have an Orders table that contains an OrderDate field and a ShippedDate field. You can create a calculated field in a query to display the time elapsed between an order date and a shipped date for each order. In the Query window, create a new query by adding the Orders table and dragging the OrderID field to the query design grid. In an empty Field cell, enter the following to create a calculated field.

DaysElapsed: DateDiff("y", [OrderDate], [ShippedDate])


DateGrouping Property

Applies To

Report.

Description

You can use the DateGrouping property to specify how you want to group dates in a report. For example, if your country’s First Weekday setting is Monday, using the US Defaults setting will cause the week to begin on the incorrect day; if you set a Date/Time field’s GroupOn property to Week, the report will group dates from Sunday to Sunday instead of from Monday to Monday.

Note The DateGrouping property setting applies to the entire report, not to a particular group in the report.

Setting

The DateGrouping property uses the following settings.

Setting | Description | Visual Basic
US Defaults | Microsoft Access uses the default U.S. settings for First Weekday (Sunday) and First Week (starts on Jan 1). | 0
Use System Settings | (Default) Microsoft Access uses settings based on the locale selected in the Regional Settings section of the Windows Control Panel. | 1

You can set this property in the report’s property sheet, a macro, or Visual Basic.

You can set the DateGrouping property only in report Design view or in the Open event procedure of a report.

Remarks

The sort order used in a report isn’t affected by the DateGrouping property setting.

See Also

Date Function.

Example

The following example gets the value of the DateGrouping property for a report and assigns it to the intGetDateGrouping variable.

Dim intGetDateGrouping As Integer= Reports![LastYear].DateGrouping\


DatePart Function

Description

Returns a specified part of a given date.

Syntax

DatePart(interval, date[, firstdayofweek[, firstweekofyear]])

The DatePart function syntax has these named arguments:

Part | Description
interval | String expression, as described in Settings, that is the interval of time you want to return.
date | Date that you want to evaluate.
firstdayofweek | A constant, as described in Settings, that specifies the first day of the week. If not specified, Sunday is assumed.
firstweekofyear | A constant, as described in Settings, that specifies the first week of the year. If not specified, the first week is assumed to be the week in which January 1 occurs.

Settings

The interval argument has these settings:

Setting | Description
yyyy | Year
q | Quarter
m | Month
y | Day of year
d | Day
w | Weekday
ww | Week
h | Hour
n | Minute
s | Second

The firstdayofweek argument has these settings:

Constant | Value | Description
vbUseSystem | 0 | Use application setting if one exists; otherwise use NLS API setting.
vbSunday | 1 | Sunday (default)
vbMonday | 2 | Monday
vbTuesday | 3 | Tuesday
vbWednesday | 4 | Wednesday
vbThursday | 5 | Thursday
vbFriday | 6 | Friday
vbSaturday | 7 | Saturday

The firstweekofyear argument has these settings:

Constant | Value | Description
vbUseSystem | 0 | Use application setting if one exists; otherwise use NLS API setting.
vbFirstJan1 | 1 | Start with week in which January 1 occurs (default).
vbFirstFourDays | 2 | Start with the first week that has at least four days in the new year.
vbFirstFullWeek | 3 | Start with first full week of the year.

Remarks

You can use the DatePart function to evaluate a date and return a specific interval of time. For example, you might use DatePart to calculate the day of the week or the current hour.

The firstdayofweek argument affects calculations that use the “w” and “ww” interval symbols.

If date is a date literal (a date enclosed by number signs (#)), the year, if specified, becomes a permanent part of that date. However, if date is enclosed in double quotation marks (""), and you omit the year, the current year is inserted in your code each time the date expression is evaluated. This makes it possible to write code that can be used in different years.

See Also

DateAdd Function, DateDiff Function, Day Function, Format Function, Now Function, Weekday Function, Year Function.

Example

This example takes a date and, using the DatePart function, displays which quarter of the year it falls in.

Dim TheDate As Date                        ' Declare variables.Msg= InputBox("Enter a date:")= "Quarter: " & DatePart("q", TheDate)Msg

The following example uses the DatePart function to determine the day of the week on which an order was placed.

Function DayOfWeek (OrderDate As Date) As Integer
    DayOfWeek = DatePart("w", OrderDate)Function

The next example uses the DatePart function to specify criteria for a select query. For example, suppose you want to create a query based on an Orders table to list all orders placed in the first quarter of 1995. Assuming your Orders table has a OrderID field and an OrderDate field, you can drag the OrderID field to the first cell in the query design grid, and enter the following in the Criteria cell beneath it.

(DatePart("q", [OrderDate]) = 1) and (DatePart("yyyy", [OrderDate]) = 1995)


DateSerial Function

Description

Returns a Date for a specified year, month, and day.

Syntax

DateSerial(year, month, day)

The DateSerial function syntax has these named arguments:

Part | Description
year | Number between 100 and 9999, inclusive, or a numeric expression.
month | Any numeric expression.
day | Any numeric expression.

Remarks

To specify a date, such as December 31, 1991, the range of numbers for each DateSerial argument should be in the normally accepted range for the unit; that is, 1 – 31 for days and 1 – 12 for months. However, you can also specify relative dates for each argument using any numeric expression that represents some number of days, months, or years before or after a certain date.

The following example uses numeric expressions instead of absolute date numbers. Here the DateSerial function returns a date that is the day before the first day (1 - 1) of two months before August (8 - 2) of 10 years before 1990 (1990 - 10); in other words, May 31, 1980.

DateSerial(1990 - 10, 8 - 2, 1 - 1)

For the year argument, values between 0 and 99, inclusive, are interpreted as the years 1900 – 1999. For all other year arguments, use a complete four-digit year (for example, 1800).

When any argument exceeds the normally accepted range for that argument, it increments to the next larger unit as appropriate. For example, if you specify 35 days, it is evaluated as one month and some number of days, depending on where in the year it is applied. However, if any single argument is outside the range -32,768 to 32,767, or if the date specified by the three arguments, either directly or by expression, falls outside the acceptable range of dates, an error occurs.

See Also

Date Function, Date Statement, DateValue Function, Day Function, Month Function, Now Function, TimeSerial Function, TimeValue Function, Weekday Function, Year Function.

Example

This example uses the DateSerial function to return the date for the specified year, month, and day.

' MyDate contains the date for February 12, 1969.= DateSerial(1969, 2, 12)                    ' Return a date.

The following example uses the DateSerial function to return the number of days in a month. The function DaysInMonth requires a Date argument, since February will have an extra day in a leap year. If you pass a date literal to the DaysInMonth function, make sure it is delimited by number signs (#). For example, #2-1-95# or #February 1, 1995# are valid values for the Date argument. You can also pass in a string, such as “2-1-95”.

This example uses the Year, Month, and Day functions to return the year, month, and day parts of the date passed in.

Sub DaysInMonth(dteAny As Date)
    Dim intDays As Integer

    ' Add one month, subtract dates to find difference.
    intDays = DateSerial(Year(dteAny), Month(dteAny) + 1, Day(dteAny)) _
        - DateSerial(Year(dteAny), Month(dteAny), Day(dteAny))
    Debug.Print intDaysSub

The next example uses named arguments to provide values to the DateSerial function. Since the arguments are named, their relative position is not important. Note the difference between using named arguments in the following example, and using the Year, Month, and Day functions in the preceding example.

Sub ConstructDate()
    Debug.Print DateSerial(Day:=1, Month:=2, Year:=1995)Sub


DateValue Function

Description

Returns a Date.

Syntax

DateValue(date)

The date argument is normally a string expression representing a date from January 1, 100 through December 31, 9999. However, date can also be any expression that can represent a date, a time, or both a date and time, in that range.

Remarks

If the date argument includes time information, DateValue doesn’t return it. However, if date includes invalid time information (such as “89:98”), an error occurs.

If date is a string that includes only numbers separated by valid date separators, DateValue recognizes the order for month, day, and year according to the Short Date format you specified for your system. DateValue also recognizes unambiguous dates that contain month names, either in long or abbreviated form. For example, in addition to recognizing 12/30/1991 and 12/30/91, DateValue also recognizes December 30, 1991 and Dec 30, 1991.

If the year part of date is omitted, DateValue uses the current year from your computer’s system date.

See Also

CDate Function, Date Function, Date Statement, DateSerial Function, Day Function, Month Function, Now Function, TimeSerial Function, TimeValue Function, Weekday Function, Year Function.

Example

This example uses the DateValue function to convert a string to a date. You can also use date literals to directly assign a date to a Variant or Date variable (for example, MyDate = #2/12/69#).

MyDate = DateValue("February 12, 1969")    ' Return a date.


DAvg Function

Description

You can use the DAvg function to calculate the average of a set of values in a specified set of records (domain). Use DAvg in a macro or module, in a query expression, or in a calculated control.

For example, you could use DAvg in the criteria row of a select query on freight cost to restrict the results to only those records for which the freight cost is above the average. Or you could use an expression including DAvg in a calculated control, and display the average value of previous orders next to the value of a new order.

Syntax

DAvg(expr, domain[, criteria])

The DAvg function uses the following arguments.

Part | Description
expr | Expression that identifies the field containing the numeric data you want to average. It can be a string expression identifying a field in a table or query, or it can be an expression that performs a calculation on data in that field. You can include in expr the name of a table field, a control on a form, a constant, or a function. If expr includes a function, it can be either built-in or user-defined, but not another domain aggregate or SQL aggregate function.
domain | String expression identifying the set of records that constitutes the domain. It can be a table name or a query name.
criteria | Optional string expression used to restrict the range of data on which DAvg is performed. For example, criteria is often equivalent to the WHERE clause in an SQL expression, without the word WHERE. If criteria is omitted, DAvg evaluates expr against the entire domain. Any field included in criteria must also be a field in domain; otherwise DAvg returns a Null.

Remarks

DAvg finds the average value of the field or expression defined by expr in the table or query referred to by domain, according to any restrictions specified by criteria.

Records containing Null values are not included in the calculation of the average.

Whether you use DAvg in a macro or module, a query expression, or a calculated control, you must construct the criteria argument carefully to ensure that it will be evaluated correctly.

You can use DAvg to specify criteria in the Criteria row of a query. For example, suppose you want to view a list of all products ordered in quantities above the average order quantity. You could create a query on the Orders and Products tables, and include the Product Name field and the Quantity field, with the following expression in the Criteria row beneath the Quantity field.

> DAvg("[Quantity]", "Orders")

You can also use DAvg within a calculated field expression in a query, or in the Update To row of an update query.

Note You can use either DAvg or Avg in a calculated field expression in a totals query. If you use DAvg, values are averaged before the data is grouped. If you use Avg, the data is grouped before values in the field expression are averaged.

Use DAvg in a calculated control when you need to specify criteria to restrict the range of data on which DAvg is performed. For example, to display the average cost of freight for shipments sent to California, set the ControlSource property of a text box to the following expression.

= DAvg("[Freight]", "Orders", "[ShipRegion] = 'CA'")

If you simply want to average all records in domain, use the Avg function.

You can use DAvg in a module or macro or in a calculated control on a form if a field that you need to display is not in the record source on which your form is based. For example, suppose you have a form based on the Orders table, and you want to include the Quantity field from the Order Details table in order to display the average number of items ordered by a particular customer. You can use DAvg to perform this calculation and display the data on your form.

Note Tips

  • If you use DAvg in a calculated control, you may want to place the control on the form header or footer so that the value for this control is not recalculated each time you move to a new record.
  • If the data type of the field from which expr is derived is a number, DAvg returns a Double. If you use DAvg in a calculated control, include a data type conversion function in the expression to improve performance.
  • Although you can use DAvg to determine the average of values in a field in a foreign table, it may be more efficient to create a query that contains all of the fields that you need, and then base your form or report on that query.

Note Unsaved changes to records in domain are not included when you use this function. If you want the DAvg function to be based on the changed values, you must first save the changes by choosing the Save Record command from the File menu, moving the focus to another record, or using the Update method.

See Also

Domain Aggregate Functions.

Example

This example returns the average freight cost for orders shipped to the United Kingdom before January 1, 1995. The domain is an Orders table. The criteria argument restricts the resulting set of records to those for which ShipCountry equals UK and ShippedDate is greater than 1-1-95. Note that the keyword AND is included in the string to separate the multiple fields in the criteria argument. All records included in the DAvg calculation will have both of these criteria.

Dim dblX As Double= DAvg("[Freight]", "Orders", _
    "[ShipCountry] = 'UK' AND [ShippedDate] > #1-1-95#")

The next example calculates an average using a variable, strCountry, in the criteria argument. Note that single quotation marks (') are included in the string expressions, so that when all of the strings are concatenated, the string literal UK will be enclosed in single quotation marks. In this example, the keyword OR is used to separate the multiple fields. This example will return all records that have either or both criteria.

Dim dblX As Double, strCountry As String= "UK"= DAvg("[Freight]", "Orders", _
    "[ShipCountry] = '" & strCountry & "'OR [ShippedDate] > #1-1-95#")


Day Function

Description

Returns a whole number between 1 and 31, inclusive, representing the day of the month.

Syntax

Day(date)

The date argument is any numeric or string expression, or any combination, that can represent a date. If date contains Null, Null is returned.

See Also

Date Function, Date Statement, Hour Function, Minute Function, Month Function, Now Function, Second Function, Weekday Function, Year Function.

Example

This example uses the Day function to obtain the day of the month from a specified date. In the development environment, the date literal is displayed in short format using the locale settings of your code.

MyDate = #February 12, 1969#            ' Assign a date.= Day(MyDate)                    ' MyDay contains 12.


DBEngine Property

Applies To

Application Object.

Description

You can use the DBEngine property in Visual Basic to access the current DBEngine object and its related properties.

Setting

The DBEngine property is set by Microsoft Access and is read-only.

Remarks

The DBEngine property of the Application object represents the Microsoft Jet database engine. The DBEngine object is the top-level object in the Data Access Object (DAO) model and it contains and controls all other objects in the hierarchy of data access objects.

See Also

Application Property.

Example

See the Application property example.


DblClick Event

Applies To

Bound Object Frame Control, Chart Control, Check Box Control, Combo Box Control, Command Button Control, Form, Form Section, Image Control, Label Control, List Box Control, Option Button Control, Option Group Control, Rectangle Control, Subform/Subreport Control, Text Box Control, Toggle Button Control, Unbound Object Frame Control.

Description

The DblClick event occurs when the user presses and releases the left mouse button twice over an object.

On a form, the DblClick event occurs when the user double-clicks a disabled control or a blank area of the form. For a control, it occurs when the user double-clicks a control or its label in Form view. The DblClick event occurs when the user double-clicks the form or control but before the result of the double-click action occurs (for example, before Microsoft Access selects the word that the insertion point is on in a text box).

Notes

  • The DblClick event applies only to forms, form sections, and controls on a form.
  • This event doesn’t apply to check boxes, option buttons, or toggle buttons in an option group. It applies only to the option group itself.
  • This event doesn’t apply to a label attached to another control, such as the label for a text box. It applies only to “freestanding” labels. Double-clicking an attached label has the same effect as double-clicking the associated control. The normal events for the control occur, not any events for the attached label.

Remarks

For controls, the result of double-clicking depends on the control. For example, double-clicking a word in a text box selects the entire word. Double-clicking a control containing an OLE object starts the application used to create the object, allowing it to be edited.

If the DblClick event doesn’t occur within the double-click time limit of the system, the form, form section, or control recognizes two Click events instead of a single DblClick event. The double-click time limit depends on the Double-click speed setting in the Mouse section of the Microsoft Windows Control Panel.

By running a macro or an event procedure when the DblClick event occurs, you can open a window or document when an icon is double-clicked.

Double-clicking a control causes both Click and DblClick events to occur. If the control doesn’t already have the focus when you double-click it, the Enter and GotFocus events for the control occur before the Click and DblClick events.

For objects that receive mouse events, the events occur in this order:

MouseDown [image] MouseUp [image] Click [image] DblClick.

When you double-click a command button, the following events occur in this order:

MouseDown [image] MouseUp [image] Click [image] DblClick [image] MouseUp [image] Click

The second click may have no effect (for example, if the Click macro opens a modal dialog box in response to the first Click event). To prevent the second Click macro or event procedure from running, put a CancelEvent action in the DblClick macro or use the Cancel argument in the DblClick event procedure.

If you double-click any other control besides a command button, the second Click event doesn’t occur.

See Also

Click Event; MouseDown, MouseUp Events.


DblClick Event -- Event Procedures

Description

To create an event procedure that is run when the DblClick event occurs, set the OnDblClick property to [Event Procedure], and click the Build button.

Syntax

Private Sub Form_DblClick (Cancel As Integer)Private Sub controlname_DblClick (Cancel As Integer)

The DblClick event procedure uses the following arguments.

Argument | Description
controlname | A string that is the name of the control affected by the DblClick event procedure.
Cancel | The setting determines if the DblClick event occurs. Setting Cancel to True (-1) cancels the DblClick event.

Remarks

You can use a DblClick event procedure to modify a control’s default double-click behavior. For example, you can have the event procedure execute in response to double-clicking an embedded object before an OLE application is opened. The event procedure could display a message asking if the user wants to print or edit the object. You could use a user-defined function to print the object. If the user decides to print the object instead of editing it, you could print the object, and then use the Cancel argument to cancel opening of the OLE application.

This event procedure is also useful for carrying out multiple steps with a single action, such as double-clicking to select an item in a list box or to close a dialog box. To carry out more than one command using a single action, you can use a DblClick event procedure for a list box in tandem with a command button whose Default property is set to True (-1). As part of the DblClick event procedure for the list box, you call the command button’s Click event procedure.

When you create event procedures for MouseDown, MouseUp, Click, and DblClick events, make sure that their code doesn’t conflict. (For example, the Click event procedure shouldn’t contain code that cancels actions carried out in the DblClick event procedure.)

When you double-click a command button, the following events occur in this order:

Click [image] DblClick [image] Click

To prevent the second Click event from occurring, you can set the Cancel argument to True (-1) or use the CancelEvent method of the DoCmd object in the DblClick event procedure. If you don’t cancel the second Click event, the code in the Click event procedure is run. The following example cancels the second Click event:

Private Sub CmdButton_DblClick (Cancel As Integer)
    Cancel = True                    ' Cancel the second Click event.Sub

See Also

DblClick Event — Macros.

Example

This example shows how you can use a DblClick event procedure to call a Click event procedure for a command button. When the user double-clicks the Products box, the Click event for the Close button is triggered when its Value property is set to True (-1). This causes the Close button’s Click event procedure to run.

To try the following example, add the code to the Declarations section of a form named Main that contains a list box called Products.

Private Sub Products_DblClick (Cancel As Integer)
    Close_Click                        ' Trigger Click event.Sub


DblClick Event -- Macros

Description

To run a macro when the DblClick event occurs, set the OnDblClick property to the name of the macro.

Remarks

By running a macro when the DblClick event occurs, you can modify a control’s default double-click behavior. For example, you can run a macro before an OLE application is opened in response to double-clicking an embedded object. The macro could display a message asking if the user wants to print or edit the object. You could use a user-defined function to print the object.

You can also use the DblClick event to enable a dialog box to be closed by double-clicking a control instead of clicking the OK button. The DblClick macro runs a Close action for the dialog box. You could also have the macro hide the dialog box by using the SetValue action to set the dialog box’s Visible property to No.

You use the CancelEvent action in a DblClick macro to cancel the default double-click behavior of the control. If the user wanted to print the object mentioned earlier in this topic instead of editing it, you would use a user-defined function to print the object, and then use a CancelEvent action to cancel opening of the OLE application.

Note When you double-click a command button, the following events occur in this order:

Click [image] DblClick [image] Click

The second click may have no effect (for example, if the Click macro opens a modal form). To prevent the second Click event from occurring, you can use the CancelEvent action in the DblClick macro. This sequence of Click, DblClick, Click events occurs when you double-click a command button only, not other types of controls.

See Also

DblClick Event — Event Procedures.


DCount Function

Description

You can use the DCount function to determine the number of records that are in a specified set of records (domain). Use DCount in a macro or module, in a query expression, or in a calculated control.

For example, you could use DCount in a module to return the number of records in an Orders table that correspond to orders placed on a particular date.

Syntax

DCount(expr, domain[, criteria])

The DCount function uses the following arguments.

Part | Description
expr | Expression that identifies the field for which you want to count records. It can be a string expression identifying a field in a table or query, or it can be an expression that performs a calculation on data in that field. You can include in expr the name of a table field, a control on a form, a constant, or a function. If expr includes a function, it can be either built-in or user-defined, but not another domain aggregate or SQL aggregate function.

Part | Description
domain | String expression identifying the set of records that constitutes the domain. It can be a table name or a query name.
criteria | Optional string expression used to restrict the range of data on which DCount is performed. For example, criteria is often equivalent to the WHERE clause in an SQL expression, without the word WHERE. If criteria is omitted, DCount evaluates expr against the entire domain. Any field included in criteria must also be a field in domain; otherwise DCount returns a Null.

Remarks

DCount finds the number of records in the field or expression defined by expr in the table or query referred to by domain, according to any restrictions specified by criteria.

Use DCount to count the number of records in a domain when you don’t need to know their particular values. Although the expr argument can perform a calculation on a field, DCount simply tallies the number of records. The value of any calculation performed by expr is unavailable.

Whether you use DCount in a macro or module, a query expression, or a calculated control, you must construct the criteria argument carefully to ensure that it will be evaluated correctly.

Use DCount in a calculated control when you need to specify criteria to restrict the range of data on which the function is performed. For example, to display the number of orders to be shipped to California, set the ControlSource property of a text box to the following expression:

= DCount("[OrderID]", "Orders", "[ShipRegion] = 'CA'")

If you simply want to count all records in domain without specifying any restrictions, use the Count function.

Tip The Count function has been optimized to speed counting of records in queries. Use Count in a query expression instead of DCount, and set optional criteria to enforce any restrictions on the results. Use DCount when you must count records in a domain from within a code module or macro, or in a calculated control.

You can use DCount to count the number of records containing a particular field that is not in the record source on which your form or report is based. For example, you could display the number of orders in the Orders table in a calculated control on a form based on the Products table.

The DCount function doesn’t count records that contain Null values in the field referenced by expr, unless expr is the asterisk (*) wildcard character. If you use an asterisk, DCount calculates the total number of records, including those that contain Null fields. The following example calculates the number of records in an Orders table.

intX = DCount("*", "Orders")

If domain is a table with a primary key, you can also count the total number of records by setting expr to the primary key field, since there will never be a Null in the primary key field.

If expr identifies multiple fields, separate the field names with a concatenation operator, either an ampersand (&) or the addition operator (+). If you use an ampersand to separate the fields, DCount returns records containing a Null value as well as records containing data. If you use the addition operator, DCount returns only records containing data. The following example demonstrates the effects of each operator when used with a field that contains no Null values (ShipName) and a field that contains Null values (ShipRegion).

intW = DCount("[ShipName]", "Orders")                    ' Returns 1078.= DCount("[ShipRegion]", "Orders")                    ' Returns 834.= DCount("[ShipName] + [ShipRegion]", "Orders")        ' Returns 834.= DCount("[ShipName] & [ShipRegion]", "Orders")        ' Returns 1078.

Note The ampersand (&) is the preferred operator for performing string concatenation. You should avoid using the addition operator (+) for anything other than numeric addition, unless you specifically wish to propagate nulls through an expression.

Unsaved changes to records in domain are not included when you use this function. If you want the DCount function to be based on the changed values, you must first save the changes by clicking Save Record on the File menu, moving the focus to another record, or using the Update method.

See Also

DAvg Function, Domain Aggregate Functions, DSum Function.

Example

This example returns the number of orders shipped to the United Kingdom after January 1, 1995. The domain is an Orders table. The criteria argument restricts the resulting set of records to those for which ShipCountry equals UK and ShippedDate is greater than 1-1-95.

intX = DCount("[ShippedDate]", "Orders", _
    "[ShipCountry] = 'UK' AND [ShippedDate] > #1-1-95#")

In the next example, the criteria argument includes the current value of a combo box called ShipCountry. The values in the ShipCountry combo box come from the field ShipCountry in an Orders table. Note that the reference to the control is not included in the quotation marks that denote the strings. This ensures that each time the DCount function is called, Microsoft Access will obtain the current value from the control.

intX = DCount("[ShippedDate]", "Orders", "[ShipCountry] = '" _
    & Forms!Orders![ShipCountry] & "'AND [ShippedDate] > #1-1-95#")


DDB Function

Description

Returns the depreciation of an asset for a specific period using the double-declining balance method or some other method you specify.

Syntax

DDB(cost, salvage, life, period[, factor])

The DDB function has these named arguments:

Part | Description
cost | Initial cost of the asset.
salvage | Value of the asset at the end of its useful life.
life | Length of useful life of the asset.
period | Period for which asset depreciation is calculated.
factor | Rate at which the balance declines. If omitted, 2 (double-declining method) is assumed.

Remarks

The double-declining balance method computes depreciation at an accelerated rate. Depreciation is highest in the first period and decreases in successive periods.

The arguments life and period must be expressed in the same units. For example, if life is given in months, period must also be given in months. All arguments must be positive numbers.

The DDB function uses the following formula to calculate depreciation for a given period:

Depreciation over period = ((cost – salvage) * factor) / life

Example

Using the double-declining balance method, this example uses the DDB function to return the depreciation of an asset for a specified period given the initial cost (InitCost), the salvage value at the end of the asset’s useful life (SalvageVal), the total life of the asset in years (LifeTime), and the period for which the depreciation is calculated (Depr), also in years.

Const YRMOS = 12                            ' Number of months in a year.= "###,##0.00"= InputBox("What's the initial cost of the asset?")= InputBox("Enter the asset's value at end of its life.")= InputBox("What's the asset's useful life in months?")While MonthLife < YRMOS                ' Ensure period is >= 1 year.
    MsgBox "Asset life must be a year or more."
    MonthLife = InputBox("What's the asset's useful life in months?")= MonthLife / YRMOS                ' Convert months to years.LifeTime <> Int(MonthLife / YRMOS) Then
    LifeTime = Int(LifeTime + 1)            ' Round up to nearest year.If= CInt(InputBox("Enter year for depreciation calculation."))While DepYear < 1 Or DepYear > LifeTime
    MsgBox "You must enter at least 1 but not more than " & LifeTime
    DepYear = InputBox("Enter year for depreciation calculation.")= DDB(InitCost, SalvageVal, LifeTime, DepYear)"The depreciation for year " & DepYear & " is " & _
    Format(Depr, Fmt) & "."


DDE Function

Description

You can use the DDE function to initiate a dynamic data exchange (DDE) conversation with another application, request an item of information from that application, and display that information in a control on a form or report.

Use the DDE function in the ControlSource property setting of a text box, option group, check box, or combo box on a form.

For example, you can use the DDE function in the ControlSource property of a text box to display data from a specified cell in a Microsoft Excel spreadsheet.

Syntax

DDE(application, topic, item)

The DDE function syntax has the following arguments.

Argument | Description
application | A string expression identifying an application that can participate in a DDE conversation. Usually, application is the name of an .exe file (without the .exe extension) for a Microsoft Windows-based application. For example, to initiate a DDE conversation with Microsoft Excel, type “Excel” for the application argument.
topic | A string expression that is the name of a topic recognized by application. Topic is often a document or data file. Check the other application’s documentation for a list of possible topics.
item | A string expression that is the name of a data item recognized by application. Check the other application’s documentation for a list of possible items.

Remarks

The DDE function attempts to initiate a DDE conversation with the specified application and topic, and requests the data in item. If successful, the DDE function returns a string that contains the requested information.

If you are requesting data from Microsoft Excel, item might be a row-and-column identifier, such as "R1C1" or the name of a range of cells. In the following example, the DDE function requests information from the cell at row 1, column 1 in a Microsoft Excel worksheet. You can enter this expression for a text box control in the ControlSource property box on the control’s property sheet.

= DDE("Excel", "Sheet1", "R1C1")

You can use the DDE function only in the ControlSource property of a text box, option group, check box or combo box. You cannot call the DDE function from Visual Basic.

When you use the DDE function, the control becomes read-only in Form view and Print Preview. For example, if you use the DDE function in a text box, the text in the text box cannot be edited. You must edit the text in the other application. Because the ControlSource property is read-only in Form view and Print Preview, changes to the control must be made in Design view.

The maximum number of DDE conversations that can be open simultaneously is determined by Microsoft Windows and your computer’s memory and resources. If the conversation can’t be initiated because application isn’t running or doesn’t recognize topic, or if the maximum number of conversations has already been reached, DDE returns a Null.

Note The other application may be configured to ignore your request for a DDE conversation. If so, DDE returns a Null. Similarly, you can set Microsoft Access to ignore requests from other applications: click Options on the Tools menu, and on the Advanced tab of the Options dialog box, under DDE Operations, select Ignore DDE Requests.

Note If you need to manipulate another application’s objects from Microsoft Access, you may want to consider using OLE Automation.

The following table illustrates how the DDE function behaves when you use it with each of the controls.

Control | Remarks
Text box | The item argument can refer to text or numbers. If item refers to more than one piece of information, such as a named range in a Microsoft Excel worksheet that contains multiple cells, DDE returns the first entry. You could use the DDE function with a text box to display the data contained in a cell on the worksheet.
Combo box | The DDE function fills the combo box with the information referred to by item. You can’t enter data in the text portion of the box. You might use the DDE function with a combo box to display a list of states or countries that you maintain in a Microsoft Excel worksheet.
Option group | The OptionValue property of each option button in an option group is set to a number. Usually, the first button value is 1, the second is 2, and so on. The number returned by the DDE function determines which option button will be selected.
For example, if DDE returns 2, the second button will be selected. If DDE returns a value that doesn’t match any of the OptionValue property settings, none of the buttons will be selected. If item refers to more than one piece of information, such as a named range in a Microsoft Excel worksheet that contains multiple cells, DDE returns the first entry.
Check box | If the DDE function returns 0, the check box will be cleared. If DDE returns a nonzero number, such as 1 or -1, the box will be selected. If item refers to text or to more than one piece of information, such as a named range in a Microsoft Excel worksheet that contains multiple cells, the check box will be unavailable.

See Also

DDEExecute Statement; DDEInitiate Function; DDEPoke Statement; DDERequest Function; DDESend Function; DDETerminate Statement; DDETerminateAll Statement; Enabled, Locked Properties.

Example

This example establishes a DDE link with Microsoft Excel, places some values into cells in the first row of a new worksheet, and charts the values. First, the DDEInitiate function opens a channel to begin the DDE conversation. Then, the DDEExecute statement sends Microsoft Excel the command to open a new worksheet, and the DDERequest function asks Microsoft Excel for the name of the newly created worksheet. A new channel is opened, and the DDEPoke statement sends to Microsoft Excel the data to be charted. Finally, the DDETerminate statement terminates the DDE link with Microsoft Excel, and the DDETerminateAll statement terminates all active DDE links.

On Error Resume Next                            ' Set up error handler.Chan, SheetName, I, TopicList            ' Declare variables.= DDEInitiate("Excel", "System")        ' Establish spreadsheet
                                            ' link.Err Then                                    ' If error occurs,
                                            ' spreadsheet
    Err = 0                                    ' isn't running. Reset
                                            ' error and start
    I = Shell("Excel", 1)                    ' spreadsheet.
    If Err Then Exit Sub                        ' If another error, exit.
    Chan = DDEInitiate("Excel", "System")    ' Establish spreadsheet
                                            ' link.IfChan, "[New(1)]"                    ' Create new worksheet.= DDERequest(Chan, "Selection")    ' Get topic list, worksheet
                                            ' name.= Left(TopicList, InStr(1, TopicList, "!") - 1)Chan                            ' Terminate DDE link.= DDEInitiate("Excel", SheetName)         ' Establish link with new
                                            ' worksheet.I = 1 To 10                                ' Put some values into
    DDEPoke Chan, "R1C" & I, I                ' first row.IChan, "[Select(""R1C1:R1C10"")][New(2,2)]"    ' Make chart.                                ' Terminate all links.


DDEExecute Statement

Description

You can use the DDEExecute statement to send a command from a client application to a server application over an open dynamic data exchange (DDE) channel.

For example, suppose you have opened a DDE channel in Microsoft Access to transfer text data from a Microsoft Excel spreadsheet into a Microsoft Access database. Use the DDEExecute statement to send the New command to Microsoft Excel to specify that you wish to open a new spreadsheet. In this example, Microsoft Access acts as the client application, and Microsoft Excel acts as the server application.

Syntax

DDEExecute channum, command

The DDEExecute statement syntax has these arguments.

Argument | Description
channum | The channel number returned by the DDEInitiate function.
command | A string expression specifying a command recognized by the server application. Check the server application’s documentation for a list of these commands.

Remarks

The value of command depends on the application and topic specified when the channel channum is opened. An error occurs if channum isn’t an integer corresponding to an open channel or if the other application can’t carry out the specified command.

From Visual Basic, you can use the DDEExecute statement only to send commands to another application.

Tip If you need to manipulate another application’s objects from Microsoft Access, you may want to consider using OLE Automation.

See Also

DDE Function, DDEInitiate Function, DDEPoke Statement, DDERequest Function, DDESend Function, DDETerminate Statement, DDETerminateAll Statement.

Example

See the DDE function example.


DDEInitiate Function

Description

You can use the DDEInitiate function to begin a dynamic data exchange (DDE) conversation with another application. The DDEInitiate function opens a DDE channel for transfer of data between a DDE server and client application.

For example, if you wish to transfer data from a Microsoft Excel spreadsheet to a Microsoft Access database, you can use the DDEInitiate function to open a channel between the two applications. In this example, Microsoft Access acts as the client application, and Microsoft Excel acts as the server application.

Syntax

DDEInitiate(application, topic)

The DDEInitiate function has these arguments.

Argument | Description
application | A string expression identifying an application that can participate in a DDE conversation. Usually, application is the name of an .exe file (without the .exe extension) for a Microsoft Windows-based application, such as Microsoft Excel.
topic | A string expression that is the name of a topic recognized by application. Check the application’s documentation for a list of topics.

Remarks

If successful, the DDEInitiate function begins a DDE conversation with the specified application and topic and returns a Variant containing an integer value. This integer represents a unique channel number identifying a channel over which data transfer can take place. This channel number is subsequently used with other DDE functions and statements.

If the application is not already running or if it is running but doesn’t recognize topic or doesn’t support DDE, the DDEInitiate function returns a run-time error.

The value of topic depends on application. For applications that use documents or data files, valid topic names often include the names of those files.

Note The maximum number of channels that can be open simultaneously is determined by Windows and your system’s memory and resources. If you aren’t using a channel, you should conserve resources by terminating it using a DDETerminate or DDETerminateAll statement.

Tip If you need to manipulate another application’s objects from Microsoft Access, you may want to consider using OLE Automation.

See Also

DDE Function, DDEExecute Statement, DDEPoke Statement, DDERequest Function, DDESend Function, DDETerminate Statement, DDETerminateAll Statement.

Example

See the DDE function example.


DDEPoke Statement

Description

You can use the DDEPoke statement to supply text data from a client application to a server application over an open dynamic data exchange (DDE) channel.

For example, if you have an open DDE channel between Microsoft Access, and Microsoft Excel, you can use the DDEPoke statement to transfer text from a Microsoft Access database to a Microsoft Excel spreadsheet. In this example, Microsoft Access acts as the client application, and Microsoft Excel acts as the server application.

Syntax

DDEPoke channum, item, data

The DDEPoke statement syntax has these arguments.

Argument | Description
channum | A channel number, an integer value returned by the DDEInitiate function.
item | A string expression that is the name of a data item recognized by application. Check the application’s documentation for a list of possible items.
data | A string containing the data to be supplied to the other application.

Remarks

The value of item depends on the application and topic specified when the channel channum is opened. For example, item may be a range of cells in a Microsoft Excel spreadsheet.

The string comprising data must be an alphanumeric text string. No other formats are supported. For instance, data could be a number to fill a cell in a specified range in an Excel worksheet.

If channum isn’t an integer corresponding to an open channel or if the other application doesn’t recognize or accept the specified data, an error occurs.

Tip If you need to manipulate another application’s objects from Microsoft Access, you may want to consider using OLE Automation.

See Also

DDE Function, DDEExecute Statement, DDEInitiate Function, DDERequest Function, DDESend Function, DDETerminate Statement, DDETerminateAll Statement.

Example

See the DDE function example.


DDERequest Function

Description

You can use the DDERequest function over an open dynamic data exchange (DDE) channel to request an item of information from a DDE server application.

For example, if you have an open DDE channel between Microsoft Access and Microsoft Excel, you can use the DDERequest function to transfer text from a Microsoft Excel spreadsheet to a Microsoft Access database. In this example, Microsoft Access acts as the client application, and Microsoft Excel acts as the server application.

Syntax

DDERequest(channum, item)

The DDERequest function syntax has these arguments.

Argument | Description
channum | A channel number, an integer value returned by the DDEInitiate function.
item | A string expression that is the name of a data item recognized by application. Check the application’s documentation for a list of possible items.

Remarks

The channum argument specifies the channel number of the desired DDE conversation, and the item argument identifies which data should be retrieved from the server application. The value of item depends on the application and topic specified when the channel channum is opened. For example, item may be a range of cells in a Microsoft Excel spreadsheet.

The DDERequest function returns a Variant containing the requested information as a string if the request was successful.

The data is requested in alphanumeric text format. Graphics or text in any other format cannot be transferred.

If channum isn’t an integer corresponding to an open channel, or if the data requested cannot be transferred, an error occurs.

Tip If you need to manipulate another application’s objects from Microsoft Access, you may want to consider using OLE Automation.

See Also

DDE Function, DDEExecute Statement, DDEInitiate Function, DDEPoke Statement, DDESend Function, DDETerminate Statement, DDETerminateAll Statement.

Example

See the DDE function example.


DDESend Function

Description

You can use the DDESend function to initiate a dynamic data exchange (DDE) conversation with another application and send an item of information to that application from a control on a form or report.

Use the DDESend function in the ControlSource property setting of a text box, option group, check box, or combo box on a form.

For example, you can use the DDESend function in the ControlSource property of a text box to send the data displayed in that text box to a specified cell in a Microsoft Excel spreadsheet.

Syntax

DDESend(application, topic, item, data)

The DDESend function has the following arguments.

Argument | Description
application | String expression identifying an application that can participate in a DDE conversation. Usually, application is the name of an .exe file (without the .exe extension) for a Microsoft Windows-based application, such as Microsoft Excel. For example, to initiate a DDE conversation with Microsoft Excel, type “Excel” for the application argument.
topic | String expression that is the name of a topic recognized by application. Topic is often a document or data file. Check the other application’s documentation for a list of possible topics.
item | String expression that is the name of a data item recognized by application. Check the other application’s documentation for a list of possible items.
data | String or expression containing the data to send to application.

Remarks

The DDESend function initiates a DDE conversation with application and topic, and identifies item as the data item which will receive data. For example, if application is Microsoft Excel, topic might be "Sheet1", and item might be a row-and-column identifier, such as "R1C1", or the name of a range of cells.

The data argument specifies the information you want to send. It can be a literal string, such as "Report prepared by John". Or it can be an expression that includes the result of a function that creates a string, such as "Prepared on " & Date(). If item refers to more than one piece of information, such as a named range in a Microsoft Excel worksheet that contains multiple cells, DDESend sends data to the first entry.

In the following example, the DDESend function sends the string "Some text" to the cell at Row 1, Column 1 in a Microsoft Excel worksheet. You can enter this expression for a text box control in the ControlSource property box on the control’s property sheet.

= DDESend("Excel", "Sheet1", "R1C1", "Some text")

Suppose you want to send data from a bound control on a Microsoft Access form to a cell on a Microsoft Excel spreadsheet. The ControlSource property of the bound control already contains a field name or expression. You can create another text box or combo box, and set its ControlSource property an expression including DDESend, where data is the name of the bound control. For instance, if you have a bound text box called Last Name, you can create another text box and set its ControlSource property to the following.

= DDESend("Excel", "Sheet1", "R1C1", [LastName])

This intermediary control must be either a text box or a combo box. You can’t use the name of a bound control as the data argument for a check box or option group.

You can use the DDESend function only in the ControlSource property setting of a text box, option group, check box, or combo box on a form. You cannot call the DDESend function from Visual Basic.

When you use DDESend, the control becomes read-only in Form view and Print Preview. Because the ControlSource property is also read-only in Form view and Print Preview, changes to the control must be made in Design view.

The maximum number of DDE conversations that can be open simultaneously is determined by Microsoft Windows and your computer’s memory and resources. If the conversation can’t be initiated because application isn’t running or doesn’t recognize topic or if the maximum number of conversations has already been reached, DDESend returns a Null.

Note The other application may be configured to ignore your DDE conversation. If so, DDESend returns a Null. Similarly, you can set Microsoft Access to ignore requests from other applications: click Options on the Tools menu, and on the Advanced tab of the Options dialog box, under DDE Operations, select Ignore DDE Requests.

Tip If you need to manipulate another application’s objects from Microsoft Access, you may want to consider using OLE Automation.

The following table illustrates how DDESend behaves when you use it with each of the controls.

Control | Remarks
Text box | Because the text box appears blank in Form view and Print Preview, you may want to set its Visible property to False. The data argument can refer to another control. The following example shows how you can send the contents of a control called LastName to a Microsoft Excel worksheet. = DDESend("Excel", "Sheet1", "R1C1", [LastName])
Combo box | Because the combo box appears blank in Form view and Print Preview, you may want to set its Visible property to False. The data argument can refer to another control. The following example shows how you can send the contents of a control called LastName to a Microsoft Excel worksheet. = DDESend("Excel", "Sheet1", "R1C1", [LastName])
Option group | None of the option buttons in the option group is selected in Form view and Print Preview. You may want to make the option group (and its buttons) invisible by setting its Visible property to False. The data argument must contain numeric data, such as "2". If the data argument isn’t numeric, DDESend doesn’t send the information and item isn’t changed.
Check box | The check box is dimmed in Form view and Print Preview. You may want to make it invisible by setting its Visible property to False. The data argument must contain numeric data, such as "2". If the data argument isn’t numeric, DDESend doesn’t send the information and item isn’t changed.

See Also

DDE Function; DDEExecute Statement; DDEInitiate Function; DDEPoke Statement; DDERequest Function; DDETerminate Statement; DDETerminateAll Statement; Enabled, Locked Properties.

Example

See the DDE function example.


DDETerminate Statement

Description

You can use the DDETerminate statement to close a specified dynamic data exchange (DDE) channel.

For example, if you have opened a DDE channel to transfer data between Microsoft Excel and Microsoft Access, you can use the DDETerminate statement to close that channel once the transfer is complete.

Syntax

DDETerminate channum

Remarks

The argument channum specifies the channel number to close. It refers to a channel opened by the DDEInitiate function. An error occurs if channum isn’t an integer corresponding to an open channel.

Once a channel is closed, any subsequent DDE functions or statements performed on that channel cause an error.

The DDETerminate statement has no effect on active DDE link expressions in fields on forms or reports.

Tip If you need to manipulate another application’s objects from Microsoft Access, you may want to consider using OLE Automation.

See Also

DDE Function, DDEExecute Statement, DDEInitiate Function, DDEPoke Statement, DDERequest Function, DDESend Function, DDETerminateAll Statement.

Example

See the DDE function example.


DDETerminateAll Statement

Description

You can use the DDETerminateAll statement to close all open dynamic data exchange (DDE) channels.

For example, suppose you have opened two DDE channels between Microsoft Excel and Microsoft Access, one to retrieve system information about Microsoft Excel and one to transfer data. You can use the DDETerminateAll statement to close both channels simultaneously.

Syntax

DDETerminateAll

Remarks

Using the DDETerminateAll statement is equivalent to executing a DDETerminate statement for each open channel number. Like the DDETerminate statement, the DDETerminateAll statement has no effect on active DDE link expressions in fields on forms or reports.

If there are no DDE channels open, the DDETerminateAll statement runs without causing an error.

Tip If you interrupt a procedure that performs DDE, you may inadvertently leave channels open. To avoid exhausting system resources, use the DDETerminateAll statement in your code or from the Immediate tab of the Debug window while debugging code that performs DDE.

Tip If you need to manipulate another application’s objects from Microsoft Access, you may want to consider using OLE Automation.

See Also

DDE Function, DDEExecute Statement, DDEInitiate Function, DDEPoke Statement, DDERequest Function, DDESend Function, DDETerminate Statement.

Example

See the DDE function example.


Deactivate Event

See Activate, Deactivate Events


Debug Object

Description

The Debug object sends output to the Debug window at run time.

Syntax

Debug

Methods

Print Method.


DecimalPlaces Property

Applies To

Table Fields, Text Box Control.

Description

You can use the DecimalPlaces property to specify the number of decimal places Microsoft Access uses to display numbers.

Setting

The DecimalPlaces property uses the following settings.

Setting | Description | Visual Basic
Auto | (Default) Numbers appear as specified by the Format property setting. | 255
0 to 15 | Digits to the right of the decimal separator appear with the specified number of decimal places; digits to the left of the decimal separator appear as specified by the Format property setting. | 0 to 15

You can set this property for text boxes and combo boxes in the control’s property sheet, for table fields in the table’s property sheet.

For controls, you can also set this property using a macro or Visual Basic.

Note The DecimalPlaces property setting has no effect if the Format property is blank or is set to General Number.

Remarks

The DecimalPlaces property affects only the number of decimal places that display, not how many decimal places are stored. To change the way a number is stored you must change the FieldSize property.

You can use the DecimalPlaces property to display numbers differently from the Format property setting or from the way they are stored. For example, the Currency setting of the Format property displays only two decimal places ($5.35). To display Currency numbers with four decimal places (for example, $5.3523), set the DecimalPlaces property to 4.

Tip You should set the DecimalPlaces property in the table’s property sheet. A bound control you create on a form or report inherits the DecimalPlaces property set in the field in the underlying table or query, so you won’t have to specify the property individually for every bound control you create.

See Also

FieldSize Property, Format Property.


Declare Statement

Description

Used at module level to declare references to external procedures in a dynamic-link library (DLL).

Syntax 1

[Public | Private ] Declare Sub name Lib "libname" [Alias"aliasname" ][([arglist])]

Syntax 2

[Public | Private ] Declare Function name Lib "libname" [Alias"aliasname" ] [([arglist])][As type]

The Declare statement syntax has these parts:

Part | Description
Public | Used to declare procedures that are available to all other procedures in all modules.
Private | Used to declare procedures that are available only within the module where the declaration is made.
Sub | Indicates that the procedure doesn’t return a value.
Function | Indicates that the procedure returns a value that can be used in an expression.
name | Any valid procedure name.
Lib | Indicates that a DLL or code resource contains the procedure being declared. The Lib clause is required for all declarations.
libname | Name of the DLL or code resource that contains the declared procedure.
Alias | Indicates that the procedure being called has another name in the DLL. This is useful when the external procedure name is the same as a keyword. You can also use Alias when a DLL procedure has the same name as a public variable or constant or any other procedure in the same scope. Alias is also useful if any characters in the DLL procedure name aren’t allowed by the DLL naming convention.
aliasname | Name of the procedure in the DLL or code resource.
If the first character is not a #, aliasname is the name of the procedure’s entry point in the DLL. If # is the first character, all characters that follow must indicate the ordinal number of the procedure’s entry point.
The resourcetype is any valid four-character constant. If omitted, the default resourcetype is CODE. The resourcename is the procedure name in the code resource. If resourcename is omitted, it is assumed to be the same as name.

Part | Description
arglist | List of variables representing arguments that are passed to the procedure when it is called.
type | Data type of the value returned by a Function procedure; may be Byte, Boolean, Integer, Long, Currency, Single, Double, Date, String (variable length only), Object, Variant, a user-defined type, or an object type.

The arglist argument has the following syntax and parts:

[Optional][ByVal | ByRef][ParamArray] varname[( )][As type]

Part | Description
Optional | Indicates that an argument is not required. If used, all subsequent arguments in arglist must also be optional and declared using the Optional keyword. All Optional arguments must be Variant. Optional can’t be used for any argument if ParamArray is used.
ByVal | Indicates that the argument is passed by value.
ByRef | Indicates that the argument is passed by reference.
ParamArray | Used only as the last argument in arglist to indicate that the final argument is an Optional array of Variant elements. The ParamArray keyword allows you to provide an arbitrary number of arguments. May not be used with ByVal, ByRef, or Optional.
varname | Name of the variable representing the argument being passed to the procedure; follows standard variable naming conventions.
type | Data type of the argument passed to the procedure; may be Byte, Boolean, Integer, Long, Currency, Single, Double, Date, String (variable length only), Object, Variant, a user-defined type, or an object type.

Remarks

For Function procedures, the data type of the procedure determines the data type it returns. You can use an As clause following the arglist to specify the return type of the function. Within arglist you can use an As clause to specify the data type of any of the arguments passed to the procedure. In addition to specifying any of the standard data types, you can specify As Any in the arglist to inhibit type checking and allow any data type to be passed to the procedure.

Empty parentheses indicate that the Sub or Function procedure has no arguments and that Visual Basic should ensure that none are passed. In the following example, First takes no arguments. If you use arguments in a call to First, an error occurs:

Declare Sub First Lib "MyLib" ()

If you include an argument list, the number and type of arguments are checked each time the procedure is called. In the following example, First takes one Long argument:

Declare Sub First Lib "MyLib" (X As Long)

Note You can’t have fixed-length strings in the argument list of a Declare statement — only variable-length strings can be passed to procedures. Fixed-length strings can appear as procedure arguments, but they are converted to variable-length strings before being passed.

Note A constant, vbNullString, is provided by Visual Basic for use when calling external procedures, where the external procedure requires a string whose value is zero. This is not the same thing as a zero-length ("") string.

In the 32-bit version of Microsoft Windows, dynamic-link library (DLL) procedure names are case-sensitive; those in the 16-bit version of Microsoft Windows (3.1 and earlier) are not.

See Also

Call Statement, Function Statement, LastDLLError Property, Sub Statement.

Specifics (Microsoft Access)

In Microsoft Access, Declare statements are public by default. In a standard module, a public Declare statement is available to both the current database and any referencing databases. You can preface a Declare statement with the Private keyword to ensure that it is not available outside of the current database. To use a Declare statement in a form module or report module, you must precede the statement with the Private keyword.

Example

In Microsoft Access, you can use the Declare statement at the module level of a standard module to declare a reference to an external procedure in a dynamic-link library (DLL). A Declare statement is public by default. In order to include a Declare statement in a form or report module, precede it with the Private keyword.

The following example references a procedure in a DLL, then calls that procedure from Visual Basic.

' In standard module.Sub MessageBeep Lib "User32" (ByVal intN As Integer)

' In form or report module.Declare Sub MessageBeep Lib "User32" (ByVal intN As Integer)

' Once you have referenced procedure in DLL with Declare
' statement, you can call that procedure normally from code.SystemBeep()
    Dim intB As Integer, intI As Integer
    Dim sngStart, sngPause
    sngPause = 2
    intB = InputBox("How many beeps would you like to hear?")
    For intI = 1 to intB
        ' Call system function.
        MessageBeep(intB)
        ' Get start time.
        sngStart = Timer
        Do While Timer < sngStart + sngPause
        ' Pause for two seconds.
        Loop
    Next intISub


Default Property

Applies To

Command Button Control.

Description

You can use the Default property to specify whether a command button on a form has the focus.

Setting

The Default property uses the following settings.

Setting | Description | Visual Basic
Yes | The command button is the default button. | True (-1)
No | (Default) The command button isn’t the default button. | False (0)

You can set this property using the command button’s property sheet, a macro, or Visual Basic.

Remarks

When the command button’s Default property setting is Yes and the form is in the active window, the user can choose the command button by pressing ENTER (if no other command button has the focus) or by clicking on it.

Only one command button on a form can be the default button. When the Default property is set to Yes for one command button, it is automatically set to No for all other command buttons on the form.

Tip For a form that supports irreversible operations, such as deletions, it’s a good idea to make the Cancel button the default command button. To do this, set both the Default property and the Cancel property to Yes.

See Also

Cancel Property.


DefaultControl Method

Applies To

Form Object, Report Object.

Description

The DefaultControl method returns a Control object with which you can set the default properties for a particular type of control on a particular form. For example, before you create a text box on a form, you might want to set the default properties for the text box. Then you can create a number of text boxes that have the same base property settings, rather than having to set properties for each text box individually once it has been created.

Syntax

Set control = object.DefaultControl(controltype)

The DefaultControl method uses the following arguments.

Argument

Description

control | A Control object for which the default properties are to be set.
object | A Form or Report object on which controls are to be created. The default property settings defined for a type of control apply only to controls of the same type created on this form or report.
controltype | An intrinsic constant indicating the type of control for which default property settings are to be set.

Remarks

The DefaultControl method enables you to set a control’s default properties from code. Once you have set the default properties for a particular type of control, each subsequently created control of that type will have the same default values.

For example, if you set the FontSize property of the default command button to 12, each new command button will have a font size of 12 points.

Not all of a control’s properties are available as default properties. The default properties available for a control depend on the type of control.

The DefaultControl method returns a Control object of the type specified by the controltype argument. This Control object doesn’t represent an actual control on a form, but rather a default control that is a template for all subsequently created controls of that type. You set the default control properties for the Control object returned by the DefaultControl method in the same manner that you would set properties for an individual control on a form.

For a list of intrinsic constants that can be passed as the controltype argument, see the CreateControl function. These constants are also listed in the Constants module of the Microsoft Access library in the Object Browser.

The DefaultControl method applies only to form Design view or report Design view. If you try to apply this method to a form or report that is not in Design view, a run-time error will result.

If you try to set a property that can’t be set as a default property with the DefaultControl method, a run-time error will result. To determine which properties can be default properties, enumerate the Properties collection of the Control object returned by the DefaultControl method.

See Also

Control Object; ControlType Property; CreateControl, CreateReportControl Functions; FontName, FontSize Properties.

Example

The following example creates a new form and uses the DefaultControl method to return a control object representing the default command button. The procedure sets some of the default properties for the command button, then creates a new command button on the form.

Sub SetDefaultProperties()
    Dim frm As Form, ctlDefault As Control, ctlNew As Control

    ' Create new form.
    Set frm = CreateForm
    ' Return Control object representing default command button.
    Set ctlDefault = frm.DefaultControl(acCommandButton)
    ' Set some default properties.
    With ctlDefault
        .FontWeight = 700
        .FontSize = 12
        .Width = 3000
        .Height = 1000
    End With
    ' Create new command button.
    Set ctlNew = CreateControl(frm.Name, acCommandButton, , , , _
        500, 500)
    ' Set control's caption.
    ctlNew.caption = "New Command Button"
    ' Restore form.
    DoCmd.RestoreSub


DefaultEditing Property

See AllowEditing, DefaultEditing Properties.


DefaultValue Property

Applies To

Check Box Control, Combo Box Control, List Box Control, Option Button Control, Option Group Control, Table Fields, Text Box Control, Toggle Button Control.

Description

You can use the DefaultValue property to specify a value that is automatically entered in a field when a new record is created. For example, in an Addresses table you can set the default value for the City field to New York. When users add a record to the table, they can either accept this value or enter the name of a different city.

Notes

  • The DefaultValue property doesn’t apply to check box, option button, or toggle button controls when contained in an option group. It does apply to the option group itself.
  • The DefaultValue property applies to all table fields except those fields with the data type of AutoNumber or OLE Object.

Setting

The DefaultValue property specifies text or an expression that is automatically entered in a field when a new record is created. For example, if you set the DefaultValue property for a text box control to = Now(), the control displays the current time. The maximum length for a DefaultValue property setting is 255 characters.

You can set this property in the property sheet in table Design view (under Field Properties), a macro, or Visual Basic.

In Visual Basic, use a string expression to set the value of this property. For example, the following sets the DefaultValue property for a text box control named PaymentMethod to “Cash”.

Forms!frmInvoice!PaymentMethod.DefaultValue = """Cash"""

Note To set this property for a field using Visual Basic, use the Data Access Objects DefaultValue property.

Remarks

If you create a control by dragging a field from the field list, the field’s DefaultValue property setting, as defined in the table, is applied to the control on the form.

One control can provide the default value for another control. For example, if you set the DefaultValue property for a control to the following expression, the field’s default value is set to the DefaultValue property setting for the txtShipTo control.

= Forms![frmInvoice]![txtShipTo]

If the controls are on the same form, the control that is the source of the default value must appear earlier in the tab order than the control containing the expression.

The DefaultValue property is applied only when you add a new record. If you change the DefaultValue property, the change is not automatically applied to existing records.

If you set the DefaultValue property for a control on a form for a field that also has a DefaultValue property setting defined in the table, the control setting overrides the table setting.

See Also

AllowZeroLength Property, DefaultValue Property (Microsoft Office 95 Data Access Reference), Required Property, Value Property.


DefaultView, ViewsAllowed Properties

Applies To

Form.

Description

You can use these two properties to specify the view a form displays when it opens and whether users can switch to and from Datasheet view and Form view.

  • DefaultView — You can use this property to specify the opening view of a form.
  • ViewsAllowed — You can use this property to specify whether users can switch between Datasheet view and Form view by clicking the Form or Datasheet command on the View menu.

Setting

The DefaultView property uses the following settings.

Setting | Description | Visual Basic
Single Form | (Default) Displays one record at a time. | 0
Continuous Forms | Displays multiple records (as many as will fit in the current window), each in its own copy of the detail section of the form. | 1
Datasheet | Displays the form fields arranged in rows and columns like a spreadsheet | 2

The ViewsAllowed property uses the following settings.

Setting | Description | Visual Basic
Both | (Default) Users can switch between Form view and Datasheet view. | 0
Form | Users can’t switch to Datasheet view from Form view. | 1
Datasheet | Users can’t switch to Form view from Datasheet view. | 2

Design view is always available (unless permissions are set otherwise).

You can set these properties in the property sheet, a macro, or Visual Basic.

Remarks

The combination of these properties creates the following conditions.

DefaultView | ViewsAllowed | Description
Single, Continuous Forms, or Datasheet | Both | Users can switch between Form view and Datasheet view.
Single or Continuous Forms | Form | Users can’t switch from Form view to Datasheet view.
Single or Continuous Forms | Datasheet | Users can switch from Form view to Datasheet view but not back again.
Datasheet | Form | Users can switch from Datasheet view to Form view but not back again.
Datasheet | Datasheet | Users can’t switch from Datasheet view to Form view.

See Also

AutoResize Property.


DefaultWorkspaceClone Method

Applies To

Application Object.

Description

You can use the DefaultWorkspaceClone method to create a new Workspace object without requiring the user to log in again. For example, if you need to conduct two sets of transactions simultaneously in separate workspaces, you can use the DefaultWorkspaceClone method to create a second Workspace object with the same user name and password without prompting the user for this information again.

Syntax

Application.DefaultWorkspaceClone

The DefaultWorkspaceClone method uses the following argument.

Argument | Description
Application | The Application object.

Remarks

The DefaultWorkspaceClone method creates a clone of the default Workspace object in Microsoft Access. The properties of the Workspace object clone have settings identical to those of the default Workspace object, except for the Name property setting. For the default Workspace object, the value of the Name property is always #Default Workspace#. For the cloned Workspace object, it is #CloneAccess#.

The UserName property of the default Workspace object indicates the name under which the current user logged in. The Workspace object clone is equivalent to the Workspace object that would be created if the same user logged in again with the same password.

Example

The following example clones the default workspace, then enumerates the properties of each workspace.

Sub CloneWorkspace()
    Dim wrkDefault As Workspace, wrkClone As Workspace
    Dim prp As Property

    ' Get default workspace.
    Set wrkDefault = DBEngine.Workspaces(0)
    ' Clone default workspace.
    Set wrkClone = Application.DefaultWorkspaceClone
    ' Enumerate properties of each workspace.
    For Each prp In wrkDefault.Properties
        Debug.Print ">>>"; prp.Name; "   "; prp.Value
    Next prp
    For Each prp In wrkClone.Properties
        Debug.Print ">>>"; prp.Name; "   "; prp.Value
    Next prpSub


Deftype Statements

Description

Used at module level to set the default data type for variables, arguments passed to procedures, and the return type for Function and Property Get procedures whose names start with the specified characters.

Syntax

DefBool letterrange[, letterrange] . . .DefByte letterrange[, letterrange] . . .DefInt letterrange[, letterrange] . . .DefLng letterrange[, letterrange] . . .DefCur letterrange[, letterrange] . . .DefSng letterrange[, letterrange] . . .DefDbl letterrange[, letterrange] . . .DefDate letterrange[, letterrange] . . .DefStr letterrange[, letterrange] . . .DefObj letterrange[, letterrange] . . .DefVar letterrange[, letterrange] . . .

The argument letterrange has the following syntax:

letter1[-letter2]

The letter1 and letter2 arguments specify the name range for which you can set a default data type. Each argument represents the first letter of the variable, argument, Function procedure, or Property Get procedure name and can be any letter of the alphabet. The case of letters in letterrange isn’t significant.

Remarks

The statement name determines the data type:

Statement | Data Type
DefBool | Boolean
DefByte | Byte
DefInt | Integer
DefLng | Long
DefCur | Currency
DefSng | Single
DefDbl | Double
DefDate | Date
Statement | Data Type
DefStr | String
DefObj | Object
DefVar | Variant

For example, in the following program fragment, Message is a string variable:

DefStr A-Q
. . .= "Out of stack space."

A Def type statement affects only the module where it is used. For example, a DefInt statement in one module affects only the default data type of variables, arguments passed to procedures, and the return type for Function and Property Get procedures declared in that module; the default data type of variables, arguments, and return types in other modules is unaffected. If not explicitly declared with a Def type statement, the default data type for all variables, all arguments, all Function procedures, and all Property Get procedures is Variant.

When you specify a letter range, it usually defines the data type for variables that begin with letters in the first 128 characters of the character set. However, when you specify the letter range A – Z, you set the default to the specified data type for all variables, including any that begin with international characters from the extended part of the character set (128 – 255).

Once the range A – Z has been specified, you can’t further redefine any subranges of variables using Def type statements. In fact, once a range has been specified, if you include a previously defined letter in another Def type statement, an error occurs. However, you can explicitly specify the data type of any variable, defined or not, using a Dim statement with an As type clause. For example, you can use the following code at module level to define a variable as a Double even though the default data type is Integer:

DefInt A-ZTaxRate As Double

Def type statements don’t affect elements of user-defined types since the elements must be explicitly declared.

See Also

Function Statement, Let Statement, Property Get Statement.

Example

This example shows various uses of the Def type statements to set default data types of variables and function procedures whose names start with specified characters. The default data type can be overridden only by explicit assignment using the Dim statement. Def type statements can only be used at the module level (that is, not within procedures).

' Variable names beginning with A through K default to Integer.A-K
' Variable names beginning with L through Z default to String.L-Z= 4                            ' Initialize Integer.= "Hello there"            ' Initialize String.= "Hello"                     ' Causes "Type mismatch" error.Calc As Double                    ' Explicitly set the type to Double.= 2.3455                        ' Assign a Double.

' Deftype statements also apply to function procedures.= ATestFunction(4)            ' Call user-defined function.
' ATestFunction function procedure definition.ATestFunction(INumber)
    ATestFunction = INumber * 2        ' Return value is an integer.Function


Delete, BeforeDelConfirm, AfterDelConfirm Events

Applies To

Form.

Description

These events occur:

  • Delete — when the user performs some action, such as pressing the DEL key, to delete a record, but before the record is actually deleted.
  • BeforeDelConfirm — after the user deletes one or more records, but before Microsoft Access displays a dialog box asking the user to confirm the deletions.
  • AfterDelConfirm — after the user confirms the deletions and the records are actually deleted or when the deletions are canceled.

Remarks

After a record is deleted, it’s stored in a temporary buffer. The BeforeDelConfirm event occurs after the Delete event (or if you’ve deleted more than one record, after all the records are deleted), but before the delete confirm dialog box is displayed. Canceling the BeforeDelConfirm event restores a record from the buffer and prevents the delete confirm dialog box from being displayed.

The AfterDelConfirm event occurs after a record is actually deleted or after a deletion is canceled. If the BeforeDelConfirm event isn’t canceled, the AfterDelConfirm event occurs after the delete confirm dialog box is displayed. The AfterDelConfirm event occurs even if the BeforeDelConfirm event is canceled. The AfterDelConfirm event procedure returns status information about the deletion. You can use a macro or event procedure associated with the AfterDelConfirm event to recalculate totals affected by the deletion of records.

If you cancel the Delete event, the BeforeDelConfirm and AfterDelConfirm events don’t occur and the delete confirm dialog box isn’t displayed.

By running a macro or executing an event procedure when the Delete event occurs, you can prevent a record from being deleted or allow a record to be deleted only under certain conditions. You can also use a Delete event to display a dialog box asking whether the user wants to delete a record before it’s deleted.

To delete a record, you must first click the record selector or choose Select Record from the Edit menu to select the record. If you click the record selector of the current record or choose Select Record, the Exit and LostFocus events for the control that has the focus occur. If you’ve changed any data in the record, the BeforeUpdate and AfterUpdate events for the record occur before the Exit and LostFocus events. If you click the record selector of a different record, the Current event for that record also occurs.

After you delete the record, the focus moves to the next record following the deleted record, and the Current event for that record occurs, followed by the Enter and GotFocus events for the first control in that record.

The BeforeDelConfirm event then occurs, just before Microsoft Access displays a dialog box asking you to confirm the deletion. After you respond to the dialog box (or after the deletion is confirmed or canceled), the AfterDelConfirm event occurs. (However, the BeforeDelConfirm and AfterDelConfirm events don’t occur and the deletion confirmation dialog box isn’t displayed if you set the Confirm Record Changes option in the Edit/Find tab of the Options dialog box to No.)

You can delete one or more records at a time. The Delete event occurs after each record is deleted. This enables you to access the data in each record before it’s actually deleted, and selectively confirm or cancel each deletion in the Delete macro or event procedure. When you delete more than one record, the Current event for the record following the last deleted record and the Enter and GotFocus events for the first control in this record don’t occur until all the records are deleted. In other words, a Delete event occurs for each selected record, but no other events occur until all the selected records are deleted. The BeforeDelConfirm and AfterDelConfirm events also don’t occur until all the selected records are deleted.

See Also

BeforeUpdate, AfterUpdate Events; Current Event.


Delete, BeforeDelConfirm, AfterDelConfirm Events -- Event Procedures

Description

To create an event procedure that is run when a Delete, BeforeDelConfirm, or AfterDelConfirm event occurs, set the OnDelete, BeforeDelConfirm, or AfterDelConfirm property to [Event Procedure], and click the Build button.

Syntax

Private Sub Form_Delete (Cancel As Integer)

Private Sub Form_BeforeDelConfirm (Cancel As Integer, Response As)

Private Sub Form_AfterDelConfirm (Status As Integer)

The Delete event procedure uses the following argument.

Argument | Description
Cancel | The setting determines if the Delete event occurs. Setting Cancel to True (-1) cancels the Delete event.

The BeforeDelConfirm event procedure uses the following arguments.

Argument | Description
Cancel | The setting determines if the BeforeDelConfirm event occurs. Setting Cancel to True (-1) cancels the BeforeDelConfirm event and prevents the delete confirm dialog box from being displayed. If the event is canceled, the original records are restored, but the AfterDelConfirm event still occurs. If Cancel is set to True (-1), the Response argument is ignored.
Setting Cancel is set to False (0), does not cancel the BeforeDelConfirm event and the value in the Response argument is used by Microsoft Access to determine the type of response to the delete event.
Response | An intrinsic constant that determines whether Microsoft Access displays a dialog box asking if the record should be deleted. The Response argument can have the following constants.

Constant | Description
acDataErrContinue | Enables Microsoft Access to delete records without prompting the user.
acDataErrDisplay | Displays the default message

The AfterDelConfirm event procedure uses the following argument.

Argument | Description
Status | An intrinsic constant that determines whether a record has been deleted. The Status argument can be any the following constants:

Constant | Description
acDeleteOK | Indicates the deletion was successful.
acDeleteCancel | Indicates the deletion was canceled in Visual Basic.
acDeleteUserCancel | Indicates the deletion was canceled by the user.

Remarks

The AfterDelConfirm event can’t be canceled.

You can use these events to customize how records are deleted. For example, when a user deletes a record, such as an employee record, the Delete event occurs. You can place code in the Delete event procedure to save the data from the Employee ID and Name fields in a temporary buffer. When the BeforeDelConfirm event occurs, you can prevent the delete confirm dialog box from being displayed by setting the Response argument to acDataErrContinue. This enables you to display a custom dialog box. When the AfterDelConfirm event occurs and the Status argument is set to acDeleteOK, you can do the actual delete in the table and clear the record from the temporary buffer.

See Also

Delete, BeforeDelConfirm, AfterDelConfirm Events — Macros.

Examples

This example shows how you can prevent a user from deleting records from a table.

To try this example, add the following code to the Declarations section of a form that is based on an Employees table. Switch to the form’s Datasheet view and try to delete a record.

Private Sub Form_Delete (Cancel As Integer)
    Cancel = True
    MsgBox "This record can't be deleted."Sub

The following example shows how you can use the BeforeDelConfirm event procedure to suppress the default confirmation dialog box and display a custom dialog box when a record is deleted. It also shows how you can use the AfterDelConfirm event procedure to display a message indicating whether the deletion progressed in the usual way or whether it was canceled in Visual Basic or by the user.

To try this example, add the following code to the Declarations section of a form that is based on a table or query.

Private Sub Form_BeforeDelConfirm (Cancel As Integer, _
        Response As Integer)
    ' Suppress default delete confirm dialog box.
    Response = acDataErrContinue
    ' Display custom dialog box.
    If MsgBox ("Delete this record?", vbOKCancel) = vbCancel Then
        Cancel = True
    End IfSub
Sub Form_AfterDelConfirm (Status As Integer)
    Select Case Status
        Case acDeleteOK
            MsgBox "Deletion occurred normally."
        Case acDeleteCancel
            MsgBox "Programmer canceled the deletion."
        Case acDeleteUserCancel
            MsgBox "User canceled the deletion."
    End SelectSub


Delete, BeforeDelConfirm, AfterDelConfirm Events -- Macros

Description

To run a macro when a Delete, BeforeDelConfirm, or AfterDelConfirm event occurs, set the OnDelete, BeforeDelConfirm, or AfterDelConfirm property to the name of the macro.

Remarks

You can use a Delete macro to display a dialog box asking whether the user wants to delete a record before it’s deleted.

You can use a BeforeDelConfirm or AfterDelConfirm macro to respond whenever the user deletes a record. However, the BeforeDelConfirm and AfterDelConfirm macros can’t set the argument determining whether the delete confirm dialog box is displayed and can’t return the argument indicating the status of the deletion, so you typically use event procedures with these events.

You can use the CancelEvent action in a Delete macro to cancel the deletion.

You can use the CancelEvent action in a BeforeDelConfirm macro to cancel the deletion of all the deleted records. If you do this, the delete confirm dialog box isn’t displayed. However, the AfterDelConfirm event occurs even if you cancel the BeforeDelConfirm event.

You can’t use the CancelEvent action in an AfterDelConfirm macro.

See Also

Delete, BeforeDelConfirm, AfterDelConfirm Events — Event Procedures.


DeleteControl, DeleteReportControl Statements

Description

You can use the DeleteControl and DeleteReportControl statements to delete a specified control from a form or report.

For example, suppose you have a procedure that must be run the first time each user logs into your database. You can set the OnClick property of a button on the form to this procedure. Once the user has logged on and run the procedure, you can use the DeleteControl statement to dynamically remove the command button from the form.

Syntax

DeleteControl formname, controlname DeleteReportControl reportname, controlname

The DeleteControl and DeleteReportControl statements have the following arguments.

Argument | Description
formname, reportname | A string expression identifying the name of the form or report containing the control you want to delete.
controlname | A string expression identifying the name of the control you want to delete.

Remarks

The DeleteControl and DeleteReportControl statements are available only in form Design view or report Design view, respectively.

Tip If you are building a wizard that deletes a control from a form or report, your wizard must open the form or report in Design view before it can delete the control.

See Also

CreateControl, CreateReportControl Functions.

Example

The following example creates a form with a command button and displays a message asking if the user wants to delete the command button. If the user chooses Yes, the command button is deleted.

Sub DeleteCommandButton()
    Dim frm As Form, ctlNew As Control
    Dim strMsg As String, intResponse As Integer, intDialog As Integer

    ' Create new form and get pointer to it.
    Set frm = CreateForm
    ' Create new command button.
    Set ctlNew = CreateControl(frm.Name, acCommandButton)
    ' Restore form.
    DoCmd.Restore
    ' Set caption.
    ctlNew.Caption = "New Command Button"
    ' Size control.
    ctlNew.SizeToFit
    ' Prompt user to delete control.
    strMsg = "About to delete " & ctlNew.Name &". Continue?"
    intDialog = vbYesNo + vbCritical + vbDefButton2
    intResponse = MsgBox(strMsg, intDialog)
    If intResponse = vbYes Then
        ' Delete control.
        DeleteControl frm.Name, ctlNew.Name
    End IfSub


DeleteObject Action

Description

You can use the DeleteObject action within a macro to delete a specified database object.

Setting

The DeleteObject action uses the following arguments.

Action argument | Description
Object Type | The type of object to delete. Click Table, Query, Form, Report, Macro, or Module in the Object Type box in the Action Arguments section of the Macro window. To delete the object selected in the Database window, leave this box blank.

Action argument | Description
Object Name | The name of the object to delete. The Object Name box shows all objects in the database of the type selected by the Object Type argument. If you left the Object Type box blank, leave this box blank also.
If you run a macro containing the DeleteObject action in a library database, Microsoft Access will look for the object with this name first in the library database, then in the current database.

Warning If you leave the Object Type and Object Name arguments blank, Microsoft Access will delete the object selected in the Database window without displaying a warning message when it encounters the DeleteObject action. To select an object in the Database window, you can use the SelectObject action with the In Database Window argument set to Yes.

Remarks

You can use the DeleteObject action to delete temporary objects you’ve created while running the macro. For example, you could use the OpenQuery action to run a make-table query that creates a temporary table. When you’re finished using the temporary table, you can use the DeleteObject action to delete it.

This action has the same effect as selecting an object in the Database window and then pressing the DEL key or clicking Delete on the Edit menu. When you use the DeleteObject action, you don’t need to select the object in the Database window, and Microsoft Access doesn’t display a dialog box asking you to confirm the deletion.

To run the DeleteObject action in Visual Basic, you can use the DeleteObject method of the DoCmd object.

See Also

DeleteObject Method, SelectObject Action.


DeleteObject Method

Applies To

DoCmd Object.

Description

The DeleteObject method carries out the DeleteObject action in Visual Basic. For more information on how the action and its arguments work, see the action topic.

Syntax

DoCmd.DeleteObject [objecttype, objectname]

The DeleteObject method uses the following arguments.

Argument | Description
objecttype | One of the following intrinsic constants: acTable acQuery acForm acReport acMacro acModule
objectname | A string expression that is the valid name of an object of the type selected with the objecttype argument.
If you run Visual Basic code containing the DeleteObject method in a library database, Microsoft Access looks for the object with this name first in the library database, then in the current database.

Remarks

If you leave the objecttype and objectname arguments blank, Microsoft Access deletes the object selected in the Database window. To select an object in the Database window, you can use the SelectObject action or SelectObject method with the In Database Window argument set to Yes (True).

See Also

DeleteObject Action, DoCmd Object, SelectObject Method.

Example

This example deletes the specified table.

DoCmd.DeleteObject acTable, "Former Employees Table"


DeleteReportControl Statement

See DeleteControl, DeleteReportControl Statements.


DeleteSetting Statement

Description

Deletes a section or key setting from the Windows Registry entry.

Syntax

DeleteSetting(appname, section[, key])

The DeleteSetting statement syntax has these named arguments:

Part | Description
appname | String expression containing the name of the application or project to which the section or key setting applies.
section | String expression containing the name of the section where the key setting is being deleted. If only appname and section are provided, the specified section is deleted along with all related key settings.
key | String expression containing the name of the key setting being deleted.

Remarks

If all arguments are provided, the specified key setting is deleted. However, the DeleteSetting statement does nothing if the specified section or key setting does not exist.

See Also

GetAllSettings Function, GetSetting Function, SaveSetting Statement.

Example

The following example first uses the SaveSetting statement to make entries in the Windows Registry (or .ini file on 16-bit Windows platforms) for the MyApp application, then uses the DeleteSetting statement to remove them. Because no key is specified, the whole section is deleted, including the section name and all its keys.

' Place some settings in the registry.(appname := "MyApp", section := "Startup", _
    key := "Top", setting := 75)("MyApp","Startup", "Left", 50)
' Remove section and all its settings from registry.("MyApp", "Startup")


Derived Math Functions

Description

The following is a list of nonintrinsic math functions that can be derived from the intrinsic math functions:

Function | Derived equivalents
Secant | Sec(X) = 1 / Cos(X)
Cosecant | Cosec(X) = 1 / Sin(X)
Cotangent | Cotan(X) = 1 / Tan(X)
Inverse Sine | Arcsin(X) = Atn(X / Sqr(-X * X + 1))
Inverse Cosine | Arccos(X) = Atn(-X / Sqr(-X * X + 1)) + 2 * Atn(1)

Function | Derived equivalents
Inverse Secant | Arcsec(X) = Atn(X / Sqr(X * X - 1)) + Sgn((X) -1) * (2 * Atn(1))
Inverse Cosecant | Arccosec(X) = Atn(X / Sqr(X * X - 1)) + (Sgn(X) - 1) * (2 * Atn(1))
Inverse Cotangent | Arccotan(X) = Atn(X) + 2 * Atn(1)
Hyperbolic Sine | HSin(X) = (Exp(X) - Exp(-X)) / 2
Hyperbolic Cosine | HCos(X) = (Exp(X) + Exp(-X)) / 2
Hyperbolic Tangent | HTan(X) = (Exp(X) - Exp(-X)) / (Exp(X) + Exp(-X))
Hyperbolic Secant | HSec(X) = 2 / (Exp(X) + Exp(-X))
Hyperbolic Cosecant | HCosec(X) = 2 / (Exp(X) - Exp(-X))
Hyperbolic Cotangent | HCotan(X) = (Exp(X) + Exp(-X)) / (Exp(X) - Exp(-X))
Inverse Hyperbolic Sine | HArcsin(X) = Log(X + Sqr(X * X + 1))
Inverse Hyperbolic Cosine | HArccos(X) = Log(X + Sqr(X * X - 1))
Inverse Hyperbolic Tangent | HArctan(X) = Log((1 + X) / (1 - X)) / 2
Inverse Hyperbolic Secant | HArcsec(X) = Log((Sqr(-X * X + 1) + 1) / X)
Inverse Hyperbolic Cosecant | HArccosec(X) = Log((Sgn(X) * Sqr(X * X + 1) +1) / X)
Inverse Hyperbolic Cotangent | HArccotan(X) = Log((X + 1) / (X - 1)) / 2
Logarithm to base N | LogN(X) = Log(X) / Log(N)

See Also

Atn Function, Cos Function, Exp Function, Log Function, Sin Function, Sqr Function, Tan Function.


Description Property (Microsoft Access)

Applies To

Query, Query Fields, Table, Table Fields.

Description

You can use the Description property to provide information about objects contained in the database window as well as about individual table or query fields.

Setting

For a database object, choose the Properties command from the View menu and enter the description text in the Description box. For tables or queries, you can also enter the description in the table’s or query’s property sheet. An object’s description appears next to the object’s name in the database window

For individual table or query fields, enter the field description in the upper portion of table Design view, or in the Query window. The maximum length is 255 characters.

In Visual Basic, to set this property for the first time you must create an application-defined property using the CreateProperty method.

Remarks

An object’s description is displayed in the Description column in Database window Details view by clicking Details View on the View menu.

If you create controls by dragging a field from the field list, Microsoft Access copies the field’s Description property to the control’s StatusBarText property.

Note For a linked table, Microsoft Access displays the connection information in the Description property.

See Also

Caption Property, Description Property (Microsoft Office 95 Data Access Reference), Object Properties.


Description Property (Visual Basic)

Applies To

Err Object.

Description

Returns or sets a descriptive string associated with an error.

Syntax

object.Description [= stringexpression]

The Description property syntax has these parts:

Part | Description
object | Always the Err object.
stringexpression | A string expression containing a description of the error.

Remarks

The Description property comprises a short description of the error. Use this property to alert the user to an error that you cannot or do not want to handle. When generating a user-defined error, assign a short description of your error to this property. If Description is not filled in, and the value of Number corresponds to a Visual Basic run-time error, the string returned by the Error function is placed in Description when the error is generated.

See Also

Err Object, Error Function, HelpContext Property (Visual Basic), HelpFile Property (Visual Basic), LastDLLError Property, Number Property, Source Property.

Example

This example assigns a user-defined message to the Description property of the Err object.

Err.Description = "It was not possible to access an object necessary " _
    & "for this operation."


DestConnectStr, DestinationDB, DestinationTable Properties

Applies To

Query.

Description

You can use these properties with make-table or append queries only.

  • DestinationDB — You can use this property to specify the type of application used to create an external database.
  • DestConnectStr — You can use this property to specify the connection string for the name of the database that will contain the new table (for make-table queries) or the name of the database that contains the table to which data will be appended (for append queries).
  • DestinationTable — You can use this property to specify the name of the new table or the name of the table to be appended to that will hold the results of the query.

Note The DestConnectStr, DestinationDB, and DestinationTable properties apply only to make-table and append queries.

Setting

You set the DestConnectStr, DestinationDB, and DestinationTable properties using a string expression.

The default setting for DestinationDB property is “(current)”, which refers to the currently active database.

You can set these properties in the query property sheet, or in SQL view of the Query window.

In the SQL statement for an append query, the table name in the INSERT INTO statement corresponds to the DestinationTable property setting. The IN clause corresponds to the DestinationDB and DestConnectStr property settings.

In the SQL statement for a make-table query, the table name in the INTO clause corresponds to the DestinationTable property setting. The IN clause corresponds to the DestinationDB and DestConnectStr property settings.

Note Microsoft Access sets these properties automatically based on the information you enter in the query property sheet or in SQL view of the Query window.

Remarks

When you choose Make Table or Append on the Query menu, Microsoft Access prompts you for the information needed to set these properties. Microsoft Access uses the value you enter in the Table Name box to set the DestinationTable property, and it uses the information you type in the File Name box to set the DestConnectStr and DestinationDB properties.

To use the property sheet to specify a table in a Microsoft Access database, enter the name of the table in the Destination Table box (for example, Clients). In the Destination DB box, enter the path and database name without the filename extension (for example, C:\Accounts\Customers). Microsoft Access adds the extension automatically. You don’t need to set the DestConnectStr property.

To specify a table in a database created by a different product, such as Paradox®, enter the name of the table in the Destination Table box. In the Destination DB box, enter the path (for example, C:\Paradoxdata). In the Dest Connect Str box, enter the specifier for the database type (for example, Paradox 3.5). For a list of specifiers, see the Connect property.

To specify an Open Database Connectivity (ODBC) database, enter the name of the database in the Dest Connect Str box along with additional information, such as a logon identification (ID) and password, as required by the product. For example, you might use the following setting for a Microsoft SQL Server database.

ODBC;DSN=salessrv;UID=jace;PWD=password;DATABASE=sales;

For more information about ODBC drivers, such as Microsoft SQL Server, see the online Help provided with the driver.

You don’t need to set the DestinationDB property for ODBC databases.

See Also

Source Property (Microsoft Access); SourceConnectStr, SourceDatabase Properties; TransferDatabase Action.

Example

The following example appends the records in the Customers table to the Clients table in a Microsoft Access database named Clients in the C:\Data directory. You can enter this SQL statement in SQL view of the Query window.

INSERT INTO Clients IN 'C:\Data\Clients.mdb'DISTINCTROW Customers.[CompanyName], Customers.PhoneCustomers;

The next example creates a new table named Contacts in a Paradox version 3.5 database in the C:\Paradoxdata directory.

SELECT DISTINCTROW Customers.[CompanyName], Customers.PhoneContacts IN 'C:\Paradoxdata' [Paradox 3.5]Customers;


DFirst, DLast Functions

Description

You can use the DFirst and DLast functions to return a random record from a particular field when you simply need any value from that field.

Syntax

DFirst(expr, domain[, criteria])DLast(expr, domain[, criteria])

The DFirst and DLast functions use the following arguments.

Argument | Description
expr | Expression that identifies the field from which you want find the first or last value. It can be either a string expression identifying a field in a table or query, or an expression that performs a calculation on data in that field. You can include in expr the name of a table field, a control on a form, a constant, or a function. If expr includes a function, it can be either built-in or user-defined, but not another domain aggregate or SQL aggregate function.
domain | String expression identifying the set of records that constitutes the domain.
criteria | Optional string expression used to restrict the range of data on which DFirst or DLast is performed. For example, criteria is often equivalent to the WHERE clause in an SQL expression, without the word WHERE. If criteria is omitted, DFirst and DLast evaluate expr against the entire domain. Any field included in criteria must also be a field in domain; otherwise, DFirst and DLast return a Null.

Remarks

You can use DFirst and DLast in a calculated control on a form or report, in a query expression, or in a macro or module.

You can use DFirst and DLast to return a random record in a table or query.

If you want to return the first or last record in a set of records, you should create a query sorted as either Ascending or Descending and set the TopValues property to 1. For more information, see the TopValues property topic. From Visual Basic, you can also create a Recordset object, and use the MoveFirst or MoveLast method to return the first or last record in a set of records.

See Also

DLookup Function, Domain Aggregate Functions.


Dim Statement

Description

Declares variables and allocates storage space.

Syntax

Dim varname[([subscripts])][As [New] type][, varname[([subscripts])][As [New] åtype]] . . .

The Dim statement syntax has these parts:

Part | Description
varname | Name of the variable; follows standard variable naming conventions.
subscripts | Dimensions of an array variable; up to 60 multiple dimensions may be declared. The subscripts argument uses the following syntax: [lower To] upper [,[lower To] upper] . . .
When not explicitly stated in lower, the lower bound of an array is controlled by the Option Base statement. The lower bound is zero if no Option Base statement is present.
New | Keyword used to indicate that a declared object variable is a new instance of a Visual Basic object or an externally creatable OLE Automation object. The New keyword can’t be used to declare variables of any intrinsic data type and can’t be used to declare instances of dependent OLE Automation objects.
type | Data type of the variable; may be Byte, Boolean, Integer, Long, Currency, Single, Double, Date, String (for variable-length strings), String * length (for fixed-length strings), Object, Variant, a user-defined type, or an object type. Use a separate As type clause for each variable you declare.

Remarks

Variables declared with Dim at the module level are available to all procedures within the module. At the procedure level, variables are available only within the procedure.

Use the Dim statement at module or procedure level to declare the data type of a variable. For example, the following statement declares a variable as an Integer.

Dim NumberOfEmployees As Integer

Also use a Dim statement to declare the object type of a variable. The following declares a variable for a new instance of a worksheet.

Dim X As New Worksheet

If the New keyword is not used when declaring an object variable, no instance of the object actually exists. A variable that refers to an object must be assigned an existing object using the Set statement before it can be used. Until it is assigned an object, the declared object variable has the special value Nothing, which indicates that it does not refer to any particular instance of an object.

You can also use the Dim statement with empty parentheses to declare a dynamic array. After declaring a dynamic array, use the ReDim statement within a procedure to define the number of dimensions and elements in the array. If you try to redeclare a dimension for an array variable whose size was explicitly specified in a Private, Public, or Dim statement, an error occurs.

If you do not specify a data type or object type, and there is no Def type statement in the module, the variable is Variant by default.

When variables are initialized, a numeric variable is initialized to 0, a variable-length string is initialized to a zero-length string, and a fixed-length string is filled with zeros. Variant variables are initialized to Empty. Each element of a user-defined type variable is initialized as if it were a separate variable.

Tip When you use the Dim statement in a procedure, it is a generally accepted programming practice to put the Dim statement at the beginning of the procedure.

See Also

Array Function, Option Base Statement, Private Statement, Public Statement, ReDim Statement, Set Statement, Static Statement, Type Statement.

Specifics (Microsoft Access)

You can use the New keyword to declare an object variable of a specific type. If you include the New keyword in your variable declaration, you automatically create a new instance of the object and point the object variable to it. Therefore, if you declare an object variable using the New keyword, you don’t need to use the Set statement.

Using the New keyword, you can create an object variable to point to any type of object — a Microsoft Access object, data access object, user-defined object, or Visual Basic Collection object. For example, you can use the following statements to create a new TableDef object.

' Create object variable and point it to new object.tdfOrders As New TableDef
' Set Name property of object..Name = "Orders"

These statements are equivalent to the following two statements.

' Create an empty object variable.tdfOrders As TableDef
' Create the new TableDef object and point the object variable to it.
' "dbs" is an object variable pointing to the current database.tdfOrders = dbs.CreateTableDef("Orders")

You should use the New keyword to create a Collection object. For example, the following statement creates a new Collection object.

Dim colCustomers As New Collection

You should also use the New keyword to create a new instance of a user-defined object. For example, a form whose module contains public procedures can be a user-defined object. If a form called CustomerObject has a module in which you have defined procedures as public, you can create a new instance of this form object from another module, and its procedures become methods and properties of the object. You can then manipulate the form object by calling the methods and setting the properties you defined in the form module.

' Create new instance of your object.frmCustomer As New Form_CustomerObject
' Call the method Show from the form object..Show

You can use the New keyword to create a new instance of a Microsoft Access object from some applications that are OLE Automation controllers. Check the other application’s documentation to determine whether or not the application supports this syntax.

For example, from another OLE Automation controller, assuming you have established a reference to the Microsoft Access type library, you can create a new Microsoft Access object with the following code.

Dim appAccess As New Access.Application

Example

This example shows various uses of the Dim statement to declare variables. It also shows the Dim statement being used to declare arrays. The default lower bound for array subscripts is 0 and can be overridden at the module level using the Option Base statement.

' AnyValue and MyValue are declared as Variant by default with values
' set to Empty.AnyValue, MyValue
' Explicitly declare a variable of type Integer.Number As Integer
' Multiple declarations on a single line. AnotherVar is of type Variant
' because its type is omitted.AnotherVar, Choice As Boolean, BirthDate As Date
' DayArray is an array of Variants with 51 elements indexed, from
' 0 thru 50, assuming Option Base is set to 0 (default) for
' the current module.DayArray(50)
' Matrix is a two-dimensional array of integers.Matrix(3, 4) As Integer
' MyMatrix is a three-dimensional array of doubles with explicit
' bounds.MyMatrix(1 To 5,  4 To 9,  3 To 5) As Double
' BirthDay is an array of dates with indexes from 1 to 10.BirthDay(1 To 10) As Date
' MyArray is a dynamic array of variants.MyArray()


Dir Function

Description

Returns the name of a file, directory, or folder that matches a specified pattern or file attribute, or the volume label of a drive.

Syntax

Dir[(pathname[, attributes])]

The Dir function syntax has these parts:

Part | Description
pathname | String expression that specifies a filename — may include directory or folder, and drive. Null is returned if pathname is not found.
attributes | Constant or numeric expression, the sum of which specifies file attributes. If omitted, all normal files are returned that match pathname.

Settings

The attributes argument settings are:

Constant | Value | Description
vbNormal | 0 | Normal.
vbHidden | 2 | Hidden.
vbSystem | 4 | System file.
vbVolume | 8 | Volume label; if specified, all other attributes are ignored.
vbDirectory | 16 | Directory or folder.

Note These constants are specified by Visual Basic for applications. As a result, the names can be used anywhere in your code in place of the actual values.

Remarks

Dir supports the use of * (multiple character) and ? (single character) wildcards to specify multiple files.

You must specify pathname the first time you call the Dir function, or an error occurs. If you also specify file attributes, pathname must be included.

Dir returns the first filename that matches pathname. To get any additional filenames that match pathname, call Dir again with no arguments. When no more filenames match, Dir returns a zero-length string. Once a zero-length string is returned, you must specify pathname in subsequent calls or an error occurs. You can change to a new pathname without retrieving all of the filenames that match the current pathname. However, you can’t recursively call the Dir function.

Tip Because filenames are retrieved in no particular order, you may want to store returned filenames in an array and then sort the array. Also, calling Dir with the vbDirectory attribute does not continually return subdirectories.

See Also

ChDir Statement, CurDir Function.

Example

This example uses the Dir function to check if certain files and directories exist.

' Returns "WIN.INI" if it exists.= Dir("C:\WINDOWS\WIN.INI")
' Returns filename with specified extension. If more than one *.INI
' file exists, the first file found is returned.= Dir("C:\WINDOWS\*.INI")
' Call Dir again without arguments to return the next *.INI file in the
' same directory.= Dir
' Return first *.TXT file with a set hidden attribute.= Dir("*.TXT", vbHidden)

' Display the names in C:\ that represent directories.= "c:\"    ' Set the path.= Dir(MyPath, vbDirectory)    ' Retrieve the first entry.While MyName <> ""    ' Start the loop.
    ' Ignore the current directory and the encompassing directory.
    If MyName <> "." And MyName <> ".." Then
        ' Use bitwise comparison to make sure MyName is a directory.
        If (GetAttr(MyPath & MyName) And vbDirectory) = vbDirectory Then
            Debug.Print MyName    ' Display entry only if it
        End If    ' it represents a directory.
    End If
    MyName = Dir    ' Get next entry.


Dirty Property

Applies To

Form.

Description

You can use the Dirty property to determine whether the current record has been modified since it was last saved. For example, you may want to ask the user whether changes to a record were intended and, if not, allow the user to move to the next record without saving the changes.

Setting

The Dirty property has the following settings.

Setting | Description | Visual Basic
True | The current record has been changed. | True (-1)
False | The current record has not been changed. | False (0)

This property is available only in Form view and Datasheet view.

This property is read-only and available only in a macro or using Visual Basic.

Remarks

When a record is saved, the Dirty property is automatically set to False. When a user makes changes to a record, the property is set to True.

Example

The following example enables the btnUndo button when data is changed. The UndoEdits( ) subroutine is called from the AfterUpdate event of text box controls. Clicking the enabled btnUndo button restores the original value of the control using the OldValue property.

Sub UndoEdits()
    If Me.Dirty Then
        Me!btnUndo.Enabled = True            ' Enable button.
    Else
        Me!btnUndo.Enabled = False            ' Disable button.
    End IfSub
btnUndo_Click()
    Dim intNumControls As Integer, i As Integer
    Dim C As Control
        intNumControls = Forms!EditForm.Count
        For i = 0 to intNumControls - 1    ' For each control.
            Set C = Forms!EditForm(i)
            If TypeOf C Is TextBox Then    ' If control is TextBox.
                C.Value = C.OldValue        ' Restore Old Value.
            End If
        Next iSub


DisplayControl Property

Applies To

Query Fields, Table Fields.

Description

You can use the DisplayControl property in table Design view to specify the default control you want to use for displaying a field.

Setting

The DisplayControl property contains a drop-down list of the available controls for the selected field. For fields with a Text or Number data type, the DisplayControl property can be set to Text Box, List Box, or Combo Box. For fields with a Yes/No data type, the DisplayControl property can be set to Check Box, Text Box, or Combo Box.

You can set this property in the table’s property sheet in table Design view by clicking the Lookup tab under Field Properties.

Microsoft Access sets the DisplayControl property automatically when you select Lookup Wizard as the data type for a field in table Design view.

Remarks

When you select a control for the DisplayControl property, any additional properties needed to configure the control are also displayed on the Lookup tab.

Tip Let Microsoft Access set the DisplayControl property and any related properties for you by using the Lookup Wizard.

Setting the DisplayControl property and any related control type properties will affect the field display in both Datasheet view and Form view. The field is displayed using the control and control property settings set in table Design view. If a field had its DisplayControl property set in table design view and you drag it from the field list in form Design view, Microsoft Access copies the appropriate properties to the control’s property sheet.


DisplayType Property

Applies To

Bound Object Frame Control, Chart Control, Unbound Object Frame Control.

Description

You can use the DisplayType property to specify whether Microsoft Access displays an OLE object’s content or an icon. For example, if the OLE object is a Microsoft Word document and you set this property to Content, the control displays the Word document; if you set this property to Icon, the control displays the Word icon.

Setting

The DisplayType property uses the following settings.

Setting | Description | Visual Basic
Content | (Default) When the control contains an OLE object, the control displays the object’s data, such as a document or spreadsheet. | acOLEDisplayContent (0)
Icon | When the control contains an OLE object, the control displays the object’s icon. | acOLEDisplayIcon (1)

You can set the DisplayType property using the property sheet, a macro, or Visual Basic. You can also set this property in a control’s default control style.

For a bound object frame, the DisplayType property can be set only in Design view but can be read in all views. For an unbound object frame or chart, the property can be set in the Insert Object dialog box when the object is created.

Remarks

The DisplayType property determines the default setting of the Display As Icon check box in the Paste Special and Object dialog boxes. When you display these dialog boxes in Form view, Datasheet view, or Design view, the Display As Icon check box is automatically selected if the DisplayType property is set to Icon. For example, you will see these boxes selected when using Visual Basic to set the control’s Action property to acOLEInsertObjDlg or acOLEPasteSpecialDlg.

The DisplayType property setting has no effect on the state of the Display As Icon check box in the Object dialog box when you insert an object into an unbound object frame. When you paste an object from the Clipboard, the Display As Icon check box reflects the state of the object on the Clipboard.

Changing the DisplayType property of a bound object frame doesn’t affect the display of existing objects in the control; however, it will affect new objects that you add to the control using the Object command on the Insert menu.

See Also

Action Property.


DisplayWhen Property

Applies To

Bound Object Frame Control, Chart Control, Check Box Control, Combo Box Control, Command Button Control, Form Section, Image Control, Label Control, Line Control, List Box Control, Option Button Control, Option Group Control, Rectangle Control, Subform/Subreport Control, Text Box Control, Toggle Button Control, Unbound Object Frame Control.

Description

You can use the DisplayWhen property to specify which of a Form’s sections or controls you want displayed on screen and in print.

Note The DisplayWhen property applies only to all controls (except page breaks) on a form.

Setting

The DisplayWhen property uses the following settings.

Setting | Description | Visual Basic
Always | (Default) The object appears in Form view and when printed. | 0
Print Only | The object is hidden in Form view but appears when printed. | 1
Screen Only | The object appears in Form view but not when printed. | 2

You can set this property in the object’s property sheet, a macro, or Visual Basic.

For controls, you can set this property using the control’s default control style.

Remarks

In many cases certain controls are useful only in Form view. To prevent Microsoft Access from printing these controls, you can set their DisplayWhen property to Screen Only. For example, you might have a command button or instructions on a form that you don’t want printed. Or you might have form header and form footer sections that you don’t want displayed on screen but that you do want printed. In this case, you should set the DisplayWhen property to Print Only.

Tip For reports, use the Format and Retreat events to specify an event procedure or macro that sets the Visible property of controls you don’t want printed.

See Also

Enabled, Locked Properties; Visible Property (Microsoft Access).


DividingLines Property

Applies To

Form.

Description

You can use the DividingLines property to specify whether dividing lines will separate sections on a form or records displayed on a continuous form.

Setting

The DividingLines property uses the following settings.

Setting | Description | Visual Basic
Yes | (Default) Dividing lines will separate sections and records on continuous forms. | True (-1)
No | There are no dividing lines. | False (0)

You can set the DividingLines property in the form’s property sheet, a macro, or using Visual Basic.

This property can be set in any view.


DLookup Function

Description

You can use the DLookup function to get the value of a particular field from a specified set of records (domain). Use DLookup in a macro or module, in a query expression, or in a calculated control on a form or report.

You can use DLookup to display the value of a field that is not in the record source for your form or report. For example, suppose you have a form based on an Order Details table. The form displays the OrderID, ProductID, UnitPrice, Quantity, and Discount fields. However, the ProductName field is in another table, the Products table. You could use DLookup in a calculated control to display the ProductName on the same form.

Syntax

DLookup(expr, domain[, criteria])

The DLookup function uses the following arguments.

Part | Description
expr | Expression that identifies the field whose value you want to return. It can be a string expression identifying a field in a table or query, or it can be an expression that performs a calculation on data in that field. You can include in expr the name of a table field, a control on a form, a constant, or a function. If expr includes a function, it can be either built-in or user-defined, but not another domain aggregate or SQL aggregate function.
domain | String expression identifying the set of records that constitutes the domain. It can be a table name or a query name.
criteria | Optional string expression used to restrict the range of data on which DLookup is performed. For example, criteria is often equivalent to the WHERE clause in an SQL expression, without the word WHERE. If criteria is omitted, DLookup evaluates expr against the entire domain. Any field included in criteria must also be a field in domain; otherwise, DLookup returns a Null.

Remarks

DLookup finds a value in the field or expression defined by expr from the table or query referred to by domain, according to any restrictions specified by criteria.

DLookup returns a single field value based on the information specified in criteria. Although criteria is an optional argument, if you don’t supply a value for criteria, DLookup returns a random value in the domain.

If no record satisfies criteria or if domain contains no records, DLookup returns a Null.

If more than one field meets criteria, DLookup returns the first occurrence. You should specify criteria that will ensure that the field value returned by DLookup is unique. You may want to use a primary key value for your criteria, such as [EmployeeID] in the following example, to ensure that DLookup returns a unique value.

X = DLookup("[LastName]", "Employees", "[EmployeeID] = 1")

Whether you use DLookup in a macro or module, a query expression, or a calculated control, you must construct the criteria argument carefully to ensure that it will be evaluated correctly.

You can use DLookup to specify criteria in the Criteria row of a query, within a calculated field expression in a query, or in the Update To row in an update query.

You can also use DLookup in an expression in a calculated control on a form or report if the field that you need to display is not in the record source on which your form or report is based. For example, suppose you have an Orders form with a text box called SKU that displays the ProductID field, and you want to look up ProductName from a Products table, based on the value in the text box. You could create another text box and set its ControlSource property to the following expression.

=DLookup("[ProductName]", "Products", "[ProductID] ='" _
    & Forms!Orders!SKU & "'")

Tips Although you can use DLookup to display a value from a field in a foreign table, it may be more efficient to create a query that contains the fields that you need from both tables, and base your form or report on that query.

You can also use the Lookup Wizard to find values in a foreign table.

Note Unsaved changes to records in domain are not included when you use this function. If you want the DLookup function to be based on the changed values, you must first save the changes by choosing the Save Record command from the File menu, moving the focus to another record, or using the Update method.

See Also

Domain Aggregate Functions.

Example

This example returns name information from the CompanyName field of the record satisfying criteria. The domain is a Shippers table. The criteria argument restricts the resulting set of records to those for which ShipperID equals 1.

Dim strX As String= DLookup("[CompanyName]", "Shippers", "[ShipperID] = 1")

The following example from the Shippers table uses the form control ShipperID to provide criteria for DLookup. Note that the reference to the control is not included in the quotation marks that denote the strings. This ensures that each time the DLookup function is called, Microsoft Access will obtain the current value from the control.

Dim strX As String= DLookup("[CompanyName]", "Shippers", "[ShipperID] =" _
    & Forms!Shippers!ShipperID)

The next example uses a variable, intSearch, to perform a lookup.

Dim intSearch As Integer, strX As String= 1= DLookup("[CompanyName]", "Shippers", _
    "[ShipperID] = " & intSearch)


DMin, DMax Functions

Description

You can use the DMin and DMax functions to determine the minimum and maximum values in a specified set of records (domain). Use DMin and DMax in a macro or module, in a query expression, or in a calculated control.

For example, you could use DMin and DMax in calculated controls on a report to display the greatest and least order amounts for a particular customer. Or you could use DMin in a query expression to display all orders with a discount greater than the minimum possible discount.

Syntax

DMin(expr, domain[, criteria])DMax(expr, domain[, criteria])

The DMin and DMax functions use the following arguments.

Argument | Description
expr | Expression that identifies the field for which you want to find the minimum or maximum value. It can be a string expression identifying a field in a table or query, or it can be an expression that performs a calculation on data in that field. You can include in expr the name of a table field, a control on a form, a constant, or a function. If expr includes a function, it can be either built-in or user-defined, but not another domain aggregate or SQL aggregate function.
domain | String expression identifying the set of records that constitutes the domain. It can be a table name or a query name.
criteria | Optional string expression used to restrict the range of data on which DMin or DMax is performed. For example, criteria is often equivalent to the WHERE clause in an SQL expression, without the word WHERE. If criteria is omitted, DMin and DMax evaluate expr against the entire domain. Any field included in criteria must also be a field in domain, otherwise DMin and DMax returns a Null.

Remarks

DMin and DMax find the least and greatest value in the field or expression defined by expr from the table or query referred to by domain, according to any restrictions specified by criteria.

DMin and DMax return the minimum and maximum values that satisfy criteria. If expr identifies numeric data, DMin and DMax return numeric values. If expr identifies string data, they return the string that is first or last alphabetically.

DMin and DMax ignore Null values in the field referenced by expr. However, if no record satisfies criteria or if domain contains no records, DMin and DMax return a Null.

Whether you use DMin or DMax in a macro or module, a query expression, or a calculated control, you must construct the criteria argument carefully to ensure that it will be evaluated correctly.

You can use DMin and DMax to specify criteria in the Criteria row of a query, in a calculated field expression in a query, or in the Update To row of an update query.

Note You can use DMin and DMax or Min and Max in a calculated field expression in a totals query. If you use DMin or DMax, values are evaluated before the data is grouped. If you use Min or Max, the data is grouped before values in the field expression are evaluated.

Use DMin or DMax in a calculated control when you need to specify criteria to restrict the range of data on which the function is performed. For example, to display the maximum freight charged for an order shipped to California, set the ControlSource property of a text box to the following expression.

=DMax("[Freight]", "Orders", "[ShipRegion] = 'CA'")

If you simply want to find the minimum or maximum value of all records in domain, use the Min or Max function.

You can use DMin or DMax in a module or macro or in a calculated control on a form if the field that you need to display is not in the record source on which your form is based.

Tip Although you can use DMin or DMax to find the minimum or maximum value from a field in a foreign table, it may be more efficient to create a query that contains the fields that you need from both tables, and base your form or report on that query.

Note Unsaved changes to records in domain are not included when you use these functions. If you want the DMax or DMin function to be based on the changed values, you must first save the changes by choosing the Save Record command from the File menu, moving the focus to another record, or using the Update method.

See Also

Domain Aggregate Functions.

Example

This example returns the lowest and highest values from the Freight field for orders shipped to the United Kingdom. The domain is an Orders table. The criteria argument restricts the resulting set of records to those for which ShipCountry equals UK.

Dim curX As Currency, curY As Currency= DMin("[Freight]", "Orders", "[ShipCountry] = 'UK'")= DMax("[Freight]", "Orders", "[ShipCountry] = 'UK'")

In the next example, the criteria argument includes the current value of a text box called OrderDate. The text box is bound to an OrderDate field in an Orders table. Note that the reference to the control is not included in the double quotation marks (") that denote the strings. This ensures that each time the DMax function is called, Microsoft Access obtains the current value from the control.

Dim curX As Currency= DMax("[Freight]", "Orders", "[OrderDate] = #" _
    & Forms!Orders!OrderDate & "#")

In the next example, the criteria expression includes a variable, dteOrderDate. Note that number signs (#) are included in the string expression, so that when the strings are concatenated, they will enclose the date.

Dim dteOrderDate As Date, curX As Currency= #3/30/95#= DMin("[Frieght]", "Orders", _
    "[OrderDate] = #" & dteOrderDate & "#")


Do...Loop Statement

Description

Repeats a block of statements while a condition is True or until a condition becomes True.

Syntax

Do [{While | Until} condition]
[statements]
[Exit Do]
[statements]
Loop

Or you can use this equally valid syntax:

Do
[statements]
[Exit Do]
[statements]
Loop [{While | Until} condition]

The Do...Loop statement syntax has these parts:

Part | Description
condition | Numeric or string expression that is True or False. If condition is Null, condition is treated as False.
statements | One or more statements that are repeated while or until condition is True.

Remarks

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

When used within nested Do...Loop statements, Exit Do transfers control to the loop that is one nested level above the loop where it occurs.

See Also

Exit Statement, For...Next Statement, While...Wend Statement.

Example

This example shows how Do...Loop statements can be used. The inner Do...Loop statement loops 10 times, sets the value of the flag to False, and exits prematurely using the Exit Do statement. The outer loop exits immediately upon checking the value of the flag.

Check = True: Counter = 0    ' Initialize variables.                ' Outer loop.
    Do While Counter < 20    ' Inner loop.
        Counter = Counter + 1    ' Increment Counter.
        If Counter = 10 Then    ' If condition is True.
            Check = False    ' Set value of flag to False.
            Exit Do    ' Exit inner loop.
        End If
    LoopUntil Check = False    ' Exit outer loop immediately.


DoCmd Object

Description

You can use the methods of the DoCmd object to run Microsoft Access actions from Visual Basic. An action performs tasks such as closing windows, opening forms, and setting the value of controls. For example, you can use the OpenForm method of the DoCmd object to open a form, or use the Hourglass method to change the mouse pointer to an hourglass icon.

Syntax

[application.]DoCmd.method [arg1, arg2, ...]

The DoCmd object uses the following arguments.

Argument | Description
application | Optional. The Application object.
method | One of the methods supported by this object.
arg1, arg2, ... | The arguments for the selected method. These arguments are the same as the action arguments for the corresponding action.

Remarks

Most of the methods of the DoCmd object have arguments — some are required, while others are optional. If you omit optional arguments, the arguments assume the default values for the particular action. For example, the OpenForm method uses seven arguments, but only the first argument, formname, is required. The following example shows how you can open the Employees form in the current database. Only employees with the title Sales Representative are included.

DoCmd.OpenForm "Employees", , ,"[Title] = 'Sales Representative'"

The DoCmd object does not support methods corresponding to the following actions:

  • AddMenu
  • MsgBox — Use the MsgBox function.
  • RunApp — Use the Shell function to run another application.
  • RunCode — Run the function directly in Visual Basic.
  • SendKeys — Use the SendKeys statement.
  • SetValue — Set the value directly in Visual Basic.
  • StopAllMacros
  • StopMacro

Methods

ApplyFilter Method, Beep Method, CancelEvent Method, Close Method, CopyObject Method, DeleteObject Method, DoMenuItem Method, Echo Method (DoCmd Object), FindNext Method, FindRecord Method, GoToControl Method, GoToPage Method (DoCmd Object), GoToRecord Method, Hourglass Method, Maximize Method, Minimize Method, MoveSize Method, OpenForm Method, OpenModule Method, OpenQuery Method, OpenReport Method, OpenTable Method, OutputTo Method, PrintOut Method, Quit Method (DoCmd Object), Rename Method, RepaintObject Method, Requery Method (DoCmd Object), Restore Method, RunMacro Method, RunSQL Method, Save Method, SelectObject Method, SendObject Method, SetMenuItem Method, SetWarnings Method, ShowAllRecords Method, ShowToolbar Method, TransferDatabase Method, TransferSpreadsheet Method, TransferText Method.

See Also

ApplyFilter Action, Beep Action, CancelEvent Action, Close Action, CopyObject Action, DeleteObject Action, DoMenuItem Action, Echo Action, FindRecord Action, GoToControl Action, GoToPage Action, GoToRecord Action, Hourglass Action, Maximize Action, Minimize Action, MoveSize Action, OpenForm Action, OpenModule Action, OpenQuery Action, OpenReport Action, OpenTable Action, OutputTo Action, PrintOut Action, Quit Action, Rename Action, RepaintObject Action, Requery Action, Restore Action, RunMacro Action, RunSQL Action, Save Action, SelectObject Action, SendObject Action, SetWarnings Action, ShowAllRecords Action, ShowToolbar Action, TransferDatabase Action, TransferSpreadsheet Action, TransferText Action.

Example

The following example opens a form in Form view and moves to a new record.

Sub NewRecord()
    DoCmd.OpenForm "Employees", acNormal    ' Open form.
    DoCmd.GoToRecord , , acNewRec    ' Move to new record.Sub


DoEvents Function

Description

Yields execution so that the operating system can process other events.

Syntax

DoEvents( )

Remarks

The DoEvents function returns the number of open forms in standalone versions of Visual Basic, such as Visual Basic, Standard Edition. DoEvents returns 0 in all other applications.

DoEvents passes control to the operating system. Control is not returned until the operating system has finished processing the events in its queue and, for Microsoft Windows only, all keys in the SendKeys queue have been sent.

If parts of your code take up a lot of processor time, use DoEvents periodically to relinquish control to the operating system so that events, such as keyboard input and mouse clicks, can be processed without significant delay.

Caution Make sure the procedure that has given up control with DoEvents is not executed again from a different part of your code before the first DoEvents call returns; this could cause unpredictable results. In addition, do not use DoEvents if other applications could possibly interact with your procedure in unforeseen ways during the time you have yielded control.

See Also

SendKeys Statement.

Specifics (Microsoft Access)

In Microsoft Access, the DoEvents function is ignored if you use it in:

  • A user-defined function or a procedure that calculates a field in a query, form, or report.
  • A user-defined function that creates a list to fill a combo box, a list box, or an OLE object.

If you include the DoEvents function in any of these, Microsoft Access will not relinquish control to the operating system.

Example

This example uses the DoEvents function to cause execution to yield to the operating system once every 1000 iterations of the loop. DoEvents returns the number of open Visual Basic forms, but only when the host application is Visual Basic.

' Create a variable to hold number of Visual Basic forms loaded
' and visible.OpenFormsI = 1 To 150000    ' Start loop.
    If I Mod 1000 = 0 Then     ' If loop has repeated 1000 times.
        OpenForms = DoEvents    ' Yield to operating system.
    End IfI        ' Increment loop counter.


Domain Aggregate Functions

Description

Aggregate functions provide statistical information about sets of records (domain). For example, you can use an aggregate function to count the number of records in a particular set of records, or to determine the average of values in a particular field.

The two types of aggregate functions, domain aggregate functions and SQL aggregate functions, provide similar functionality but are used in different situations. The SQL aggregate functions can be included in the syntax of an SQL statement, but can’t be called from Visual Basic. Conversely, the domain aggregate functions can be called from Visual Basic. They can also be included in an SQL statement, but using an SQL aggregate function is generally more efficient.

If you are performing statistical calculations from within a macro or module, you must use the domain aggregate functions. You can also use the domain aggregate functions to specify criteria, update values, or create calculated fields in a query expression. You can use either the SQL aggregate or domain aggregate functions in a calculated control on a form or report.

The domain aggregate functions include:

  • DAvg Function
  • DCount Function
  • DLookup Function
  • DMin, DMax Functions
  • DStDev, DStDevP Functions
  • DSum Function
  • DVar, DVarP Functions


DoMenuItem Action

Description

You can use the DoMenuItem action to carry out a Microsoft Access menu command.

You can use this action to do the following:

  • Carry out any Microsoft Access command from a macro. You must select a command that is appropriate for your current view when the macro carries out the command. For example, a macro can’t carry out any of the Records menu commands if the active object is in table Design view, form Design view, query Design view, or report Design view.
  • Add a Microsoft Access command to a custom menu bar for a form or report, or to a menu on the global menu bar. For each command you want to add, enter a DoMenuItem action in the macro group for that menu.
  • Add a Microsoft Access command to a custom shortcut menu for a form, form control, or report, or to the global shortcut menu. For each command you want to add, enter a DoMenuItem action in the macro group for the custom shortcut menu or global shortcut menu.

Setting

The DoMenuItem action uses the following arguments.

Action argument | Description
Menu Bar | The name of the menu bar that contains the command you want to carry out. The Menu Bar box list in the Action Arguments section of the Macro window shows the different views in which menu bars appear. This is a required argument.
Menu Name | The name of the menu that contains the command you want to carry out. The Menu Name box shows all menus on the menu bar that you selected with the Menu Bar argument. This is a required argument.
Command | The command you want to carry out. The Command box shows all commands in the menu that you selected with the Menu Name argument. This is a required argument.
Subcommand | The subcommand you want to carry out. This applies only if the desired command has a submenu.

Remarks

The DoMenuItem action has the same effect as clicking the specified command on a Microsoft Access menu. If clicking a command displays a dialog box, the dialog box is also displayed when you carry out the DoMenuItem action. You can use the SendKeys action to enter the appropriate information in the dialog box.

If you open a Microsoft Access version 1.x or version 2.0 database in Microsoft Access for Windows 95, the arguments for the DoMenuItem action in macros in this database show the appropriate menus and menu commands. However, you can’t edit objects from a version 1.x or version 2.0 database using a Microsoft Access 95 database. When you convert the database to Microsoft Access 95, the DoMenuItem action arguments will show the new menus and menu commands.

Note The Microsoft Access 95 File menu shows the most recently used databases. You can click one of these databases instead of clicking Open Database. These database items do not appear in the drop-down list for the Command Name argument for the File Menu, and are not available using the DoMenuItem action in a macro.

To run the DoMenuItem action in Visual Basic, use the DoMenuItem method of the DoCmd object.

See Also

AddMenu Action, DoMenuItem Method, SendKeys Action.


DoMenuItem Method

Applies To

DoCmd Object.

Description

The DoMenuItem method carries out the DoMenuItem action in Visual Basic. For more information on how the action and its arguments work, see the action topic.

Syntax

DoCmd.DoMenuItem menubar, menuname, command [, subcommand] [, version]

The DoMenuItem method uses the following arguments.

Argument | Description
menubar | Use the intrinsic constant acFormBar for the menu bar in Form view. For other views, switch to the Macro window, and use the number of the view in the Menu Bar argument list (count down the list, starting from 0).
menuname | You can use one of the following intrinsic constants: acFile acEditMenu acRecordsMenu You can use acRecordsMenu only for the Form view menu bar in Microsoft Access version 2.0 and Microsoft Access for Windows 95 databases. For other menus, switch to the Macro window, and use the number of the menu in the Menu Name argument list (count down the list, starting from 0).

Argument | Description
command | You can use one of the following intrinsic constants: acNew acSaveForm acSaveFormAs acSaveRecord acUndo acCut acCopy acPaste acDelete acSelectRecord acSelectAllRecords acObject acRefresh For other commands, switch to the Macro window, and use the number of the command in the Command argument list (count down the list, starting from 0).
subcommand | You can use one of the following intrinsic constants: acObjectVerb acObjectUpdate The acObjectVerb constant represents the first command on the submenu of the Object command on the Edit menu. The type of object determines the first command on the submenu. For example, this command is Edit for a Paintbrush™ object that can be edited. For other commands on submenus, switch to the Macro window, and use the number of the subcommand in the Subcommand argument list (count down the list, starting from 0).
version | Use the intrinsic constant acMenuVer70 for code written for Microsoft Access 95 databases, the intrinsic constant acMenuVer20 for code written for Microsoft Access version 2.0 databases, and the intrinsic constant acMenuVer1X for code written for Microsoft Access version 1.x databases. This argument is available only in Visual Basic.

Note The default for this argument is acMenuVer1X, so that any code written for Microsoft Access version 1.x databases will run unchanged. If you’re writing code for a Microsoft Access 95 or version 2.0 database and want to use the Microsoft Access 95 or version 2.0 menu commands with the DoMenuItem method, you must set this argument to acMenuVer70 or acMenuVer20.

Also, when you are counting down the lists for the Menu Bar, Menu Name, Command, and Subcommand action arguments in the Macro window to get the numbers to use for the arguments in the DoMenuItem method, you must use the Microsoft Access 95 lists if the version argument is acMenuVer70, the Microsoft Access version 2.0 lists if the version argument is acMenuVer20, and the Microsoft Access version 1.x lists if version is acMenuVer1X (or blank).

Remarks

The selections in the lists for the Menu Name, Command, and Subcommand action arguments in the Macro window depend on what you have selected for the previous arguments. You must use numbers or intrinsic constants that are appropriate for each menubar, menuname, command, and subcommand argument.

If you leave the subcommand argument blank but specify the version argument, you must include the subcommand argument’s comma. If you leave the subcommand and version arguments blank, don’t use a comma following the command argument.

See Also

AddMenu Action, DoCmd Object, DoMenuItem Action, SendKeys Statement.

Example

This example uses the DoMenuItem method to carry out the Paste command on the Edit menu in Form view in a Microsoft Access for Windows 95 database.

DoCmd.DoMenuItem acFormBar, acEditMenu, acPaste, , acMenuVer70

The next example carries out the Tile command on the Window menu in Form view in a Microsoft Access version 2.0 database.

DoCmd.DoMenuItem acFormBar, 4, 0, , acMenuVer20


Double Data Type

Description

Double(double-precision floating-point) variables are stored as IEEE 64-bit
(8-byte) floating-point numbers ranging in value from -1.79769313486232E308 -4.94065645841247E-324 for negative values and from 4.94065645841247E-324 to 1.79769313486232E308 for positive values. The type-declaration character for Double is #.

See Also

CDbl Function, Data Type Summary, Def type Statements, Single Data Type.


DrawMode Property

Applies To

Report.

Description

You can use the DrawMode property to specify how the pen (the color used in drawing) interacts with existing background colors on the report when the Line, Circle, or PSet method is used to draw on a report when printing.

Setting

The DrawMode property uses the following settings.

Setting | Description
1 | Black pen.
2 | Inverse of setting 15 (NotMergePen).
3 | Combination of the colors common to the background color and the inverse of the pen (MaskNotPen).
4 | Inverse of setting 13 (NotCopyPen).
5 | Combination of the colors common to both the pen and the inverse of the display (MaskPenNot).
6 | Inverse of the display color (Invert).
7 | Combination of the colors in the pen and in the display color, but not in both (XorPen).
8 | Inverse of setting 9 (NotMaskPen).
9 | Combination of the colors common to both the pen and the display (MaskPen).
10 | Inverse of setting 7 (NotXorPen).
11 | No operation — output remains unchanged. In effect, this setting turns drawing off (Nop).
12 | Combination of the display color and the inverse of the pen color (MergeNotPen).
13 | (Default) Color specified by the ForeColor property (CopyPen).
14 | Combination of the pen color and the inverse of the display color (MergePenNot).
15 | Combination of the pen color and the display color (MergePen).
16 | White pen.

The DrawMode property setting is an Integer data type value.

You can set the DrawMode property only in a macro or a Visual Basic event procedure specified by a section’s OnPrint property setting.

Remarks

Use this property to produce visual effects when drawing on a report. Microsoft Access compares each pixel in the draw pattern to the corresponding pixel in the existing background to determine how the drawing is displayed on the report. For example, setting 7 uses the Xor operator to combine a draw-pattern pixel with a background pixel.

See Also

BackColor Property, BackStyle Property, Circle Method, DrawStyle Property, DrawWidth Property, Event Properties, FillColor Property, FillStyle Property, ForeColor Property, Line Method, PSet Method.


DrawStyle Property

Applies To

Report.

Description

You can use the DrawStyle property to specify the line style when using the Line and Circle methods to print lines on reports.

Setting

The DrawStyle property uses the following settings.

Setting | Description
0 | (Default) Solid line, transparent interior
1 | Dash, transparent interior
2 | Dot, transparent interior
3 | Dash-dot, transparent interior
4 | Dash-dot-dot, transparent interior
5 | Invisible, transparent interior
6 | Invisible line, solid interior

The DrawStyle property setting has an Integer data type value.

You can set this property only in a macro or a Visual Basic event procedure specified by a section’s OnPrint property setting.

Remarks

The DrawStyle property produces the results described in the preceding table if the DrawWidth property is set to 1. If the DrawWidth property setting is greater than 1, DrawStyle settings 1 through 4 produce a solid line (the DrawStyle property value isn’t changed).

See Also

BackColor Property, Circle Method, DrawMode Property, DrawWidth Property, Event Properties, FillColor Property, FillStyle Property, ForeColor Property, Line Method, PSet Method.


DrawWidth Property

Applies To

Report.

Description

You can use the DrawWidth property to specify the line width for the Line, Circle, and PSet methods.

Setting

You can set the DrawWidth property to an Integer value of 1 through 32,767. This value represents the width of the line in pixels. The default is 1, or 1 pixel wide.

You can set this property only in a macro or a Visual Basic event procedure specified by a section’s OnPrint property setting.

Remarks

Increase the value of this property to increase the width of the line. If DrawWidth is greater than 1, DrawStyle property settings 1 through 4 produce a solid line (the DrawStyle property value isn’t changed). Setting the DrawWidth property to 1 enables the DrawStyle property to produce the results shown in the setting table of the DrawStyle property.

See Also

BackColor Property, Circle Method, DrawMode Property, DrawStyle Property, Event Properties, FillColor Property, FillStyle Property, ForeColor Property, Line Method, PSet Method.


Dropdown Method

Applies To

Combo Box Control.

Description

You can use the Dropdown method to force the list in the specified combo box to drop down. For example, you can use this method to cause a combo box listing vendor codes to drop down when the vendor code field receives the focus during data entry.

Syntax

combobox.Dropdown

The Dropdown method uses the following argument.

Argument | Description
combobox | A combo box control on a form.

Remarks

If the specified combo box control does not have the focus, an error occurs. Using this method is identical to pressing the F4 key when the control has the focus.

Example

The following example shows how you can use the Dropdown method within the GotFocus event procedure to force a combo box named Employees to drop down when it receives the focus.

Private Sub Employees_GotFocus()
    Me!Employees.DropdownSub


DStDev, DStDevP Functions

Description

You can use the DStDev and DStDevP functions to estimate the standard deviation across a set of values in a specified set of records (domain). Use DStDev and DStDevP in a macro or module, in a query expression, or in a calculated control on a form or report.

Use DStDevP to evaluate a population, and DStDev to evaluate a population sample.

For example, you could use the DStDev function in a module to calculate the standard deviation across a set of students’ test scores.

Syntax

DStDev(expr, domain[, criteria])DStDevP(expr, domain[, criteria])

The DStDev and DStDevP functions use the following arguments.

Argument | Description
expr | Expression that identifies the numeric field on which you want to find the standard deviation. It can be a string expression identifying a field from a table or query, or it can be an expression that performs a calculations on data in that field. You can include in expr the name of a table field, a control on a form, a constant, or a function. If expr includes a function, it can be either built-in or user-defined, but not another domain aggregate or SQL aggregate function.
domain | String expression identifying the set of records that constitutes the domain. It can be a table name or a query name.
criteria | Optional string expression used to restrict the range of data on which DStDev or DStDevP is performed. For example, criteria is often equivalent to the WHERE clause in an SQL expression, without the word WHERE. If criteria is omitted, DStDev and DStDevP evaluate expr against the entire domain. Any field included in criteria must also be a field in domain; otherwise, DStDev and DStDevP will return a Null.

Remarks

DStDev and DStDevP find the standard deviation on a set of values defined by expr in the table or query referred to by domain, according to any restrictions specified by criteria.

If domain refers to fewer than two records or if fewer than two records satisfy criteria, DStDev and DStDevP return a Null, indicating that a standard deviation can’t be calculated.

Whether you use DStDev or DStDevP in a macro or module, a query expression, or a calculated control, you must construct the criteria argument carefully to ensure that it will be evaluated correctly.

You can use DStDev and DStDevP to specify criteria in the criteria row of a select query. For example, you could create a query on an Orders table and a Products table to display all products for which the freight cost fell above the mean plus the standard deviation for freight cost. The criteria row beneath the Freight field would contain the following expression:

> (DStDev("[Freight]", "Orders") + DAvg("[Freight]", "Orders"))

You can use DStDev and DStDevP within a calculated field expression in a query, or in the Update To row of an update query.

Note You can use DStDev and DStDevP or StDev and StDevP in a calculated field expression in a totals query. If you use DStDev or DStDevP, values are calculated before data is grouped. If you use StDev or StDevP, the data is grouped before values in the field expression are evaluated.

Use DStDev and DStDevP in a calculated control when you need to specify criteria to restrict the range of data on which the function is performed. For example, to display standard deviation for orders to be shipped to California, set the ControlSource property of a text box to the following expression:

= DStDev("[Freight]", "Orders", "[ShipRegion] = 'CA'")

If you simply want to find the standard deviation across all records in domain, use the StDev or StDevP function.

Tip If the data type of the field from which expr is derived is a number, DStDev and DStDevP return a Double. If you use DStDev or DStDevP in a calculated control, include a data type conversion function in the expression to improve performance.

Note Unsaved changes to records in domain are not included when you use these functions. If you want the DStDev or DStDevP function to be based on the changed values, you must first save the changes by choosing the Save Record command from the File menu, moving the focus to another record, or using the Update method.

See Also

Domain Aggregate Functions.

Example

This example returns estimates of the standard deviation for a population and a population sample for orders shipped to the United Kingdom. The domain is an Orders table. The criteria argument restricts the resulting set of records to those for which the ShipCountry is UK.

Dim dblX As Double, dblY As Double
' Sample estimate.= DStDev("[Freight]", "Orders", "[ShipCountry] = 'UK'")
' Population estimate.= DStDevP("[Freight]", "Orders", "[ShipCountry] = 'UK'")

The next example calculates the same estimates using a variable, strCountry, in the criteria argument. Note that single quotation marks (') are included in the string expression, so that when the strings are concatenated, the string literal UK will be enclosed in single quotation marks.

Dim strCountry As String, dblX As Double, dblY As Double= "UK"= DStDev("[Freight]", "Orders", _
    "[ShipCountry] = '" & strCountry & "'")= DStDevP("[Freight]", "Orders", _
    "[ShipCountry] = '" & strCountry & "'")


DSum Function

Description

You can use the DSum functions to calculate the sum of a set of values in a specified set of records (domain). Use DSum in a macro or module, in a query expression, or in a calculated control.

For example, you could use DSum in a calculated field expression in a query to calculate the total sales made by a particular employee over a period of time. Or you could use DSum in a calculated control to display a running sum of sales for a particular product.

Syntax

DSum(expr, domain[, criteria])

The DSum function uses the following arguments.

Argument | Description
expr | Expression that identifies the numeric field whose values you want to sum. It can be a string expression identifying a field in a table or query, or it can be an expression that performs a calculation on data in that field. You can include in expr the name of a table field, a control on a form, a constant, or a function. If expr includes a function, it can be either built-in or user-defined, but not another domain aggregate or SQL aggregate function.
domain | String expression identifying the set of records that constitutes the domain. It can be a table name or a query name.
criteria | Optional string expression used to restrict the range of data on which DSum is performed. For example, criteria is often equivalent to the WHERE clause in an SQL expression, without the word WHERE. If criteria is omitted, DSum evaluates expr against the entire domain. Any field included in criteria must also be a field in domain; otherwise, DSum returns a Null.

Remarks

DSum finds the sum of values in the field or expression defined by expr, in the table or query referred to by domain, according to any restrictions specified by criteria.

If no record satisfies the criteria argument or if domain contains no records, DSum returns a Null.

Whether you use DSum in a macro or module, a query expression, or a calculated control, you must construct the criteria argument carefully to ensure that it will be evaluated correctly.

You can use DSum to specify criteria in the Criteria row of a query, in a calculated field in a query expression, or in the Update To row of an update query.

Note You can use either DSum or Sum in a calculated field expression in a totals query. If you use DSum, values are calculated before data is grouped. If you use Sum, the data is grouped before values in the field expression are evaluated.

You may want to use DSum when you need to display the sum of a set of values from a field that is not in the record source for your form or report. For example, suppose you have a form which displays information about a particular product. You could use DSum to maintain a running total of sales of that product in a calculated control.

Tip If you need to maintain a running total in a control on a report, you can use the RunningSum property of that control if the field on which it is based is included in the record source for the report. Use DSum to maintain a running sum on a form.

Note Unsaved changes to records in domain are not included when you use this function. If you want the DSum function to be based on the changed values, you must first save the changes by choosing the Save Record command from the File menu, moving the focus to another record, or using the Update method.

See Also

DCount Function, Domain Aggregate Functions, RunningSum Property.

Example

This example totals the values from the Freight field for orders shipped to the United Kingdom. The domain is an Orders table. The criteria argument restricts the resulting set of records to those for which ShipCountry equals UK.

Dim curX As Currency= DSum("[Freight]", "Orders", "[ShipCountry] = 'UK'")

The next example calculates a total using two separate criteria. Note that single quotation marks (') and number signs (#) are included in the string expression, so that when the strings are concatenated, the string literal will be enclosed in single quotation marks, and the date will be enclosed in number signs.

Dim curX As Currency= DSum("[Freight]", "Orders", _
    "[ShipCountry] = 'UK' AND [ShippedDate] > #1-1-95#")

You can use a domain function in the Update To row of an update query. For instance, suppose you want to track current sales by product in a Products table. You could add a new field called SalesSoFar to the Products table, and run an update query to calculate the correct values and update the records. Create a new query based on the Products table, and choose Update from the Query menu. Add the SalesSoFar field to the query grid, and enter the following in the Update To row:

DSum("[Quantity]*[UnitPrice]", "Order Details", _
    "[ProductID] = " & [ProductID])

When the query is run, Microsoft Access calculates the total amount of sales for each product, based on information from an Order Details table. The sum of sales for each product is added to the Products table.


DVar, DVarP Functions

Description

You can use the DVar and DVarP functions to estimate variance across a set of values in a specified set of records (domain). Use DVar and DVarP in a macro or module, in a query expression, or in a calculated control on a form or report.

Use DVarP to evaluate variance across a population, and DVar to evaluate variance across a population sample.

For example, you could use the DVar function to calculate the variance across a set of students’ test scores.

Syntax

DVar(expr, domain[, criteria])DVarP(expr, domain[, criteria])

The DVar and DVarP functions use the following arguments.

Argument | Description
expr | Expression that identifies the numeric field on which you want to find the variance. It can be a string expression identifying a field from a table or query, or it can be an expression that performs a calculation on data in that field. You can include in expr the name of a table field, a control on a form, a constant, or a function. If expr includes a function, it can be either built-in or user-defined, but not another domain aggregate or SQL aggregate function. Any field included in expr must be a numeric field.
domain | String expression identifying the set of records that constitutes the domain. It can be a table name or a query name.
criteria | Optional string expression used to restrict the range of data on which DVar or DVarP is performed. For example, criteria is often equivalent to the WHERE clause in an SQL expression, without the word WHERE. If criteria is omitted, DVar and DVarP evaluate expr against the entire domain. Any field included in criteria must also be a field in domain; otherwise DVar and DVarP return a Null.

DVar and DVarP find the variance of a set of values defined by expr in the table or query referred to by domain, according to any restrictions specified by criteria.

If domain refers to fewer than two records or if fewer than two records satisfy criteria, DVar and DVarP return a Null, indicating that a variance can’t be calculated.

Whether you use DVar or DVarP in a macro or module, a query expression, or a calculated control, you must construct the criteria argument carefully to ensure that it will be evaluated correctly.

You can use DVar and DVarP to specify criteria in the Criteria row of a select query; in a calculated field expression in a query; or in the Update To row of an update query.

Note You can use DVar and DVarP or Var and VarP in a calculated field expression in a totals query. If you use DVar or DVarP, values are calculated before data is grouped. If you use Var or VarP, the data is grouped before values in the field expression are evaluated.

Use DVar and DVarP in a calculated control when you need to specify criteria to restrict the range of data on which the function is performed. For example, to display a variance for orders to be shipped to California, set the ControlSource property of a text box to the following expression.

= DVar("[Freight]", "Orders", "[ShipRegion] = 'CA'")

If you simply want to find the standard deviation across all records in domain, use the Var or VarP function.

Note Unsaved changes to records in domain are not included when you use these functions. If you want the DVar or DVarP function to be based on the changed values, you must first save the changes by choosing the Save Record command from the File menu, moving the focus to another record, or using the Update method.

See Also

Domain Aggregate Functions.

Example

This example returns estimates of the variance for a population and a population sample for orders shipped to the United Kingdom. The domain is an Orders table. The criteria argument restricts the resulting set of records to those for which ShipCountry equals UK.

Dim dblX As Double, dblY As Double
' Sample estimate.= DVar("[Freight]", "Orders", "[ShipCountry] = 'UK'")
' Population estimate.= DVarP("[Freight]", "Orders", "[ShipCountry] = 'UK'")

The next example returns estimates using a variable, strCountry, in the criteria argument. Note that single quotation marks (') are included in the string expression, so that when the strings are concatenated, the string literal UK will be enclosed in single quotation marks.

Dim strCountry As String, dblX As Double= "UK"= DVar("[Freight]", "Orders", "[ShipCountry] = '" _
    & strCountry & "'")


Dynaset Property

Applies To

Form.

Description

You can use the Dynaset property to obtain a result set for a form’s underlying records.

Note The Dynaset property is included in this version of Microsoft Access only for compatibility with previous versions. It is recommended that you use the RecordsetClone property instead.

Setting

The Dynaset property is available only in Visual Basic and is read-only in all views.

Remarks

The Dynaset property refers to the same underlying query or data as the form. If a form is based on a query, for example, referring to the Dynaset property is the equivalent of cloning a result set with the same query. If you then apply a filter to the form, the Dynaset property reflects the filtering.

Unlike its form, the result set initially has no current record. To make the same record current in the result set, assign the value of the form’s Bookmark property to a string variable, and then set the result set’s Bookmark property to that variable. You can also use one of the Find or Move methods to make any record in the result set current.

Tip You can make the form’s current record the same as the result set’s by setting the form’s Bookmark property to the result set’s Bookmark property.

Use the Dynaset property when you want to apply a method that can’t be used with forms, such as the FindFirst method. The Dynaset property provides access to all the methods and properties that you can use with a result set.

You can use the RecordCount property to count the number of records in a result set. The following example shows how you can combine the RecordCount property with the Dynaset property to count the records in a form.

Forms![Orders].Dynaset.MoveLast"My form contains " & Forms![Orders].Dynaset.RecordCount _
    & " records.", , "Record Count"

Note If you close the form or if you change the form’s set of underlying records, the result set is no longer valid. Subsequently, if you refer to the result set or to previously saved bookmarks in the form or the result set, an error occurs.

See Also

RecordsetClone Property.


Echo Action

Description

You can use the Echo action to specify whether echo is turned on. For example, you can use this action to hide or show the results of a macro while it runs.

Setting

The Echo action uses the following arguments.

Action argument | Description
Echo On | Click Yes to turn echo on or No to turn it off. The default is Yes.
Status Bar Text | The text to display in the status bar when echo is turned off. For example, when echo is turned off, the status bar can display “The macro is running.”

Remarks

When Microsoft Access runs a macro, screen updating often shows information not essential to the functioning of the macro. When you set the Echo On argument to No, the macro runs without updating the screen. When the macro finishes, Microsoft Access automatically turns echo back on and repaints the window. The No setting for Echo On doesn’t affect the macro or its results.

The Echo action doesn’t suppress the display of modal dialog boxes, such as error messages, or pop-up forms, such as property sheets. You can use these to gather or display information when echo is turned off. Use the SetWarnings action to turn off all message or dialog boxes except error message boxes and dialog boxes that require the user to enter information.

You can run the Echo action more than once in a macro. This allows you to change the status bar text while the macro runs.

If you turn echo off, you can use the Hourglass action to change the mouse pointer into an hourglass (or whatever mouse pointer icon you have set for “Busy” in Microsoft Windows 95 or “Wait” in Windows NT) to provide a visual indication that the macro is running.

To run the Echo action in Visual Basic, use the Echo method of the DoCmd object.

See Also

Echo Method (DoCmd Object), SetWarnings Action.


Echo Method (Application Object)

Description

The Echo method specifies whether Microsoft Access repaints or updates the computer screen.

Syntax

Application.Echo echoon[, statusbartext]

The Echo method uses the following arguments.

Argument | Description
echoon | True (default) indicates that the screen is repainted; False indicates that the screen isn’t repainted.
statusbartext | Optional string expression that specifies the text to display in the status bar when repainting is turned on or off.

Remarks

If you are running Visual Basic code that makes a number of changes to objects displayed on the screen, your code may be faster if you turn off screen repainting until the procedure has finished running. You may also want to turn repainting off if your code makes changes that the user shouldn’t see or doesn’t need to see.

The Echo method doesn’t suppress the display of modal dialog boxes, such as error messages, or pop-up forms, such as property sheets.

If you turn screen repainting off, the screen will not show any changes, even if the user presses CTRL+BREAK or Visual Basic encounters a breakpoint, until you turn screen repainting back on. You may want to create a macro that turns repainting on and assign the macro to a key or custom menu command. You can then use the key combination or menu command to turn repainting on if it has been turned off in Visual Basic.

If you turn screen repainting off and then try to step through your code, you won’t be able to see your progress through the code, or any other visual cues, until repainting is turned back on. However, your code will continue to execute.

Note Don’t confuse the Echo method with the Repaint method. The Echo method turns screen updating on or off. The Repaint method forces an immediate screen update.

See Also

Application Object, Echo Action.

Example

The following example uses the Echo method to prevent the screen from being repainted while certain operations are underway. While the procedure opens a form and minimizes it, the user only sees an hourglass to indicate that processing is taking place, and the screen is not repainted. When this task is completed, the hourglass changes back to a pointer and screen repainting is restored.

Sub EchoOff()
    Application.Echo False    ' Echo off.
    DoCmd.Hourglass True    ' Hourglass on.
    DoCmd.OpenForm "Employees", acNormal    ' Open form.
    DoCmd.Minimize    ' Minimize form.
    Application.Echo True    ' Echo on.
    DoCmd.Hourglass False    ' Hourglass off.Sub


Echo Method (DoCmd Object)

Applies To

DoCmd Object.

Description

The Echo method of the DoCmd object carries out the Echo action in Visual Basic. For more information on how the action and its arguments work, see the action topic.

Syntax

DoCmd.Echo echoon [, statusbartext]

The Echo method uses the following arguments.

Argument | Description
echoon | Use True (-1) to turn echo on and False (0) to turn it off.
statusbartext | A string expression.

Remarks

If you leave the statusbartext argument blank, don’t use a comma following the echoon argument.

If you turn echo off in Visual Basic, you must turn it back on, or it will remain off, even if the user presses CTRL+BREAK or Visual Basic encounters a breakpoint. You may want to create a macro that turns echo on and then assign that macro to a key combination or a custom menu command. You could then use the key combination or menu command to turn echo on if it has been turned off in Visual Basic.

The Echo method of the DoCmd object was added to provide backwards compatibility for running the Echo action in Visual Basic code in Microsoft Access for Windows 95. It is recommended that you use the existing Echo method of the Application object instead. The Echo method of the DoCmd object is different from the Echo method of the Application object.

See Also

Application Object, DoCmd Object, Echo Action, Echo Method (Application Object), SetWarnings Method.

Example

This example uses the Echo method to turn echo off and display the specified text in the status bar while your Visual Basic code is executing.

DoCmd.Echo False, "Visual Basic code is executing."


Enabled, Locked Properties

Applies To

  • Enabled — Bound Object Frame Control, Check Box Control, Combo Box Control, Command Button Control, List Box Control, Option Button Control, Option Group Control, Subform/Subreport Control, Text Box Control, Toggle Button Control, Unbound Object Frame Control.
  • Locked — Bound Object Frame Control, Check Box Control, Combo Box Control, List Box Control, Option Button Control, Text Box Control, Toggle Button Control.

Description

  • Enabled — You can use this property to specify whether a control can have the focus in Form view.
  • Locked — You can use this property to specify whether you can edit data in a control in Form view.

Setting

The Enabled property uses the following settings.

Setting | Description | Visual Basic
Yes | (Default for all controls except unbound object frames) The control can have the focus. If the control is an unbound object frame, double-clicking it executes the control’s primary verb. For example, an unbound object frame could play an embedded sound object. | True (-1)
No | (Default for unbound object frames) The control can’t have the focus and appears dimmed. If the control is an option group, neither the option group nor the controls inside the option group can have the focus. | False (0)

The Locked property uses the following settings.

Setting | Description | Visual Basic
Yes | (Default for unbound object frames) The control functions normally but doesn’t allow editing, adding, or deleting data. | True (-1)
No | (Default for all controls except unbound object frames) The control functions normally and allows editing, adding, and deleting data. | False (0)

You can set this property in the control’s property sheet, a macro, or Visual Basic.

Remarks

Use the Enabled property to enable and disable controls. For example, in Form view you can disable a command button until you have changed data in a text box control. You can then use the control’s AfterUpdate event to call an event procedure or macro to enable the command button.

Use the Locked property to protect data in a field by making it read-only. For example, you might want a control only to display information without allowing editing, or you might want to lock a control until a specific condition is met.

You can combine the Enabled and Locked property settings to achieve the following effects.

Enabled | Locked | Effect
Yes | Yes | The control can have the focus. Data is displayed normally and can be copied but not edited.
Yes | No | The control can have the focus. Data is displayed normally and can be copied and edited.
No | Yes | The control can’t have the focus. Data is displayed normally but can’t be copied or edited.
No | No | The control can’t have the focus. Control and data are disabled (gray).

The TabStop property can be combined with the Enabled property to prevent the use of the TAB key to select a command button, while still allowing use of the button by clicking on it. Setting the TabStop property to No means that the command button won’t be in the tab order. However, if the Enabled property is set to Yes, then you can still click the command button.

To allow edits to an embedded or linked object in an unbound object frame, you must set the Enabled property for the unbound object frame to Yes and the Locked property to No.

See Also

AllowEdits Property, DisplayWhen Property, SetValue Action, TabStop Property, Visible Property (Microsoft Access).

Example

The following example toggles the Enabled property of a command button and the Enabled and Locked properties of a control depending on the type of Employee displayed in the current record. If the employee is a manager, then the SalaryDetails button is enabled and the PersonalInfo control is unlocked and enabled.

Sub Form_Current()
    If Me!EmployeeType = "Manager" Then
        Me!SalaryDetails.Enabled = True
        Me!PersonalInfo.Enabled = True
        Me!PersonalInfo.Locked = False
    Else
        Me!SalaryDetails.Enabled = False
        Me!PersonalInfo.Enabled = False
        Me!PersonalInfo.Locked = True
    End IfSub


End Statement

Description

Ends a procedure or block.

Syntax

EndEnd Function End IfEnd Property End SelectEnd SubEnd TypeEnd With

The End statement syntax has these forms:

Statement | Description
End | Terminates execution. Never required by itself but may be placed anywhere in a procedure to close files opened with the Open statement and to clear variables.
End Function | Required to end a Function statement.
End If | Required to end a block If...Then...Else statement.

Statement | Description
End Property | Required to end a Property Let, Property Get, or Property Set procedure.
End Select | Required to end a Select Case statement.
End Sub | Required to end a Sub statement.
End Type | Required to end a user-defined type definition (Type statement).
End With | Required to end a With statement.

Remarks

When executed, the End statement resets all module-level variables and all static local variables in all modules. If you need to preserve the value of these variables, use the Stop Statement instead. You can then resume execution while preserving the value of those variables.

See Also

Exit Statement, Function Statement, If...Then...Else Statement, Property Get Statement, Property Let Statement, Property Set Statement, Select Case Statement, Stop Statement, Sub Statement, Type Statement, With Statement.

Example

This example uses the End Statement to end code execution if the user enters an invalid password.

Sub Form_Load
    PassWord = "Swordfish"
    Pword = InputBox("Type in your password")
    If Pword <> PassWord Then
        MsgBox "Sorry, incorrect password"
        End
    End IfSub


Enter, Exit Events

Applies To

Bound Object Frame Control, Check Box Control, Combo Box Control, Command Button Control, List Box Control, Option Button Control, Option Group Control, Subform/Subreport Control, Text Box Control, Toggle Button Control, Unbound Object Frame Control.

Description

These events occur:

  • Enter — before a control actually receives the focus from a control on the same form.
  • Exit — just before a control loses the focus to another control on the same form.

Note Notes

  • The Enter and Exit events apply only to controls on a form.
  • These events don’t apply to check boxes, option buttons, or toggle buttons in an option group. They apply only to the option group itself.

Remarks

The Enter event occurs before the GotFocus event. The Exit event occurs before the LostFocus event.

Unlike GotFocus and LostFocus, the Enter and Exit events don’t occur when a form receives or loses the focus. For example, suppose you select a check box on a form, and then click a report. The GotFocus and Enter events occur when you select the check box. Only the LostFocus event occurs when you click the report. The Exit event doesn’t occur (because the focus is moving to a different window). If you select the check box on the form again to bring it to the foreground, the GotFocus event occurs, but not the Enter event (because the control had the focus when the form was last active). The Exit event occurs only when you click another control on the form.

If you move the focus on another form to a control that doesn’t have the focus on that form, the Exit and LostFocus events for the control that does have the focus on the other form occur before the Enter and GotFocus events for the control you moved to.

If you use the mouse to move the focus from a control on a main form to a control on a subform of that form, the following events occur:

Exit (for the control on the main form)

LostFocus (for the control on the main form)

Enter (for the subform control)

Exit (for the control on the subform that had the focus)

LostFocus (for the control on the subform that had the focus)

Enter (for the control on the subform that the focus moved to)

GotFocus (for the control on the subform that the focus moved to)

If the control you move to on the subform previously had the focus, neither its Enter event nor its GotFocus event occurs, but the Enter event for the subform control does occur. If you move the focus from a control on a subform to a control on the main form, the Exit and LostFocus events for the control on the subform don’t occur, just the Exit event for the subform control and the Enter and GotFocus events for the control on the main form.

Note You often use the mouse or a key such as TAB to move the focus to another control. This causes mouse or keyboard events to occur in addition to the events discussed in this topic.

Because the Enter event occurs before the focus moves to a particular control, you can use an Enter macro or event procedure to display instructions; for example, you could use a macro or event procedure to display a small form or message box identifying the type of data the control typically contains.

See Also

BeforeUpdate, AfterUpdate Events; GotFocus, LostFocus Events.


Enter, Exit Events -- Event Procedures

Description

To create an event procedure that is run when the Enter or Exit event occurs, set the OnEnter or OnExit property to [Event Procedure], and click the Build button.

Syntax

Private Sub controlname_Enter ( )Private Sub controlname_Exit (Cancel As Integer)

The Enter event procedure uses the following argument.

Argument | Description
controlname | A string that is the name of the control affected by the event procedure.

The Exit event procedure uses the following arguments.

Argument | Description
controlname | A string that is the name of the control affected by the Exit event procedure.
Cancel | The setting determines if the Exit event occurs. Setting Cancel to True (-1) cancels the Exit event

Remarks

You can’t cancel the Enter event.

See Also

Enter, Exit Events — Macros.

Example

In this example, two event procedures are attached to the LastName text box. The Enter event procedure displays a message specifying what type of data the user can enter in the text box. The Exit event procedure displays a dialog box asking the user if changes should be saved before the focus moves to another control. If the user chooses Cancel, the Cancel argument is set to True (-1), which moves the focus to the text box without saving changes. If the user chooses OK, the changes are saved, and the focus moves to another control.

To try the following example, add the code to the Declarations section of a form that contains a text box named CodeName.

Private Sub LastName_Enter ()
    MsgBox "Enter your last name."Sub
Sub LastName_Exit (Cancel As Integer)
    Dim strMsg As String

    strMsg = "You entered '" & Me!LastName & "' as your last name." & _
        vbCrLf & "Is this correct?"
    If MsgBox(strMsg, vbYesNo) = vbNo Then
        Cancel = True            ' Cancel exit.
    Else
        Exit Sub            ' Save changes and exit.
    End IfSub


Enter, Exit Events -- Macros

Description

To run a macro when the Enter or Exit event occurs, set the OnEnter or OnExit property to the name of the macro.

Remarks

When the Enter or Exit event occurs, you can run a macro that uses a GoToControl action to change the tab order based on current data in a control. For example, if the user enters Single in the MaritalStatus field, the focus won’t move to the SpouseName field.

You can use the CancelEvent action in an Exit macro to cancel exiting the control. You can’t use the CancelEvent action in an Enter macro. However, you can use the GoToControl action in an Enter macro to move the focus to a different control.

See Also

Enter, Exit Events — Event Procedures.


EnterKeyBehavior Property

Applies To

Text Box Control.

Description

You can use the EnterKeyBehavior property to specify what happens when you press ENTER in a text box control in Form view or Datasheet view. For example, you can use the EnterKeyBehavior property if you have a control bound to a Memo field in a table to make entering multiple-line text easier. If you don’t set this property to New Line In Field, you must press CTRL+ENTER to enter a new line in the text box.

Setting

The EnterKeyBehavior property uses the following settings.

Setting | Description | Visual Basic
Default | (Default) Microsoft Access uses the result specified in the Move After Enter option on the Keyboard tab of the Options dialog box, available by clicking Options on the Tools menu. For details, see the Remarks section. | False (0)
New Line In Field | Pressing ENTER in the control creates a new line in the control so you can enter additional text. | True (-1)

You can set this property in the control’s property sheet, a macro, or Visual Basic.

You can also set this property using the control’s default control style.

Remarks

If you set the EnterKeyBehavior property to Default, Microsoft Access uses the setting for the Move After Enter option on the Keyboard tab in the Options dialog box, available by clicking Options on the Tools menu. The Move After Enter section has the following settings.

Setting | Description
Don’t Move | Pressing ENTER has no effect.
Next Field | Pressing ENTER moves the insertion point to the next control or field in the form or datasheet in the Tab order.
Next Record | Pressing ENTER moves the insertion point to the first control or field in the next record on the form or datasheet.

See Also

AutoTab Property.


Environ Function

Description

Returns the string associated with an operating system environment variable.

Syntax

Environ({envstring | number})

The Environ function syntax has these named arguments:

Part | Description
envstring | String expression containing the name of an environment variable.
number | Numeric expression corresponding to the numeric order of the environment string in the environment-string table. The number argument can be any numeric expression, but is rounded to a whole number before it is evaluated.

Remarks

If envstring can’t be found in the environment-string table, a zero-length string is returned. Otherwise, Environ returns the text assigned to the specified envstring; that is, the text following the equal sign in the environment-string table for that environment variable.

If you specify number, the string occupying that numeric position in the environment-string table is returned. In this case, Environ returns all of the text, including envstring. If there is no environment string in the specified position, Environ returns a zero-length string ("").

Example

This example uses the Environ function to supply the entry number and length of the PATH statement from the environment-string table.

Dim EnvString, Indx, Msg, PathLen    ' Declare variables.= 1                ' Initialize index to 1.
    EnvString = Environ(Indx)    ' Get environment
                    ' variable.
    If Left(EnvString, 5) = "PATH=" Then    ' Check PATH entry.
        PathLen = Len(Environ("PATH"))    ' Get length.
        Msg = "PATH entry = " & Indx & " and length = " & PathLen
        Exit Do
    Else
        Indx = Indx + 1    ' Not PATH entry,
    End If            ' so increment.Until EnvString = ""PathLen > 0 Then
    MsgBox Msg        ' Display message.
    MsgBox "No PATH environment variable exists."If


EOF Function

Description

Returns a value that indicates whether the end of a file has been reached.

Syntax

EOF(filenumber)

The filenumber argument is any valid file number.

Remarks

Use EOF to avoid the error generated by the attempt to get input past the end of a file.

The EOF function returns False unless the end of the file has been reached; then it returns True. When used with files opened for Random or Binary access, EOF returns False unless the last executed Get statement is unable to read an entire record; then it returns True.

See Also

Get Statement, Loc Function, LOF Function, Open Statement.

Example

This example uses the EOF function to detect the end of a file. This example assumes that MYFILE is a text file with a few lines of text.

Open "MYFILE" For Input As #1    ' Open file for input.While Not EOF(1)    ' Check for end of file.
    Line Input #1, InputData    ' Read line of data.
    Debug.Print InputData    ' Print to Debug window.#1    ' Close file.


Eqv Operator

Description

Used to perform a logical equivalence on two expressions.

Syntax

result = expression1 Eqv expression2

The Eqv operator syntax has these parts:

Part | Description
result | Any numeric variable.
expression1 | Any expression.
expression2 | Any expression.

Remarks

If either expression is Null, result is also Null. When neither expression is Null, result is determined according to the following table:

If expression1 is | And expression2 is | The result is
True | True | True
True | False | False
False | True | False
False | False | True

The Eqv operator performs a bit-wise comparison of identically positioned bits in two numeric expressions and sets the corresponding bit in result according to the following truth table:

If bit in expression1 is | And bit in expression2 is | The result is
0 | 0 | 1
0 | 1 | 0
1 | 0 | 0
1 | 1 | 1

See Also

Operator Precedence.

Example

This example uses the Eqv operator to perform logical equivalence on two expressions.

A = 10: B = 8: C = 6: D = Null    ' Initialize variables.= A > B Eqv B > C    ' Returns True.= B > A Eqv B > C    ' Returns False.= A > B Eqv B > D    ' Returns Null.= A Eqv B    ' Returns -3 (bit-wise comparison).


Erase Statement

Description

Reinitializes the elements of fixed-size arrays and deallocates dynamic-array storage space.

Syntax

Erase arraylist

The arraylist argument is one or more comma-delimited array variables to be erased.

Remarks

It is important to know whether an array is fixed-size (ordinary) or dynamic because Erase behaves differently depending on the type of array. Erase recovers no memory for fixed-size arrays. Erase sets the elements of a fixed array as follows:

Type of array | Effect of Erase on fixed-array elements
Fixed numeric array | Sets each element to zero.
Fixed string array (variable length) | Sets each element to zero-length ("").
Fixed string array (fixed length) | Sets each element to zero.
Fixed Variant array | Sets each element to Empty.
Array of user-defined types | Sets each element as if it were a separate variable.
Array of objects | Sets each element to the special value Nothing.

Erase frees the memory used by dynamic arrays. Before your program can refer to the dynamic array again, it must redeclare the array variable’s dimensions using a ReDim statement.

See Also

Array Function, Dim Statement, Nothing, Private Statement, Public Statement, ReDim Statement, Static Statement.

Example

This example uses the Erase statement to reinitialize the elements of fixed-size arrays and deallocate dynamic-array storage space.

' Declare array variables.NumArray(10) As Integer    ' Integer array.StrVarArray(10) As String    ' Variable-string array.StrFixArray(10) As String * 10    ' Fixed-string array.VarArray(10) As Variant    ' Variant array.DynamicArray() As Integer    ' Dynamic array.DynamicArray(10)    ' Allocate storage space.NumArray    ' Each element set to 0.StrVarArray    ' Each element set to zero-length
        ' string ("").StrFixArray    ' Each element set to 0.VarArray    ' Each element set to Empty.DynamicArray    ' Free memory used by array.


Err Object

Description

Contains information about run-time errors. Accepts the Raise and Clear methods for generating and clearing run-time errors.

Syntax

Err[.{property | method}]

Remarks

The properties of the Err object are set by the generator of an error — Visual Basic, an OLE object, or the Visual Basic programmer.

The default property of the Err object is Number. Its value corresponds the value returned by the Err function in previous versions of Visual Basic. Assigning an error code to the Number property corresponds to specifying a number in the Err statement in previous versions of Visual Basic. Since the default property can be represented by the object name Err, existing code that expects a valid error number to be returned or set by Err doesn’t have to be modified. While the value of Err.Number is compatible with previous versions of Basic, it now contains a Long integer and can be used by an OLE Automation object to return an OLE SCode.

When a run-time error occurs, the properties of the Err object are filled with information that uniquely identifies the error and information that can be used to handle it. To generate a run-time error in your code, use the Raise method.

The Err object’s properties are reset to zero or zero-length strings ("") after any form of the Resume or On Error statement and after an Exit Sub, Exit Function, or Exit Property statement within an error-handling routine. The Clear method can be used to explicitly reset Err.

Caution If you set up an error handler using On Error GoTo and that handler calls another procedure, the properties of the Err object may be reset to zero and zero-length strings. To retain values for later use, assign the values of Err properties to variables before calling another procedure, or before executing Resume, On Error, Exit Sub, Exit Function, or Exit Property statements.

When writing code for an OLE Automation object in Visual Basic, use the Raise method (rather than the Error statement) to generate run-time errors. Whether or not to use the Raise method in new non-OLE Automation code depends on the richness of the information you want to return. In code that uses Error statements instead of the Raise method to generate errors, the properties of the Err object are assigned the following default values when Error is executed:

Property | Value
Number | Value specified as argument to Error statement. Can be any valid error number.
Source | Name of the current Visual Basic project.
Description | A string corresponding to the return of the Error function for the specified Number, if this string exists. If the string doesn’t exist, Description contains “Application-defined or object-defined error”.
HelpFile | The fully qualified drive, path, and filename of the Visual Basic Help file.
HelpContext | The Visual Basic Help file context ID for the error corresponding to the Number property.
LastDLLError | On 32-bit Microsoft Windows operating systems only, contains the system error code for the last call to a dynamic-link library (DLL). The LastDLLError property is read-only.

There is no need to change existing code that used Err and the Error statement. However, mixing use of the Err object and the Error statement can result in unintended consequences. For instance, even if you fill in the Err object’s properties, they are reset to the default values indicated in the preceding table as soon as the Error statement is executed. Although you can still use the Error statement to generate Visual Basic run-time errors, it is retained principally for compatibility with existing code. Use the Err object and the Raise and Clear methods for system errors and in new code, especially for OLE Automation objects.

The Err object is an intrinsic object with global scope — there is no need to create an instance of it in your code.

Properties

Description Property, HelpContext Property (Visual Basic), HelpFile Property (Visual Basic), LastDLLError Property, Number Property, Source Property.

Methods

Clear Method, Raise Method.

See Also

Error Function, Error Statement, On Error Statement, Resume Statement.

Example

This example uses the properties of the Err object in constructing an error-message dialog box. Note that when you generate a Visual Basic error with the Raise method, if you use the Clear method first, Visual Basic’s default values become the properties of the Err object.

' If an error occurs, construct an error messageError Resume Next    ' Defer error handling..Clear.Raise 6        ' Generate an "Overflow" error.
' Check for error, then show message.Err.Number <> 0 Then
    Msg = "Error # " & Str(Err.Number) & " was generated by " _
        & Err.Source & Chr(13) & Err.Description
    MsgBox Msg, , "Error", Err.Helpfile, Err.HelpContextIf


Error Event

Applies To

Form, Report.

Description

The Error event occurs when a run-time error is produced in Microsoft Access when a form or report has the focus. This includes Microsoft Jet database engine errors, but not run-time errors in Visual Basic.

Remarks

By executing an event procedure or running a macro when an Error event occurs, you can intercept a Microsoft Access error message and display a custom message that conveys a more specific meaning for your application.

See Also

Err Object, Error Function.


Error Event -- Event Procedures

Description

To create an event procedure that is executed when the Error event occurs, set the OnError property to [Event Procedure], and click the Build button.

Syntax

Private Sub Form_Error(DataErr As Integer, Response As Integer)Private Sub Report_Error(DataErr As Integer, Response As Integer)

The Error event procedure uses the following arguments.

Argument | Description
DataErr | The error code returned by the Err object when an error occurs. You can use the DataErr argument with the Error function to map the number to the corresponding error message.
Response | An intrinsic constant determining whether or not an error message is displayed. The Response argument can be one of the following constants.

Constant acDataErrContinue acDataErrDisplay | Description Ignore the error and continue without displaying the default Microsoft Access error message. You can supply a custom error message in place of the default error message. (Default) Display the default Microsoft Access error message.

Remarks

You can’t cancel the Error event.

See Also

Error Event — Macros.

Example

The following example shows how you can replace a default error message with a custom error message. When Microsoft Access returns an error message indicating it has found a duplicate key (error code 3022), this event procedure displays a message that gives more application-specific information to users.

Private Sub Form_Error(DataErr As Integer, Response As Integer)
    Const conDuplicateKey = 3022
    Dim strMsg As String

    If DataErr = conDuplicateKey Then
        Response = acDataErrContinue
        strMsg = "Each employee record must have a unique " _
            & "employee ID number. Please recheck your data."
        MsgBox strMsg
    End IfSub


Error Event -- Macros

Description

To run a macro when the Error event occurs, set the OnError property to the name of the macro.

Remarks

You can use an Error macro to display a general message whenever a run-time error occurs. However, macros can’t return the error code and determine which error occurred, so you typically use event procedures with this event.

You can’t use the CancelEvent action in an Error macro.

See Also

Error Event — Event Procedures.


Error Function

Description

Returns the error message that corresponds to a given error number.

Syntax

Error[(errornumber)]

The errornumber argument can be any valid error number. If errornumber is a valid error number, but is not defined, Error returns the string “Application-defined or object-defined error.” If errornumber is not valid, an error occurs. If errornumber is omitted, the message corresponding to the most recent run-time error is returned. If no run-time error has occurred, or errornumber is 0, Error returns a zero-length string ("").

Remarks

Examine the property settings of the Err object to identify the most recent run-time error. The return value of the Error function corresponds to the Description property of the Err object.

See Also

Err Object.

Example

This example uses the Error function to print error messages that correspond to the specified error numbers.

For ErrorNumber = 61 To 64    ' Loop through values 61 - 64.
    Debug.Print Error(ErrorNumber)    ' Print error to Debug window.ErrorNumber


Error Statement

Description

Simulates the occurrence of an error.

Syntax

Error errornumber

The errornumber can be any valid error number.

Remarks

The Error statement is supported for backward compatibility. In new code, especially when creating OLE Automation objects, apply the Raise method to the Err object to generate run-time errors. Not all Visual Basic host applications can create OLE Automation objects. See your host application’s documentation to determine whether it can create classes and OLE Automation objects.

If errornumber is defined, the Error statement calls the error handler after filling the Err object’s properties with default values (as shown in the following table):

Property | Value
Number | Value specified as argument to Error statement. Can be any valid error number.
Source | Name of the current Visual Basic project.
Description | A string expression corresponding to the return value of the Error function for the specified Number, if this string exists. If the string doesn’t exist, Description contains a zero-length string ("").
HelpFile | The fully qualified drive, path, and filename of the Visual Basic Help file.
HelpContext | The Visual Basic Help file context ID for the error corresponding to the Number property.

If no error handler exists or if none is enabled, an error message is created and displayed from the Err object properties.

See Also

Clear Method, Err Object, Error Function, On Error Statement, Raise Method, Resume Statement.

Example

This example uses the Error statement to simulate error number 11.

On Error Resume Next            ' Defer error handling.11                        ' Simulate the "Division by zero" error.


Eval Function

Description

You can use the Eval function to evaluate an expression that results in a text string or a numeric value.

You can construct a string and then pass it to the Eval function as if the string were an actual expression. The Eval function evaluates the string expression and returns its value. For example, Eval("1 + 1") returns 2.

If you pass to the Eval function a string that contains the name of a function, the Eval function returns the return value of the function. For example, Eval("Chr$(65)") returns “A”.

Syntax

Eval(stringexpr)

The stringexpr argument is an expression that evaluates to an alphanumeric text string. For example, stringexpr can be a function that returns a string or a numeric value. Or it can be a reference to a control on a form. The stringexpr must evaluate to a string or numeric value; it cannot evaluate to a Microsoft Access object.

Remarks

You can use the Eval function in a calculated control on a form or report, or in a macro or module. The Eval function returns a Variant that is either a string or a numeric type.

The argument stringexpr must be an expression that is stored in a string. If you pass to the Eval function a string that does not contain an numeric expression or a function name but only a simple text string, a run-time error occurs. For example, Eval("Smith") results in an error.

You can use the Eval function to determine the value stored in the Value property of a control. The following example passes a string containing a full reference to a control to the Eval function. It then displays the current value of the control in a dialog box.

Dim ctl As Control, strCtl As Stringctl = Forms!Employees!LastName = "Forms!Employees!LastName"("The current value of " & ctl.Name & " is " & Eval(strCtl))

You can use the Eval function to access expression operators that aren’t ordinarily available in Visual Basic. For example, you cannot use the SQL operators Between...And or In operators directly in your code, but you can use them in an expression passed to the Eval function.

The next example determines whether the value of the ShipRegion control on an Orders form is one of several specified state abbreviations. If the field contains one of the abbreviations, intState will be True (-1). Note that you use single quotation marks (‘) to include one string within another string.

Dim intState As Integer= Eval("Forms!Orders!ShipRegion In " _
    & "('AK', 'CA', 'ID', 'WA', 'MT', 'NM', 'OR')")

Example

The following example assumes that you have a series of 50 functions defined as A1, A2, and so on. This example uses the Eval function to call each function in the series.

Sub CallSeries()
    Dim intI As Integer

    For intI = 1 To 50
        Eval("A" & intI & "()")
    Next intISub

The next example triggers a Click event as if the user had clicked a button on a form. If the value of the button’s OnClick property begins with an equal sign (=), signifying that it is the name of a function, the Eval function calls the function, which is equivalent to triggering the Click event. If the value does not begin with an equal sign, then the value must name a macro. The RunMacro method of the DoCmd object runs the named macro.

Dim ctl As Control, varTemp As Variantctl = Forms!Contacts!HelpButton(Left(ctl.OnClick, 1) = "=") Then
    varTemp = Eval(Mid(ctl.OnClick,2))
    DoCmd.RunMacro ctl.OnClickIf


Event Properties

Description

Event properties cause a macro or the associated Visual Basic event procedure to run when a particular event occurs. For example, if you enter the name of a macro in a command button’s OnClick property, that macro runs when the command button is clicked.

Setting

To run a macro, enter the name of the macro. You can choose an existing macro in the list. If the macro is in a macro group, it will be listed under the macro group name, as macrogroupname.macroname.

To run the event procedure associated with the event, select [Event Procedure] in the list.

Note Although using an event procedure is the recommended method for running Visual Basic code in response to an event, you can also run a user-defined function when an event occurs. To run a user-defined function, place an equal sign (=) before the function name and parentheses after it, as in =functionname( ).

You can set event properties in the property sheet for an object or in a macro or Visual Basic. Note that you can’t set any event properties while you’re formatting or printing a form or report.

Tip You can use builders to help you set an event property. Click the Build button to the right of the property box, or click the right mouse button when the pointer is over the property box and then click Build on the shortcut menu. In the Choose Builder dialog box, select:

  • The Macro Builder to create and specify a macro for this event property. You can also use the Macro Builder to edit a macro already specified by the property.
  • The Code Builder to create and specify an event procedure for this event property. You can also use the Code Builder to edit an event procedure already specified by the property.
  • The Expression Builder to choose and specify a user-defined function for this event property.

In Visual Basic, set the property to a string expression.

To run this | Use this syntax | Example
Macro | "macroname" | Button1.OnClick = "MyMacro"
Event procedure | "[Event Procedure]" | Button1.OnClick = "[Event Procedure]"
User-defined function | "=functionname( )" | Button1.OnClick = "=MyFunction()"

Example

The following example shows how you can use the value entered in the Country control to determine which of two different macros to run when you click the Print Country Report button.

Sub Country_AfterUpdate()
    If Country = "Canada" Then
        [Print Country Report].OnClick = "PrintCanadaReport"
    ElseIf Country = "USA" Then
        [Print Country Report].OnClick = "PrintUSAReport"
    End IfSub


Event Properties and Objects They Apply To

Event Property | Applies To
AfterDelConfirm | Forms.
AfterInsert | Forms.
AfterUpdate* | Forms. Controls (bound object frame, check box, combo box, list box, option button, option group, text box, toggle button) on a form.
BeforeDelConfirm | Forms.
BeforeInsert | Forms.
BeforeUpdate* | Forms. Controls (bound object frame, check box, combo box, list box, option button, option group, text box, toggle button) on a form.
OnActivate | Forms and reports.
OnApplyFilter | Forms.
OnChange | Controls (combo box, text box) on a form.
OnClick* | Forms. Form sections. Controls (bound object frame, chart, check box, combo box, command button, label, list box, option button, option group, rectangle, text box, toggle button, unbound object frame) on a form.
OnClose | Forms and reports.
OnCurrent | Forms.
OnDblClick* | Forms. Form sections. Controls (bound object frame, chart, check box, combo box, command button, label, list box, option button, option group, rectangle, text box, toggle button, unbound object frame) on a form.
OnDeactivate | Forms and reports.
OnDelete | Forms.
OnEnter* | Controls (bound object frame, chart, check box, combo box, command button, list box, option button, option group, subform/subreport, text box, toggle button, unbound object frame) on a form.
OnError | Forms and reports.
OnExit* | Controls (bound object frame, chart, check box, combo box, command button, list box, option button, option group, subform/subreport, text box, toggle button, unbound object frame) on a form.
OnFilter | Forms.
OnFormat | Report sections.

Event Property | Applies To
OnGotFocus | Forms. Controls (bound object frame, check box, combo box, command button, list box, option button, text box, toggle button, unbound object frame) on a form.
OnKeyDown | Forms. Controls (bound object frame, check box, combo box, command button, list box, option button, text box, toggle button, unbound object frame) on a form.
OnKeyPress | Forms. Controls (bound object frame, check box, combo box, command button, list box, option button, text box, toggle button, unbound object frame) on a form.
OnKeyUp | Forms. Controls (bound object frame, check box, combo box, command button, list box, option button, text box, toggle button, unbound object frame) on a form.
OnLoad | Forms.
OnLostFocus | Forms. Controls (bound object frame, check box, combo box, command button, list box, option button, text box, toggle button, unbound object frame) on a form.
OnMouseDown | Forms. Form sections. Controls (bound object frame, chart, check box, combo box, command button, label, list box, option button, option group, rectangle, text box, toggle button, unbound object frame) on a form.
OnMouseMove | Forms. Form sections. Controls (bound object frame, chart, check box, combo box, command button, label, list box, option button, option group, rectangle, text box, toggle button, unbound object frame) on a form.
OnMouseUp | Forms. Form sections. Controls (bound object frame, chart, check box, combo box, command button, label, list box, option button, option group, rectangle, text box, toggle button, unbound object frame) on a form.
OnNoData | Reports.
OnNotInList | Controls (combo box) on a form.
OnOpen | Forms and reports.
OnPage | Reports.
OnPrint | Report sections.
OnResize | Forms.
OnRetreat | Report sections.
OnTimer | Forms.
OnUnload | Forms.
OnUpdated | Controls (bound object frame, unbound object frame) on a form.

* These properties don’t apply to check boxes, option buttons, or toggle buttons in an option group. They apply only to the option group itself.


EventProcPrefix Property

Applies To

Bound Object Frame Control, Chart Control, Check Box Control, Combo Box Control, Command Button Control, Form Section, Image Control, Label Control, Line Control, List Box Control, Option Button Control, Option Group Control, Page Break Control, Rectangle Control, Report Section, Subform/Subreport Control, Text Box Control, Toggle Button Control, Unbound Object Frame Control.

Description

You can use the EventProcPrefix property to get the prefix portion of an event procedure name. For example, if you have a command button with an event procedure named Details_Click, the EventProcPrefix property returns the string “Details”.

Setting

The EventProcPrefix property setting is a string expression.

This property is available only in a macro or Visual Basic and is read-only in all views.

Remarks

Microsoft Access appends the prefix portion of an event procedure name to the event name with an underscore character (_).


Exit Event

See Enter, Exit Events.


Exit Statement

Description

Exits a block of Do...Loop, For...Next, Function, Sub, or Property code.

Syntax

Exit DoExit ForExit FunctionExit PropertyExit Sub

The Exit statement syntax has these forms:

Statement | Description
Exit Do | Provides a way to exit a Do...Loop statement. It can be used only inside a Do...Loop statement. Exit Do transfers control to the statement following the Loop statement. When used within nested Do...Loop statements, Exit Do transfers control to the loop that is one nested level above the loop where it occurs.
Exit For | Provides a way to exit a For loop. It can be used only in a For...Next or For Each...Next loop. Exit For transfers control to the statement following the Next statement. When used within nested For loops, Exit For transfers control to the loop that is one nested level above the loop where it occurs.
Exit Function | Immediately exits the Function procedure in which it appears. Execution continues with the statement following the statement that called the Function.
Exit Property | Immediately exits the Property procedure in which it appears. Execution continues with the statement following the statement that called the Property procedure.
Exit Sub | Immediately exits the Sub procedure in which it appears. Execution continues with the statement following the statement that called the Sub.

Remarks

Do not confuse Exit statements with End statements. Exit does not define the end of a structure.

See Also

Do...Loop Statement, End Statement, For Each...Next Statement, For...Next Statement, Function Statement, Property Get Statement, Property Let Statement, Property Set Statement, Stop Statement, Sub Statement.

Example

This example uses the Exit statement to exit a For...Next loop, a Do...Loop, and a Sub procedure.

Sub ExitStatementDemo()
    Do                ' Set up infinite loop.
        For I = 1 To 1000    ' Loop 1000 times.
            MyNum = Int(Rnd * 1000)    ' Generate random numbers.
            Select Case MyNum    ' Evaluate random number.
                Case 7: Exit For    ' If 7, exit For...Next.
                Case 29: Exit Do    ' If 29, exit Do...Loop.
                Case 54: Exit Sub    ' If 54, exit Sub procedure.
            End Select
        Next I
    LoopSub


Exp Function

Description

Returns e (the base of natural logarithms) raised to a power.

Syntax

Exp(number)

The number argument can be any valid numeric expression.

Remarks

If the value of number exceeds 709.782712893, an error occurs. The constant e is approximately 2.718282.

Note The Exp function complements the action of the Log function and is sometimes referred to as the antilogarithm.

See Also

Derived Math Functions, Log Function.

Example

This example uses the Exp function to return e raised to a power.

' Define angle in radians.= 1.3
' Calculate hyperbolic sine.= (Exp(MyAngle) - Exp(-1 * MyAngle)) / 2


FastLaserPrinting Property

Applies To

Form, Report.

Description

You can use the FastLaserPrinting property to specify whether lines and rectangles are replaced by text character lines — similar to underscore (_) and vertical bar (|) characters — when you print a form or report using most laser printers.

Setting

The FastLaserPrinting property uses the following settings.

Setting | Description | Visual Basic
Yes | (Default) Lines and rectangles are replaced text character lines. | True (-1)
No | Lines and rectangles aren’t replaced by text character lines. | False (0)

You can set this property only in Design view using the property sheet, a macro, or Visual Basic.

Remarks

The FastLaserPrinting property affects any line or rectangle on a form or report, including controls that include these shapes (for example, a border around a text box).

You use this property to speed printing; replacing lines and rectangles with text character lines can make printing much faster. When the FastLaserPrinting property is set to No, Microsoft Access prints lines and rectangles as graphics. When the this property is set to Yes, lines and rectangles are printed as text character lines, resulting in faster printing.

Note This property has no effect on PostScript™ printers, dot-matrix printers, or earlier versions of laser printers that don’t support text character lines.

When this property is set to Yes and the form or report being printed has overlapping rectangles or lines, the rectangles or lines on top don’t erase the rectangles or lines they overlap. If you require overlapping graphics on your report, set the FastLaserPrinting property to No.

Example

The following example demonstrates setting the FastLaserPrinting property for the Invoice report while in report Design view.

DoCmd.OpenReport "Invoice", acDesign!Invoice.FastLaserPrinting = True.Close acReport, "Invoice", acSaveYes


FieldName Property

Applies To

Table Fields.

Description

You can use the FieldName property to specify the name of a field within a table. For example, you can specify “Last Name” for a field that stores employees’ last names within the Employees table.

Setting

Enter a field name, following Microsoft Access object naming rules. The name can’t duplicate any other field name in the table.

Note Avoid specifying a name for a field that could cause a conflict with built-in Microsoft Access function or property names, such as the Name property.

You can set this property in the upper portion of table Design view or using Visual Basic.

In Visual Basic, use the Data Access Object’s Name property to read and set a table’s field name.

Remarks

Microsoft Access identifies a field by its field name. Once you have specified a field name in table Design view, you can use that name in expressions, Visual Basic procedures, and SQL statements.

See Also

Caption Property, Name Property (Microsoft Office 95 Data Access Reference).


FieldSize Property

Applies To

Table Fields.

Description

You can use the FieldSize property to set the maximum size of data that can be stored in a field set to Text or Number data type.

Setting

If the DataType property is set to Text, enter a number from 0 to 255. The default setting is 50.

If the DataType property is set to Number, the FieldSize property settings and their values are related in the following way.

 |  | Decimal Precision | Storage Size
Byte | Stores numbers from 0 to 255 (no fractions). | None | 1 byte
Integer | Stores numbers from -32,768 to 32,767 (no fractions). | None | 2 bytes
Long Integer | (Default) Stores numbers from ,147,483,648 to 2,147,483,647 (no fractions). | None | 4 bytes
Single | Stores numbers from .402823E38 to 3.402823E38. | 7 | 4 bytes
Double | Stores numbers from .79769313486232E308 to 1.79769313486232E308. | 15 | 8 bytes
ReplicationID | Globally Unique Identifier (GUID) | N/A | 16 bytes

You can set this property in the table’s property sheet or using Visual Basic.

In Visual Basic, use the Data Access Object’s Size property to read and set the maximum size of text fields (for data types other than Text, the Type property setting automatically determines the Size property setting).

Note You can specify the default field sizes for text and number fields by changing the values under the Default Field Sizes option on the Tables/Queries tab, available by clicking Options on the Tools menu.

Remarks

You should use the smallest possible FieldSize property setting because smaller data sizes can be processed faster and require less memory.

Caution If you convert a large FieldSize setting to a smaller one in a field that already contains data, you might lose data in the field. For example, if you change the FieldSize setting for a Text data type field from 255 to 50, data beyond the 50 characters will be discarded.

If the data in a Number data type field doesn’t fit in a new FieldSize setting, fractional numbers may be rounded or you might get a Null value. For example, if you change from Single to Integer data type, fractional values will be rounded to the nearest whole number and values greater than 32,767 or less than -32,768 will result in Null fields.

You can’t undo changes to a table’s design after saving it in table Design view.

Tip You can use the Currency data type if you plan to perform many calculations on a field that contains data with one to four decimal places. Single and Double data type fields require floating-point calculation. Currency data type fields use a faster fixed-point calculation.

See Also

DecimalPlaces Property, Size Property (Microsoft Office 95 Data Access Reference).


FileAttr Function

Description

Returns file mode or operating system file handle information for files opened using the Open statement.

Syntax

FileAttr(filenumber, returntype)

The FileAttr function syntax has these named arguments:

Part | Description
filenumber | Any valid file number.
returntype | Number indicating the type of information to return. Specify 1 to return a value indicating the file mode. Specify 2 to return the operating system file handle.

Return Values

When the returntype argument is 1, the following return values indicate the file access mode:

Value | File Mode
1 | Input
2 | Output
4 | Random
8 | Append
32 | Binary

See Also

GetAttr Function, Open Statement, SetAttr Statement.

Example

This example uses the FileAttr function to return the file mode and file handle of an open file.

FileNum = 1    ' Assign file number."TESTFILE" For Append As FileNum    ' Open file.= FileAttr(FileNum, 1)    ' Returns 8 (Append file mode).= FileAttr(FileNum, 2)    ' Returns file handle.FileNum    ' Close file.


FileCopy Statement

Description

Copies a file.

Syntax

FileCopy source, destination

The FileCopy statement syntax has these named arguments:

Part

Description

source | String expression that specifies the name of the file to be copied. The source may include directory or folder, and drive.
destination | String expression that specifies the target filename. The destination may include directory or folder, and drive.

Remarks

If you try to use the FileCopy statement on a currently open file, an error occurs.

See Also

Kill Statement, Name Statement.

Example

This example uses the FileCopy statement to copy one file to another. For purposes of this example, assume that SRCFILE is a file containing some data.

SourceFile = "SRCFILE"    ' Define source filename.= "DESTFILE"    ' Define target filename.SourceFile, DestinationFile    ' Copy source to target.


FileDateTime Function

Description

Returns a date (VarType 7) that indicates the date and time when a file was created or last modified.

Syntax

FileDateTime(pathname)

The pathname argument is a string expression that specifies a filename. The pathname may include the directory or folder, and the drive.

See Also

FileLen Function, GetAttr Function, VarType Function.

Example

This example uses the FileDateTime function to determine the date and time a file was created or last modified. The format of the date and time displayed is based on the locale settings of your system.

' Assume TESTFILE was last modified on February 12, 1993 at 4:35:47 PM.
' Assume English/United States locale settings.= FileDateTime("TESTFILE")    ' Returns "2/12/93 4:35:47 PM".


FileLen Function

Description

Returns the length of a file in bytes.

Syntax

FileLen(pathname)

The pathname argument is a string expression that specifies a file. The pathname may include the directory or folder, and the drive.

Remarks

If the specified file is open when the FileLen function is called, the value returned represents the size of the file immediately before it was opened.

To obtain the length of an open file, use the LOF function.

See Also

FileDateTime Function, GetAttr Function, LOF Function.

Example

This example uses the FileLen function to return the length of a file in bytes. For purposes of this example, assume that TESTFILE is a file containing some data.

MySize = FileLen("TESTFILE")    ' Returns file length (bytes).


FillColor Property

Applies To

Report.

Description

You use the FillColor property to specify the color that fills in boxes and circles drawn on reports with the Line and Circle methods. You can also use this property with Visual Basic to create special visual effects on custom reports when you print using a color printer.

Setting

The FillColor property contains a numeric expression that specifies the fill color for all boxes and circles.

You can set this property only in a macro or an Visual Basic event procedure specified by a section’s OnPrint event property.

Remarks

You can use the RGB or QBColor functions to set this property. The FillColor property setting has a data type of Long.

See Also

Circle Method, DrawMode Property, DrawStyle Property, DrawWidth Property, FillStyle Property, Line Method, PSet Method, QBColor Function, RGB Function.


FillStyle Property

Applies To

Report.

Description

You can use the FillStyle property to specify whether a circle or line drawn by the Circle or Line method is transparent or filled with a pattern.

Setting

The FillStyle property uses the following settings.

Setting | Description
0 | Opaque
1 | (Default) Transparent
2 | Horizontal Line
3 | Vertical Line

Setting | Description
4 | Upward Diagonal
5 | Downward Diagonal
6 | Cross
7 | Diagonal Cross

You can set the FillStyle property only in a macro or a Visual Basic event procedure specified by the OnPrint property setting of a report section.

Remarks

When the FillStyle property is set to 0, a circle or line has the color set by the FillColor property. When the FillStyle property is set to 1, the interior of the circle or line is transparent and has the color of the report behind it.

To use the FillStyle property, the SpecialEffect property must be set to Normal.

See Also

BorderColor Property, BorderStyle Property, BorderWidth Property, Circle Method, Event Properties, FillColor Property, Line Method, Print Event.


Filter Event

Applies To

Form.

Description

The Filter event occurs when the user does one of the following:

  • Clicks the Filter By Form subcommand of the Filter command on the Records menu, or clicks the Filter By Form button on the toolbar. This opens the Filter By Form window, where you can quickly create a filter based on the fields in the form.
  • Clicks the Advanced Filter/Sort subcommand of the Filter command on the Records menu. This opens the Advanced Filter/Sort window, where you can create complex filters for the form.

Remarks

You can use the Filter event to:

  • Remove any previous filter for the form. To do this, set the Filter property of the form to a zero-length string (" ") in the Filter macro or event procedure. This is especially useful if you want to make sure extraneous criteria do not appear in the new filter. For example, whenever you use the Filter By Selection feature, the criteria you use (the selected text in the form) is added to the Filter property WHERE clause expression, and appears in both the Filter By Form window and the Advanced Filter/Sort window. You can remove this old criteria using the Filter event.
  • Enter default settings for the new filter. To do this, set the Filter property to include these criteria. For example, you may want all filters for a Products form to display only current products (products for which the Discontinued control in the Products form is not selected).
  • Use your own custom filter window instead of one of the Microsoft Access filter windows. When the Filter event occurs, you can open your own custom form and use the entries on this form to set the Filter property and filter the original form. When the user closes this custom form, set the FilterOn property of the original form to True to apply the filter. Canceling the Filter event prevents the Microsoft Access filter window from opening.
  • Prevent certain controls on the form from appearing or being used in the Filter By Form window. If you hide or disable a control in the Filter macro or event procedure, the control is hidden or disabled in the Filter By Form window, and can’t be used to set filter criteria. You can then use the ApplyFilter event to show or enable this control after the filter is applied, or when the filter is removed from the form.

See Also

Filter Property, Filter Property (Microsoft Office 95 Data Access Reference), FilterLookup Property, FilterOn Property, OrderBy Property, OrderByOn Property.


Filter Event -- Event Procedures

Description

To create an event procedure that is executed when the Filter event occurs, set the OnFilter property to [Event Procedure], and click the Build button.

Syntax

Private Sub Form_Filter(Cancel As Integer, FilterType As Integer)

The Filter event procedure uses the following arguments.

Argument | Description
Cancel | The setting determining whether to open the filter window. Setting Cancel to True (-1) prevents the filter window from opening. You can also use the CancelEvent method of the DoCmd object to cancel opening the filter window.
FilterType | The filter window the user is trying to open. The FilterType argument can be one of the following intrinsic constants: Constant Value acFilterByForm 0 acFilterAdvanced 1

Remarks

You can use the Filter event procedure to disable or hide certain controls in the Filter By Form window, preventing them from being used in filter criteria. For example, you may always want your Orders form to show records that have a value in the TotalDue control, no matter how small. You can disable or hide this control in the Filter event procedure, then enable or show it in the ApplyFilter event procedure. Disabling and hiding controls in the Filter By Form window is best accomplished in the Filter event procedure rather than the Filter macro, because you can check the FilterType argument to see if the user opened the Filter By Form window. All of the fields in a form appear in the Advanced Filter/Sort window, even if the controls are disabled or hidden.

See Also

Filter Event — Macros.

Example

The following example shows how to disable the TotalDue control on an Orders form when the user tries to create a filter, so that the user can’t filter on this field. Any records that have a TotalDue value and meet the other filter criteria will always be shown on the filtered form. This example also forces the user to use the Filter By Form window and not the Advanced Filter/Sort window.

Private Sub Form_Filter(Cancel As Integer, FilterType As Integer)
    If FilterType = acFilterByForm Then
        Forms!Orders!TotalDue.Enabled = False
    ElseIf FilterType = acFilterAdvanced Then
        MsgBox "The best way to filter this form is to use the " & _
            "Filter By Form command or toolbar button.", vbOKOnly + _            vbInformation
        Cancel = True
    End IfSub


Filter Event -- Macros

Description

To run a macro when the Filter event occurs, set the OnFilter property to the name of the macro.

Remarks

You can set the Filter property in a Filter macro using the SetValue action. This enables you to customize the filter criteria that the user sees when the Filter By Form window or Advanced Filter/Sort window is displayed.

You can use the CancelEvent action in a Filter macro to cancel opening the filter window.

See Also

Filter Event — Event Procedures.


Filter Property

Applies To

Form, Query, Report, Table.

Description

You can use the Filter property to specify a subset of records to be displayed when a filter is applied to a form, query, or table.

Setting

The Filter property is a string expression consisting of a WHERE clause without the WHERE keyword. For example, the following Visual Basic code defines applies a filter to show only customers from the USA:

Me.Filter = "Country = 'USA'".FilterOn = True

You can set this property in the following ways:

  • Forms
  • Table property sheets
  • Macros
  • Visual Basic

You can also set this property in Form view or Datasheet view by pointing to Filter on the Records menu and clicking one of the commands on the submenu.

Note Setting the Filter property has no affect on the data access Filter property.

Remarks

You can use the Filter property to save a filter and apply it at a later time. Filters are saved with the objects in which they are created. They are automatically loaded when the object is opened, but they aren’t automatically applied.

When a new object is created, it inherits the RecordSource, Filter, OrderBy, and OrderByOn properties of the table or query it was created from. For forms and reports, inherited filters aren’t automatically applied when an object is opened.

To apply a saved filter to a form, query, or table, you can click the Apply Filter button on the toolbar, click Apply Filter/Sort on the Records menu, or use a macro or Visual Basic to set the FilterOn property to True (-1). For reports, you can apply a filter by setting the FilterOn property to Yes in the report’s property sheet.

The Apply Filter button indicates the state of the Filter and FilterOn properties. The button remains disabled until there is a filter to apply. If an existing filter is currently applied, the Apply Filter button appears pressed in.

To apply a filter automatically when a form is opened, specify in the OnOpen event property setting of the form either a macro that uses the ApplyFilter action or an event procedure that uses the ApplyFilter method of the DoCmd object.

You can remove a filter by clicking the pressed-in Apply Filter button, clicking Remove Filter/Sort on the Records menu, or using Visual Basic to set the FilterOn property to False (0).

Note You can save a filter as a query by clicking Save As Query on the File menu while in the Filter By Form window or the Advanced Filter/Sort window.

When the Filter property is set in form Design view, Microsoft Access does not attempt to validate the SQL expression. If the SQL expression is invalid, an error occurs when the filter is applied.

See Also

AllowFilters Property, ApplyFilter Action, ApplyFilter Event, ApplyFilter Method, BuildCriteria Method, Filter Event, Filter Property (Microsoft Office 95 Data Access Reference), FilterOn Property, OrderBy Property, OrderByOn Property.


FilterLookup Property

Applies To

Form, Report.

Description

You can use the FilterLookup property to specify whether values appear in a bound text box control when using the Filter By Form window.

Setting

The FilterLookup property uses the following arguments.

Setting | Description | Visual Basic
Never | The field values aren’t displayed. You can specify whether the filtered records can contain Null values. | 0
Database Default | (Default) The field values are displayed according to the settings in the Filter By Form Defaults section on the Option dialog box’s Edit/Find tab, available by clicking Options on the Tools menu. | 1
Always | The field values are always displayed. | 2

You can set the FilterLookup property in the text box’s property sheet, a macro, or using Visual Basic.

You can also set the FilterLookup property for a text box using the control’s default control style.

Remarks

If you find that a large list of field values take too long to display, you can limit the number of fields that will be displayed. To do this, clear the appropriate check box in the Filter By Form Defaults section on the Option dialog box’s Edit/Find tab, available by clicking Options on the Tools menu. If field lists aren’t displaying values correctly, you can increase the number in the Don’t Display Lists Where More Than This Number Of Records Read box so the setting is greater than or equal to the maximum number of records in any nonindexed field in the underlying source of records.

See Also

AllowFilters Property, ApplyFilter Action, ApplyFilter Event, ApplyFilter Method, Filter Event, Filter Property (Microsoft Office 95 Data Access Reference), Filter Property, OrderBy Property, OrderByOn Property.


FilterOn Property

Applies To

Form, Report.

Description

You can use the FilterOn property to specify or determine whether the Filter property for a form or report is applied.

Setting

The FilterOn property uses the following arguments.

Setting | Description | Visual Basic
Yes | The object’s Filter property is applied. | True (-1)
No | (Default) The object’s Filter property isn’t applied. | False (0)

For reports, you can set the FilterOn property in the report’s property sheet or using Visual Basic.

For forms, you can set the FilterOn property using a macro or Visual Basic. You can also set this property by clicking the Apply Filter button on the Form view toolbar or the Filter/Sort toolbar.

Remarks

To apply a saved filter, press the Apply Filter button for forms, or apply the filter using a macro or Visual Basic by setting the FilterOn property to True (-1) for forms or reports. For reports, you can set the FilterOn property to Yes in the report’s property sheet.

The Apply Filter button indicates the state of the Filter and FilterOn properties. The button remains disabled until there is a filter to apply. If an existing filter is currently applied, the Apply Filter button appears pressed in. To apply a filter automatically when a form or report is opened, specify in the OnOpen event property setting of the form either a macro that uses the ApplyFilter action or an event procedure that uses the ApplyFilter method of the DoCmd object.

You can remove a filter by clicking the pressed-in Apply Filter button, clicking Remove Filter/Sort on the Records menu, or using Visual Basic to set the FilterOn property to False (0). For reports, you can remove a filter by setting the FilterOn property to No in the report’s property sheet.

Note When a new object is created, it inherits the RecordSource, Filter, OrderBy, and OrderByOn properties of the table or query it was created from. For forms and reports, inherited filters aren’t automatically applied when an object is opened.

See Also

AllowFilters Property, ApplyFilter Action, ApplyFilter Event, ApplyFilter Method, Filter Event, Filter Property, Filter Property (Microsoft Office 95 Data Access Reference), OrderBy Property, OrderByOn Property.


FindNext Action

Description

You can use the FindNext action to find the next record that meets the criteria specified by the previous FindRecord action or the Find In Field dialog box, available by clicking Find on the Edit menu. You can use the FindNext action to search repeatedly for records. For example, you can move successively through all the records for a specific customer.

Setting

The FindNext action doesn’t use any arguments. The FindNext action finds the next record that meets the criteria set either by the FindRecord action or in the Find In Field dialog box. The arguments for the FindRecord action are shared with the options in the Find In Field dialog box.

To set the search criteria, use the FindRecord action. Typically, you enter a FindRecord action in a macro and then use the FindNext action to find succeeding records that meet the same criteria. To search for records only when a certain condition is met, you can enter a conditional expression in the Condition box of the FindNext action.

Remarks

This action has the same effect as using the Find Next button in the Find In Field dialog box.

Note While the FindRecord action corresponds to Find on the Edit menu for tables, queries, and forms, it does not correspond to Find on the Edit menu in the Module window. You can’t use the FindRecord action or FindNext action to search for text in modules.

Tip If you’ve set the Only Current Field argument of the FindRecord action to Yes, you may need to use the GoToControl action to move the focus to the control containing the data you’re searching for before you use the FindNext action.

To run the FindNext action in Visual Basic, use the FindNext method of the DoCmd object.

See Also

FindNext Method, FindRecord Action.


FindNext Method

Applies To

DoCmd Object.

Description

The FindNext method carries out the FindNext action in Visual Basic. For more information on how the action works, see the action topic.

Syntax

DoCmd.FindNext

This method uses no arguments.

See Also

DoCmd Object; FindFirst, FindLast, FindNext, FindPrevious Methods (Microsoft Office 95 Data Access Reference); FindNext Action; FindRecord Method.


FindRecord Action

Description

You can use the FindRecord action to find the first record following the current record that meets the criteria specified by the FindRecord action arguments. You can find records in the active table datasheet, query datasheet, form datasheet, or form.

Setting

The FindRecord action uses the following arguments.

Action argument | Description
Find What | Specifies the data you want to find in the record. Enter the text, number, or date you want to find or type an expression, which is preceded by an equal sign (=). You can use wildcard characters. This is a required argument.

Action argument | Description
Match | Specifies where the data is located in the field. You can specify a search for data in any part of the field (Any Part Of Field), for data that fills the entire field (Whole Field), or for data located at the beginning of the field (Start Of Field). The default is Whole Field.
Match Case | Specifies whether the search is case-sensitive (uppercase and lowercase letters must match exactly). Click Yes to conduct a case-sensitive search or No to search without matching uppercase and lowercase letters exactly. The default is No.
Search | Specifies whether the search proceeds from the current record up to the beginning of the records (Up); down to the end of the records (Down); or down to the end of the records and then from the beginning of the records to the current record, so all records are searched (All). The default is All.
Search As Formatted | Specifies whether the search includes formatted data. If you click Yes, Microsoft Access searches for the data as it is formatted and displayed in the field. If you click No, Microsoft Access searches for the data as it is stored in the database, which is not always the same as it is displayed. The default is No.
 | You can use this feature to restrict the search to data in a particular format. For example, click Yes and enter 1,234 in the Find What argument to find a value of 1,234 in a field formatted to include commas. Click No if you want to enter 1234 to search for the data in this field.
 | To search for dates, click Yes to find a date exactly as it is formatted, such as 03-March-1991. If you click No, enter the date in the Find What argument in the format set in the Regional Settings Properties dialog box in the Microsoft Windows Control Panel. (This is the Short Date style found on the Date tab of the Regional Settings Properties dialog box.) For example, if the Short Date style format is set to M/d/yy, you can enter 3/9/91, and Microsoft Access will find all entries in a Date field that correspond to March 9, 1991, regardless of how this field is formatted.

Note Note This argument takes effect only if the current field is a bound control, the Match argument is set to Whole Field, the Only Current Field argument is set to Yes, and the Match Case argument is set to No.

If you set Match Case to Yes or Only Current Field to No, you must also set Search As Formatted to Yes.

Action argument

Description

Only Current Field | Specifies whether the search is confined to the current field in each record or includes all fields in each record. The current field search is faster. Click Yes to confine the search to the current field or No to search in all fields in each record. The default is Yes.
Find First | Specifies whether the search starts at the first record or at the current record. Click Yes to start at the first record. Click No to start at the current record. The default is Yes.

Remarks

When a macro runs the FindRecord action, Microsoft Access moves to the next record containing the specified data and selects the data in the record.

The FindRecord action is equivalent to clicking Find on the Edit menu, and its arguments are the same as the options in the Find In Field dialog box. If you set the FindRecord action arguments in the Macro window and then run the macro, you’ll see the corresponding options selected in the Find In Field dialog box when you click Find.

Microsoft Access retains the most recent FindRecord arguments during a database session so that you don’t need to enter the same criteria repeatedly as you perform subsequent FindRecord operations. If you leave an argument blank, Microsoft Access uses the most recent setting for the argument, as set either by a previous FindRecord action or in the Find In Field dialog box.

When you want to find a record using a macro, use the FindRecord action, not the DoMenuItem action with arguments set to run the Find command.

Note While the FindRecord action corresponds to Find on the Edit menu for tables, queries, and forms, it does not correspond to Find on the Edit menu in the Module window. You can’t use the FindRecord action to search for text in modules.

To run the FindRecord action in Visual Basic, use the FindRecord method of the DoCmd object.

See Also

FindNext Action, FindRecord Method.


FindRecord Method

Applies To

DoCmd Object.

Description

The FindRecord method carries out the FindRecord action in Visual Basic. For more information on how the action and its arguments work, see the action topic.

Syntax

DoCmd.FindRecord findwhat [, match] [, matchcase] [, search] [, åsearchasformatted] [, onlycurrentfield] [, findfirst]

The FindRecord method uses the following arguments.

Argument | Description
findwhat | An expression that evaluates to text, a number, or a date. The expression contains the data to search for.
match | One of the following intrinsic constants: acAnywhere acEntire acStart If you leave this argument blank, the default (acEntire) is assumed.
matchcase | Use True (-1) for a case-sensitive search and False (0) for a search that is not case-sensitive. If you leave this argument blank, the default (False) is assumed.
search | One of the following intrinsic constants: acUp acDown acSearchAll If you leave this argument blank, the default (acSearchAll) is assumed.
searchasformatted | Use True to search for data as it is formatted and False to search for data as it is stored in the database. If you leave this argument blank, the default (False) is assumed.
onlycurrentfield | One of the following intrinsic constants: acCurrent acAll If you leave this argument blank, the default (acCurrent) is assumed.
findfirst | Use True to start the search at the first record. Use False to start the search at the record following the current record. If you leave this argument blank, the default (True) is assumed.

Remarks

You can leave an optional argument blank in the middle of the syntax, but you must include the argument’s comma. If you leave one or more trailing arguments blank, don’t use a comma following the last argument you specify.

See Also

DoCmd Object, FindRecord Method, FindRecord Action.

Example

This example finds the first occurrence in the records of the name Smith in the current field. It doesn’t find occurrences of smith or Smithson.

DoCmd.FindRecord "Smith",, True,, True

Fix Function

See Int, Fix Functions.


Fix Function

See Int, Fix Functions.


FontBold Property

Applies To

Combo Box Control, Command Button Control, Label Control, List Box Control, Report, Text Box Control, Toggle Button Control.

Description

You can use the FontBold property to specify whether a font appears in a bold style in a control or when you use the Print method on a report.

Setting

The FontBold property uses the following settings.

Setting | Description
True (-1) | Text is bold.
False (0) | (Default) Text isn’t bold.

You can set the FontBold property only using Visual Basic.

Remarks

To use the FontBold property on a report, first create a Print event procedure that prints the desired text.

The font’s appearance on screen and in print may differ, depending on your computer and printer. If you select a font that your system can’t display or that isn’t installed, Windows substitutes a similar font.

See Also

BorderColor Property; FillColor Property; FontItalic, FontUnderline Properties; FontName, FontSize Properties; FontWeight Property; Print Event; Print Method.

Example

You can use the following event procedure to print the current date in a bold font on a report at the coordinates specified by the CurrentX and CurrentY property settings.

Sub ReportHeader0_Print (Cancel As Integer, PrintCount As Integer)
    Me.FontBold = True
    Me.Print Date()          ' Print date in bold.Sub


FontItalic, FontUnderline Properties

Applies To

Combo Box Control, Command Button Control, Label Control, List Box Control, Report, Text Box Control, Toggle Button Control.

Description

You can use the FontItalic and FontUnderline properties to specify these font characteristics in reports and controls.

Setting

The FontItalic property uses the following settings.

Setting | Description | Visual Basic
Yes | Text is italic. | True (-1)
No | (Default) Text is normal. | False (0)

The FontUnderline property uses the following settings.

Setting | Description | Visual Basic
Yes | Text is underlined. | True
No | (Default) Text is normal. | False

For controls, you can set these properties using the control’s property sheet, a macro, or Visual Basic.

You can also set these properties using the Formatting toolbar.

You can set the defaults for these properties using the default control style.

Remarks

For reports, you can use these properties only in an event procedure or in a macro specified by the OnPrint event property setting.

See Also

FontBold Property; FontName, FontSize Properties; FontWeight Property.


FontName, FontSize Properties

Applies To

Combo Box Control, Command Button Control, Label Control, List Box Control, Report, Text Box Control, Toggle Button Control.

Description

You can use the FontName and FontSize properties to specify these font characteristics in reports and controls.

  • Reports — You use these properties to specify the name and point size of the font used for text with the Print method.

Controls — You use these properties to specify the name and point size of the font used for text in a control.

Setting

The FontName property specifies one of the font names displayed on the property sheet, which depend on the fonts installed on your system or in your printer.

The FontSize property uses the following settings.

Setting | Description
8 | (Default for all reports and controls except buttons) Text is 8-point type.
10 | (Default for command buttons) Text is 10-point type.
<Other sizes> | Text is the indicated size.

When modifying controls, set these properties using the property sheet, a macro, or Visual Basic.

You can also set these properties using the Font Name box and the Font Size box on the Formatting toolbar.

For reports, you can set these properties in an event procedure or in a macro specified by the OnPrint event property setting.

You can set the default for these properties using a control’s default control style.

In Visual Basic, you set the FontName property using a string expression that is the name of the desired font and you set the FontSize property using a numeric expression equal to the size of the desired font.

Remarks

If you select a font that your system can’t display or that isn’t installed, Windows substitutes a similar font.

See Also

FontBold Property; FontItalic, FontUnderline Properties; FontWeight Property.


FontUnderline Property

See FontItalic, FontUnderline Properties.


FontWeight Property

Applies To

Combo Box Control, Command Button Control, Label Control, List Box Control, Report, Text Box Control, Toggle Button Control.

Description

You use the FontWeight property to specify the line width that Windows uses to display and print characters in a control.

Setting

The FontWeight property uses the following settings.

Setting | Visual Basic
Thin | 100
Extra Light | 200
Light | 300
Normal | 400
Medium | 500
Semi-bold | 600
Bold | 700
Extra Bold | 800
Heavy | 900

You can set this property using the control’s property sheet, a macro, or Visual Basic. You can also use the Bold button on the Formatting toolbar.

You can set the default for this property using a control’s default control style.

Remarks

Font availability depends on your system and printer. If you select a font that your system can’t display or that isn’t installed, Windows substitutes a similar font.

A font’s appearance on screen and in print may differ, depending on your computer and printer. For example, a FontWeight property setting of Thin may look identical to Normal on screen but appear lighter when printed.

See Also

FontBold Property; FontItalic, FontUnderline Properties; FontName, FontSize Properties.


For Each...Next Statement

Description

Repeats a group of statements for each element in an array or collection.

Syntax

For Each element In group
[statements]
[Exit For]
[statements]
Next [element]

The For Each...Next statement syntax has these parts:

Part | Description
element | Variable used to iterate through the elements of the collection or array. For collections, element can only be a Variant variable, a generic Object variable, or any specific OLE Automation object variable. For arrays, element can only be a Variant variable.
group | Name of an object collection or array (except an array of user-defined types).
statements | One or more statements that are executed on each item in group.

Remarks

The For Each block is entered if there is at least one element in group. Once the loop has been entered, all the statements in the loop are executed for the first element in group. Then, as long as there are more elements in group, the statements in the loop continue to execute for each element. When there are no more elements in group, the loop is exited and execution continues with the statement following the Next statement.

The Exit For can only be used within a For Each...Next or For...Next control structure to provide an alternate way to exit. Any number of Exit For statements may be placed anywhere in the loop. The Exit For is often used with the evaluation of some condition (for example, If...Then), and transfers control to the statement immediately following Next.

You can nest For Each...Next loops by placing one For Each...Next loop within another. However, each loop element must be unique.

Note If you omit element in a Next statement, execution continues as if you had included it. If a Next statement is encountered before its corresponding For statement, an error occurs.

You can’t use the For Each...Next statement with an array of user-defined types because a Variant can’t contain a user-defined type.

See Also

Data Type Summary, Do...Loop Statement, Exit Statement, For...Next Statement, While...Wend Statement.

Example

This example uses the For Each...Next statement to search the Text property of all elements in a collection for the existence of the string “Hello”. In the example, MyObject is a text-related object and is an element of the collection MyCollection. Both are generic names used for illustration purposes only.

Found = False                            ' Initialize variable.Each MyObject In MyCollection        ' Iterate through each element.
    If MyObject.Text = "Hello" Then        ' If Text equals "Hello".
        Found = True                        ' Set Found to True.
        Exit For                            ' Exit loop.
    End If


For...Next Statement

Description

Repeats a group of statements a specified number of times.

Syntax

For counter = start To end [Step step]
[statements]
[Exit For]
[statements]
Next [counter]

The For...Next statement syntax has these parts:

Part | Description
counter | Numeric variable used as a loop counter. The variable can’t be an array element or an element of a user-defined type.
start | Initial value of counter.
end | Final value of counter.
step | Amount counter is changed each time through the loop. If not specified, step defaults to one.
statements | One or more statements between For and Next that are executed the specified number of times.

Remarks

The step argument can be either positive or negative. The value of the step argument determines loop processing as follows:

Value | Loop executes if
Positive or 0 | counter <= end
Negative | counter >= end

Once the loop starts and all statements in the loop have executed, step is added to counter. At this point, either the statements in the loop execute again (based on the same test that caused the loop to execute initially), or the loop is exited and execution continues with the statement following the Next statement.

Tip Changing the value of counter while inside a loop can make it more difficult to read and debug your code.

The Exit For can only be used within a For Each...Next or For...Next control structure to provide an alternate way to exit. Any number of Exit For statements may be placed anywhere in the loop. The Exit For is often used with the evaluation of some condition (for example, If...Then), and transfers control to the statement immediately following Next.

You can nest For...Next loops by placing one For...Next loop within another. Give each loop a unique variable name as its counter. The following construction is correct:

For I = 1 To 10
    For J = 1 To 10
        For K = 1 To 10
            . . .
        Next K
    Next JI

Note If you omit counter in a Next statement, execution continues as if you had included it. If a Next statement is encountered before its corresponding For statement, an error occurs.

See Also

Do...Loop Statement, Exit Statement, For Each...Next Statement, While...Wend Statement.

Example

This example uses the For...Next statement to create a string that contains 10 instances of the numbers 0 through 9, each string separated from the other by a single space. The outer loop uses a loop counter variable that is decremented each time through the loop.

For Words = 10 To 1 Step -1     ' Set up 10 repetitions.
    For Chars = 0 To 9    ' Set up 10 repetitions.
        MyString = MyString & Chars    ' Append number to string.
    Next Chars    ' Increment counter.
    MyString = MyString & " "    ' Append a space.Words


ForceNewPage Property

Applies To

Form Section, Report Section.

Description

You can use the ForceNewPage property to specify whether form (header, detail, footer) or report (header, detail, footer) sections print on a separate page, rather than on the current page. For example, you may have designed the last page of a report as an order form. If the report footer’s ForceNewPage property is set to Before Section, the order form is always printed on a new page.

Note The ForceNewPage property does not apply to page headers or page footers.

Setting

The ForceNewPage property uses the following settings.

Setting | Description | Visual Basic
None | (Default) The current section (the section for which you’re setting the property) is printed on the current page. | 0
Before Section | The current section is printed at the top of a new page. | 1
After Section | The section immediately following the current section is printed at the top of a new page. | 2
Before & After | The current section is printed at the top of a new page, and the next section is printed at the top of a new page. | 3

You can set this property using the section’s property sheet, a macro, or Visual Basic.

Remarks

Here are some examples of the ForceNewPage property setting.

Section | Sample setting | Description
A group header displaying the year | Before Section | The group header is printed at the top of the page, followed by the detail section, group footer, and page footer.
A report detail section | After Section | The group footer is printed at the top of a new page.
A report header containing the report title and company logo. | After Section | The report title and logo are printed on a separate page at the beginning of the report.

See Also

Format Event; KeepTogether Property - Groups; NewRowOrCol Property; Page, Pages Properties.

Example

The following example returns the ForceNewPage property setting for the detail section of the Sales By Date report and assigns it to the intGetVal variable.

Dim intGetVal As Integer= Reports![Sales by Date].Section(0).ForceNewPage


ForeColor Property

Applies To

Combo Box Control, Command Button Control, Label Control, List Box Control, Text Box Control, Toggle Button Control.

Description

You can use the ForeColor property to specify the color for text in a control. You can use this property for controls on forms to make them easy to read or to convey a special meaning. For example, you can change the color of the text in the UnitsInStock control when its value falls below the reorder level.

You can use this property on reports to create special visual effects when you print with a color printer. When used on a report, this property specifies the printing and drawing color for the Print, Line, and Circle methods.

Setting

The ForeColor property contains a numeric expression that represents the value of the text color in the control.

For reports, you can set the ForeColor property only in a macro or an event procedure specified in a section’s OnPrint event property setting.

For controls, set this property using the Formatting toolbar or the Color Builder.

You can also set this property using the controls default control style.

See Also

BackColor Property, BackStyle Property, Circle Method, DrawMode Property, DrawStyle Property, DrawWidth Property, FillStyle Property, Line Method, Print Method, QBColor Function, RGB Function.

Example

The following example uses the RGB function to set the BorderColor, BackColor, and ForeColor properties depending on the value of the txtPastDue text box. You can also use the QBColor function to set these properties. Putting the following code in the Form_Current( ) event sets the control display characteristics as soon as the user opens a form or moves to a new record.

Sub Form_Current()
    Dim curAmntDue As Currency, lngBlack As Long
    Dim lngRed As Long, lngYellow As Long, lngWhite As Long
    If Not IsNull(Me!txtPastDue.Value) Then
        curAmntDue =Me!txtPastDue.Value
    Else
        Exit Sub
    End If
    lngRed = RGB(255, 0, 0)
    lngBlack = RGB(0, 0, 0)
    lngYellow = RGB(255, 255, 0)
    lngWhite = RGB(255, 255, 255)
    If curAmntDue > 100 Then
        Me!txtPastDue.BorderColor = lngRed
        Me!txtPastDue.ForeColor = lngRed
        Me!txtPastDue.BackColor = lngYellow
    Else
        Me!txtPastDue.BorderColor = lngBlack
        Me!txtPastDue.ForeColor = lngBlack
        Me!txtPastDue.BackColor = lngWhite
    End IfSub


Form Object

Description

A Form object refers to a particular Microsoft Access form.

Remarks

A Form object is a member of the Forms collection. Within the Forms collection, individual forms are numbered by an index beginning with zero. You can refer to an individual Form object in the Forms collection either by referring to the form by name, or by referring to its index within the collection. If the form name includes a space, the name must be surrounded by brackets.

Syntax | Example
Forms!formname | Forms!OrderForm
Forms![form name] | Forms![Order Form]
Forms("formname") | Forms("OrderForm")
Forms(index) | Forms(0)

Each Form object has a Controls collection, which contains all controls on the form. You can refer to a control on a form either by implicitly or explicitly referring to the Controls collection. Your code will be faster if you refer to the Controls collection implicitly. The following examples show two of the ways you might refer to a control named NewData on the form called OrderForm.

Forms!OrderForm!NewData        ' Implicit reference.!OrderForm.Controls!NewData        ' Explicit reference.

Many of the properties of a Form object can also be set from a form’s property sheet. For information on how to set individual properties, search the online index for those properties.

See Also

Control Object, Controls Collection, Forms Collection, Me.

Example

See the Backcolor property example.


Form, Report Properties

Applies To

Form, Report.

Description

You can use the Form and Report properties to refer to a form or report, or refer to the form or report associated with a subform control or subreport control.

Setting

These properties refer to a form or report object. They are read-only in all views.

You can use these properties in a macro or in Visual Basic.

Remarks

These properties are typically used to refer to the form or report contained in a subform or subreport control. For example, the following code uses the Form property to access the OrderID control on a subform contained in the subOrderDetails subform control.

Dim intOrderID As Integer= Forms!Orders![subOrderDetails].Form![OrderID]

The next example calls a function from a property sheet using the Form property to refer to the active form that contains the control named CustomerID.

= MyFunction(Form![CustomerID])

When you use the Form property in this manner, you are referring to the active form and the name of the form isn’t necessary.

The next example is the Visual Basic equivalent of the preceding example.

X = MyFunction(Forms![Customers]![CustomerID])

Note When you use the Forms or Reports collection, you must specify the name of the form or report.

See Also

ActiveForm Property, ActiveReport Property, Forms Collection, Me Property, Parent Property, Reports Collection.

Example

The following example uses the Form and Report properties to refer to a control on a subform and a subreport.

Dim curTotalAmount As CurrencycurTotalSales As Currency= Forms![Orders]![OrderDetails].Form![TotalAmount]= Reports![Sales]![Employees].Report![TotalSales]


Format Event

Applies To

Report Section.

Description

The Format event occurs when Microsoft Access determines which data belongs in a report section, but before Microsoft Access formats the section for previewing or printing.

Remarks

A Format event occurs for each section in a report. This allows you to create complex running calculations using data from each section, including sections that aren’t printed.

For report detail sections, the Format event occurs for each record in the section just before Microsoft Access formats the data in the record. A Format macro or event procedure has access to the data in the current record.

For report group headers, the Format event occurs for each new group, and a Format macro or event procedure has access to data in the group header and data in the first record in the detail section. For report group footers, the Format event occurs for each new group, and a Format macro or event procedure has access to the data in the group footer and the data in the last record in the detail section.

By running a macro or running an event procedure when the Format event occurs, you can use data in the current record to make changes to the report that affect page layout. For example, you can display or hide a congratulatory message next to a salesperson’s monthly sales total in a sales report, depending on the sales total. After the control is displayed or hidden, Microsoft Access formats the section using the values of format properties, such as CanGrow, CanShrink, HideDuplicates, KeepTogether, and Visible.

For changes that don’t affect page layout or for event procedures or macros that should run only after the data on a page has been formatted, such as a macro that prints page totals, use the Print event for the report section.

There are times when Microsoft Access must return to previous sections on a report to perform multiple formatting passes. When this happens, the Retreat event occurs as the report returns to each previous section, and the Format event occurs more than once for each section. You can run a macro or event procedure when the Retreat event occurs to undo any changes that you made when the Format event occurred for the section. This is useful when your Format macro or event procedure carries out actions, such as calculating page totals or controlling the size of a section, that you want to perform only once for each section.

See Also

FormatCount Property, NoData Event, Page Event, Print Event, PrintCount Property, Retreat Event.


Format Event -- Event Procedures

Description

To create an event procedure that is executed when the Format event occurs, set the OnFormat property to [Event Procedure], and click the Build button.

Syntax

Private Sub sectionname_Format (Cancel As Integer, FormatCount As Integer)

The Format event procedure uses the following arguments.

Argument | Description
sectionname | A string that is the name of the section affected by the Format event procedure.
Cancel | The setting determines if the formatting of the section occurs. Setting the Cancel argument to True (-1) cancels formatting of the section.
FormatCount | An integer value that specifies whether the Format event has occurred more than once for a section. For example, if a section doesn’t fit on one page and part of it moves to the next page of the report, the FormatCount argument is set to 2.

Remarks

If you cancel formatting, Microsoft Access doesn’t format the section for printing and prints the next section instead. You can use this event procedure to skip a section in a report without leaving a blank space on the page when the report is printed.

See Also

Format Event — Macros.

Example

This example displays or hides a congratulatory message next to a calculated control that shows sales totals by salesperson. In report sections where the sales total is greater than the sales goal, a label named Message displays the message “Congratulations! You have met your sales goal” before the section is printed; in sections where the sales total is less than the sales goal, the label is hidden.

To try the following example, add the following code to a report that contains a label called Message and a text box called GrandTotal.

Private Sub SalesDetail_Format (Cancel As Integer, _
        FormatCount As Integer)
    Const conSalesGoal = 1000
    If Me!GrandTotal > conSalesGoal Then
        Me!Message.Visible = True
    Else
        Me!Message.Visible = False
    End IfSub


Format Event -- Macros

Description

To run a macro when the Format event occurs, set the OnFormat property to the name of the macro.

Remarks

You can use the FormatCount property to check whether the Format event has occurred more than once for a section. For example, if a section doesn’t fit on one page and part of it moves to the next page of the report, the Format event occurs once for each page, and the FormatCount property is set to 2. You can check the FormatCount property setting to determine how many times a Format macro is run per section.

You can use the CancelEvent action in a Format macro to cancel formatting of a section. Microsoft Access doesn’t format the section for printing and prints the next section instead. You can use CancelEvent to skip a section in a report without leaving a blank space on the page when the report is printed.

See Also

Format Event — Event Procedures.


Format Function

Description

Formats an expression according to instructions contained in a format expression.

Syntax

Format(expression[, format[, firstdayofweek[, firstweekofyear]]])

The Format function syntax has these parts:

Part | Description
expression | Any valid expression.
format | A valid named or user-defined format expression.
firstdayofweek | A constant that specifies the first day of the week, as described in Settings.
firstweekofyear | A constant that specifies the first week of the year, as described in Settings.

Settings

The firstdayofweek argument has these settings:

Constant

Value

Description

vbUseSystem | 0 | Use NLS API setting.
vbSunday | 1 | Sunday (default)
vbMonday | 2 | Monday
vbTuesday | 3 | Tuesday
vbWednesday | 4 | Wednesday
vbThursday | 5 | Thursday
vbFriday | 6 | Friday
vbSaturday | 7 | Saturday

The firstweekofyear argument has these settings:

Constant | Value | Description
vbUseSystem | 0 | Use NLS API setting.
vbFirstJan1 | 1 | Start with week in which January 1 occurs (default).
vbFirstFourDays | 2 | Start with the first week that has at least four days in the year.
vbFirstFullWeek | 3 | Start with the first full week of the year.

Remarks

To Format | Do This
Numbers | Use predefined named numeric formats or create user-defined numeric formats.
Dates and times | Use predefined named date/time formats or create user-defined date/time formats.
Date and time serial numbers | Use date and time formats or numeric formats.
Strings | Create your own user-defined string formats.

If you try to format a number without specifying format, Format provides the same functionality as the Str function. However, positive numbers formatted as strings using Format lack the leading space reserved for displaying the sign of the value; whereas, those converted using Str retain the leading space.

See Also

Format Function — Formats for Different Numeric Values, Format Function — Formats for Different String Values, Format Function — Named Date/Time Formats, Format Function — Named Numeric Formats, Str Function, Format Function — User-Defined Date/Time Formats, Format Function — User-Defined Numeric Formats, Format Function — User-Defined String Formats.

Example

This example shows various uses of the Format function to format values using both named and user-defined formats. For the date separator (/), time separator (:), and AM/ PM literal, the actual formatted output displayed by your system depends on the locale settings on which the code is running. When times and dates are displayed in the development environment, the short time and short date formats of the code locale are used. When displayed by running code, the short time and short date formats of the system locale are used, which may differ from the code locale. For this example, English/United States is assumed.

MyTime and MyDate are displayed in the development environment using current system short time and short date settings.

MyTime = #17:04:23#= #January 27, 1993#

' Returns current system time in the system-defined long time format.= Format(Time, "Long Time")

' Returns current system date in the system-defined long date format.= Format(Date, "Long Date")
= Format(MyTime, "h:m:s")    ' Returns "17:4:23".= Format(MyTime, "hh:mm:ss AMPM")    ' Returns "05:04:23 PM".= Format(MyDate, "dddd, mmm d yyyy")    ' Returns "Wednesday,
        ' Jan 27 1993".
' If format is not supplied, a string is returned.= Format(23)    ' Returns "23".

' User-defined formats.= Format(5459.4, "##,##0.00")    ' Returns "5,459.40".= Format(334.9, "###0.00")    ' Returns "334.90".= Format(5, "0.00%")    ' Returns "500.00%".= Format("HELLO", "<")    ' Returns "hello".


Format Function -- Formats for Different Numeric Values

Description

A user-defined format expression for numbers can have from one to four sections separated by semicolons. (If the format argument contains one of the named numeric formats, only one section is allowed.)

If you use | The result is
One section only | The format expression applies to all values.
Two sections | The first section applies to positive values and zeros, the second to negative values.
Three sections | The first section applies to positive values, the second to negative values, and the third to zeros.
Four sections | The first section applies to positive values, the second to negative values, the third to zeros, and the fourth to Null values.

The following example has two sections: the first defines the format for positive values and zeros; the second section defines the format for negative values.

"$#,##0;($#,##0)"

If you include semicolons with nothing between them, the missing section is printed using the format of the positive value. For example, the following format displays positive and negative values using the format in the first section and displays “Zero” if the value is zero.

"$#,##0;;\Z\e\r\o"

See Also

Format Function, Format Function — Different Formats for Different String Values.


Format Function -- Formats for Different String Values

Description

A format expression for strings can have one section, or two sections separated by a semicolon.

If you use | The result is
One section only | The format applies to all string data.
Two sections | The first section applies to string data, the second to Null values and zero-length strings.

See Also

Format Function, Format Function — Different Formats for Different Numeric Values.


Format Function -- Named Date/Time Formats

Description

The following table identifies the predefined date and time format names:

Format Name | Description
General Date | Display a date and/or time. For real numbers, display a date and time (for example, 4/3/93 05:34 PM); if there is no fractional part, display only a date (for example, 4/3/93); if there is no integer part, display time only (for example, 05:34 PM). Date display is determined by your system settings.
Long Date | Display a date according to your system’s long date format.
Medium Date | Display a date using the medium date format appropriate for the language version of the host application.
Short Date | Display a date using your system’s short date format.
Long Time | Display a time using your system’s long time format: includes hours, minutes, seconds.
Medium Time | Display time in 12-hour format using hours and minutes and the AM/PM designator.
Short Time | Display a time using the 24-hour format (for example, 17:45).

See Also

Format Function, Format Function — Named Numeric Formats.


Format Function -- Named Number Formats

Description

The following table identifies the predefined numeric format names:

Format name | Description
General Number | Display number as is, with no thousand separators.
Currency | Display number with thousand separator, if appropriate; display two digits to the right of the decimal separator. Note that output is based on system locale settings.
Fixed | Display at least one digit to the left and two digits to the right of the decimal separator.
Standard | Display number with thousands separator, at least one digit to the left and two digits to the right of the decimal separator.
Percent | Display number multiplied by 100 with a percent sign (%) appended to the right; always display two digits to the right of the decimal separator.
Scientific | Use standard scientific notation.
Yes/No | Display No if number is 0; otherwise, display Yes.
True/False | Display False if number is 0; otherwise, display True.
On/Off | Display Off if number is 0; otherwise, display On.

See Also

Format Function, Format Function — Named Date/Time Formats.


Format Function -- User-Defined Date/Time Formats

Description

The following table identifies characters you can use to create user-defined date/time formats:

Character | Description
: | Time separator. In some locales, other characters may be used to represent the time separator. The time separator separates hours, minutes, and seconds when time values are formatted. The actual character used as the time separator in formatted output is determined by your system settings.

Character | Description
/ | Date separator. In some locales, other characters may be used to represent the date separator. The date separator separates the day, month, and year when date values are formatted. The actual character used as the date separator in formatted output is determined by your system settings.
c | Display the date as ddddd and display the time as t t t t t, in that order. Display only date information if there is no fractional part to the date serial number; display only time information if there is no integer portion.
d | Display the day as a number without a leading zero (1 – 31).
dd | Display the day as a number with a leading zero (01 – 31).
ddd | Display the day as an abbreviation (Sun – Sat).
dddd | Display the day as a full name (Sunday – Saturday).
ddddd | Display the date as a complete date (including day, month, and year), formatted according to your system’s short date format setting. For Microsoft Windows, the default short date format is m/d/yy.
dddddd | Display a date serial number as a complete date (including day, month, and year) formatted according to the long date setting recognized by your system. For Microsoft Windows, the default long date format is mmmm dd, yyyy.
w | Display the day of the week as a number (1 for Sunday through 7 for Saturday).
ww | Display the week of the year as a number (1 – 53).
m | Display the month as a number without a leading zero (1 – 12). If m immediately follows h or hh, the minute rather than the month is displayed.
mm | Display the month as a number with a leading zero (01 – 12). If m immediately follows h or hh, the minute rather than the month is displayed.
mmm | Display the month as an abbreviation (Jan – Dec).
mmmm | Display the month as a full month name (January – December).
q | Display the quarter of the year as a number (1 – 4).
y | Display the day of the year as a number (1 – 366).
yy | Display the year as a 2-digit number (00 – 99).
yyyy | Display the year as a 4-digit number (100 – 9999).
h | Display the hour as a number without leading zeros (0 – 23).
hh | Display the hour as a number with leading zeros (00 – 23).

Character | Description
n | Display the minute as a number without leading zeros (0 – 59).
nn | Display the minute as a number with leading zeros (00 – 59).
s | Display the second as a number without leading zeros (0 – 59).
ss | Display the second as a number with leading zeros (00 – 59).
t t t t t | Display a time as a complete time (including hour, minute, and second), formatted using the time separator defined by the time format recognized by your system. A leading zero is displayed if the leading zero option is selected and the time is before 10:00 A.M. or P.M. The Microsoft Windows default time format is h:mm:ss.
AM/PM | Use the 12-hour clock and display an uppercase AM with any hour before noon; display an uppercase PM with any hour between noon and 11:59 P.M.
am/pm | Use the 12-hour clock and display a lowercase AM with any hour before noon; display a lowercase PM with any hour between noon and 11:59 P.M.
A/P | Use the 12-hour clock and display an uppercase A with any hour before noon; display an uppercase P with any hour between noon and 11:59 P.M.
a/p | Use the 12-hour clock and display a lowercase A with any hour before noon; display a lowercase P with any hour between noon and 11:59 P.M.
AMPM | Use the 12-hour clock and display the AM string literal as defined by your system with any hour before noon; display the PM string literal as defined by your system with any hour between noon and 11:59 P.M. AMPM can be either uppercase or lowercase, but the case of the string displayed matches the string as defined by your system settings. For Microsoft Windows, the default format is AM/PM.

See Also

Format Function, Format Function — User-Defined Numeric Formats, Format Function — User-Defined String Formats.

Example

The following are examples of user-defined date and time formats for December 7, 1958:

Format | Display
m/d/yy | 12/7/58
d-mmm | 7-Dec
d-mmmm-yy | 7-December-58
d mmmm | 7 December
mmmm yy | December 58
hh:mm AM/PM | 08:50 PM
h:mm:ss a/p | 8:50:35 p
h:mm | 20:50
h:mm:ss | 20:50:35
m/d/yy h:mm | 12/7/58 20:50


Format Function -- User-Defined Numeric Formats

Description

The following table identifies characters you can use to create user-defined number formats:

Character | Description
None | No formatting
 | Display the number with no formatting.
0 | Digit placeholder
 | Display a digit or a zero. If the expression has a digit in the position where the 0 appears in the format string, display it; otherwise, display a zero in that position.
 | If the number has fewer digits than there are zeros (on either side of the decimal) in the format expression, display leading or trailing zeros. If the number has more digits to the right of the decimal separator than there are zeros to the right of the decimal separator in the format expression, round the number to as many decimal places as there are zeros. If the number has more digits to the left of the decimal separator than there are zeros to the left of the decimal separator in the format expression, display the extra digits without modification.
# | Digit placeholder
 | Display a digit or nothing. If the expression has a digit in the position where the # appears in the format string, display it; otherwise, display nothing in that position.

Character

Description

This symbol works like the 0 digit placeholder, except that leading and trailing zeros aren’t displayed if the number has the same or fewer digits than there are # characters on either side of the decimal separator in the format expression.

.

Decimal placeholder

In some locales, a comma is used as the decimal separator. The decimal placeholder determines how many digits are displayed to the left and right of the decimal separator. If the format expression contains only number signs to the left of this symbol, numbers smaller than 1 begin with a decimal separator. If you always want a leading zero displayed with fractional numbers, use 0 as the first digit placeholder to the left of the decimal separator instead. The actual character used as a decimal placeholder in the formatted output depends on the Number Format recognized by your system.

%

Percentage placeholder

The expression is multiplied by 100. The percent character (%) is inserted in the position where it appears in the format string.

,

Thousand separator

In some locales, a period is used as a thousand separator. The thousand separator separates thousands from hundreds within a number that has four or more places to the left of the decimal separator. Standard use of the thousand separator is specified if the format contains a thousand separator surrounded by digit placeholders (0 or #). Two adjacent thousand separators or a thousand separator immediately to the left of the decimal separator (whether or not a decimal is specified) means “scale the number by dividing it by 1000, rounding as needed.” You can scale large numbers using this technique. For example, you can use the format string “##0,,” to represent 100 million as 100. Numbers smaller than 1 million are displayed as 0. Two adjacent thousand separators in any position other than immediately to the left of the decimal separator are treated simply as specifying the use of a thousand separator. The actual character used as the thousand separator in the formatted output depends on the Number Format recognized by your system.

:

Time separator

In some locales, other characters may be used to represent the time separator. The time separator separates hours, minutes, and seconds when time values are formatted. The actual character used as the time separator in formatted output is determined by your system settings.

/

Date separator

In some locales, other characters may be used to represent the date separator. The date separator separates the day, month, and year when date values are formatted. The actual character used as the date separator in formatted output is determined by your system settings.

Character | Description
E- E+ e- e+ | Scientific format
 | If the format expression contains at least one digit placeholder (0 or #) to the right of E-, E+, e-, or e+, the number is displayed in scientific format and E or e is inserted between the number and its exponent. The number of digit placeholders to the right determines the number of digits in the exponent. Use E- or e- to place a minus sign next to negative exponents. Use E+ or e+ to place a minus sign next to negative exponents and a plus sign next to positive exponents.
- + $ ( ) space | Display a literal character
 | To display a character other than one of those listed, precede it with a backslash (\) or enclose it in double quotation marks (" ").
\ | Display the next character in the format string
 | Many characters in the format expression have a special meaning and can’t be displayed as literal characters unless they are preceded by a backslash. The backslash itself isn’t displayed. Using a backslash is the same as enclosing the next character in double quotation marks. To display a backslash, use two backslashes (\\).
 | Examples of characters that can’t be displayed as literal characters are the date- and time-formatting characters (a, c, d, h, m, n, p, q, s, t, w, y, and /:), the numeric-formatting characters (#, 0, %, E, e, comma, and period), and the string-formatting characters (@, &, <, >, and !).
“ABC” | Display the string inside the double quotation marks
 | To include a string in format from within code, you must use Chr(34) to enclose the text (34 is the character code for a double quotation mark).

See Also

Format Function — Different Formats for Different Numeric Values, Format Function, Format Function — User-Defined Date/Time Formats, Format Function — User-Defined String Formats.

Example

Some sample format expressions for numbers are shown below. (These examples all assume that your system’s locale setting is English-U.S.) The first column contains the format strings. The other columns contain the output that results if the formatted data has the value given in the column headings.

Format (format) | Positive 5 | Negative 5 | Decimal .5 | Null
Zero-length string | 5 | -5 | 0.5 |
0 | 5 | -5 | 1 |
0.00 | 5.00 | -5.00 | 0.50 |
#,##0 | 5 | -5 | 1 |
#,##0.00;;;Nil | 5.00 | -5.00 | 0.50 | Nil
$#,##0;($#,##0) | $5 | ($5) | $1 |
$#,##0.00;($#,##0.00) | $5.00 | ($5.00) | $0.50 |
0% | 500% | -500% | 50% |
0.00% | 500.00% | -500.00% | 50.00% |
0.00E+00 | 5.00E+00 | -5.00E+00 | 5.00E-01 |
0.00E-00 | 5.00E00 | -5.00E00 | 5.00E-01 |


Format Function -- User-Defined String Formats

Description

You can use any of the following characters to create a format expression for strings:

Character | Description
@ | Character placeholder
 | Display a character or a space. If the string has a character in the position where the @ appears in the format string, display it; otherwise, display a space in that position. Placeholders are filled from right to left unless there is an ! character in the format string. See below.
& | Character placeholder
 | Display a character or nothing. If the string has a character in the position where the & appears, display it; otherwise, display nothing. Placeholders are filled from right to left unless there is an ! character in the format string. See below.
< | Force lowercase
 | Display all characters in lowercase format.

Character | Description
> | Force uppercase
 | Display all characters in uppercase format.
! | Force left to right fill of placeholders
 | The default is to fill from right to left.

See Also

Format Function — Different Formats for Different String Values, Format Function — User-Defined Date/Time Formats, Format Function — User-Defined Numeric Formats.


Format Property

Applies To

Combo Box Control, Query Control, Table Fields, Text Box Control

Description

You can use the Format property to customize the way numbers, dates, times, and text are displayed and printed. For example, if you’ve created a Price text box control, you can set its Format property to Currency. If you enter 4321.678 in the control, the number would be displayed as $4,321.68.

Setting

The Format property uses different settings for different data types. For information about settings for a specific data type, see one of the following topics.

  • Format Property—Number and Currency Data Types
  • Format Property—Date/Time Data Types
  • Format Property—Yes/No Data Types
  • Format Property—Text and Memo Data Types

For a control, you can set this property in the control’s property sheet. For a field, you can set this property in table Design view (under Field Properties) or in Design view of the Query window (in the Field Properties property sheet). You can also use a macro or Visual Basic.

You can use one of the predefined formats or you can create a custom format using formatting symbols.

Note In Visual Basic, enter a string expression that corresponds to one of the predefined formats or enter a custom format.

Remarks

The Format property affects only how data is displayed. It does not affect how data is stored.

Microsoft Access provides predefined formats for Number, Date/Time, Yes/No, and Text and Memo data types. The predefined formats depend on the country specified in the Regional Settings section of the Windows Control Panel. Microsoft Access displays formats appropriate for the country selected. For example, with the United States indicated in the Regional Settings tab, 1234.56 in the Currency format appears as $1,234.56; but when the United Kingdom is indicated in the Regional Settings tab, the number appears as £1,234.56.

If you set a field’s Format property in table Design view, Microsoft Access uses that format to display data in datasheets. It also applies the field’s Format property to new controls on forms and reports.

You can use the following symbols in custom formats for any data type.

Symbol | Meaning
(space) | Display spaces as literal characters.
“ABC” | Display anything inside quotation marks as literal characters.
! | Force left alignment instead of right alignment.
* | Fill available space with the next character.
\ | Display the next character as a literal character. You can place quotation marks around literal characters.
[color] | Display in the color named between the brackets. Available colors: Black, Blue, Green, Cyan, Red, Magenta, Yellow, White.

You can’t mix custom formatting symbols for Number data types with Date/Time or with Text formatting symbols.

When you have defined an input mask and set the Format property for the same data, the Format property takes precedence when the data is displayed and the input mask is ignored. For example, if you create a Password input mask in table Design view and also enter the Format property, either in the table or in a control on a form, the Password input mask is ignored and the data is displayed according to the Format property.

See Also

DecimalPlaces Property, FieldSize Property, Format Function, InputMask Property.

Example

The following three examples set the Format property using a predefined format.

Me![Date].Format = "Medium Date"![Time].Format = "Long Time"![Registered].Format = "Yes/No"

The next example sets the Format property using a custom format. This format displays a date as: Jan 1995.

Forms![Employees]![HireDate].Format = "mmm yyyy"

This example demonstrates a Visual Basic function that formats numeric data with the Currency format and formats text data entirely in capital letters. The function is called from the OnLostFocus event of an unbound control named TaxRefund.

Function FormatValue () As Integer
    Dim varEnteredValue As Variant
    varEnteredValue = Forms!Survey!TaxRefund.Value
    If IsNumeric(varEnteredValue) = True Then
        Forms!Survey!TaxRefund.Format = "Currency"
    Else
        Forms!Survey!TaxRefund.Format = ">"
    End IfFunction


Format Property -- Date/Time Data Types

Description

You can set the Format property to predefined date and time formats or custom formats for date/time data types.

Setting

Predefined Formats

The following table shows the predefined Format property settings for Date/Time data types.

Setting | Description
General Date | (Default) If the value is a date only, no time is displayed; if the value is a time only, no date is displayed. This setting is a combination of the Short Date and the Long Time settings.
 | Examples: 4/3/93, 05:34:00 PM, and 4/3/93 05:34:00 PM
Long Date | Same as the Long Date setting in the Regional Settings section of the Windows Control Panel.
 | Example: Saturday, April 3, 1993
Medium Date | Example: 03-Apr-93
Short Date | Same as the Short Date setting in the Regional Settings section of the Windows Control Panel.
 | Example: 4/3/93
Long Time | Same as the Time setting in the Regional Settings section of the Windows Control Panel.
 | Example: 5:34:23 PM
Medium Time | Example: 05:34 PM
Short Time | Example: 17:34

Custom Formats

You can create custom date and time formats using the following symbols.

Symbol | Description
: (colon) | Time separator. Separators are set in the Regional Settings section of the Windows Control Panel.
/ | Date separator. Separators are set in the Regional Settings section of the Windows Control Panel.
c | Same as the General Date predefined format.
d | Day of the month in one or two numeric digits, as needed (1 to 31).
dd | Day of the month in two numeric digits (01 to 31).
ddd | First three letters of the weekday (Sun to Sat).
dddd | Full name of the weekday (Sunday to Saturday).
ddddd | Same as the Short Date predefined format.
dddddd | Same as the Long Date predefined format.
w | Day of the week (1 to 7).
ww | Week of the year (1 to 53).
m | Month of the year in one or two numeric digits, as needed (1 to 12).
mm | Month of the year in two numeric digits (01 to 12).
mmm | First three letters of the month (Jan to Dec).
mmmm | Full name of the month (January to December).
q | Date displayed as the quarter of the year (1 to 4).
y | Number of the day of the year (1 to 366).
yy | Last two digits of the year (01 to 99).
yyyy | Full year (0100 to 9999).
h | Hour in one or two digits, as needed (0 to 23).
hh | Hour in two digits (00 to 23).
n | Minute in one or two digits, as needed (0 to 59).
nn | Minute in two digits (00 to 59).
s | Second in one or two digits, as needed (0 to 59).
ss | Second in two digits (00 to 59).
ttttt | Same as the Long Time predefined format.
AM/PM | Twelve-hour clock with the uppercase letters AM or PM, as appropriate.

Symbol | Description
am/pm | Twelve-hour clock with the lowercase letters am or pm, as appropriate.
A/P | Twelve-hour clock with the uppercase letter A or P, as appropriate.
a/p | Twelve-hour clock with the lowercase letter a or p, as appropriate.
AMPM | Twelve-hour clock with the appropriate morning/afternoon designator as defined in the Regional Settings section of the Windows Control Panel.

Note If you want to add a comma or other separator to your custom format, enclose the separator in quotation marks like this: mmm d", "yyyy.

Example

The following are examples of custom date/time formats.

Setting | Display
ddd", "mmm d", "yyyy | Mon, Jun 2, 1996
mmmm dd", "yyyy | June 02, 1996
"This is week number "ww | This is week number 22
"Today is "dddd | Today is Tuesday


Format Property -- Number and Currency Data Types

Description

You can set the Format property to predefined number formats or custom number formats for number and currency data types.

Setting

Predefined Formats

The following table shows the predefined Format property settings for numbers.

Setting | Description
General Number | (Default) Display the number as entered.
Currency | Use the thousand separator; display negative numbers enclosed in parentheses; the default DecimalPlaces property setting is 2.
Fixed | Display at least one digit; the default DecimalPlaces property setting is 2.
Standard | Use the thousand separator; the default DecimalPlaces property setting is 2.

Setting | Description
Percent | Multiply the value by 100 and append a percent sign (%); the default DecimalPlaces property setting is 2.
Scientific | Use standard scientific notation.

Custom Formats

You can create custom number formats using the following symbols.

Symbol | Description
. (period) | Decimal separator. Separators are set in the Regional Settings section of the Windows Control Panel.
, (comma) | Thousand separator.
0 | Digit placeholder. Display a digit or 0.
# | Digit placeholder. Display a digit or nothing.
$ | Display the literal character $.
% | Percentage. The value is multiplied by 100 and a percent sign is appended.
E- or e- | Scientific notation with a minus sign (-) next to negative exponents and nothing next to positive exponents. It must be used with other symbols, as in 0.00E-00 or 0.00E00.
E+ or e+ | Scientific notation with a minus sign next to negative exponents and a plus sign (+) next to positive exponents. It must be used with other symbols, as in 0.00E+00.

Custom number formats can have one to four sections with semicolons (;) as the list separator. Each section contains the format specification for a different type of number.

Section | Description
First | The format for positive numbers.
Second | The format for negative numbers.
Third | The format for zero values.
Fourth | The format for Null values.

For example, the standard Currency format has the following pattern.

$#,##0.00;($#,##0.00)[Red]

This number format contains two sections separated by a semicolon and uses one format for positive numbers (determined by the first section) and another for negative numbers (determined by the second section). Since the third and fourth sections are omitted, zero or Null values are not formatted in a special way.

Remarks

You can use the DecimalPlaces property to display a different number of decimal places than the Format property specifies.

Example

The following are examples of the predefined number formats.

Setting | Data | Display
General Number | 3456.789 .789 $213.21 | 3456.789 .789 $213.21
Currency | 3456.789 .789 | $3,456.79 ($3,456.79)
Fixed | 3456.789 .789 .56645 | 3456.79 .79 .57
Standard | 3456.789 | 3,456.79
Percent | 3 .45 | 300% %
Scientific | 3456.789 .789 | 3.46E+03 .46E+03

The following are examples of custom number formats.

Setting | Description
0;(0);; "Null" | Display positive values normally; display negative values in parentheses; display nothing if the value is zero; display the word “Null” if the value is Null.
+0.0;-0.0;0.0 | Display a plus (+) or minus (-) sign with positive or negative numbers; display 0.0 if the value is zero or Null.


Format Property -- Text and Memo Data Types

Description

You can set the Format property to create custom formats for Text and Memo fields using special symbols.

Setting

The Format property uses the following symbols to define text and memo data types.

Symbol | Description
@ | Text character (either a character or a space) is required.
& | Text character is not required.
< | Force all characters to lowercase.
> | Force all characters to uppercase.

Custom formats for Text and Memo fields can have up to three sections. Each section contains the format specification for different data in a field.

Section | Description
First | Format for fields with text.
Second | Format for fields with zero-length strings.
Third | Format for fields with Null values.

If you specify only two sections, the second section refers to fields with zero-length strings and Null values.

For example, if you have a text box control in which you want the word “None” to appear when there is no string in the field, you could enter the custom format @;"None";"Null" as the control’s Format property setting. The @ symbol causes the text from the field to be displayed; the second section causes the word “None” to appear when there is a zero-length string in the field, the third section causes the word “Null” to appear when there is a Null value in the field.

Example

The following are examples of Text and Memo custom formats.

Setting | Data | Display
@@@-@@-@@@@ | 465043799 | 465-04-3799
@@@@@@@@@ | 465-04-3799 | 465-04-3799
> | davolio | DAVOLIO
< | davolio | davolio
@;;"Unknown" | Null value | Unknown
 | Zero-length string | Nothing is displayed
 | Any text | Same text as entered is displayed


Format Property -- Yes/No Data Types

Description

You can set the Format property to Yes/No, True/False, or On/Off predefined formats or a custom format for Yes/No data types.

Setting

Predefined Formats

The Format property provides the Yes/No, True/False, and On/Off predefined formats. Yes, True, and On are equivalent, as are No, False, and Off. If you specify one predefined format and then enter an equivalent value, the predefined format of equivalent value will be displayed. For example, if you enter True or On in a text box control with its Format property set to Yes/No, the value is automatically converted to Yes.

Custom Formats

Yes/No data types use custom formats containing up to three sections.

Section | Description
First | This section has no effect on Yes/No data types. However, a semicolon (;) is required as a placeholder.
Second | The text to display in place of Yes, True, or On values.
Third | The text to display in place of No, False, or Off values.

Example

The following example shows a custom format that displays the word “Always” in blue text for Yes, True, or On, and the word “Never” in red text for No, False, or Off.

;"Always"[Blue];"Never"[Red]


FormatCount Property

Applies To

Report.

Description

You can use the FormatCount property to determine the number of times the OnFormat property has been evaluated for the current section on a report.

Setting

You can use this property only in a macro or an event procedure specified by a section’s OnFormat property setting.

The FormatCount property setting has a Long data type value.

This property isn’t available in Design view and is read-only in other views.

Remarks

Microsoft Access increments the FormatCount property each time the OnFormat property setting is evaluated for the current section. As the next section is formatted, Microsoft Access resets the FormatCount property to 1.

Under some circumstances, Microsoft Access formats a section more than once. For example, you might design a report in which the KeepTogether property for the detail section is set to Yes. When Microsoft Access reaches the bottom of a page, it formats the current detail section once to see if it will fit. If it doesn’t fit, Microsoft Access moves to the next page and formats the detail section again. In this case, the setting for the FormatCount property for the detail section is 2 because it was formatted twice before it was printed.

Use the FormatCount property to ensure that a time-consuming operation that affects formatting gets executed only once for a section. In the following example, the DLookup function is evaluated only when the FormatCount property is set 1.

If FormatCount = 1 Then
    If DLookup("[CustomerName]","[Customers]", "[CustomerID] = _
    Reports![Customers]![CustomerID]") = 7 Then
        [CustomerName].FontWeight = Bold
    Else
        [CustomerName].FontWeight = Normal
    End IfIf

If you include the Else block in this procedure, you don’t need to create an OnRetreat event procedure for the section.

Tip To calculate totals, use the PrintCount property.

See Also

Format Event, PrintCount Property.


Forms Collection

Description

The Forms collection contains all of the currently open forms in a Microsoft Access database.

Remarks

Use the Forms collection in Visual Basic or in an expression to refer to forms that are currently open. For example, you can enumerate the Forms collection to set or return the values of properties of individual forms in the collection.

Tip The For Each...Next statement is useful for enumerating a collection.

You can’t add or delete a Form object from the Forms collection.

You can refer to an individual Form object in the Forms collection either by referring to the form by name, or by referring to its index within the collection.

The Forms collection is indexed beginning with zero. If you refer to a form by its index, the first form is Forms(0), the second form is Forms(1), and so on.

Note To list all forms in the database, whether open or closed, enumerate the Documents collection of the Forms Container object. You can then use the Name property of each individual Document object to return the name of a form.

Properties

Count Property.

See Also

Application Object; For Each...Next Statement; Form Object; Microsoft Office 95 Data Access Reference: Container Object, Document Object, Documents Collection.

Example

The following example enumerates the Forms collection and prints the name of each form in the Forms collection. It then enumerates the Controls collection of each form and prints the name of each control on the form.

Sub AllOpenForms()
    Dim frm As Form, ctl As Control

    ' Enumerate Forms collection.
    For Each frm In Forms
        ' Print name of form.
        Debug.Print frm.Name
        ' Enumerate Controls collection of each form.
        For Each ctl In frm.Controls
            ' Print name of each control.
            Debug.Print ">>>"; ctl.Name
        Next ctl
    Next frmSub

The following example uses the Forms collection in an expression. If you have a form OrderForm with a control ShipCountry, you can use the IIf function to return a value based on the current value of the control. If the value of ShipCountry is Null, the expression returns a zero-length string; otherwise, it returns the field’s contents. Enter the following expression in the ControlSource property of a text box on a form.

= IIf(IsNull(Forms![Orders]![ShipCountry]), "", _    Forms![Orders]![ShipCountry])


FreeFile Function

Description

Returns the next file number available for use by the Open statement.

Syntax

FreeFile[(rangenumber)]

The rangenumber argument specifies the range from which the next free file number is to be returned. Specify a 0 (default) to return a file number in the range 1 to 255, inclusive. Specify a 1 to return a file number in the range 256 to 511.

Remarks

Use FreeFile when you have to supply a file number and you want to make sure the file number is not already in use.

See Also

Open Statement.

Example

This example uses the FreeFile function to return the next available file number. Five files are opened for output within the loop and some sample data is written to each.

For MyIndex = 1 To 5    ' Loop 5 times.
    FileNumber = FreeFile    ' Get unused file
            ' number.
    Open "TEST" & MyIndex For Output As #FileNumber    ' Create filename.
    Write #FileNumber, "This is a sample."    ' Output text.
    Close #FileNumber    ' Close file.MyIndex


FrozenColumns Property

Applies To

Form, Query, Table.

Description

You can use the FrozenColumns property to determine how many columns in a datasheet are frozen. Frozen columns are displayed on the left side of the datasheet and don’t move when you scroll horizontally through the datasheet.

Note The FrozenColumns property applies only to tables, forms, and queries in Datasheet view.

Setting

The FrozenColumns property is set by Microsoft Access when you click Freeze Columns on the Format menu.

In Visual Basic, this property setting is an Integer indicating the number of columns in the datasheet that have been frozen using the Freeze Columns command. The record selector column is always frozen, so the default value is 1. Consequently, if you freeze one column, the FrozenColumns property is set to 2; if you freeze two columns, it’s set to 3; and so on.

This property setting is read-only in all views.

Remarks

When you freeze columns using the Freeze Columns command, Microsoft Access automatically moves the columns to the leftmost edge of the datasheet in the order in which you froze them. For example, if you freeze three columns, these become the first, second, and third columns in the datasheet. Because the record selector column is always frozen, the FrozenColumns property in this case will be set to 4. The three columns you freeze will have their ColumnOrder properties set to 1, 2, and 3 (in the order they are frozen).

If you click Unfreeze All Columns on the Format menu, all frozen columns will be unfrozen, and the FrozenColumns property will be set to 1.

Example

The following example uses the FrozenColumns property to determine how many columns are frozen in a table in Datasheet view. If more than three columns are frozen, the table size is maximized so you can see as many unfrozen columns as possible.

Sub CheckFrozen(tblName As String)
    Dim db As Database
    Dim td As TableDef
    Dim prop As Property
    conPropertyNotFound = 3270        ' Property not found error.
    Set db = CurrentDb        ' Get current database.
    Set td = db.TableDefs(tblName)        ' Get object for table.
    DoCmd.OpenTable tblName, acNormal        ' Open table.
    td.Properties.Refresh
    On Error GoTo Frozen_Err
    If td.Properties("FrozenColumns") > 3 Then     ' Check property.
        DoCmd.Maximize
    End If_Bye:
    Exit Sub_Err:
    If Err = conPropertyNotFound Then    ' Property not in collection.
        Set prop = td.CreateProperty("FrozenColumns", dbInteger, 1)
        td.Properties.Append prop
        Resume Frozen_Bye
    End IfSub


Function Statement

Description

Declares the name, arguments, and code that form the body of a Function procedure.

Syntax

[Public | Private] [Static] Function name [(arglist)] [As type]
[statements]
[name = expression]
[Exit Function]
[statements]
[name = expression]
End Function

The Function statement syntax has these parts:

Part | Description
Public | Indicates that the Function procedure is accessible to all other procedures in all modules. If used in a private module (one that contains an Option Private statement) the procedure is not available outside the project.
Private | Indicates that the Function procedure is accessible only to other procedures in the module where it is declared.
Static | Indicates that the Function procedure’s local variables are preserved between calls. The Static attribute doesn’t affect variables that are declared outside the Function, even if they are used in the procedure.
name | Name of the Function; follows standard variable naming conventions.
arglist | List of variables representing arguments that are passed to the Function procedure when it is called. Multiple variables are separated by commas.
type | Data type of the value returned by the Function procedure; may be Byte, Boolean, Integer, Long, Currency, Single, Double, Date, String (except fixed length), Object, Variant, or any user-defined type. Arrays of any type can’t be returned, but a Variant containing an array can.
statements | Any group of statements to be executed within the body of the Function procedure.
expression | Return value of the Function.

The arglist argument has the following syntax and parts:

[Optional][ByVal | ByRef][ParamArray] varname[( )][As type]

Part | Description
Optional | Indicates that an argument is not required. If used, all subsequent arguments in arglist must also be optional and declared using the Optional keyword. All Optional arguments must be Variant. Optional can’t be used for any argument if ParamArray is used.
ByVal | Indicates that the argument is passed by value.
ByRef | Indicates that the argument is passed by reference.
ParamArray | Used only as the last argument in arglist to indicate that the final argument is an Optional array of Variant elements. The ParamArray keyword allows you to provide an arbitrary number of arguments. It may not be used with ByVal, ByRef, or Optional.
varname | Name of the variable representing the argument; follows standard variable naming conventions.
type | Data type of the argument passed to the procedure; may be Byte, Boolean, Integer, Long, Currency, Single, Double, Date, String (variable length only), Object, Variant, a user-defined type, or an object type.

Remarks

If not explicitly specified using either Public or Private, Function procedures are public by default. If Static is not used, the value of local variables is not preserved between calls.

All executable code must be in procedures. You can’t define a Function procedure inside another Function, Sub, or Property procedure.

The Exit Function keywords cause an immediate exit from a Function procedure. Program execution continues with the statement following the statement that called the Function procedure. Any number of Exit Function statements can appear anywhere in a Function procedure.

Like a Sub procedure, a Function procedure is a separate procedure that can take arguments, perform a series of statements, and change the values of its arguments. However, unlike a Sub procedure, you can use a Function procedure on the right-hand side of an expression in the same way you use any intrinsic function, such as Sqr, Cos, or Chr, when you want to use the value returned by the function.

You call a Function procedure using the function name, followed by the argument list in parentheses, in an expression. See the Call statement for specific information on how to call Function procedures.

Caution Function procedures can be recursive; that is, they can call themselves to perform a given task. However, recursion can lead to stack overflow. The Static keyword is usually not used with recursive Function procedures.

To return a value from a function, assign the value to the function name. Any number of such assignments can appear anywhere within the procedure. If no value is assigned to name, the procedure returns a default value: a numeric function returns 0, a string function returns a zero-length string (""), and a Variant function returns Empty. A function that returns an object reference returns Nothing if no object reference is assigned to name (using Set) within the Function.

The following example shows how to assign a return value to a function named BinarySearch. In this case, False is assigned to the name to indicate that some value was not found.

Function BinarySearch(. . .) As Boolean
. . .
    ' Value not found. Return a value of False.
    If lower > upper Then
        BinarySearch = False
        Exit Function
    End If
. . .Function

Variables used in Function procedures fall into two categories: those that are explicitly declared within the procedure and those that are not. Variables that are explicitly declared in a procedure (using Dim or the equivalent) are always local to the procedure. Variables that are used but not explicitly declared in a procedure are also local unless they are explicitly declared at some higher level outside the procedure.

Caution A procedure can use a variable that is not explicitly declared in the procedure, but a naming conflict can occur if anything you have defined at the module level has the same name. If your procedure refers to an undeclared variable that has the same name as another procedure, constant or variable, it is assumed that your procedure is referring to that module-level name. Explicitly declare variables to avoid this kind of conflict. You can use an Option Explicit statement to force explicit declaration of variables.

Caution Visual Basic may rearrange arithmetic expressions to increase internal efficiency. Avoid using a Function procedure in an arithmetic expression when the function changes the value of variables in the same expression.

See Also

Call Statement, Dim Statement, Nothing, Option Explicit Statement, Property Get Statement, Property Let Statement, Property Set Statement, Set Statement, Sub Statement.

Specifics (Microsoft Access)

In Microsoft Access, a public Function procedure in a standard module is available to all other procedures in the database and in all other Microsoft Access databases. However, it is not available to any other applications.

If a Function procedure is declared as public within a private module, then the procedure is available to all other procedures in that database, but is not available to other Microsoft Access databases. Form modules and report modules are always private, as are standard modules that contain an Option Private Module statement.

If you declare a Function procedure as private in any module, that procedure is available only to other procedures in the same module.

Note If a Function procedure is available to other Microsoft Access databases, it will be visible from those databases in the Object Browser.

Example

This example uses the Function statement to declare the name, arguments, and code that form the body of a Function procedure. A named argument is used in last example.

' The following user-defined function returns the square root of the
' argument passed to it.CalculateSquareRoot(NumberArg As Double) As Double
    If NumberArg < 0 Then    ' Evaluate argument.
        Exit Function    ' Exit to calling procedure.
    Else
        CalculateSquareRoot = Sqr(NumberArg)    ' Return square root.
    End IfFunction

Using the ParamArray keyword enables a function to accept a variable number of arguments. In the following definition, FirstArg is passed by value.

Function CalcSum(ByVal FirstArg As Integer, ParamArray OtherArgs())
' If the function is invoked as follows:= CalcSum(4, 3 ,2 ,1)
' Local variables are assigned the following values: FirstArg = 4,
' OtherArgs(1) = 3, OtherArgs(2) = 2, and so on, assuming default
' lowerbound for arrays = 1.
' If a function's arguments are defined as follows:MyFunc(MyStr As String, Optional MyArg1, Optional MyArg2)
' The function can be invoked as follows:= MyFunc("Hello", 2, "World")    ' All 3 arguments supplied.= MyFunc("Test", , 5)    ' Second argument omitted.= MyFunc(MyArg1 := 7)    ' Second argument only,
                ' using named-argument.


FV Function

Description

Returns the future value of an annuity based on periodic, constant payments and a constant interest rate.

Syntax

FV(rate, nper, pmt[, pv[, type]])

The FV function has these named arguments:

Part | Description
rate | Interest rate per period. For example, if you get a car loan at an annual percentage rate (APR) of 10 percent and make monthly payments, the rate per period is 0.1/12, or 0.0083.
nper | Total number of payment periods in the annuity. For example, if you make monthly payments on a four-year car loan, your loan has a total of 4 * 12 (or 48) payment periods.
pmt | Payment to be made each period. Payments usually contain principal and interest that doesn’t change over the life of the annuity.
pv | Present value (or lump sum) that a series of payments to be paid in the future is worth now. For example, when you borrow money to buy a car, the loan amount is the present value to the lender of the monthly car payments you will make. If omitted, 0 is assumed.
type | Number indicating when payments are due. Use 0 if payments are due at the end of the payment period, or use 1 if payments are due at the beginning of the period. If omitted, 0 is assumed.

Remarks

An annuity is a series of constant cash payments made over a period of time. An annuity can be a loan (such as a home mortgage) or an investment (such as a monthly savings plan).

The arguments rate and nper must be calculated using payment periods expressed in the same units. For example, if rate is calculated using months, nper must also be calculated using months.

For all arguments, cash paid out (such as deposits to savings) is represented by negative numbers; cash received (such as dividend checks) is represented by positive numbers.

Example

This example uses the FV function to return the future value of an investment given the percentage rate that accrues per period (APR / 12), the total number of payments (TotPmts), the payment (Payment), the current value of the investment (PVal), and a number that indicates whether the payment is made at the beginning or end of the payment period (PayType). Note that because Payment represents cash paid out, it’s a negative number.

Const ENDPERIOD = 0, BEGINPERIOD = 1        ' When payments are made.= "###,###,##0.00"                    ' Define money format.= InputBox("How much do you plan to save each month?")= InputBox("Enter the expected interest annual percentage rate.")APR > 1 Then APR = APR / 100            ' Ensure proper form.= InputBox("For how many months do you expect to save?")= MsgBox("Do you make payments at the end of month?", vbYesNo)PayType = vbNo Then PayType = BEGINPERIOD Else PayType = ENDPERIOD= InputBox("How much is in this savings account now?")= FV(APR / 12, TotPmts, -Payment, -PVal, PayType)"Your savings will be worth " & Format(FVal, Fmt) & "."


Get Statement

Description

Reads from an open disk file into a variable.

Syntax

Get [#]filenumber, [recnumber], varname

The Get statement syntax has these parts:

Part | Description
filenumber | Any valid file number.
recnumber | Record number (Random mode files) or byte number (Binary mode files) at which reading begins.
varname | Valid variable name into which data is read.

Remarks

The first record or byte in a file is at position 1, the second record or byte is at position 2, and so on. If you omit recnumber, the next record or byte (the one after the last Get or Put statement or the one pointed to by the last Seek function) is read. Delimiting commas must be included, for example:

Get #4,,FileBuffer

For files opened in Random mode, the following rules apply:

  • If the length of the data being read is less than the length specified in the Len clause of the Open statement, Get still reads subsequent records on record-length boundaries. The space between the end of one record and the beginning of the next record is padded with the existing contents of the file buffer. Because the amount of padding data can’t be determined with any certainty, it is generally a good idea to have the record length match the length of the data being read.
  • If the variable being read into is a variable-length string, Get reads a 2-byte descriptor containing the string length and then the data that goes into the variable. Therefore, the record length specified by the Len clause in the Open statement must be at least 2 bytes greater than the actual length of the string.
  • If the variable being read into is a Variant of numeric type, Get reads 2 bytes identifying the VarType of the Variant and then the data that goes into the variable. For example, when reading a Variant of VarType 3, Get reads 6 bytes: 2 bytes identifying the Variant as VarType 3 (Long) and 4 bytes containing the Long data. The record length specified by the Len clause in the Open statement must be at least 2 bytes greater than the actual number of bytes required to store the variable.

Note You can use the Get statement to read a Variant array from disk but you cannot use Get to read a scalar Variant containing an array. You also cannot use Get to read objects from disk.

  • If the variable being read into is a String Variant (VarType 8), Get reads 2 bytes identifying the VarType, 2 bytes indicating the length of the string, and then the string data. The record length specified by the Len clause in the Open statement must be at least 4 bytes greater than the actual length of the string.
  • If the variable being read into is a dynamic array, Get reads a descriptor whose length equals 2 plus 8 times the number of dimensions, that is, 2 + 8 * NumberOfDimensions. The record length specified by the Len clause in the Open statement must be greater than or equal to the sum of all the bytes required to read the array data and the array descriptor. For example, the following array declaration requires 118 bytes when the array is written to disk.

Dim MyArray(1 To 5,1 To 10) As Integer

The 118 bytes are distributed as follows: 18 bytes for the descriptor (2 + 8 * 2), and 100 bytes for the data (5 * 10 * 2).

  • If the variable being read into is a fixed-size array, Get reads only the data. No descriptor is read.
  • If the variable being read into is any other type of variable (not a variable-length string or a Variant), Get reads only the variable data. The record length specified by the Len clause in the Open statement must be greater than or equal to the length of the data being read.
  • Get reads elements of user-defined types as if each were being read individually, except that there is no padding between elements. On disk, a dynamic array in a user-defined type (written with Put) is prefixed by a descriptor whose length equals 2 plus 8 times the number of dimensions, that is, 2 + 8 * NumberOfDimensions. The record length specified by the Len clause in the Open statement must be greater than or equal to the sum of all the bytes required to read the individual elements, including any arrays and their descriptors.

For files opened in Binary mode, all of the Random rules apply, except:

  • In Binary mode, the Len clause in the Open statement has no effect. Get reads all variables from disk contiguously; that is, with no padding between records.
  • For any array other than an array in a user-defined type, Get reads only the data. No descriptor is read.
  • Get reads variable-length strings that aren’t elements of user-defined types without expecting the 2-byte length descriptor. The number of bytes read equals the number of characters already in the string. For example, the following statements read 10 bytes from file number 1:

VarString = String(10," ")#1,,VarString

See Also

Open Statement, Put Statement, Seek Function, Type Statement, VarType Function.

Example

This example uses the Get statement to read data from a file into a variable. This example assumes that TESTFILE is a file containing five records of the user-defined type Record.

Type Record    ' Define user-defined type.
    ID As Integer
    Name As String * 20TypeMyRecord As Record    ' Declare variable.
' Open sample file for random access."TESTFILE" For Random As #1 Len = Len(MyRecord)
' Read the sample file using the Get statement.= 3    ' Define record number.#1, Position, MyRecord    ' Read third record.#1    ' Close file.


GetAllSettingsFunction

Description

Returns a list of key settings and their respective values from an application’s Windows registry entry.

Syntax

GetAllSettings(appname, section)

The GetAllSettings function syntax has these named arguments:

Part

Description

appname | String expression containing the name of the application or project whose key settings are requested.
section | String expression containing the name of the section whose key settings are requested. GetAllSettings returns a Variant whose contents is a two-dimensional array of strings containing all the key settings in the specified section and their corresponding values.

Remarks

GetAllSettings returns an uninitialized Variant if either appname or section do not exist.

See Also

DeleteSetting Statement, GetSetting Function, SaveSetting Statement.

Example

This example first uses the SaveSetting statement to make entries in the Windows registry (or .INI file on 16-bit Windows platforms) for the application specified as appname, then uses the GetAllSettings function to display the settings. Note that application names and section names cannot be retrieved with GetAllSettings. Finally, the DeleteSetting statement removes the application’s entries.

' Variant to hold 2-dimensional array returned by GetAllSettings.MySettings As Variant
' Place some settings in the registry.(appname := "MyApp", section := "Startup", _
    key := "Top", setting := 75)("MyApp","Startup", "Left", 50)
' Retrieve the settings.= GetAllSettings(appname := "MyApp", section := "Startup")
    For Settings = LBound(MySettings, 1) To UBound(MySettings, 1)
        Debug.Print MySettings(Settings, 0), MySettings(Settings, 1)
    Next Settings("MyApp", "Startup")


GetAttr Function

Description

Returns a number representing the attributes of a file, directory or folder.

Syntax

GetAttr(pathname)

The pathname argument is a string expression that specifies a filename. The pathname may include the directory or folder, and the drive.

Return Values

The value returned by GetAttr is the sum of the following attribute values:

Value

Constant

Description

0 | vbNormal | Normal.
1 | vbReadOnly | Read-only.
2 | vbHidden | Hidden.
4 | vbSystem | System file .
16 | vbDirectory | Directory or folder.
32 | vbArchive | File has changed since last backup .

Note These constants are specified by Visual Basic for applications. As a result, the names can be used anywhere in your code in place of the actual values.

Remarks

To determine which attributes are set, use the And operator to perform a bit-wise comparison of the value returned by the GetAttr function and the value of the individual file attribute you want. If the result is not zero, that attribute is set for the named file. For example, the return value of the following And expression is zero if the Archive attribute is not set:

Result = GetAttr(FName) And vbArchive

A nonzero value is returned if the Archive attribute is set.

See Also

And Operator, FileAttr Function, SetAttr Statement.

Example

This example uses the GetAttr function to determine the attributes of a file and directory or folder.

' Assume file TESTFILE has hidden attribute set.= GetAttr("TESTFILE")                ' Returns 2.
' Returns nonzero if hidden attribute is set on TESTFILE..Print MyAttr And vbHidden
' Assume file TESTFILE has hidden and read-only attributes set.= GetAttr("TESTFILE")                ' Returns 3.
' Returns nonzero if hidden attribute is set on TESTFILE..Print MyAttr And (vbHidden + vbReadOnly)
' Assume MYDIR is a directory or folder.= GetAttr("MYDIR")                ' Returns 16.


GetObject Function

Description

Retrieves an OLE Automation object from a file.

Syntax

GetObject([pathname][, class])

The GetObject function syntax has these named arguments:

Part | Description
pathname | The full path and name of the file containing the object to retrieve. If pathname is omitted, class is required.
class | A string representing the class of the object.

The class argument uses the syntax “appname.objecttype” and has these parts:

Part | Description
appname | The name of the application providing the object.
objecttype | The type or class of object to create.

Remarks

Use the GetObject function to access an OLE Automation object from a file and assign the object to an object variable. To do this, use the Set statement to assign the object returned by GetObject to the object variable. For example:

Dim CADObject As ObjectCADObject = GetObject("C:\CAD\SCHEMA.CAD")

When this code is executed, the application associated with the specified pathname is started and the object in the specified file is activated.

If pathname is a zero-length string (""), GetObject returns a new object instance of the specified type. If the pathname argument is omitted entirely, GetObject returns a currently active object of the specified type. If no object of the specified type exists, an error occurs.

The above example shows how to activate an entire file. However, some applications allow you to activate part of a file. To do this, add an exclamation point (!) to the end of the filename and follow it with a string that identifies the partof the file you want to activate. For information on how to create this string, see the documentation for the application that created the object.

For example, in a drawing application you might have multiple layers to a drawing stored in a file. You could use the following code to activate a layer within a drawing called SCHEMA.CAD:

Set LayerObject = GetObject("C:\CAD\SCHEMA.CAD!Layer3")

If you do not specify the object’s class, based on the filename you provide, OLE determines the application to start and the object to activate. Some files, however, may support more than one class of object. For example, a drawing might support three different types of objects: an application object, a drawing object, and a toolbar object, all of which are part of the same file. To specify which object in a file you want to activate, use the optional class argument. For example:

Dim MyObject As ObjectMyObject = GetObject("C:\DRAWINGS\SAMPLE.DRW", "FIGMENT.DRAWING")

In the above example, FIGMENT is the name of a drawing application and DRAWING is one of the object types it supports.

Once an object is activated, you reference it in code using the object variable you defined. In the above example, you access properties and methods of the new object using the object variable MyObject. For example:

MyObject.Line 9, 90.InsertText 9, 100, "Hello, world.".SaveAs "C:\DRAWINGS\SAMPLE.DRW"

Note Use the GetObject function when there is a current instance of the object, or if you want to create the object with a file already loaded. If there is no current instance, and you don’t want the object started with a file loaded, use the CreateObject function.

If an object has registered itself as a single-instance object (for example, the Word.Basic object in Microsoft Word 6.0), only one instance of the object is created, no matter how many times CreateObject is executed. In addition, with a single-instance object, GetObject always returns the same instance when called with the zero-length string syntax (""), and it causes an error if the pathname argument is omitted. You cannot use GetObject to obtain a reference to a class created with Visual Basic.

See Also

CreateObject Function, Set Statement.

Example

This example uses the GetObject function to get a reference to a specific Microsoft Excel Worksheet (MyXL). It uses the worksheet’s Application property to make Microsoft Excel visible, to close it, and so on. The first call to GetObject causes an error if Microsoft Excel is not already running. In the example, the error causes the ExcelWasNotRunning flag to be set to True. The second call to GetObject specifies a file to open. If Microsoft Excel is not already running, this second call starts it, and returns a reference to the worksheet represented by the specified file. The file, MYTEST.XLS in the example, must exist in the specified location; otherwise the Visual Basic error OLE Automation error is generated. Next, the example code makes both Microsoft Excel and the window containing the specified worksheet visible. Finally, if there was no previous version of Microsoft Excel running, the code uses the Application object’s Quit method to close Microsoft Excel. If the application was already running, no attempt is made to close it. The reference itself is released by setting it to Nothing.

Dim MyXL As Object                    ' Variable to hold reference
                                    ' to Microsoft Excel.ExcelWasNotRunning As Boolean    ' Flag for final release.

' Test to see if there is a copy of Microsoft Excel already running.Error Resume Next                    ' Defer error trapping.
' GetObject function called without the first argument returns a
' reference to an instance of the application. If the application isn't
' running, an  error occurs. Note the comma used as the first argument
' placeholder.MyXL = GetObject(, "Excel.Application")Err.Number <> 0 Then ExcelWasNotRunning = True.Clear                            ' Clear Err object in case error
                                    ' occurred.

' Set the object variable to reference the file you want to see.MyXL = GetObject("c:\vb4\MYTEST.XLS")

' Show Microsoft Excel through its Application property. Then
' show the actual window containing the file using the Windows
' collection of the MyXL object reference..Application.Visible = True.Parent.Windows(1).Visible = True
                                    ' Do manipulations of your
                                    ' file here.
                                    ' ...
' If this copy of Microsoft Excel was not already running when you
' started, close it using the Application property's Quit method.
' Note that when you try to quit Microsoft Excel, the Microsoft Excel
' title bar blinks and Microsoft Excel displays a message asking if you
' want to save any loaded files.ExcelWasNotRunning = True Then MyXL.Application.Quit
MyXL = Nothing                    ' Release reference to the
                                    ' application and spreadsheet.


GetOption, SetOption Methods

Applies To

Application Object.

Description

  • The GetOption method returns the current value of an option in the Options dialog box, available by clicking Options on the Tools menu.
  • The SetOption method sets the current value of an option in the Options dialog box, available by clicking Options on the Tools menu.

Syntax

Application.GetOption(optionname)Application.SetOption optionname, setting

The GetOption and SetOption methods use the following arguments.

Argument | Description
optionname | The name of the option.
setting | A Variant value corresponding to the option setting. The value of setting depends on the possible settings for a particular option.

Remarks

The GetOption and SetOption methods provide a means of changing environment options from Visual Basic code. With these methods, you can set or read any option available in the Options dialog box, except for options on the Modules tab.

The option setting depends on the type of option being set. There are three general types of options:

  • Yes/No options that can be set by selecting or clearing a check box.
  • Options that can be set by entering a string or numeric value.
  • Predefined options that can be chosen from a drop-down box or option group.

For options that the user sets by selecting or clearing a check box, the GetOption method returns True if the option setting is Yes (the check box is selected) or False if the option setting is No (the check box is cleared). To set an option of this kind using the SetOption method, specify True or False for the setting argument, as in the following example.

Application.SetOption "Show Status Bar", True

For options that the user sets by typing a string or numeric value, the GetOption method returns the setting as it is displayed in the dialog box. The following example returns a string containing the left margin setting.

Dim varX As Variant= Application.GetOption("Left Margin")

To set this type of option using the SetOption method, specify the string or numeric value that would be typed in the dialog box. The following example sets the default form template to OrderTemplate.

Application.SetOption "Form Template", "OrderTemplate"

For options with settings that are choices in list boxes, the GetOption method returns a number corresponding to the position of the setting in the list. Indexing begins with zero, so the GetOption method returns zero for the first item, 1 for the second item, and so on. For example, if the Default Field Type option on the Tables/Queries tab is set to AutoNumber, the sixth item in the list, the GetOption method returns 5.

To set this type of option, specify the option’s numeric position within the list as an argument to the SetOption method. The following example sets the Default Field Type option to AutoNumber.

Application.SetOption "Default Field Type", 5

Other options are set by clicking on an option button in an option group in the Options dialog box. In Visual Basic, these options are also set by specifying a particular option’s position within the option group. The first option in the group is numbered zero, the second, 1, and so on. For example, if the Selection Behavior option on the Forms/Reports tab is set to Partially Enclosed, the GetOption method returns zero.

Debug.Print Application.GetOption("Selection Behavior")

To set an option that is a member of an option group, specify the index number of the option within the group. The following example sets Selection Behavior to Fully Enclosed.

Application.SetOption "Selection Behavior", 1

Note When you use the GetOption method or the SetOption method to set an option in the Options dialog box, you don’t need to specify the individual tab on which the option is found.

You can’t use the GetOption method or the SetOption method to read or set any of the options found on the Module tab of the Options dialog box.

If the return value of the GetOption method is assigned to a variable, the variable must be declared as a Variant.

When you quit Microsoft Access, you can reset all options to their original settings by using the SetOption method on all changed options. You may want to create public variables to store the values of the original settings. You might include code to reset options in the Close event procedure for a form, or in a custom exit procedure that the user must run to quit the application.

Example

The following example uses the GetOption method to return the Default Field Type option setting from the Tables/Queries tab of the Options dialog box and then saves the setting in a variable. If the Default Field Type option isn’t currently set to Text, Microsoft Access displays a dialog box asking the user whether it should set the option to Text. If the user clicks Yes, the SetOption method changes the option.

Sub ChangeFieldSize()
    ' Constant represents Text setting of Default Field Type option.
    Const conText = 0
    Dim varSize As Variant, intResponse As Integer, strMsg As String

    ' Determine current setting.
    varSize = Application.GetOption("Default Field Type")
    strMsg = "Set default field type to Text?"
    If varSize <> conText Then
    ' Prompt user to change setting if it's not Text.
        If MsgBox(strMsg, vbYesNo) = vbYes Then
            ' Change setting to Text.
            Application.SetOption "Default Field Type", conText
        End If
    End IfSub


GetSetting Function

Description

Returns a key setting value from an application’s Windows registry entry.

Syntax

GetSetting(appname, section, key[, default])

The GetSetting function syntax has these named arguments:

Part | Description
appname | String expression containing the name of the application or project whose key setting is requested.
section | String expression containing the name of the section where the key setting is found.
key | String expression containing the name of the key setting to return.
default | Expression containing the value to return if no value is set in the key setting. If omitted, default is assumed to be a zero-length string ("").

Remarks

If any of the items named in the GetSetting arguments do not exist, GetSetting returns the value of default.

See Also

DeleteSetting Statement, GetAllSettings Function, SaveSetting Statement.

Example

This example first uses the SaveSetting statement to make entries in the Windows registry (or .INI file on 16-bit Windows platforms) for the application specified as appname, then uses the GetSetting function to display one of the settings. Because the default argument is specified, some value is guaranteed to be returned. Note that section names cannot be retrieved with GetSetting. Finally, the DeleteSetting statement removes all the application’s entries.

' Variant to hold 2-dimensional array returned by GetAllSettings.MySettings As Variant
' Place some settings in the registry.("MyApp","Startup", "Top", 75)("MyApp","Startup", "Left", 50)
.Print GetSetting(appname := "MyApp", section := "Startup", _
    key := "Left", default := "25")
("MyApp", "Startup")


GoSub...Return Statement

Description

Branches to and returns from a subroutine within a procedure.

Syntax

GoSub line
. . .
line
. . .
Return

The line argument can be any line label or line number.

Remarks

You can use GoSub and Return anywhere in a procedure, but GoSub and the corresponding Return must be in the same procedure. A subroutine can contain more than one Return statement, but the first Return statement encountered causes the flow of execution to branch back to the statement immediately following the most recently executed GoSub statement.

Note You can’t enter or exit Sub procedures with GoSub...Return.

Tip Creating separate procedures that you can call may provide a more structured alternative to using GoSub...Return.

See Also

GoTo Statement; On...GoSub, On...GoTo Statements; Sub Statement.

Example

This example uses GoSub to call a subroutine within a Sub procedure. The Return statement causes the execution to resume at the statement immediately following the GoSub statement. The Exit Sub statement is used to prevent control from accidentally flowing into the subroutine.

Sub GosubDemo()
        ' Solicit a number from the user.
        Num = InputBox("Enter a positive number to be divided by 2.")
        ' Only use routine if user enters a positive number.
        If Num > 0 Then GoSub MyRoutine
        Debug.Print Num
        Exit Sub            ' Use Exit to prevent an error.
    MyRoutine:
        Num = Num/2        ' Perform the division.
        Return            ' Return control to statement.Sub                    ' following the GoSub statement.


GotFocus, LostFocus Events

Applies To

Bound Object Frame Control, Check Box Control, Combo Box Control, Command Button Control, Form, List Box Control, Option Button Control, Text Box Control, Toggle Button Control, Unbound Object Frame Control.

Description

These events occur:

  • GotFocus — When a form or control receives the focus.
  • LostFocus — When a form or control loses the focus.

Note The GotFocus and LostFocus events apply only to forms and controls on a form.

Remarks

These events occur when the focus moves in response to a user action, such as pressing the TAB key or clicking the object, or when you use the SetFocus method in Visual Basic or the SelectObject, GoToRecord, GoToControl, or GoToPage action in a macro.

A control can receive the focus only if its Visible and Enabled properties are set to Yes. A form can receive the focus only if it has no controls or if all visible controls are disabled. If a form contains any visible, enabled controls, the GotFocus event for the form doesn’t occur.

You can specify what happens when a form or control receives the focus by running a macro or executing an event procedure when the GotFocus event occurs. For example, by attaching a GotFocus event procedure to each control on a form, you can guide the user through your application by displaying brief instructions or messages in a text box. You can also provide visual cues by enabling, disabling, or displaying controls that depend on the control with the focus.

The GotFocus event differs from the Enter event in that the GotFocus event occurs every time a control receives the focus. For example, suppose the user clicks a check box on a form, then clicks a report, and finally clicks the check box on the form to bring it to the foreground. The GotFocus event occurs both times the check box receives the focus. In contrast, the Enter event occurs only the first time the user clicks the check box. The GotFocus event occurs after the Enter event.

The LostFocus event differs from the Exit event in that the LostFocus event occurs every time a control loses the focus. The Exit event occurs only before a control loses the focus to another control on the same form. The LostFocus event occurs after the Exit event.

If you move the focus on one form to a control that doesn’t have the focus on another form, the Exit and LostFocus events for the control that does have the focus on the first form occur before the Enter and GotFocus events for the control on the second form.

If you use the mouse to move the focus from a control on a main form to a control on a subform of that form, the following events occur:

Exit (for the control on the main form)

LostFocus (for the control on the main form)

Enter (for the subform control)

Exit (for the control on the subform that had the focus)

LostFocus (for the control on the subform that had the focus)

Enter (for the control on the subform that the focus moved to)

GotFocus (for the control on the subform that the focus moved to)

If the control you move to on the subform previously had the focus, neither its Enter event nor its GotFocus event occurs, but the Enter event for the subform control does occur. If you move the focus from a control on a subform to a control on the main form, the Exit and LostFocus events for the control on the subform don’t occur, just the Exit event for the subform control and the Enter and GotFocus events for the control on the main form.

Note You often use the mouse or a key such as TAB to move the focus to another control. This causes mouse or keyboard events to occur in addition to the events discussed in this topic.

When you switch between two open forms, the Deactivate event occurs for the first form, and the Activate event occurs for the second form. If the forms contain no visible, enabled controls, the LostFocus event occurs for the first form before the Deactivate event, and the GotFocus event occurs for the second form after the Activate event.

Note To customize the order in which the focus moves from control to control on a form when you press the TAB key, set the tab order or specify access keys for the controls.

See Also

Activate, Deactivate Events; ActiveControl Property; ActiveForm Property; Enabled, Locked Properties; Enter, Exit Events; GoToControl Action; GoToControl Action; Open, Close Events; SelectObject Action; SetFocus Method; Visible Property (Microsoft Access).


GotFocus, LostFocus Events -- Event Procedures

Description

To create an event procedure that is executed when the GotFocus or LostFocus event occurs, set the OnGotFocus or OnLostFocus property to [Event Procedure], and click the Build button.

Syntax

Private Sub Form_GotFocus( )Private Sub controlname_GotFocus( )Private Sub Form_LostFocus( )Private Sub controlname_LostFocus( )

The GotFocus and LostFocus event procedures use the following argument.

Argument | Description
controlname | A string that is the name of the control affected by the GotFocus and LostFocus event procedures.

Remarks

You can use a LostFocus event procedure to validate entered data as the user moves the focus from a control. You can also reverse or change conditions that you set up in the object’s GotFocus event procedure.

Other uses for LostFocus and GotFocus event procedures are enabling, disabling, hiding, and displaying other objects.

You can’t cancel a GotFocus or LostFocus event.

See Also

GotFocus, LostFocus Events — Macros.

Example

The following example displays a message in a label when the focus moves to an option button.

To try this example, add the following code to the Declarations section of a module for a form called Contacts that contains an option button named OptionYes and a label named LabelYes.

Private Sub OptionYes_GotFocus()
    Me!LabelYes.Caption = "Option button     'Yes' has the focus."SubSub OptionYes_LostFocus()
    Me!LabelYes.Caption = ""                    ' Clear caption.Sub


GotFocus, LostFocus Events -- Macros

Description

To run a macro when the GotFocus or LostFocus event occurs, set the OnGotFocus or OnLostFocus property to the name of the macro.

Remarks

You can use a LostFocus macro to validate entered data as the user moves the focus from a control. You can also reverse or change conditions that you set up in the object’s GotFocus macro.

Other uses for LostFocus and GotFocus macros are enabling, disabling, displaying, and hiding other objects.

You can’t use the CancelEvent action in a GotFocus or LostFocus macro.

See Also

GotFocus, LostFocus Events — Event Procedures.


GoTo Statement

Description

Branches unconditionally to a specified line within a procedure.

Syntax

GoTo line

The line argument can be any line label or line number.

Remarks

GoTo can branch only to lines within the procedure where it appears.

Note Too many GoTo statements can be difficult to read and debug. Use structured control statements (Do...Loop, For...Next, If...Then...Else, Select Case) whenever possible.

See Also

Do...Loop Statement, For...Next Statement, GoSub...Return Statement, If...Then...Else Statement, Select Case Statement.

Example

This example uses the GoTo statement to branch to line labels within a procedure.

Sub GotoStatementDemo()
    Number = 1                 ' Initialize variable.
                            ' Evaluate Number and branch to appropriate                             ' label.
    If Number = 1 Then GoTo Line1 Else GoTo Line2
    :
    MyString = "Number equals 1"
    GoTo LastLine            ' Go to LastLine.:
    ' The following statement never gets executed.
    MyString = "Number equals 2":
    Debug.Print MyString        ' Print "Number equals 1" in
                            ' Debug window.Sub


GoToControl Action

Description

You can use the GoToControl action to move the focus to the specified field or control in the current record of the open form, form datasheet, table datasheet, or query datasheet. You can use this action when you want a particular field or control to have the focus. This field or control can then be used for comparisons or FindRecord actions. You can also use this action to navigate in a form according to certain conditions. For example, if the user enters No in a Married control on a health insurance form, the focus can automatically skip the Spouse Name control and move to the next control.

Setting

The GoToControl action uses the following argument.

Action argument | Description
Control Name | The name of the field or control where you want the focus. This is a required argument.

Note Note Enter only the name of the field or control in the Control Name argument, not the fully qualified identifier, such as Forms!Products![Product ID].

Remarks

You can’t use the GoToControl action to move the focus to a control on a hidden form.

Tip You can use the GoToControl action to move to a subform, which is a type of control. You can then use the GoToRecord action to move to a particular record in the subform. You can also move to a control on a subform by using the GoToControl action to move first to the subform and then to the control on the subform.

To run the GoToControl action in Visual Basic, use the GoToControl method of the DoCmd object. You can also use the SetFocus method to move the focus to a control on a form or any of its subforms, or to a field in an open table, query, or form datasheet.

See Also

GoToControl Method, GoToPage Action, GoToRecord Action, SelectObject Action, SetFocus Method.


GoToControl Method

Applies To

DoCmd Object.

Description

The GoToControl method carries out the GoToControl action in Visual Basic. For more information on how the action and its argument work, see the action topic.

Syntax

DoCmd.GoToControl controlname

The GoToControl method uses the following arguments.

Argument | Description
controlname | A string expression that is the name of a control on the active form or datasheet

Remarks

Use only the name of the control for the controlname argument, not the full syntax.

You can also use a variable declared as a Control data type for this argument:

Dim Ctl As ControlCtl = Forms!Form1!Field3.GoToControl Ctl.Name

You can also use the SetFocus method to move the focus to a control on a form or any of its subforms, or to a field in an open table, query, or form datasheet. This is the preferred method for moving the focus in Visual Basic, especially to controls on subforms and nested subforms, because you can use the full syntax to specify the control you want to move to.

See Also

DoCmd Object, GoToControl Action, GoToPage Method (DoCmd Object), GoToRecord Method, SelectObject Method, SetFocus Method.

Example

This example uses the GoToControl method to move the focus to the EmployeeID field.

DoCmd.GoToControl "EmployeeID"


GoToPage Action

Description

You can use the GoToPage action to move the focus in the active form to the first control on a specified page. You can use this action if you have created a form with page breaks that contains groups of related information. For example, you might have an Employees form with personal information on one page, office information on another page, and sales information on a third page. You can use the GoToPage action to move to the desired page.

Setting

The GoToPage action uses the following arguments.

Action argument | Description
Page Number | The number of the page to which you want to move the focus. If you leave this argument blank, the focus stays on the current page. You can use the Right and Down arguments to display the part of the page you want to see.
Right | The current horizontal position of the spot on the page, measured from the left edge of its containing window, that is to appear at the left edge of the window. This is required if you specify a Down argument.
Down | The current vertical position of the spot on the page, measured from the top edge of its containing window, that is to appear at the top edge of the window. This is required if you specify a Right argument.

Note The Right and Down measurements are in inches or centimeters, depending on the units set for Measurement system on the Number tab of the Regional Settings Properties dialog box in the Microsoft Windows Control Panel.

Remarks

You can use this action to select the first control (as defined by the form’s tab order) on the specified page. Use the GoToControl action to move to a particular control on the form.

You can use the Right and Down arguments for forms with pages larger than the Microsoft Access window. Use the Page Number argument to move to the desired page, and then use the Right and Down arguments to display the part of the page you want to see.

You can’t use the GoToPage action to move the focus to a page on a hidden form.

To run the GoToPage action in Visual Basic, use the GoToPage method of the DoCmd object.

See Also

GoToControl Action, GoToPage Method (DoCmd Object), GoToRecord Action, SelectObject Action, TabStop Property.


GoToPage Method

Applies To

Form

Description

The GoToPage method moves the focus to the first control on a specified page in the active form.

Syntax

form.GoToPage pagenumber[, right, down]

The GoToPage method uses the following arguments.

Argument | Description
form | A Form object that represents the active form
pagenumber | A numeric expression that is a valid page number for the active form
right | A numeric expression that is a valid horizontal offset (in twips) from the left side of the window to the part of the page to be viewed
down | A numeric expression that is a valid vertical offset (in twips) for from the top of the window to the part of the page to be viewed

Remarks

When you use this method to move to a specified page of a form, the focus is set to the first control on the page, as defined by the form’s tab order. To move to a particular control on the form, use the SetFocus method.

You can use the GoToPage method if you have created page breaks on a form to group related information. For example, you might have an Employees form with personal information on the first page, office information on the second page, and sales information on the third page. You can use the GoToPage method to move to the desired page.

You can use the right and down arguments for forms with pages larger than the Microsoft Access application window. Use the pagenumber argument to move to the desired page, and then use the right and down arguments to display the part of the page you want to see. Microsoft Access displays the part of the page which is offset from the upper-left corner of the window by the distance specified in the right and down arguments.

See Also

Form Object, GoToPage Action.

Example

The following example uses the GoToPage method to move the focus to the second page of the Customer form at the position specified by the right and down arguments.

Forms!Customer.GoToPage 2, 1440, 600


GoToPage Method (DoCmd Object)

Applies To

DoCmd Object.

Description

The GoToPage method of the DoCmd object carries out the GoToPage action in Visual Basic. For more information on how the action and its arguments work, see the action topic.

Syntax

DoCmd.GoToPage [pagenumber] [, right, down]

The GoToPage method uses the following arguments.

Argument | Description
pagenumber | A numeric expression that is a valid page number for the active form. If you leave this argument blank, the focus stays on the current page. You can use the right and down arguments to display the part of the page you want to see.
right | A numeric expression that is a valid horizontal offset for the page
down | A numeric expression that is a valid vertical offset for the page

Remarks

The units for the right and down arguments are twips.

If you specify the right and down arguments and leave the pagenumber argument blank, you must include the pagenumber argument’s comma. If you don’t specify the right and down arguments, don’t use a comma following the pagenumber argument.

The GoToPage method of the DoCmd object was added to provide backwards compatibility for running the GoToPage action in Visual Basic code in Microsoft Access for Windows 95. It is recommended that you use the existing GoToPage method of the Form object instead. The GoToPage method of the DoCmd object is different from the GoToPage method of the Form object

See Also

DoCmd Object, GoToControl Method, GoToPage Action, GoToPage Method, GoToRecord Method, SelectObject Method, SetFocus Method.

Example

This example uses the GoToPage method to move the focus to the position specified by the horizontal and vertical offsets on the second page of the active form.

DoCmd.GoToPage 2, 1440, 567


GoToRecord Action

Description

You can use the GoToRecord action to make the specified record the current record in an open table or form recordset or query result set.

Setting

The GoToRecord action uses the following arguments.

Action argument | Description
Object Type | The type of object that contains the record you want to make current. You can click Table, Query, or Form in the Object Type box in the Action Arguments section of the Macro window. Leave this box blank to select the active object.
Object Name | The name of the object that contains the record you want to make the current record. The Object Name box shows all objects in the current database of the type selected with the Object Type argument. If you left the Object Type box blank, leave this box blank also.
Record | The record to make the current record. Click Previous, Next, First, Last, Go To, or New from the Record box. The default is Next.
Offset | An integer or expression, which is preceded by an equal sign (=) that evaluates to an integer. This argument specifies the record to make the current record. You can use Offset in two ways:

  • When the Record argument is Next or Previous, Microsoft Access moves the number of records forward or backward specified in the Offset argument.
  • When the Record argument is Go To, Microsoft Access moves to the record with the number equal to the Offset argument. The record number is shown in the record number box at the bottom of the screen.

Note If you click First, Last, or New for Record, Microsoft Access ignores any Offset number. If you enter an Offset number that is too large, Microsoft Access displays an error message. You can’t enter negative Offset numbers.

Remarks

If the focus is in a particular control in a record, this action leaves it in the same control for the new record.

You can use the New setting for the Record argument to move to the blank record at the end of a form or table so you can enter new data.

This action is similar to choosing the Go To command from the Edit menu. The First, Last, Next, Previous, and New subcommands of the Go To command have thesame effect on the selected object as the First, Last, Next, Previous, and New settings for the Record argument. You can also move to records using the navigation buttons at the bottom of the window.

You can use the GoToRecord action to make a record on a hidden form the current record if you specify the hidden form in the Object Type and Object Name arguments.

To run the GoToRecord action in Visual Basic, use the GoToRecord method of the DoCmd object.

See Also

GoToControl Action, GoToPage Action, GoToRecord Method, SelectObject Action.


GoToRecord Method

Applies To

DoCmd Object.

Description

The GoToRecord method carries out the GoToRecord action in Visual Basic. For more information on how the action and its arguments work, see the GoToRecord action topic.

Syntax

DoCmd.GoToRecord [objecttype, objectname] [, record] [, offset]

The GoToRecord method uses the following arguments.

Argument | Description
objecttype | One of the following intrinsic constants:
 | acTable acQuery acForm
objectname | A string expression that is the valid name of an object of the type selected with the objecttype argument.
record | One of the following intrinsic constants:
 | acPrevious acNext acFirst acLast acGoTo acNewRec
 | If you leave this argument blank, the default (acNext) is assumed.

Argument | Description
offset | A numeric expression that represents the number of records to move forward or backward if you specify acNext or acPrevious for the record argument, or the record to move to if you specify acGoTo for the record argument. The expression must result in a valid record number.

Remarks

If you leave the objecttype and objectname arguments blank, the active object is assumed.

You can leave an optional argument blank in the middle of the syntax, but you must include the argument’s comma. If you leave one or more trailing arguments blank, don’t use a comma following the last argument you specify.

See Also

DoCmd Object, GoToControl Method, GoToPage Method (DoCmd Object), GoToRecord Action, SelectObject Method.

Example

This example uses the GoToRecord method to make the seventh record in the form Employees current.

DoCmd.GoToRecord acForm, "Employees", acGoTo, 7


GridX, GridY Properties

Applies To

Form, Report.

Description

You can use the GridX and GridY properties to specify the horizontal and vertical divisions of the alignment grid in form Design view or report Design view.

Setting

Enter an integer for the number of subdivisions per unit of measurement. If the measurement system is U.S., the default setting is 24 for the GridX property (horizontal) and 24 for the GridY property (vertical).

You can set this property in the property sheet, a macro, or Visual Basic.

In Visual Basic, you set this property using a numeric expression

Remarks

The GridX and GridY properties provide control over the placement and alignment of objects on a form or report. You can adjust the grid for greater or lesser precision. To see the grid, click Grid on the View menu. If the setting for either the GridX or GridY properties is greater than 24, the grid points disappear from view.


GroupHeader, GroupFooter Properties

Applies To

Report, Sorting And Grouping Box.

Description

You can use the GroupHeader and GroupFooter properties to create a group header or a group footer for a selected field or expression. You can use group headers and footers to label groups or summarize data in a group. For example, you can have a Beverages group header that identifies the group of records for beverage products.

Setting

The GroupHeader and GroupFooter properties use the following settings.

Setting | Description
Yes | Creates a group header or footer.
No | (Default) Doesn’t create a group header or footer.

You set these properties in the Sorting And Grouping box, available by clicking Sorting And Grouping on the View Menu or by clicking the Sorting And Grouping button on the toolbar.

You can set them only in report Design view.

Note You can’t set or refer to these properties directly in Visual Basic. To create a group header or footer for a field or expression in Visual Basic, use the CreateGroupLevel function.

Remarks

To set the Group properties — GroupOn, GroupInterval, and KeepTogether — to other than their default values, you must first set the GroupHeader or GroupFooter property to Yes for the selected field or expression.

See Also

CreateGroupLevel Function, GroupInterval Property, GroupLevel Property, GroupOn Property, KeepTogether Property — Groups, SortOrder Property.


GroupInterval Property

Applies To

Report, Sorting And Grouping Box.

Description

You can use the GroupInterval property with the GroupOn property to specify how data is grouped in reports. The GroupInterval property specifies an interval value that data is grouped by. This interval differs depending on the data type and GroupOn property setting of the values in the field or expression you’re grouping on. For example, you can set the GroupInterval property to 1 if you want to group records by the first character of a product name.

Setting

The GroupInterval property settings are Integer values that depend on the field’s data type and its GroupOn property setting. The default GroupInterval setting 1.

You can set this property in the report’s Sorting And Grouping box, a macro, or Visual Basic.

You can set the GroupInterval property only in report Design view or in the Open event procedure of a report.

Remarks

Here are examples of GroupInterval property settings for different field data types.

Field data type | GroupOn setting | GroupInterval setting
All | Each Value | (Default) Automatically set to 1.
Text | Prefix Characters | Set to 3 for grouping by the first three characters in the field (for example, Chai, Chartreuse, and Chang would be grouped together).
Date/Time | Week | Set to 2 to return data in biweekly groups.
Date/Time | Hour | Set to 12 to return data in half-day groups.

To set the GroupInterval property to a value other than its default setting (1), you must first set the GroupHeader or GroupFooter property or both to Yes for the selected field or expression.

See Also

CreateGroupLevel Function; GroupHeader, GroupFooter Properties; GroupLevel Property; GroupOn Property; KeepTogether Property — Groups; SortOrder Property.

Example

The following example sets the sort order and group properties for the first group level in the Products By Category report.

Sub Report_Open()
    ' Set SortOrder property to descending order.
    Reports![Products by Category].GroupLevel(0).SortOrder = True
    ' Set GroupOn property to Prefix Characters.
    Reports![Products by Category].GroupLevel(0).GroupOn = 1
    ' Set GroupInterval property to 1.
    Reports![Products by Category].GroupLevel(0).GroupInterval = 1
    ' Set KeepTogether property to With First Detail.
    Reports![Products by Category].GroupLevel(0).KeepTogether = 2Sub


GroupLevel Property

Applies To

Report.

Description

You can use the GroupLevel property in Visual Basic to refer to the group level you are grouping or sorting on.

Setting

The GroupLevel property setting is an array in which each entry identifies a group level. To refer to a group level, use this syntax:

GroupLevel(n)

The number n is the group level, starting with 0. The first field or expression you group on is group level 0, the second is group level 1, and so on. You can have up to 10 group levels (0 to 9).

The following sample settings show how you use the GroupLevel property to refer to a group level.

Group Level | Refers to
GroupLevel(0) | The first field or expression you sort or group on.
GroupLevel(1) | The second field or expression you sort or group on.
GroupLevel(2) | The third field or expression you sort or group on.

You can use this property in Visual Basic only to set the SortOrder, GroupOn, GroupInterval, KeepTogether, and ControlSource properties. You set these properties in the Open event procedure of a report.

Remarks

In reports, you can group or sort on more than one field or expression. Each field or expression you group or sort on is a group level.

You specify the fields and expressions to sort and group on using the CreateGroupLevel function.

If group level 0 is already defined for a report, you can use the ControlSource property to reset the group level during the report’s Open event procedure. For example, during the Open event procedure of a report, you can display a dialog box called SortForm that prompts you to enter the field to sort on. If you enter a name into a text box (txtPromptYou) in the dialog box, you can set the property to the contents of the text box.

Dim strGetSortField As String= Forms![SortForm]![txtPromptYou].GroupLevel(0).ControlSource = strGetSortField

See Also

CreateGroupLevel Function, GroupInterval Property, GroupOn Property, KeepTogether Property — Groups, SortOrder Property.

Example

See the GroupInterval property example.


GroupOn Property

Applies To

Report, Sorting And Grouping Box.

Description

You can use the GroupOn property to specify how to group data in a field or expression by data type. For example, this property lets you group a Date field by Month.

Setting

The GroupOn property settings available for a field depend on its data type, as the following table shows. For an expression, all of the settings are available. The default setting for all data types is Each Value.

Field data type | Setting | Groups records with | Visual Basic
Text | (Default) Each Value | The same value in the field or expression. | 0
 | Prefix Characters | The same first n number of characters in the field or expression. | 1
Date/Time | (Default) Each Value | The same value in the field or expression. | 0
 | Year | Dates in the same calendar year. | 2
 | Qtr | Dates in the same calendar quarter. | 3
 | Month | Dates in the same month. | 4
 | Week | Dates in the same week. | 5
 | Day | Dates on the same date. | 6
 | Hour | Times in the same hour. | 7
 | Minute | Times in the same minute. | 8
AutoNumber, Currency, Number | (Default) Each Value | The same value in the field or expression. | 0
 | Interval | Values within an interval you specify. | 9

You can set the GroupOn property in the Sorting And Grouping box, a macro, or Visual Basic.

Using Visual Basic, you set this property in the Open event procedure of a report.

Remarks

To set the GroupOn property to a value other than Each Value, you must first set the GroupHeader or GroupFooter property or both to Yes for the selected field or expression.

See Also

CreateGroupLevel Function; GroupHeader, GroupFooter Properties; GroupInterval Property; GroupLevel Property; KeepTogether Property — Groups; SortOrder Property.

Example

See the GroupInterval property example.


GrpKeepTogether Property

Applies To

Report.

Description

You can use the GrpKeepTogether property to specify whether groups in a report that have their KeepTogether property (Groups) set to Whole Group or With First Detail will be kept together by page or by column.

Setting

The GrpKeepTogether property uses the following settings.

Setting | Description | Visual Basic
Per Page | Groups are kept together by page. | 0
Per Column | (Default) Groups are kept together by column. | 1

You can set the GrpKeepTogether property in the report’s property sheet, a macro, or using Visual Basic.

This property can be set only in report Design view.

Remarks

The GrpKeepTogether property lets you specify whether all the data for a group will appear in the same column. For example, if you have a list of employees by department in a multiple-column format, you can use this property to keep all members of the same department in the same column.

See Also

GroupInterval Property, GroupOn Property, KeepTogether Property — Groups, KeepTogether Property — Sections.


HasContinued Property

Applies To

Report.

Description

You can use the HasContinued property to determine if part of the current section begins on the previous page.

Setting

The HasContinued property is set by Microsoft Access and is read-only in all views.

Value | Description
True (-1) | Part of the current section has been printed on the previous page.
False (0) | Part of the current section hasn’t been printed on the previous page.

You can get the value of the HasContinued property using a macro or Visual Basic.

Remarks

You can use the HasContinued property to determine whether to show or hide certain controls depending on the value of the property. For example, you may have a hidden label in a page header containing the text “Continued from previous page”. If the value of the HasContinued property is True, you can make the hidden label visible.

See Also

WillContinue Property.


HasData Property

Applies To

Report.

Description

You can use the HasData property to determine if a form or report is bound to an empty recordset.

Setting

The HasData property is set by Microsoft Access. The value of this property can be read only while printing or while in Print Preview.

You can get the value of the HasData property using a macro or Visual Basic.

Value | Description
-1 | The object has data.
0 | The object doesn’t have data.
1 | The object is unbound.

Remarks

You can use the HasData property to determine whether to hide a subreport that has no data. For example, the following expression hides the subreport control when its report has no data.

Me![SubReportControl].Visible = Me![SubReportControl].Report.HasData

See Also

NoData Event.


Height, Width Properties

Applies To

  • Height Property — Bound Object Frame Control, Chart Control, Check Box Control, Combo Box Control, Command Button Control, Form Section, Image Control, Label Control, Line Control, List Box Control, Option Button Control, Option Group Control, Rectangle Control, Report Section, Subform/Subreport Control, Text Box Control, Toggle Button Control, Unbound Object Frame Control.
  • Width Property — Bound Object Frame Control, Chart Control, Check Box Control, Combo Box Control, Command Button Control, Form, Form Section, Image Control, Label Control, Line Control, List Box Control, Option Button Control, Option Group Control, Rectangle Control, Report, Report Section, Subform/Subreport Control, Text Box Control, Toggle Button Control, Unbound Object Frame Control.

Description

You can use the Height and Width properties to size an object to specific dimensions. This can be useful, for example, if you want to create objects that are exactly the same size or that have the same width or height.

Setting

Enter a number for the desired height or width in the current unit of measurement. To use a unit of measurement different from the setting in the Regional Settings section of the Windows Control Panel, specify the unit, such as cm or in (for example, 5 cm or 3 in).

You can set these properties using the object’s property sheet, a macro, or Visual Basic.

For controls, you can set the default for these properties using the default control style.

In Visual Basic, use a numeric expression to set the value of each property. Values are expressed in twips.

You can’t set these properties for an object once the print process has started. For example, attempting to set the Height property in a report’s OnPrint event generates an error.

Remarks

Microsoft Access automatically sets the Height and Width properties when you create or size a control or when you size a window in form or report Design view.

The height and width of forms and reports are measured from the inside of their borders. The height and width of controls are measured from the center of their borders so controls with different border widths align correctly. The margins for forms and reports are set in the Page Setup dialog box.

Note To set the left and top location of an object, use the Left and Top properties.

See Also

BorderWidth Property; InsideHeight, InsideWidth Properties; Left, Top Properties; MoveSize Action; WindowHeight, WindowWidth Properties.

Example

The following code resizes a command button to a 1-inch by 1-inch square button (and assumes the default unit of measure is set to twips).

Me!cmdSizeButton.Height = 1440    ' 1440 twips = 1 inch.!cmdSizeButton.Width = 1440


HelpContext Property (Visual Basic)

Applies To

Err Object.

Description

Returns or sets a context ID for a topic in a Microsoft Windows Help file.

Syntax

object.HelpContext [= ContextID]

The HelpContext property syntax has these parts:

Part | Description
object | Always the Err object.
ContextID | A valid identifier for a Help topic within the Help file.

Remarks

If a Microsoft Windows Help file is specified in HelpFile, the HelpContext property is used to automatically display the Help topic it identifies. If both HelpFile and HelpContext are empty, the value of Number is checked, and, if it corresponds to a Visual Basic run-time error value, then the Visual Basic Help context ID for the error is used. If the Number value does not correspond to a Visual Basic error, the contents screen for the Visual Basic Help file is displayed.

Note You should write routines in your application to handle typical errors. When programming with an object, you can use the Help supplied by the object’s Help file to improve the quality of your error handling, or to display a meaningful message to your user if the error is not recoverable. When writing OLE Automation objects, you should tailor your Help to programmers programming with your object, as well as supply meaningful information to an end user for an unrecoverable error. Not all Visual Basic host applications can create OLE Automation objects. See your host application’s documentation to determine whether it can create classes and OLE Automation objects.

See Also

Description Property, Err Object, HelpFile Property (Visual Basic), LastDLLError Property, Number Property, Source Property.

Example

This example uses the HelpContext property of the Err object to show the Visual Basic Help topic for the error Overflow.

Err.ClearError Resume Next.Raise 6                 ' Generate "Overflow" error.Err.Number <> 0 Then
    Msg = "Press F1 or Help to see " & Err.HelpFile & " topic for" & _
        " the following HelpContext: " & Err.HelpContext
    MsgBox Msg, , "Error: " & Err.Description, Err.HelpFile, _
        Err.HelpContextIf


HelpContextID, HelpFile Properties (Microsoft Access)

Applies To

  • HelpContextID Property — Bound Object Frame Control, Chart Control, Check Box Control, Combo Box Control, Command Button Control, Form, Image Control, Label Control, Line Control, List Box Control, Option Button Control, Option Group Control, Rectangle Control, Report, Subform/Subreport Control, Text Box Control, Toggle Button Control, Unbound Object Frame Control.
  • HelpFile Property — Form, Report.

Description

  • HelpContextID — You can use this property to specify the context ID for a topic in the custom Help file specified by the HelpFile property setting.
  • HelpFile — You can use this property to specify the name of a custom Help file for the current form or report.

Setting

  • HelpContextID — Enter a Long Integer between 0 and 2,147,483,647. The default setting is 0.
  • HelpFile — Enter a string expression that contains the path and filename of a custom Help file created with the Windows Help Compiler.

You can set these properties using the property sheet, a macro, or Visual Basic.

Remarks

You can create a custom Help file to document forms, reports, or applications you create with Microsoft Access.

When you press the F1 key in Form view, Microsoft Access calls the Windows Help application, loads the custom Help file specified by the HelpFile property setting for the form or report, and displays the Help topic specified by the HelpContextID property setting.

If a control’s HelpContextID property setting is 0 (the default), Microsoft Access uses the form’s HelpContextID and HelpFile properties to identify the Help topic to display. If you press F1 in a view other than Form view or if the HelpContextID property setting for both the form and the control is 0, a Microsoft Access Help topic is displayed.

Note To create a custom Help file, you need the Windows Help Compiler and a rich-text format (RTF) text editor, such as Microsoft Word for Windows.

See Also

ControlTipText Property; HelpContext, HelpFile Properties (Microsoft Office 95 Data Access Reference); MsgBox Function.


HelpFile Property (Microsoft Access)

See HelpContextID, HelpFile Properties.


HelpFile Property (Visual Basic)

Applies To

Err Object.

Description

Returns or sets a fully qualified path to a Microsoft Windows Help file.

Syntax

object.HelpFile [= pathspec]

The HelpFile property syntax has these parts:

Part | Description
object | Always the Err object.
pathspec | Fully qualified path to the Help file.

Remarks

If a Microsoft Windows Help file is specified in HelpFile, it is automatically called when the user presses the Help button (or the F1 key) in the error message dialog box. If the HelpContext property contains a valid context ID for the specified file, that topic is automatically displayed. If no HelpFile is specified, then the Visual Basic Help file is displayed.

Note You should write routines in your application to handle typical errors. When programming with an object, you can use the Help supplied by the object’s Help file to improve the quality of your error handling, or to display a meaningful message to your user if the error is not recoverable. When writing OLE Automation objects, you should tailor your Help to programmers programming with your object, as well as supply meaningful information to an end user for an unrecoverable error. Not all Visual Basic host applications can create OLE Automation objects. See your host application’s documentation to determine whether it can create classes and OLE Automation objects.

See Also

Description Property, Err Object, HelpContext Property (Visual Basic), LastDLLError Property, Number Property, Source Property.

Example

This example uses the HelpFile property of the Err object to start the Microsoft Windows Help system. By default the HelpFile property contains the name of the Visual Basic Help file.

Err.ClearError Resume Next        ' Suppress errors for demonstration purposes..Raise 6                ' Generate "Overflow" error.= "Press F1 or Help to see " & Err.HelpFile & _
    " topic for this error"Msg, , "Error: " & Err.Description,Err.HelpFile, Err.HelpContext


Hex Function

Description

Returns a string representing the hexadecimal value of a number.

Syntax

Hex(number)

The number argument is any valid numeric or string expression.

Remarks

If number is not already a whole number, it is rounded to the nearest whole number before being evaluated.

If number is | Hex returns
Null | Null.
Empty | Zero (0).
Any other number | Up to eight hexadecimal characters.

You can represent hexadecimal numbers directly by preceding numbers in the proper range with &H. For example, &H10 represents decimal 16 in hexadecimal notation.

See Also

Oct Function.

Example

This example uses the Hex function to return the hexadecimal value of a number.

MyHex = Hex(5)            ' Returns 5.= Hex(10)            ' Returns A.= Hex(459)            ' Returns 1CB.


HideDuplicates Property

Applies To

Check Box Control, Combo Box Control, List Box Control, Option Button Control, Option Group Control, Text Box Control, Toggle Button Control.

Description

You can use the HideDuplicates property to hide a control on a report when its value is the same as in the preceding record. For example, on a report listing suppliers and their products, each supplier’s name can appear once for each group of products, rather than once for each product.

Note The HideDuplicates property applies only to controls (check box, combo box, list box, option button, option group, text box, toggle button) on a report.

The property doesn’t apply to check boxes, option buttons, or toggle buttons when they appear in an option group. It does apply to the option group itself.

Setting

The HideDuplicates property uses the following settings.

Setting | Description | Visual Basic
Yes | If the value of a control or the data it contains is the same as in the preceding record, the control is hidden. (To determine the control’s value, see the Remarks section.) | True (-1)
No | (Default) The control is visible regardless of the value in the preceding record. | False (0)

You can set this property using the control’s property sheet, a macro, or Visual Basic.

You can set the HideDuplicates property only in report Design view.

Remarks

You can use the HideDuplicates property to create a grouped report using only the detail section rather than a group header and the detail section.

Example

The following example returns the HideDuplicates property setting for the CategoryName text box and assigns the value to the intCurVal variable.

Dim intCurVal As Integer= Me![CategoryName].HideDuplicates


Hour Function

Description

Returns a whole number between 0 and 23, inclusive, representing the hour of the day.

Syntax

Hour(time)

The time argument is any numeric or string expression, or any combination, that can represent a time. If time contains Null, Null is returned.

See Also

Day Function, Minute Function, Now Function, Second Function, Time Function, Time Statement.

Example

This example uses the Hour function to obtain the hour from a specified time. In the development environment, the time (date literal) is displayed in short time format using the locale settings of your code.

MyTime = #4:35:17 PM#            ' Assign a time.= Hour(MyTime)            ' MyHour contains 16.


Hourglass Action

Description

You can use the Hourglass action to change the mouse pointer to an image of an hourglass (or another icon you’ve chosen) while a macro is running. This action can provide a visual indication that the macro is running. This is especially useful when a macro action or the macro itself takes a long time to run.

Setting

The Hourglass action uses the following argument.

Action argument | Description
Hourglass On | Select Yes to display the icon. Click No to display the normal mouse pointer. The default is Yes.

Remarks

You often use this action if you’ve turned echo off using the Echo action. When echo is off, Microsoft Access suspends screen updates until the macro is finished.

Microsoft Access automatically resets Hourglass On to No when the macro finishes running.

Note In Microsoft Windows 95, the icon shown by this action is the icon you set for Busy in the Pointers tab of the Mouse Properties dialog box in the Windows Control Panel (the default is an animated hourglass). In Windows NT, this is the icon you set for Wait in the Cursors section of the Control Panel (the default is also an hourglass). In either case, you can choose another icon if you want.

To run the Hourglass action in Visual Basic, use the Hourglass method of the DoCmd object.

See Also

Echo Action, Hourglass Method.


Hourglass Method

Applies To

DoCmd Object.

Description

The Hourglass method carries out the Hourglass action in Visual Basic. For more information on how the action and its argument work, see the Hourglass action topic.

Syntax

DoCmd.Hourglass hourglasson

The Hourglass method uses the following arguments.

Argument | Description
hourglasson | Use True (-1) to display the hourglass (or another icon you’ve chosen). Use False (0) to display the normal mouse pointer.

See Also

DoCmd Object, Echo Method, Hourglass Action, SetWarnings Method.

Example

This example uses the Hourglass method to display an hourglass (or another icon you’ve chosen) while your Visual Basic code is executing.

DoCmd.Hourglass True


hWnd Property

Applies To

Form, Report.

Description

You can use the hWnd property to determine the handle (a unique Long Integer assigned by Microsoft Windows to the current window.

Setting

This property is read-only and is available only in a macro or Visual Basic.

Remarks

You can use this property in Visual Basic when making calls to Windows Application Programming Interface (API) functions or other external routines that require the hWnd property as an argument Many Windows functions require the hWnd property value of the current window as one of the arguments.

Caution Because the value of this property can change while a program is running, don’t store the hWnd property value in a global variable.

See Also

Declare Statement, DoCmd Object, hWndAccessApp Property, Maximum Action.

Example

The following example uses the hWnd property with the Windows Application Programming Interface (API) IsZoomed function to determine if a window is maximized.

' Enter on single line in Declarations section of Module window.Function IsZoomed Lib "USER32" (ByVal hWnd As Long) As Integer
Form_Activate()
    Dim intWindowHandle As Long
    intWindowHandle = Screen.ActiveForm.hWnd
        If Not IsZoomed(intWindowHandle) Then
            DoCmd.Maximize
        End IfSub


hWndAccessApp Property

Applies To

Application Object.

Description

You can use the hWndAccessApp property in Visual Basic to determine the handle (a unique Long Integer) assigned by Microsoft Windows 95 to the main Microsoft Access window.

Setting

The hWndAccessApp property is set by Microsoft Access and is read-only.

Remarks

You can use this property in Visual Basic when making calls to Windows 95 Application Programming Interface (API) functions or other external procedures that require a window handle as an argument.

To get the handle to a window containing a Microsoft Access object such as a Form or Report, use the hWnd property.

See Also

Application Object, hWnd Property.


If...Then...Else Statement

Description

Conditionally executes a group of statements, depending on the value of an expression.

Syntax

If condition Then statements [Else elsestatements ]

Or, you can use the following, more versatile syntax:

If condition Then
[statements][ElseIf condition-n Then
[elseifstatements]] . . .[Else
[elsestatements]]End If

The If...Then...Else statement syntax has these parts:

Part | Description
condition | One or more of the following two types of expressions:
 | A numeric or string expression that evaluates to True or False. If condition is Null, condition is treated as False.
 | An expression of the form TypeOf objectname Is objecttype. The objectname is any object reference and objecttype is any valid object type. The expression is True if objectname is of the object type specified by objecttype; otherwise it is False.
statements | One or more statements separated by colons; executed if condition is True.
condition-n | Same as condition.
elseifstatements | One or more statements executed if associated condition-n is True.
elsestatements | One or more statements executed if no previous condition or condition-n expression is True.

Remarks

You can use the single-line form (first syntax) for short, simple tests. However, the block form (second syntax) provides more structure and flexibility than the single-line form and is usually easier to read, maintain, and debug.

Note With the single-line syntax it is possible to have multiple statements executed as the result of an If...Then decision, but they must all be on the same line and separated by colons, as in the following statement:

If A > 10 Then A = A + 1 : B = B + A : C = C + B

When executing a block If (second syntax), condition is tested. If condition is True, the statements following Then are executed. If condition is False, each ElseIf condition (if any) is evaluated in turn. When a True condition is found, the statements immediately following the associated Then are executed. If none of the ElseIf conditions are True (or if there are no ElseIf clauses), the statements following Else are executed. After executing the statements following Then or Else, execution continues with the statement following End If.

The Else and ElseIf clauses are both optional. You can have as many ElseIf clauses as you want in a block If, but none can appear after an Else clause. Block If statements can be nested; that is, contained within one another.

What follows the Then keyword is examined to determine whether or not a statement is a block If. If anything other than a comment appears after Then on the same line, the statement is treated as a single-line If statement.

A block If statement must be the first statement on a line. The Else, ElseIf, and End If parts of the statement can have only a line number or line label preceding them. The block If must end with an End If statement.

Tip Select Case may be more useful when evaluating a single expression that has several possible actions. However, the TypeOf objectname Is objecttype clause can’t be used with the Select Case statement.

See Also

#If ... Then ... #Else Directive, Select Case Statement.

Example

This example shows both the block and single-line forms of the If...Then...Else statement. It also illustrates the use of If TypeOf...Then...Else.

Number = 53    ' Initialize variable.Number < 10 Then
    Digits = 1Number < 100 Then
' Condition evaluates to True so the next statement is executed.
    Digits = 2
    Digits = 3If
' Assign a value using the single-line form of syntax.Digits = 1 Then MyString = "One" Else MyString = "More than one"

Use If TypeOf construct to determine whether the Control passed into a procedure is a text box.

Sub ControlProcessor(MyControl As Control)
    If TypeOf MyControl Is CommandButton Then
        Debug.Print "You passed in a " & TypeName(MyControl)
    ElseIf TypeOf MyControl Is CheckBox Then
        Debug.Print "You passed in a " & TypeName(MyControl)
    ElseIf TypeOf MyControl Is TextBox Then
        Debug.Print "You passed in a " & TypeName(MyControl)
    End IfSub


IgnoreNulls Property

Applies To

Index.

Description

You can use the IgnoreNulls property to specify that records with Null values in the indexed fields are not included in the index.

Setting

The IgnoreNulls property uses the following settings.

Setting | Description | Visual Basic
Yes | Records that contain Null values in the indexed fields aren’t included in the index. | True (-1)
No | Records that contain Null values in the indexed fields are included in the index. | False (0)

You can set this property in the Indexes window of table Design view or in Visual Basic.

Note To access the IgnoreNulls property of an index using Visual Basic, use the Data Access Object’s IgnoreNulls property.

Remarks

You can define an index for a field to facilitate fast searches for records using that field. If you allow Null entries in the indexed field and expect to have many of them, set the IgnoreNulls property for the index to Yes to reduce the amount of storage space that the index uses.

See Also

IgnoreNulls Property (Microsoft Office 95 Data Access Reference), Indexed Property, Primary Property, Unique Property.


IIf Function

Description

Returns one of two parts, depending on the evaluation of an expression.

Syntax

IIf(expr, truepart, falsepart)

The IIf function syntax has these named arguments:

Part | Description
expr | Expression you want to evaluate.
truepart | Value or expression returned if expr is True.
falsepart | Value or expression returned if expr is False.

Remarks

IIf always evaluates both truepart and falsepart, even though it returns only one of them. Because of this, you should watch for undesirable side effects. For example, if evaluating falsepart results in a division by zero error, an error occurs even if expr is True.

See Also

Choose Function, If...Then...Else Statement.

Specifics (Microsoft Access)

The IIf function (immediate if) is most useful in a calculated control on a form or report.

You can use the IIf function to evaluate an expression and return either of two other values, depending on whether the expression evaluates to True (-1) or False (0). For example, you can use the IIf function to inspect a field on a form and determine whether its value is Null. If it is, you can have the function return an empty string. If the field has a value that is not Null, the function could return the field’s contents. The following example checks the ShipCountry field in an Orders table.

= IIf(IsNull(Forms!Orders![ShipCountry]), "", _
    Forms!Orders![ShipCountry])

In Visual Basic, the IIf function evaluates both truepart and falsepart, even though it returns only one of them. On a Microsoft Access form or report, however, the IIf function evaluates either truepart or falsepart, whichever is appropriate. Therefore, you need not be concerned about the undesirable side effects of evaluating both arguments if you use the IIf function in a calculated control, query expression, or macro.

Note The Microsoft Access Nz function converts Null values to zero, a zero-length string, or another value that you specify. If your expression handles Null values, you may be able use the Nz function as an alternative to the IIf function.

The IIf function is most useful within expressions that are in a form or report, rather than in Visual Basic code in a module. In Visual Basic, the more full-featured If...Then...Else statement offers greater versatility.

Example

This example uses the IIf function to evaluate the TestMe parameter of the CheckIt procedure and returns the word “Large” if the amount is greater than 1000; otherwise, it returns the word “Small”.

Function CheckIt (TestMe As Integer)
    CheckIt = IIf(TestMe > 1000, "Large", "Small")Function

This example uses the IIf function to evaluate an OrderAmount field and returns the word “Large” if the amount is greater than 1000; otherwise, it returns the word “Small”. You can enter the following expression in the ControlSource property of a calculated control.

= IIf([OrderAmount] > 1000, "Large", "Small")

In the next example, the IIf function returns a zero-length string if the ShipCountry field is Null; otherwise, it returns the field’s contents.

= IIf(IsNull([ShipCountry]), "", [ShipCountry])

The following example shows how you can use the IIf function to return a string containing an employee’s first name, middle initial, and last name. If there is no middle initial, the expression returns the first and last names separated by a single space. If there is a middle initial, however, it includes the middle initial and a period.

= [FirstName] & IIf(IsNull([Initial]), "", " " & [Initial] & ".") & " "_    & [LastName]


ImageHeight Property

Applies To

Image Control.

Description

You can use the ImageHeight property in Visual Basic to determine the height in twips of the picture in an image control.

Setting

The ImageHeight property is an Integer value equal to the height of a picture in twips.

This property is read-only in all views.

Remarks

You can use the ImageHeight property together with the ImageWidth property to determine the size of a picture in an image control. You could then use this information to change the image control’s Height and Width properties to match the size of the picture displayed.

See Also

Height, Width Properties; ImageWidth Property; SizeToFit Method.

Example

The following example prompts the user to enter the name of a bitmap and then assigns that bitmap to the Picture property of the Image1 image control. The ImageHeight and ImageWidth properties are used to resize the image control to fit the size of the bitmap.

Sub GetNewPicture(frm As Form)
    Dim ctlImage As Control
    Set ctlImage = frm!Image1
    ctlImage.Picture = InputBox("Enter path and filename for new "& _         "bitmap")
    ctlImage.Height = ctlImage.ImageHeight
    ctlImage.Width = ctlImage.ImageWidthSub


ImageWidth Property

Applies To

Image Control.

Description

You can use the ImageWidth property in Visual Basic to determine the width in twips of a picture in an image control.

Setting

The ImageWidth property is an Integer value equal to the width of a picture in twips.

This property is read-only in all views.

Remarks

You can use the ImageWidth property together with the ImageHeight property to determine the size of a picture in an image control. You could then use this information to change the image control’s Height and Width properties to match the size of the picture displayed.

Example

The following example prompts the user to enter the name of a bitmap and then assigns that bitmap to the Picture property of the Image1 image control. The ImageHeight and ImageWidth properties are used to resize the image control to fit the size of the bitmap.

Sub GetNewPicture(frm As Form)
    Dim ctlImage As Control
    Set ctlImage = frm!Image1
    ctlImage.Picture = InputBox("Enter path and filename for new "& _        "bitmap")
    ctlImage.Height = ctlImage.ImageHeight
    ctlImage.Width = ctlImage.ImageWidthSub


IMEStatus Function

Description

Returns the current Input Method Editor (IME) mode of Microsoft Windows; available in Far East versions only.

Syntax

IMEStatus

Return Values

Japanese locale:

Constant | Value | Description
vbIMENoOP | 0 | No IME installed.
vbIMEOn | 1 | IME on.
vbIMEOff | 2 | IME off.

Constant | Value | Description
vbIMEDisable | 3 | IME disabled.
vbIMEHiragana | 4 | Hiragana double-byte characters (DBC).
vbIMEKatakanaDbl | 5 | Katakana DBC.
vbIMEKatakanaSng | 6 | Katakana single-byte characters (SBC).
vbIMEAlphaDbl | 7 | Alphanumeric DBC.
vbIMEAlphaSng | 8 | Alphanumeric SBC.

Chinese (traditional and simplified) locale:

Constant | Value | Description
vbIMENoOP |  |

0 | No IME installed.
vbIMEOn |

1 | IME on.
vbIMEOff |

2 | IME off. |
Bit | Value | Description | Value | Description

0 | 0 | No IME installed. | 1 | IME installed.
1 | 0 | IME disabled. | 1 | IME enabled.
2 | 0 | IME English mode. | 1 | Hangeul mode.
3 | 0 | Banja mode (SB). | 1 | Junja mode (DB).
4 | 0 | Normal mode. | 1 | Hanja conversion mode.


Imp Operator

Description

Used to perform a logical implication on two expressions.

Syntax

result = expression1 Imp expression2

The Imp operator syntax has these parts:

Part | Description
result | Any numeric variable.
expression1 | Any expression.
expression2 | Any expression.

Remarks

The following table illustrates how result is determined:

If expression1 is | And expression2 is | The result is
True | True | True
True | False | False
True | Null | Null
False | True | True
False | False | True
False | Null | True
Null | True | True
Null | False | Null
Null | Null | Null

The Imp operator performs a bit-wise comparison of identically positioned bits in two numeric expressions and sets the corresponding bit in result according to the following truth table:

If bit in expression1 is | And bit in expression2 is | The result is
0 | 0 | 1
0 | 1 | 1
1 | 0 | 0
1 | 1 | 1

See Also

Operator Precedence.

Example

This example uses the Imp Operator to perform logical implication on two expressions.

A = 10: B = 8: C = 6: D = Null    ' Initialize variables.= A > B Imp B > C        ' Returns True.= A > B Imp C > B        ' Returns False.= B > A Imp C > B        ' Returns True.= B > A Imp C > D        ' Returns True.= C > D Imp B > A        ' Returns Null.= B Imp A                ' Returns -1 (bit-wise comparison).


Indexed Property

Applies To

Table Fields.

Description

You can use the Indexed property to set a single-field index. An index speeds up queries on the indexed fields as well as sorting and grouping operations. For example, if you search for specific employee names in a LastName field, you can create an index for this field.

Setting

The Indexed property uses the following settings.

Setting | Description
No | (Default) No index.
Yes | (Duplicates OK) The index allows duplicates.
Yes | (No Duplicates) The index doesn’t allow duplicates.

You can set this property only in the table’s property sheet. You can also click Indexes on the View menu, or click the Indexes button on the toolbar. Microsoft Access then displays the Indexes window. If you add a single-field index in the Indexes window, Microsoft Access will set the Indexed property to Yes.

In Visual Basic, use the Data Access Objects CreateIndex method to create an index for a field.

Remarks

Use the Indexed property to find and sort records using a single field in a table. The field can hold either unique or non-unique values. For example, you can create an index on an EmployeeID field in an employees table in which each employee ID is unique or you can create an index on a name field in which some names may be duplicates.

Note You can’t index Memo and OLE Object data type fields.

You can create as many indexes as you need. The indexes are created when you save the table design and are automatically updated when you change or add records. You can add or delete indexes at any time in table Design view.

Tip You can specify text that is commonly used at the beginning or the end of a field name (such as “ID”, “code”, or “num”) for the AutoIndex On Import/Create option on the Tables/Queries tab, available by clicking Options on the Tools menu. When you import data files that contain this text in their field names, Microsoft Access creates an index for these fields.

If the primary key for a table is a single field, Microsoft Access will automatically set the Indexed property for that field to Yes (No Duplicates).

If you want to create multiple-field indexes, use the Indexes window.

See Also

CreateIndex Method, Primary Property, Primary Property (Microsoft Office 95 Data Access Reference).


Input # Statement

Description

Reads data from an open sequential file and assigns the data to variables.

Syntax

Input #filenumber, varlist

The Input # statement syntax has these parts:

Part | Description
filenumber | Any valid file number.
varlist | Comma-delimited list of variables that are assigned values read from the file — can’t be an array or object variable. However, variables that describe an element of an array or user-defined type may be used.

Remarks

Use this statement only with files opened in Input or Binary mode.

When read, standard string or numeric data is assigned to variables without modification. The following table illustrates how other input data is treated:

Data | Value assigned to variable
Delimiting comma or blank line | Empty
#NULL# | Null
#TRUE# or #FALSE# | True or False
#yyyy-mm-dd hh:mm:ss# | The date and/or time represented by the expression
#ERROR errornumber# | errornumber (variable is a Variant tagged as an error)

Double quotation marks (") within input data are ignored.

Data items in a file must appear in the same order as the variables in varlist and match variables of the same data type. If a variable is numeric and the data is not, a value of zero is assigned to the variable.

If the end of the file is reached while a data item is being input, the input is terminated and an error occurs.

Note To correctly read data from a file into variables, you should always use the Write # statement instead of the Print # statement to write the data to the files. Using Write # ensures that each separate data field is properly delimited.

See Also

Input Function, Open Statement, Print # Statement, Write # Statement.

Example

This example uses the Input # statement to read data from a file into two variables. This example assumes that TESTFILE is a file with a few lines of data written to it using the Write # statement; that is, each line contains a string in quotations and a number separated by a comma, for example, (“Hello”, 234).

Open "TESTFILE" For Input As #1        ' Open file for input.While Not EOF(1)                    ' Loop until end of file.
    Input #1, MyString, MyNumber        ' Read data into two variables.
    Debug.Print MyString, MyNumber    ' Print data to Debug window.#1                                ' Close file.


Input Function

Description

Returns characters from an open sequential or binary file.

Syntax

Input(number, [#]filenumber)

The Input function syntax has these parts:

Part | Description
number | Any valid numeric expression specifying the number of characters to return.
filenumber | Any valid file number.

Remarks

Use this function only with files opened in Input or Binary mode.

Unlike the Input # statement, the Input function returns all of the characters it reads, including commas, carriage returns, linefeeds, quotation marks, and leading spaces.

Note Another function (InputB) is provided for use with byte data contained within text files. Instead of specifying the number of characters to return, number specifies the number of bytes.

See Also

Input # Statement.

Example

This example uses the Input function to read one character at a time from a file and print it to the Debug window. This example assumes that TESTFILE is a text file with a few lines of sample data.

Open "TESTFILE" For Input As #1            ' Open file.While Not EOF(1)                        ' Loop until end of file.
    MyChar = Input(1, #1)                ' Get one character.
    Debug.Print MyChar                    ' Print to Debug window.#1                                    ' Close file.


InputBox Function

Description

Displays a prompt in a dialog box, waits for the user to input text or choose a button, and returns the contents of the text box.

Syntax

InputBox(prompt[, title][, default][, xpos][, ypos][, helpfile, context])

The InputBox function syntax has these named arguments:

Part | Description
prompt | String expression displayed as the message in the dialog box. The maximum length of prompt is approximately 1024 characters, depending on the width of the characters used. If prompt consists of more than one line, you can separate the lines using either a carriage return character (Chr(13)), a linefeed character (Chr(10)), or carriage return-linefeed character combination (Chr(13) & Chr(10)) between each line.
title | String expression displayed in the title bar of the dialog box. If you omit title, the application name is placed in the title bar.
default | String expression displayed in the text box as the default response if no other input is provided. If you omit default, the text box is displayed empty.
xpos | Numeric expression that specifies, in twips, the horizontal distance of the left edge of the dialog box from the left edge of the screen. If xpos is omitted, the dialog box is horizontally centered.
ypos | Numeric expression that specifies, in twips, the vertical distance of the upper edge of the dialog box from the top of the screen. If ypos is omitted, the dialog box is vertically positioned approximately one-third of the way down the screen.

Part | Description
helpfile | String expression that identifies the Help file to use to provide context-sensitive Help for the dialog box. If helpfile is provided, context must also be provided.
context | Numeric expression that is the Help context number the Help author assigned to the appropriate Help topic. If context is provided, helpfile must also be provided.

Remarks

When both helpfile and context are supplied, a Help button is automatically added to the dialog box.

If the user chooses OK or presses ENTER, the InputBox function returns whatever is in the text box. If the user chooses Cancel, the function returns a zero-length string ("").

Note If you want to specify more than the first named argument, you must use InputBox in an expression. If you want to omit some positional arguments, you must include the corresponding comma delimiter.

See Also

MsgBox Function.

Specifics (Microsoft Access)

You can’t open a Help file from a dialog box created by the InputBox function in Microsoft Access. If you specify values for the helpfile and context arguments, they will be ignored. However, Microsoft Access won’t generate an error.

Example

This example shows various ways to use the InputBox function to prompt the user to enter a value. If the x and y positions are omitted, the dialog box is automatically centered for the respective axes. The variable MyValue contains the value entered by the user if the user chooses OK or presses the ENTER key . If the user chooses Cancel, a zero-length string is returned.

Message = "Enter a value between 1 and 3"    ' Set prompt.= "InputBox Demo"                        ' Set title.= "1"                                ' Set default.
' Display message, title, and default value.= InputBox(Message, Title, Default)

' Use Helpfile and context. The Help button is added automatically.= InputBox(Message, Title, , , , "DEMO.HLP", 10)

' Display dialog box at position 100, 100.= InputBox(Message, Title, Default, 100, 100)

The following example uses the InputBox function to return the user’s name. Note that you can’t open a Help file from a dialog box created by the InputBox function in Microsoft Access.

Sub Greeting()
    Dim strInput As String, strMsg As String

    strMsg = "Enter your name."
    strInput = InputBox(strMsg, "User Info", , 2000, 2000)
    MsgBox "Hello, " & strInputSub


InputMask Property

Applies To

Combo Box Control, Query Fields, Table Fields, Text Box Control.

Description

You can use the InputMask property to make data entry easier and control the values users can enter in a text box control. For example, you could create an input mask for a Phone Number field that shows you exactly how to enter a new number: (___) ___-____. It is often easier to use the Input Mask Wizard to set the property for you.

Setting

The InputMask property can contain up to three sections separated by semicolons (;).

Section | Description
First | Specifies the input mask itself (for example, (999) 000-0000!). For a list of characters you can use to define the input mask, see the following table.
Second | Specifies whether Microsoft Access stores the literal display characters in the table when you enter data. If you use 0 for this section, all literal display characters (for example, the parentheses in a phone number input mask) are stored with the value; if you enter 1 or leave this section blank, only characters typed into the control are stored.
Third | Specifies the character that Microsoft Access displays for the space where you should type a character in the input mask. For this section, you can use any character; to display an empty string, use a space enclosed in quotation marks (" ").

In Visual Basic you use a string expression to set this property. For example, the following specifies an input mask for a text box control used for entering telephone:

Forms![Customers]![Telephone].InputMask = "(###) ###-####"

When you create an input mask, you can require that certain data be entered (for example, the area code for a phone number) and that other data is optional (such as a telephone extension) by using special characters. These characters specify the type of data, such as a number or character, that you must enter for each character in the input mask.

You can define an input mask using the following characters.

Character | Description
0 | Digit (0 to 9, entry required, plus (+) and minus (-) signs not allowed).
9 | Digit or space (entry not required, plus and minus signs not allowed).
# | Digit or space (entry not required, spaces are displayed as blanks while in Edit mode, but blanks are removed when data is saved, plus and minus signs allowed).
L | Letter (A to Z, entry required).
? | Letter (A to Z, entry optional).
A | Letter or digit (entry required).
a | Letter or digit (entry optional).
& | Any character or a space (entry required).
C | Any character or a space (entry optional).
. , : ; - / | Decimal placeholder and thousand, date, and time separators. (The actual character used depends on the settings in the Regional Settings section of the Windows Control Panel).
< | Causes all characters to be converted to lowercase.
> | Causes all characters to be converted to uppercase.
! | Causes the input mask to display from right to left, rather than from left to right, when characters on the left side of the input mask are optional. Characters typed into the mask always fill it from left to right. You can include the exclamation point anywhere in the input mask.
\ | Causes the character that follows to be displayed as the literal character (for example, \A is displayed as just A).

Note Setting the InputMask property to the word “Password” creates a password-entry control. Any character typed in the control is stored as the character but is displayed as an asterisk (*). You use the Password input mask to prevent displaying the typed characters on the screen.

For a control, you can set this property in the control’s property sheet. For a field in a table, you can set the property in table Design view (under Field Properties) or in Design view of the Query window (in the Field Properties property sheet).

You can also set the InputMask property in a macro or Visual Basic.

Remarks

When you type data in a field for which you’ve defined an input mask, the data is always entered in Overtype mode. If you use the BACKSPACE key to delete a character, the character is replaced by a blank space.

If you move text from a field for which you’ve defined an input mask onto the Clipboard, the literal display characters are copied, even if you have specified that they be saved with data.

Note Only characters that you type directly in a control or combo box are affected by the input mask. Microsoft Access ignores any input masks when you import data, run an action query, or enter characters in a control using Visual Basic by setting the control’s Text property or in a macro using the SetValue action.

When you’ve defined an input mask and set the Format property for the same field, the Format property takes precedence when the data is displayed. This means that even if you’ve saved an input mask, the input mask is ignored when data is formatted. The data in the underlying table itself isn’t changed; the Format property affects only how the data is displayed.

Example

The following table shows some useful input masks and the type of values you can enter into them.

Input mask | Sample values
(000) 000-0000 | (206) 555-0248
(999) 000-0000! | (206) 555-0248
 | ( ) 555-0248
(000) AAA-AAAA | (206) 555-TELE
#999 | -20
 | 2000
>L????L?000L0 | GREENGR339M3
 | MAY R 452B7
>L0L 0L0 | T2F 8M4
00000-9999 | 98115-
 | 98115-3007
>L<?????????????? | Maria
 | Brendan
ISBN 0-&&&&&&&&&-0 | ISBN 1-55615-507-7
 | ISBN 0-13-964262-5
>LL00000-0000 | DB51392-0493

See Also

AutoTab Property, Format Property.


InSelection Property

Applies To

Bound Object Frame Control, Chart Control, Check Box Control, Combo Box Control, Command Button Control, Label Control, Line Control, List Box Control, Option Button Control, Option Group Control, Page Break Control, Rectangle Control, Text Box Control, Toggle Button Control, Unbound Object Frame Control.

Description

You can use the InSelection property to determine or specify whether a control on a form in Design view is selected.

Setting

The InSelection property uses the following settings.

This property is available only in a macro or Visual Basic.

Remarks

When a control is selected, its sizing handles are visible and it can be resized by the user. More than one control can be selected at a time.

See Also

Control Object.

Example

The following example uses the InSelection property to determine whether the strControlName control on a form is selected.

Function IsControlSelected(frm As Form, strControlName As String) _
        As     Integer
    Dim intI As Integer, ctl As Control
    If frm.CurrentView <> 0 Then
        ' Form is not in Design view.
        Exit Function
    Else
        For intI = 0 To frm.Count-1
            Set ctl = frm(intI)
            If ctl.InSelection = True Then
                ' Is desired control selected?
                If UCase(ctl.Name) = UCase(strControlName) Then
                    IsControlSelected = True
                End If
            Else
                IsControlSelected = False
            End If
        Next intI
    End IfFunction


InsertText Method

Description

You can use the InsertText method from Visual Basic code to add text to another module.

For example, suppose you are building a wizard that creates a new form and adds code to that form’s module. You can use the InsertText method to add the specified text to the module when the wizard is run.

Setting

The InsertText method uses two syntax forms.

Syntax 1

object.Module.InsertText text

You can use this syntax form to insert text into a form module or a report module. This syntax form uses the following arguments.

Argument | Description
object | A Form or Report object containing the module to which you want to add text.
Module | The property that specifies a form or report module.
text | A string expression that specifies the text to insert.

Syntax 2

application.InsertText text, modulename

You can use this syntax form to insert text into a standard module. This syntax form uses the following arguments.

Argument | Description
application | The Application object.
text | The text to insert.
modulename | The name of the standard module into which text is to be inserted.

Remarks

Use the InsertText method in a custom wizard to add code to a module.

If you are adding text to a form or report module, the InsertText method is available only in form Design view or report Design view. If you try to add text to the module of a form or report that is open in any view but Design view, Microsoft Access generates a run-time error.

If a procedure in the module to which you are adding text is suspended, Microsoft Access generates a run-time error.

See Also

Module Property.

Example

The following example inserts code in the form module associated with a form called Orders. The code sounds a beep when the form is opened.

Sub AddSub()
    Dim strFormOpenCode As String

    strFormOpenCode = "Sub Form_Open(Cancel As Integer)" & vbCrLf _
        & "Beep" & vbCrLf & "End Sub"
    Forms!Orders.Module.InsertText strFormOpenCodeSub

The next example inserts code into a standard module called PublicFunctions.

Sub AddDeclaration()
    Dim strText As String

    strText = "Public varName"
    Application.InsertText strText, "PublicFunctions"Sub


InsideHeight, InsideWidth Properties

Applies To

Form.

Description

You can use the InsideHeight and InsideWidth properties to determine the height and width (in twips) of the window containing a form.

Setting

  • InsideHeight — an Integer value expressed in twips that represents the height of a form window.
  • InsideWidth — an Integer value expressed in twips that represents the width of a form window.

The InsideHeight and InsideWidth properties are available only in Visual Basic and can be set at any time.

Remarks

If you want to determine the interior dimensions of the form itself, use the Height and Width properties. The interior of a form is the region inside the form, excluding the scroll bars and the record selectors.

You can also use the WindowHeight and WindowWidth properties to determine the height and width of the window containing a form.

See Also

Height, Width Properties; WindowHeight, WindowWidth Properties.

Example

The following example shows how to use the InsideHeight and InsideWidth properties to compare the inside height and width of a form with the height and width of the form’s window. If the window’s dimensions do not equal the size of the form, then the window is resized to match the form’s height and width.

Sub ResetWindowSize(frm As Form)
    Dim intWindowHeight As Integer
    Dim intWindowWidth As Integer
    Dim intTotalFormHeight As Integer
    Dim intTotalFormWidth As Integer
    Dim intHeightHeader As Integer
    Dim intHeightDetail As Integer
    Dim intHeightFooter As Integer
    ' Determine form's height.
    intHeightHeader = frm.Section(1).Height
    intHeightDetail = frm.Section(0).Height
    intHeightFooter = frm.Section(2).Height
    intTotalFormHeight = intHeightHeader _
        + intHeightDetail + intHeightFooter
    ' Determine form's width.
    intTotalFormWidth = frm.Width
    ' Determine window's height and width.
    intWindowHeight = frm.InsideHeight
    intWindowWidth = frm.InsideWidth

    If intWindowWidth <> intTotalFormWidth Then
        intWindowWidth = intTotalFormWidth
    End If
    If intWindowHeight <> intTotalFormHeight Then
        intWindowHeight = intTotalFormHeight
    End IfSub


InStr Function

Description

Returns the position of the first occurrence of one string within another.

Syntax

InStr([start, ]string1, string2[, compare])

The InStr function syntax has these named arguments:

Part | Description
start | Numeric expression that sets the starting position for each search. If omitted, search begins at the first character position. If start contains Null, an error occurs. The start argument is required if compare is specified.

Part | Description
string1 | String expression being searched.
string2 | String expression sought.
compare | Specifies the type of string comparison. The compare argument can be omitted, it can be 0 or 1, or it can be the value of the CollatingOrder property of a Field object. Specify 0 (default) to perform a binary comparison. Specify 1 to perform a textual, case-insensitive comparison. Specify the return value of the CollatingOrder property of a Field object if you want to sort or compare values from a database in the same way the database itself would. If compare is Null, an error occurs. The start argument is required if compare is specified. If compare is omitted, the Option Compare setting determines the type of comparison.

Return Values

If | InStr returns
string1 is zero-length | 0
string1 is Null | Null
string2 is zero-length | start
string2 is Null | Null
string2 is not found | 0
string2 is found within string1 | Position at which match is found
start > string2 | 0

Note Another function (InStrB) is provided for use with byte data contained in a string. Instead of returning the character position of the first occurrence of one string within another, InStrB returns the byte position.

See Also

Option Compare Statement.

Example

This example uses the InStr function to return the position of the first occurrence of one string within another.

SearchString ="XXpXXpXXPXXP"                ' String to search in.= "P"    ' Search for "P".
' A textual comparison starting at position 4. Returns 6.= InStr(4, SearchString, SearchChar, 1)
' A binary comparison starting at position 1. Returns 9.= InStr(1, SearchString, SearchChar, 0)
' Comparison is binary by default (last argument is omitted).= InStr(SearchString, SearchChar)    ' Returns 9.= InStr(1, SearchString, "W")        ' Returns 0.


Int, Fix Functions

Description

Returns the integer portion of a number.

Syntax

Int(number)Fix(number)

The number argument can be any valid numeric expression. If number contains Null, Null is returned.

Remarks

Both Int and Fix remove the fractional part of number and return the resulting integer value.

The difference between Int and Fix is that if number is negative, Int returns the first negative integer less than or equal to number, whereas Fix returns the first negative integer greater than or equal to number. For example, Int converts -8.4 to -9, and Fix converts -8.4 to -8.

Fix(number) is equivalent to:

Sgn(number) * Int(Abs(number))

See Also

CInt Function.

Example

This example illustrates how the Int and Fix functions return integer portions of numbers. In the case of a negative number argument, the Int function returns the first negative integer less than or equal to the number; the Fix function returns the first negative integer greater than or equal to the number.

MyNumber = Int(99.8)        ' Returns 99.= Fix(99.2)        ' Returns 99.= Int(-99.8)    ' Returns -100.= Fix(-99.8)    ' Returns -99.= Int(-99.2)    ' Returns -100.= Fix(-99.2)    ' Returns -99.


Integer Data Type

Description

Integer variables are stored as 16-bit (2-byte) numbers ranging in value from
,768 to 32,767. The type-declaration character for Integer is %.

You can also use Integer variables to represent enumerated values. An enumerated value can contain a finite set of unique whole numbers, each of which has special meaning in the context in which it is used. Enumerated values provide a convenient way to select among a known number of choices. For example, when asking the user to select a color from a list, you could have black = 0, white = 1, and so on. It is good programming practice to define constants using the Const statement for each enumerated value.

See Also

CInt Function, Data Type Summary, Def type Statements, Long Data Type, Variant Data Type.


IPmt Function

Description

Returns the interest payment for a given period of an annuity based on periodic, constant payments and a constant interest rate.

Syntax

IPmt(rate, per, nper, pv[, fv[, type]])

The IPmt function has these named arguments:

Part | Description
rate | Interest rate per period. For example, if you get a car loan at an annual percentage rate (APR) of 10 percent and make monthly payments, the rate per period is 0.1/12, or 0.0083.
per | Payment period in the range 1 through nper.
nper | Total number of payment periods in the annuity. For example, if you make monthly payments on a four-year car loan, your loan has a total of 4 * 12 (or 48) payment periods.
pv | Present value, or value today, of a series of future payments or receipts. For example, when you borrow money to buy a car, the loan amount is the present value to the lender of the monthly car payments you will make.

Part | Description
fv | Future value or cash balance you want after you’ve made the final payment. For example, the future value of a loan is $0 because that’s it value after the final payment. However, if you want to save $50,000 for your child’s education over 18 years, then $50,000 is the future value. If omitted, 0 is assumed.
type | Number indicating when payments are due. Use 0 if payments are due at the end of the payment period, or use 1 if payments are due at the beginning of the period. If omitted, 0 is assumed.

Remarks

An annuity is a series of constant cash payments made over a period of time. An annuity can be a loan (such as a home mortgage) or an investment (such as a monthly savings plan).

The arguments rate and nper must be calculated using payment periods expressed in the same units. For example, if rate is calculated using months, nper must also be calculated using months.

For all arguments, cash paid out (such as deposits to savings) is represented by negative numbers; cash received (such as dividend checks) is represented by positive numbers.

Example

This example uses the IPmt function to calculate how much of a payment is interest when all the payments are of equal value. Given are the interest percentage rate per period (APR / 12), the payment period for which the interest portion is desired (Period), the total number of payments (TotPmts), the present value or principal of the loan (PVal), the future value of the loan (FVal), and a number that indicates whether the payment is due at the beginning or end of the payment period (PayType).

Const ENDPERIOD = 0, BEGINPERIOD = 1    ' When payments are made.= 0    ' Usually 0 for a loan.= "###,###,##0.00"            ' Define money format.= InputBox("How much do you want to borrow?")= InputBox("What is the annual percentage rate of your loan?")APR > 1 Then APR = APR / 100    ' Ensure proper form.= InputBox("How many monthly payments?")= MsgBox("Do you make payments at end of the month?", vbYesNo)PayType = vbNo Then PayType = BEGINPERIOD Else PayType = ENDPERIODPeriod = 1 To TotPmts        ' Total all interest.
    IntPmt = IPmt(APR / 12, Period, TotPmts, -PVal, FVal, PayType)
    TotInt = TotInt + IntPmtPeriod= "You'll pay a total of " & Format(TotInt, Fmt) = Msg & " in interest for this loan."Msg                        ' Display results.


IRR Function

Description

Returns the internal rate of return for a series of periodic cash flows (payments and receipts).

Syntax

IRR(values()[, guess])

The IRR function has these named arguments:

Part | Description
values() | Array of cash flow values. The array must contain at least one negative value (a payment) and one positive value (a receipt).
guess | Value you estimate will be returned by IRR. If omitted, guess is 0.1 (10 percent).

Remarks

The internal rate of return is the interest rate received for an investment consisting of payments and receipts that occur at regular intervals.

The IRR function uses the order of values within the array to interpret the order of payments and receipts. Be sure to enter your payment and receipt values in the correct sequence. The cash flow for each period doesn’t have to be constant, as it would for an annuity.

IRR is calculated by iteration. Starting with the value of guess, IRR cycles through the calculation until the result is accurate to within 0.00001 percent. If, after 20 tries, it can’t find a result, IRR fails.

Example

In this example, the IRR function returns the internal rate of return for a series of five cash flows contained in the array Values(). The first array element is a negative cash flow representing business start-up costs. The remaining four cash flows represent positive cash flows for the subsequent four years. Guess is the estimated internal rate of return.

Static Values(5) As Double                ' Set up array.= .1                                ' Guess starts at 10 percent.= "#0.00"                            ' Define percentage format.(0) = -70000                        ' Business start-up costs.
' Positive cash flows reflecting income for four successive years.(1) = 22000 : Values(2) = 25000(3) = 28000 : Values(4) = 31000= IRR(Values(), Guess) * 100        ' Calculate internal rate.= "The internal rate of return for these five cash flows is "= Msg & Format(RetRate, Fmt) & " percent."Msg                                ' Display internal return rate.


Is Operator

Description

Used to compare two object reference variables.

Syntax

result = object1 Is object2

The Is operator syntax has these parts:

Part | Description
result | Any numeric variable.
object1 | Any object name.
object2 | Any object name.

Remarks

If object1 and object2 both refer to the same object, result is True; if they do not, result is False. Two variables can be made to refer to the same object in several ways.

In the following example, A has been set to refer to the same object as B:

Set A = B

The following example makes A and B refer to the same object as C:

Set A = CB = C

See Also

Comparison Operators.

Example

This example uses the Is operator to compare two object references. The object variable names are generic and used for illustration purposes only.

Set YourObject = MyObject            ' Assign object references.ThisObject = MyObjectThatObject = OtherObject= YourObject Is ThisObject    ' Returns True.= ThatObject Is ThisObject    ' Returns False.
' Assume MyObject <> OtherObject= MyObject Is ThatObject        ' Returns False.


IsArray Function

Description

Returns a Boolean value indicating whether a variable is an array.

Syntax

IsArray(varname)

The varname argument can be any variable.

Remarks

IsArray returns True if the variable is an array; otherwise, it returns False. IsArray is especially useful with variants containing arrays.

See Also

Array Function, IsDate Function, IsEmpty Function, IsError Function, IsMissing Function, IsNull Function, IsNumeric Function, IsObject Function, TypeName Function, Variant Data Type, VarType Function.

Example

This example uses the IsArray function to check if a variable is an array.

Dim MyArray(1 To 5) As Integer        ' Declare array variable.= Array(1, 2, 3)            ' Use Array function.= IsArray(MyArray)            ' Returns True.= IsArray(YourArray)            ' Returns True.


IsDate Function

Description

Returns a Boolean value indicating whether an expression can be converted to a date.

Syntax

IsDate(expression)

The expression argument can be any date or string expression recognizable as a date or time.

Remarks

IsDate returns True if the expression is a date or can be converted to a valid date; otherwise, it returns False. In Microsoft Windows, the range of valid dates is January 1, 100 A.D. through December 31, 9999 A.D.; the ranges vary among operating systems.

See Also

CDate Function, Date Data Type, IsArray Function, IsEmpty Function, IsError Function, IsMissing Function, IsNull Function, IsNumeric Function, IsObject Function, TypeName Function, Variant Data Type, VarType Function.

Example

This example uses the IsDate function to determine if an expression can be converted to a date.

MyDate = "February 12, 1969": YourDate = #2/12/69#: NoDate = "Hello"= IsDate(MyDate)            ' Returns True.= IsDate(YourDate)        ' Returns True.= IsDate(NoDate)            ' Returns False.

The following example prompts the user for a string value, uses the IsDate function to determine whether the string can be converted to a date, and then displays an appropriate message.

Sub CheckDate()
    strDate = InputBox("Enter string to display as a date.")
    ' Test variable.
    If IsDate(strDate) Then
        ' If string is date, format and display in dialog.
        MsgBox "The date is: " & Format(DateValue(strDate), "Long Date")
    Else
        MsgBox "The value you entered is not a date."
    End IfSub


IsEmpty Function

Description

Returns a Boolean value indicating whether a variable has been initialized.

Syntax

IsEmpty(expression)

The expression argument can be any numeric or string expression. However, because IsEmpty is used to determine if individual variables are initialized, the expression argument is most often a single variable name.

Remarks

IsEmpty returns True if the variable is uninitialized, or is explicitly set to Empty; otherwise, it returns False. False is always returned if expression contains more than one variable. IsEmpty only returns meaningful information for variants.

See Also

IsArray Function, IsDate Function, IsError Function, IsMissing Function, IsNull Function, IsNumeric Function, IsObject Function, TypeName Function, Variant Data Type, VarType Function.

Example

This example uses the IsEmpty function to determine whether a variable has been initialized.

MyCheck = IsEmpty(MyVar)            ' Returns True.= Null    ' Assign Null.= IsEmpty(MyVar)            ' Returns False.= Empty                    ' Assign Empty.= IsEmpty(MyVar)            ' Returns True.

The following example uses the IsEmpty function to determine whether a variable has been initialized. If it hasn’t been initialized, a message prompts the user to enter the initial value.

Sub CheckInitialized()
    ' Declare variables.
    Dim varTest As Variant, varInit As Variant

    ' Test variable.
    If IsEmpty(varTest) Then
        varInit = MsgBox("Variable uninitialized; initialize now?", _             vbOKCancel)
        If varInit = vbOK Then
            ' If user clicked OK, initialize varTest.
            varTest = InputBox("Please enter the value for the "& _                     "variable.")
            ' Display confirmation.
            MsgBox "Variable 'varTest' initialized to " & varTest
        End If
    End IfSub


IsError Function

Description

Returns a Boolean value indicating whether an expression is an error value.

Syntax

IsError(expression)

The expression argument must be a Variant of VarType vbError.

Remarks

Error values are created by converting real numbers to error values using the CVErr function. The IsError function is used to determine if a numeric expression represents an error. IsError returns True if the expression argument indicates an error; otherwise, it returns False. IsError only returns meaningful information for variants of VarType vbError.

See Also

CVErr Function, IsArray Function, IsDate Function, IsEmpty Function, IsMissing Function, IsNull Function, IsNumeric Function, IsObject Function, TypeName Function, Variant Data Type, VarType Function.

Example

This example uses the IsError function to check if a numeric expression is an error value. The CVErr function is used to return an Error Variant from a user-defined function. Assume UserFunction is a user-defined function procedure that returns an error value; for example, a return value assigned with the statement UserFunction = CVErr(32767), where 32767 is a user-defined number.

ReturnVal = UserFunction()= IsError(ReturnVal)            ' Returns True.


IsMissing Function

Description

Returns a Boolean value indicating whether an optional argument has been passed to a procedure.

Syntax

IsMissing(argname)

The argname argument is the name of an optional procedure argument.

Remarks

The IsMissing function is used in a procedure that has optional arguments, including ParamArray arguments, to determine whether an argument has been passed to the procedure. IsMissing returns True if no value has been passed for the specified argument; otherwise, it returns False. If IsMissing returns True for an argument, use of the missing argument in other code may cause a user-defined error. If IsMissing is used on a ParamArray argument, it always returns False.

See Also

Function Statement, IsArray Function, IsDate Function, IsEmpty Function, IsError Function, IsNull Function, IsNumeric Function, IsObject Function, Property Get Statement, Property Let Statement, Property Set Statement, Sub Statement, TypeName Function, Variant Data Type, VarType Function.

Example

This example uses the IsMissing function to check if an optional argument has been passed to a user-defined procedure.

' The following statements call the user-defined function procedure.= ReturnTwice()        ' Returns Null.= ReturnTwice(2)        ' Returns 4.

' Function procedure definition.ReturnTwice(Optional A)
    If IsMissing(A) Then
        ' If argument is missing, return a Null.
        ReturnTwice = Null
    Else
        ' If argument is present, return twice the value.
        ReturnTwice = A * 2
    End IfFunction

The following example uses the IsMissing function to determine whether an argument has been passed to the function. If not, a message prompts the user to supply a value.

Sub RunQuery(Optional varQueryName As Variant)
    Dim strGetQuery As String

    ' Determine if optional argument was passed.
    If IsMissing(varQueryName) Then
        ' If argument was not passed, prompt for query to run.
        varGetQuery = InputBox("Enter query name.")
        DoCmd.OpenQuery varGetQuery
    Else
        ' If argument was passed, run that query.
        DoCmd.OpenQuery varQueryName
    End IfSub


IsNull Function

Description

Returns a Boolean value that indicates whether an expression contains no valid data (Null).

Syntax

IsNull(expression)

The expression argument can be any numeric or string expression.

Remarks

IsNull returns True if expression is Null, that is, it contains no valid data; otherwise, IsNull returns False. If expression consists of more than one variable, Null in any constituent variable causes True to be returned for the entire expression.

The Null value indicates that the Variant contains no valid data. Null is not the same as Empty, which indicates that a variable has not yet been initialized. It is also not the same as a zero-length string, which is sometimes referred to as a null string.

Important Use the IsNull function to determine whether an expression contains a Null value. Expressions that you might expect to evaluate to True under some circumstances, such as If Var = Null and If Var <> Null, are always False. This is because any expression containing a Null is itself Null and therefore False.

See Also

IsArray Function, IsDate Function, IsEmpty Function, IsError Function, IsMissing Function, IsNumeric Function, IsObject Function, TypeName Function, Variant Data Type, VarType Function.

Example

This example uses the IsNull function to determine if a variable contains a Null.

MyCheck = IsNull(MyVar)        ' Returns False.= ""= IsNull(MyVar)        ' Returns False.= Null= IsNull(MyVar)        ' Returns True.

The following example uses the IsNull function to determine whether the value of a control object is Null. If it is, a message prompts the user to enter data. If the value is not Null, a message displays the value of the control object.

Sub ControlValue(ctlText As Control)
    Dim strMsg As String, strCRLF As String

    strCRLF = Chr(13) & Chr(10)
    ' Check that control is text box.
    If ctlText.ControlType = acTextBox Then
        ' If value of control is Null, prompt for data.
        If IsNull(ctlText.Value) Then
            strMsg = "No data in the field '" & ctlText.Name & "'." _
                    & strCRLF & "Please enter data for this field now."
                If MsgBox(strMsg, vbQuestion) = vbOK Then
                    Exit Function
                End If
        ' If value is not Null, display value.
        Else
            MsgBox (ctlText.Value)
        End If
    End IfSub


IsNumeric Function

Description

Returns a Boolean value indicating whether an expression can be evaluated as a number.

Syntax

IsNumeric(expression)

The expression argument can be any numeric or string expression.

Remarks

IsNumeric returns True if the entire expression is recognized as a number; otherwise, it returns False.

IsNumeric returns False if expression is a date expression.

See Also

IsArray Function, IsDate Function, IsEmpty Function, IsError Function, IsMissing Function, IsNull Function, IsObject Function, TypeName Function, Variant Data Type, VarType Function.

Example

This example uses the IsNumeric function to determine if a variable can be evaluated as a number.

MyVar = "53"    ' Assign value.= IsNumeric(MyVar)            ' Returns True.= "459.95"                        ' Assign value.= IsNumeric(MyVar)            ' Returns True.= "45 Help"                    ' Assign value.= IsNumeric(MyVar)            ' Returns False.


IsObject Function

Description

Returns a Boolean value indicating whether an expression references a valid OLE Automation object.

Syntax

IsObject(expression)

The expression argument can be any expression.

Remarks

IsObject returns True if expression is a variable of Object type (or a Variant of VarType vbObject, or a user-defined object); otherwise, it returns False.

See Also

IsArray Function, IsDate Function, IsEmpty Function, IsError Function, IsMissing Function, IsNull Function, IsNumeric Function, Object Data Type, Set Statement, TypeName Function, Variant Data Type, VarType Function.

Example

This example uses the IsObject function to determine if a variable references a valid object. MyObject and YourObject are object variables of the same type. They are generic names used for illustration purposes only.

Dim MyInt As Integer                ' Declare variables.MyObject As ObjectYourObject = MyObject        ' Assign an object reference.= IsObject(YourObject)    ' Returns True.= IsObject(MyInt)        ' Returns False.

The following example uses the IsObject function to check whether an argument passed to the function is an object.

Sub CheckObject(varAny As Variant)
    Dim varX as Variant
    If IsObject(varAny) Then
        Set varX = varAny
    Else
        varX = varAny
    End IfSub


Item Method

Applies To

Collection Object.

Description

Returns a specific member of a Collection object either by position or by key.

Syntax

object.Item(index)

The Item method syntax has the following object qualifier and part:

Part | Description
object | Required. An object expression that evaluates to an object in the Applies To list.
index | Required. An expression that specifies the position of a member of the collection. If a numeric expression, index must be a number from 1 to the value of the collection’s Count property. If a string expression, index must correspond to the key specified when the member being referred to was added to the collection.

Remarks

If the value provided as index does not match any existing member of the collection, an error occurs.

The Item method is the default method for a collection. Therefore, the following lines of code are equivalent:

Print MyCollection(1)MyCollection.Item(1)

See Also

Add Method, Remove Method.

Example

This example uses the Item method to retrieve a reference to an object in a collection. Assuming Birthdays is a Collection object, the following code retrieves from the collection references to the objects representing Bill Smith’s and Adam Smith’s birthdays, using the keys “SmithBill” and “SmithAdam” as the index arguments. Note that the first call explicitly specifies the Item method, but the second does not. Both calls work because the Item method is the default for a Collection object. The references, assigned to SmithBillBD and SmithAdamBD (using Set), can be used to access the properties and methods of the specified objects. To run this code, create the collection and populate it with at least the two referenced members.

Dim SmithBillBD As ObjectSmithAdamBD As ObjectSmithBillBD = Birthdays.Item("SmithBill")SmithAdamBD = Birthdays("SmithAdam")


Item Property

Applies To

Unbound Object Frame Control.

Description

You can use the Item property to get a description of the linked data displayed in a unbound object frame.

Setting

The Item property setting is a string expression and is read-only in all views.

Remarks

The description of a linked object frame depends on the kind of OLE object it is linked to. For example, if you link it to cells in a Microsoft Excel worksheet, Microsoft Access displays the cell data in the object frame, and the Item property identifies the linked cells using the row-and-column format. For a chart, the Item property setting is the word “Chart”. For a graphic, the setting is the coordinates of the linked graphic area.

Note The data for a linked OLE object is displayed in the frame but is stored by the application that created the data. To change the data, you must use that application.

When you link an OLE object to an object frame using the Paste Special command on the Edit menu, Microsoft Access sets the SourceObject, OLEClass, and Item properties. The following table shows typical property settings for various OLE objects.

Object | SourceObject property | OLEClass property | Item property
Worksheet | C:\Excel\Xls\Mywrksht.xls | Microsoft Excel Worksheet | R1C1:R7C4
Chart | C:\Excel\Xls\Mychart.xlc | Microsoft Excel Chart | Chart
Graphic | C:\Windows\Mybitmap.bmp | Paintbrush Picture | 0 0 72 71

See Also

Action Property, OLEType Property.


ItemData Method

Description

The ItemData method returns the data in the bound column for the specified row in a list box or combo box.

Syntax

control.ItemData(rowindex)

The ItemData method uses the following arguments.

Argument | Description
control | A Control object that represents a combo box or list box.
rowindex | The row in the combo box or list box containing the data you want to return. Rows in combo and list boxes are indexed starting with zero. For example, to return the item in the sixth row of a combo box, you’d specify 5 for rowindex.

Remarks

The ItemData method enables you to iterate through the list of entries in a combo box or list box. For example, suppose you wanted to iterate through all of the items in a list box to search for a particular entry. You can use the ListCount property to determine the number of rows in the list box, and then use the ItemData method to return the data for the bound column in each row.

You can also use the ItemData method to return data only from selected rows in a list box. You can iterate through the ItemsSelected collection to determine which row or rows in the list box have been selected, and use the ItemData method to return the data in those rows. You must set the MultiSelect property of the list box to Simple or Extended to enable the user to select more than one row at a time.

Tip You can use the Column property to return data from a specified row and column, even if the specified column is not the bound column.

See Also

BoundColumn Property, Control Object.

Example

The following example prints the value of the bound column for each selected row in a list box EmployeeList on an Employees form.

Sub RowsSelected()
    Dim ctlList As Control, varItem As Variant

    ' Return Control object variable pointing to list box.
    Set ctlList = Forms!Employees!EmployeeList
    ' Set MultiSelect property to Simple.
    ctlList.MultiSelect = 2
    ' Enumerate through selected items.
    For Each varItem in ctlList.ItemsSelected
        ' Print value of bound column.
        Debug.Print ctlList.ItemData(varItem)
    Next varItemSub


ItemsSelected Collection

Description

The ItemsSelected collection provides a way to access data in the selected rows of a list box or combo box.

Remarks

The ItemsSelected collection is unlike other collections in that it is a collection of Variants rather than of objects. Each Variant is an integer index referring to a selected row in a list box or combo box.

Use the ItemsSelected collection in conjunction with the Column property or the ItemData method to retrieve data from selected rows in a list box or combo box. You can enumerate the ItemsSelected collection using the For Each...Next statement.

For example, if you have an Employees list box on a form, you can enumerate the ItemsSelected collection and use the control’s ItemData method to return the value of the bound column for each selected row in the list box.

Tip To enable multiple selection of rows in a list box or combo box, set the control’s MultiSelect property to Simple or Extended.

The ItemsSelected collection has no methods and one property, the Count property.

Properties

Count Property (Microsoft Access).

See Also

For Each...Next Statement.

Example

The following example prints the value of the bound column for each selected row in a Names list box on a Contacts form. To try this example, create the list box and set its BoundColumn property as desired and its MultiSelect property to Simple or Extended. Switch to Form view, select several rows in the list box, and run the following code.

Sub BoundData()
    Dim frm As Form, ctl As Control
    Dim varItm As Variant

    Set frm = Forms!Contacts
    Set ctl = frm!Names
    For Each varItm In ctl.ItemsSelected
        Debug.Print ctl.ItemData(varItm)
    Next varItmSub

The next example uses the same list box control, but prints the values of each column for each selected row in the list box, instead of only the values in the bound column.

Sub AllSelectedData()
    Dim frm As Form, ctl As Control
    Dim varItm As Variant, intI As Integer

    Set frm = Forms!Contacts
    Set ctl = frm!Names
    For Each varItm In ctl.ItemsSelected
        For intI = 0 To ctl.ColumnCount - 1
            Debug.Print ctl.Column(intI, varItm)
        Next intI
        Debug.Print
    Next varItm
    End Sub


KeepTogether Property -- Groups

Applies To

Report, Sorting and Grouping Box.

Description

You can use the KeepTogether property in reports to keep parts of a group — including the group header, detail section, and group footer — together on the same page. For example, you might want a group header always to be printed on the same page with the first detail section.

Setting

The KeepTogether property uses the following settings.

Setting | Description | Visual Basic
No | (Default) Prints the group without keeping the group header, detail section, and group footer on the same page. | 0
Whole Group | Prints the group header, detail section, and group footer on the same page. | 1
With First Detail | Prints the group header on a page only if it can also print the first detail record. | 2

You can set the KeepTogether property in a report’s Sorting and Grouping box, a macro, or Visual Basic.

In Visual Basic, you set the KeepTogether property in Design view or the Open event procedure of a report using the GroupLevel property.

Remarks

To set the KeepTogether property to a value other than No, you must set the GroupHeader or GroupFooter property to Yes for the selected field or expression.

A group includes the group header, detail section, and group footer. If you set the KeepTogether property to Whole Group and a group is too large to fit on one page, Microsoft Access will ignore the setting for that group. Similarly, if you choose With First Detail and either the group header or detail record is too large to fit on one page, the setting will be ignored.

See Also

CreateGroupLevel Function; GroupHeader, GroupFooter Properties; GroupInterval Property; GroupLevel Property; GroupOn Property; KeepTogether Property — Sections; SortOrder Property.

Example

The following example sets the sort order and group properties for the first group level in the Products By Category report.

Sub Report_Open()
    ' Set SortOrder property to descending order.
    Reports![Products by Category].GroupLevel(0).SortOrder = True
    ' Set GroupOn property to Prefix Characters.
    Reports![Products by Category].GroupLevel(0).GroupOn = 1
    ' Set GroupInterval property to 1.
    Reports![Products by Category].GroupLevel(0).GroupInterval = 1
    ' Set KeepTogether property to With First Detail.
    Reports![Products by Category].GroupLevel(0).KeepTogether = 2Sub


KeepTogether Property -- Sections

Applies To

Form Section, Report Section.

Description

You can use the KeepTogether property to print a report section all on one page. For example, you might have a group of related information that you don’t want printed across two pages.

Note The KeepTogether property applies only to forms and reports sections (except page headers and page footers).

Setting

The KeepTogether property uses the following settings.

Setting | Description | Visual Basic
Yes | Microsoft Access starts printing the section at the top of the next page if it can’t print the entire section on the current page. | True (-1)
No | (Default) Microsoft Access prints as much of the section as possible on the current page and prints the rest on the next page. | False (0)

You can set this property using the section’s property sheet, a macro, or Visual Basic.

You can set the KeepTogether property only in report Design view.

Remarks

Usually, when a page break occurs while a section is being printed, Microsoft Access continues printing the section on the next page. Using the section’s KeepTogether property, you can print the section all on one page. If a section is longer than one page, Microsoft Access starts printing it on the next page and continues on the following page.

See Also

ForceNewPage Property, Format Event, KeepTogether Property — Groups.

Example

This example returns the KeepTogether property setting for the report’s detail section and assigns the value to the intGetVal variable.

Dim intGetVal As Integer= Me.Section(0).KeepTogether


KeyDown, KeyUp Events

Applies To

Bound Object Frame Control, Check Box Control, Combo Box Control, Command Button Control, Form, List Box Control, Option Button Control, Text Box Control, Toggle Button Control.

Description

These events occur:

  • KeyDown — When the user presses a key while a form or control has the focus. This event also occurs if you send a keystroke to a form or control using the SendKeys action in a macro or the SendKeys statement in Visual Basic.
  • KeyUp — When the user releases a key while a form or control has the focus. This event also occurs if you send a keystroke to a form or control using the SendKeys action in a macro or the SendKeys statement in Visual Basic.

Note The KeyDown and KeyUp events apply only to forms and controls on a form.

Remarks

For both events, the object with the focus receives all keystrokes. A form can have the focus only if it has no controls or all its visible controls are disabled.

A form will also receive all keyboard events, even those that occur for controls, if you set the KeyPreview property of the form to Yes. With this property setting, all keyboard events occur first for the form, and then for the control that has the focus. You can respond to specific keys pressed in the form, regardless of which control has the focus. For example, you may want the key combination CTRL+X to always perform the same action on a form.

If you press and hold down a key, the KeyDown event occurs repeatedly until you release the key, then the KeyUp event occurs.

Although the KeyDown and KeyUp events occur when most keys are pressed, they are typically used to recognize or distinguish between:

  • Extended character keys, such as function keys.
  • Navigation keys, such as HOME, END, PAGE UP, PAGE DOWN, UP ARROW, DOWN ARROW, RIGHT ARROW, LEFT ARROW, and TAB.
  • Combinations of keys and standard keyboard modifiers (SHIFT, CTRL, or ALT keys).
  • The numeric keypad and keyboard number keys.

The KeyDown and KeyUp events don’t occur when you press:

  • The ENTER key if the form has a command button for which the Default property is set to Yes.

The ESC key if the form has a command button for which the Cancel property is set to Yes.

Note To find out the ANSI character corresponding to the key pressed, use the KeyPress event.

The KeyDown and KeyPress events occur when you press or send an ANSI key. The KeyUp event occurs after any event for a control caused by pressing or sending the key. If a keystroke causes the focus to move from one control to another control, the KeyDown event occurs for the first control, while the KeyPress and KeyUp events occur for the second control.

See Also

Change Event; Enter, Exit Events; GotFocus, LostFocus Events; KeyPress Event; KeyPreview Property; NotInList Event; SendKeys Action; SendKeys Statement.


KeyDown, KeyUp Events -- Event Procedures

Description

To create an event procedure that is executed when the KeyDown or KeyUp event occurs, set the OnKeyDown or OnKeyUp property to [Event Procedure], and click the Build button.

Syntax

Private Sub Form_KeyDown(KeyCode As Integer, Shift As Integer)Private Sub controlname_KeyDown(KeyCode As Integer, Shift As Integer)Private Sub Form_KeyUp(KeyCode As Integer, Shift As Integer)

Private Sub controlname_KeyUp(KeyCode As Integer, Shift As Integer)

Remarks

The KeyDown and KeyUp events use the following arguments.

Argument | Description
controlname | A string that is the name of the control affected by the KeyDown and KeyUp event procedures.
KeyCode | A key code, such as vbKeyF1 (the F1 key) and vbKeyHome (the HOME key). To specify key codes, use the intrinsic constants in the Object Browser. You can prevent an object from receiving a keystroke by setting KeyCode to 0.
Shift | The state of the SHIFT, CTRL, and ALT keys at the time of the event. If you need to test for the Shift argument, you can use one of the following intrinsic constants as bit masks: Constant Description acShiftMask Bit mask for the SHIFT key. acCtrlMask Bit mask for the CTRL key. acAltMask Bit mask for the ALT key.

You test for a condition by first assigning each result to a temporary Integer variable and then comparing the Shift argument to an intrinsic constant. Use the And operator with the Shift argument to test whether the condition is greater than 0, indicating that the SHIFT, CTRL, or ALT key was pressed, as in the following example.

ShiftDown = (Shift And acShiftMask) > 0

In an event procedure, you can test for any combination of conditions, as in the following example.

If ShiftDown And CtrlDown Then
.    ' Do this if SHIFT and CTRL keys are pressed.
.
.

You can use the KeyDown and KeyUp event procedures to interpret the uppercase and lowercase version of each character by testing for both the KeyCode argument and the Shift argument. The KeyCode argument indicates the physical key pressed (thus, A and a are considered the same key), and the Shift argument indicates the state of SHIFT+key and returns either A or a.

Use the KeyDown and KeyUp event procedures for keyboard handlers if you need to respond to both the pressing and releasing of a key.

You can respond to specific keys pressed in a form, regardless of which control has the focus. For example, you may want the key combination CTRL+X to always perform the same action on a form. To make sure a form receives all keyboard events, even those that occur for controls, before they occur for the controls, set the KeyPreview property of the form to Yes. With this property setting, all keyboard events occur first for the form, and then for the control that has the focus. You can respond to specific keystrokes in the form’s KeyDown, KeyPress and KeyUp events. You can prevent a control from receiving keystrokes you’ve responded to, and prevent the keyboard events from occurring for the control, by setting the KeyCode argument to 0 for both the KeyDown and KeyUp events, and setting the KeyAscii argument to 0 for the KeyPress event (if the key is an ANSI key). You must set all three arguments to 0 if you don’t want the control to receive the keystrokes.

You can use the arguments for the KeyDown, KeyPress, and KeyUp events, in conjunction with the arguments for the MouseDown, MouseUp, and MouseMove events, to make your application work smoothly for both keyboard and mouse users.

You can’t cancel the KeyDown or KeyUp event.

See Also

KeyDown, KeyUp Events — Macros.

Example

The following example determines whether you have pressed the SHIFT, CTRL, or ALT key.

To try this example, add the following code to the Declarations section of a module for a form containing a text box named KeyHandler.

Private Sub KeyHandler_KeyDown(KeyCode As Integer, Shift As Integer)
    Dim intShiftDown As Integer, intAltDown As Integer
    Dim intCtrlDown As Integer

    ' Use bit masks to determine which key was pressed.
    intShiftDown = (Shift And acShiftMask) > 0
    intAltDown = (Shift And acAltMask) > 0
    intCtrlDown = (Shift And acCtrlMask) > 0
    ' Display message telling user which key was pressed.
    If intShiftDown Then MsgBox "You pressed the SHIFT key."
    If intAltDown Then MsgBox "You pressed the ALT key."
    If intCtrlDown Then MsgBox "You pressed the CTRL key."Sub


KeyDown, KeyUp Events -- Macros

Description

To run a macro when the KeyDown or KeyUp event occurs, set the OnKeyDown or OnKeyUp property to the name of the macro.

Remarks

You can use a KeyDown or KeyUp macro to respond whenever the user presses or releases a key while a form or control has the focus. However, macros can’t return the key code and determine which key was pressed, so you typically use event procedures with this event.

You can’t use the CancelEvent action in a KeyDown or KeyUp macro.

See Also

KeyDown, KeyUp Events — Event Procedures.


KeyPress Event

Applies To

Bound Object Frame Control, Check Box Control, Combo Box Control, Command Button Control, Form, List Box Control, Option Button Control, Text Box Control, Toggle Button Control.

Description

The KeyPress event occurs when the user presses and releases a key or key combination that corresponds to an ANSI code while a form or control has the focus. This event also occurs if you send an ANSI keystroke to a form or control using the SendKeys action in a macro or the SendKeys statement in Visual Basic.

Note The KeyPress event applies only to forms and controls on a form.

Remarks

The object with the focus receives all keystrokes. A form can have the focus only if it has no controls or all its visible controls are disabled. A KeyPress event can involve any printable keyboard character, the CTRL key combined with a character from the standard alphabet or a special character, and the ENTER or BACKSPACE key.

A form will also receive all keyboard events, even those that occur for controls, if you set the KeyPreview property of the form to Yes. With this property setting, all keyboard events occur first for the form, and then for the control that has the focus. You can respond to specific keys pressed in the form, regardless of which control has the focus. For example, you may want the key combination CTRL+X to always perform the same action on a form.

If you press and hold down an ANSI key, the KeyDown and KeyPress events alternate repeatedly (KeyDown, KeyPress, KeyDown, KeyPress, and so on) until you release the key, then the KeyUp event occurs.

You can use the KeyDown and KeyUp event procedures to handle any keystroke not recognized by the KeyPress event, such as function keys, navigation keys, and any combinations of these with keyboard modifiers (ALT, SHIFT, or CTRL keys). Unlike the KeyDown and KeyUp events, the KeyPress event doesn’t indicate the physical state of the keyboard; instead, it indicates the ANSI character that corresponds to the pressed key or key combinations.

KeyPress interprets the uppercase and lowercase of each character as separate key codes and, therefore, as two separate characters.

The KeyDown and KeyPress events occur when you press or send an ANSI key. The KeyUp event occurs after any event for a control caused by pressing or sending the key. If a keystroke causes the focus to move from one control to another control, the KeyDown event occurs for the first control, while the KeyPress and KeyUp events occur for the second control.

For example, if you go to a new record and type a character in the first control in the record, the following events occur:

Current (for the new record)

?

Enter (for the first control in the new record)

GotFocus (for the control)

KeyDown (for the control)

KeyPress (for the control)

BeforeInsert (for the new record in the form)

Change (for the control if it’s a text box or combo box)

KeyUp (for the control)

Note The BACKSPACE key is part of the ANSI character set, but the DEL key isn’t. If you delete a character in a control using the BACKSPACE key, you cause a KeyPress event; if you use the DEL key, you don’t.

See Also

Asc Function; Change Event; Chr Function; Enter, Exit Events; GotFocus, LostFocus Events; KeyDown, KeyUp Events; KeyPreview Property; NotInList Event; SendKeys Action; SendKeys Statement.


KeyPress Event -- Event Procedures

Description

To create an event procedure that is executed when the KeyPress event occurs, set the OnKeyPress property to [Event Procedure], and click the Build button.

Syntax

Private Sub Form_KeyPress(KeyAscii As Integer)Private Sub controlname_KeyPress(KeyAscii As Integer)

The KeyPress event uses the following arguments.

Argument | Description
controlname | A string that is the name of the control affected by the KeyPress event procedure.
KeyAscii | Returns a numeric ANSI key code. The KeyAscii argument is passed by reference; changing it sends a different character to the object. Changing the KeyAscii argument to 0 cancels the keystroke so that the object doesn’t recognize that a key was pressed.

Remarks

A KeyPress event procedure is useful for intercepting keystrokes entered in a text box or combo box. It enables you to test keystrokes for validity or to format characters as they’re typed. Changing the value of the KeyAscii argument changes the character displayed.

You can convert the KeyAscii argument to a character by using the following expression.

Chr(KeyAscii)

You can then perform string operations and translate the character back to an ANSI number that the control can recognize by using the following syntax.

KeyAscii = Asc(character)

Note The ANSI number for the keyboard combination CTRL+@ is 0. Because Microsoft Access recognizes a KeyAscii value of 0 as a zero-length string (" "), you should avoid using CTRL+@ in your applications.

You can respond to specific keys pressed while a form is open, regardless of which control has the focus. For example, you may want the key combination CTRL+X to always perform the same action on a form. To make sure a form receives all keyboard events, even those that occur for controls, before they occur for the controls, set the KeyPreview property of the form to Yes. With this property setting, all keyboard events occur first for the form, and then for the control that has the focus. You can respond to specific keystrokes in the form’s KeyDown, KeyPress, and KeyUp events. You can prevent a control from receiving keystrokes you’ve responded to, and prevent the keyboard events from occurring for the control, by setting the KeyCode argument to 0 for both the KeyDown and KeyUp events, and setting the KeyAscii argument to 0 for the KeyPress event. You must set all three arguments to 0 if you don’t want the control to receive the keystrokes.

You can use the arguments for the KeyDown, KeyPress, and KeyUp events, in conjunction with the arguments for the MouseDown, MouseUp, and MouseMove events, to make your application work smoothly for both keyboard and mouse users.

You can’t cancel the KeyPress event in an event procedure, but you can cancel it in a macro.

See Also

Key Press Event — Macros.

Example

The following example converts text entered in a text box to uppercase as the text is typed in, one character at a time.

To try this example, add the following code to the Declarations section of a module for a form that contains a text box named ShipRegion.

Private Sub ShipRegion_KeyPress(KeyAscii As Integer)
    Dim strCharacter As String

    ' Convert ANSI value to character string.
    strCharacter = Chr(KeyAscii)
    ' Convert character to upper case, then to ANSI value.
    KeyAscii = Asc(UCase(strCharacter))Sub


KeyPress Event -- Macros

Description

To run a macro when the KeyPress event occurs, set the OnKeyPress property to the name of the macro.

Remarks

You can use a KeyPress macro to respond whenever the user presses an ANSI key while the focus is on a form or control. However, macros can’t return the ANSI key code and determine which key was pressed, so you typically use event procedures with this event.

You can use the CancelEvent action in a KeyPress macro to cancel the key or key combination. For example, you may want to disallow the entry of ANSI keystrokes in a control under certain conditions.

See Also

KeyPress Event — Event Procedures.


KeyPreview Property

Applies To

Form.

Description

You can use the KeyPreview property to specify whether form keyboard events are invoked before control keyboard events.

Note The keyboard events are KeyDown, KeyUp, and KeyPress.

Setting

The KeyPreview property uses the following settings.

Setting | Description | Visual Basic
No | (Default) Only the active control receives keyboard events. | False (0)

You can set the KeyPreview property in the form’s property sheet, a macro, or using Visual Basic.

You can set the KeyPreview property in any view.

Remarks

You can use the KeyPreview property to create a keyboard-handling procedure for a form. For example, when an application uses function keys, setting the KeyPreview property to True allows you to process keystrokes at the form level rather than writing code for each control that might receive keystroke events.

To handle keyboard events only at the form level and prevent controls from receiving keyboard events, set KeyAscii to 0 in the form’s KeyPress event, and set KeyCode to 0 in the form’s KeyDown and KeyUp events.

If a form has no visible or enabled controls, it automatically receives all keyboard events.

See Also

KeyDown, KeyUp Events; KeyPress Event.

Example

In the following example the KeyPreview property is set to True in the form’s load event. This causes the form to receive keyboard events before they are received by any control. The form KeyDown event then examines the KeyCode value to determine if the F2, F3, or F4 keys were pushed.

Private Sub Form_Load()
    Me.KeyPreview = TrueSub
Sub Form_KeyDown(KeyCode As Integer, Shift As Integer)
    Const conKey_F2 = &H71        ' F2 Key constant
    Const conKey_F3 = &H72        ' F3 Key constant
    Const conKey_F4 = &H73        ' F4 Key constant

    Select Case KeyCode
        Case conKey_F2
            ' Process F2 key events
        Case conKey_F3
            ' Process F3 key events
        Case conKey_F4
            ' Process F4 key events
        Case Else
    End SelectSub


KeyUp Event

See KeyDown, KeyUp Events.


Kill Statement

Description

Deletes files from a disk.

Syntax

Kill pathname

The pathname argument is a string expression that specifies one or more filenames to be deleted. The pathname may include the directory or folder, and the drive.

Remarks

In Microsoft Windows, Kill supports the use of * (multiple character) and ? (single character) wildcards to specify multiple files.

An error also occurs if you try to use Kill to delete an open file.

To delete directories, use the RmDir statement.

See Also

RmDir Statement.

Example

This example uses the Kill statement to delete a file from a disk.

' Assume TESTFILE is a file containing some data."TestFile"    ' Delete file.
' In Microsoft Windows:
' Delete all *.TXT files in current directory."*.TXT"


LabelAlign, TextAlign Properties

Applies To

  • LabelAlign — Bound Object Frame Control, Check Box Control, Combo Box Control, Command Button Control, List Box Control, Option Button Control, Option Group Control, Subform/Subreport Control, Text Box Control, Toggle Button Control.
  • TextAlign — Combo Box Control, Command Button Control, Label Control, Text Box Control.

Description

  • LabelAlign — You can use this property to specify the text alignment within attached labels on new controls.
  • TextAlign — You can use this property to specify the text alignment in new controls.

Setting

The LabelAlign property uses the following settings.

Setting | Description
General | (Default) Label text aligns to the left.
Left | Data aligns to the left.
Center | Data is centered.
Right | Data aligns to the right.

You can set the LabelAlign property only in the default control style.

The TextAlign property uses the following settings.

Setting | Description | Visual Basic
General | (Default) Text aligns to the left; numbers and dates align to the right. | 0
Left | Data aligns to the left. | 1
Center | Data is centered. | 2
Right | Data aligns to the right. | 3

You can set the TextAlign property in the control’s property sheet, a macro, or Visual Basic.

You can also set the TextAlign property using the Formatting toolbar.

Remarks

When created, controls have an attached label. Changes to this default control property setting affect only controls created on the current form or report.

See Also

AddColon, AutoLabel Properties; LabelX, LabelY Properties.


LabelX, LabelY Properties

Applies To

Bound Object Frame Control, Check Box Control, Combo Box Control, Command Button Control, List Box Control, Option Button Control, Option Group Control, Subform/Subreport Control, Text Box Control, Toggle Button Control.

Description

You can use the LabelX and LabelY properties to change the placement of labels attached to new controls. For example, you might want an attached label to appear to the right of a control instead of to the left.

Setting

Enter a positive or negative number that specifies the distance of label text from the upper-left corner of the label’s attached control. To use a unit of measurement different from the setting in the Regional Settings section of the Windows Control Panel, specify the unit, such as cm or in (for example, 2 cm or 1.5 in).

You can set the default for these properties using a control’s default control style.

Remarks

The LabelX property sets the distance on the horizontal axis and the LabelY property sets the distance on the vertical axis. A negative number for the LabelX property places the label’s upper-left corner to the left of the control. A negative number for the LabelY property places the label’s upper-left corner above the control. Positive numbers for both properties place the label to the right and below the upper-left corner of the control.

If the LabelAlign property is set to Right or Left, the LabelX and LabelY properties specify the distance between the right or left edge of the label and the control’s upper-left corner. If the LabelAlign property is set to Center, the LabelX and LabelY properties specify the distance between the center of the label and the control’s upper-left corner.

Combining the LabelX, LabelY, and LabelAlign properties produces the following results.

LabelX | LabelY | LabelAlign | Result
-1 in | 0 in | General | The label’s upper-left corner is 1 inch to the left of the control’s upper-left corner.
-.5 in | 0 in | Right | The label’s upper-right corner is 0.5 inch to the left of the control’s upper-left corner.
.5 in | -.5 in | Center | The center of the top of the label is 0.5 inch to the right and 0.5 inch above the control’s upper-left corner.

See Also

AddColon, AutoLabel Properties; LabelAlign, TextAlign Properties.


LastDLLError Property

Applies To

Err Object.

Description

Returns a system error code produced by a call into a dynamic-link library (DLL). Occurs only on 32-bit Microsoft Windows operating systems.

Syntax

object.LastDLLError

The LastDLLError property syntax has these parts:

Part | Description
object | Always the Err object.

Remarks

The LastDLLError property is relevant only to 32-bit Windows systems. It applies only to DLL calls that require a Declare statement within the Visual Basic code. When such a call is made, the called function usually returns a code indicating success or failure, and the LastDLLError property is filled. Check the documentation for the DLL’s functions to determine what return values indicate success or failure. Whenever the failure code is returned, the Visual Basic application should immediately check the LastDLLError property. No exception is raised when the LastDLLError property is set.

See Also

Declare Statement, Description Property, Err Object, HelpContext Property (Visual Basic), HelpFile Property (Visual Basic), Number Property, Source Property.


LayoutForPrint Property

Applies To

Form, Report.

Description

You can use the LayoutForPrint property to specify whether the form or report uses printer or screen fonts.

Setting

The LayoutForPrint property uses the following settings.

Setting | Description | Visual Basic
Yes | (Default for reports) Use printer fonts. | True (-1)
No | (Default for forms) Use screen fonts. | False (0)

The property can be set only in form Design view and report Design view.

Remarks

When you choose a font in Microsoft Access, you are choosing either a screen font or a printer font, depending on the setting of the LayoutForPrint property. Remember that printer fonts and screen fonts can differ, and characters on screen may not look exactly like those displayed on the printed page.

Tip If you select a scalable font, such as a TrueType® font, the screen and printer characters will look nearly the same.

Screen fonts are the images of letters, numbers, and symbols displayed on the screen. The screen fonts Microsoft Access uses are those that were installed when you installed Windows. If you installed a printer, additional screen fonts may have been installed automatically. You may also have added more screen fonts on your own.

Printer fonts are the letters, numbers, and symbols that are produced when you print a report or a form. The available fonts depend on your printer.

If you set the LayoutForPrint setting to Yes, the Formatting toolbar displays the fonts and point sizes available for your printer.

If you design a form or report on a system with a different printer than the one you will use to print, Microsoft Access displays a message to let you know that the form or report was designed for another kind of printer. If you print the form or report anyway, your printer may substitute different fonts. You can reselect the font for each control to specify the appearance of the form or report.

See Also

FontName, FontSize Properties.


LBound Function

Description

Returns the smallest available subscript for the indicated dimension of an array.

Syntax

LBound(arrayname[, dimension])

The LBound function syntax has these parts:

Part | Description
arrayname | Name of the array variable; follows standard variable naming conventions.
dimension | Whole number indicating which dimension’s lower bound is returned. Use 1 for the first dimension, 2 for the second, and so on. If dimension is omitted, 1 is assumed.

Remarks

The LBound function is used with the UBound function to determine the size of an array. Use the UBound function to find the upper limit of an array dimension.

LBound returns the values listed in the table below for an array with the following dimensions:

Dim A(1 To 100, 0 To 3, -3 To 4)

Statement | Return Value
LBound(A, 1) | 1
LBound(A, 2) | 0
LBound(A, 3) | -3

The default lower bound for any dimension is either 0 or 1, depending on the setting of the Option Base statement.

Arrays for which dimensions are set using the To clause in a Dim, Private, Public, ReDim, or Static statement can have any integer value as a lower bound.

See Also

Dim Statement, Option Base Statement, Private Statement, Public Statement, ReDim Statement, Static Statement, UBound Function.

Example

This example uses the LBound function to determine the smallest available subscript for the indicated dimension of an array. Use the Option Base statement to override the default base array subscript value of 0.

Dim MyArray(1 To 10, 5 To 15, 10 To 20)     ' Declare array variables.AnyArray(10)= LBound(MyArray, 1)             ' Returns 1.= LBound(MyArray, 3)            ' Returns 10.= LBound(AnyArray)                ' Returns 0 or 1, depending on
                                    ' setting of Option Base.


LCase Function

Description

Returns a string that has been converted to lowercase.

Syntax

LCase(string)

The string argument is any valid string expression. If string contains Null, Null is returned.

Remarks

Only uppercase letters are converted to lowercase; all lowercase letters and nonletter characters remain unchanged.

See Also

UCase Function.

Example

This example uses the LCase function to return a lowercase version of a string.

Uppercase = "Hello World 1234"        ' String to convert.= LCase(UpperCase)            ' Returns "hello world 1234".


Left Function

Description

Returns a specified number of characters from the left side of a string.

Syntax

Left(string, length)

The Left function syntax has these named arguments:

Part | Description
string | String expression from which the leftmost characters are returned. If string contains Null, Null is returned.
length | Numeric expression indicating how many characters to return. If 0, a zero-length string is returned. If greater than or equal to the number of characters in string, the entire string is returned.

Remarks

To determine the number of characters in string, use the Len function.

Note Another function (LeftB) is provided for use with byte data contained in a string. Instead of specifying the number of characters to return, length specifies the number of bytes.

See Also

Len Function, Mid Function, Right Function.

Example

This example uses the Left function to return a specified number of characters from the left side of a string.

AnyString = "Hello World"        ' Define string.= Left(AnyString, 1)        ' Returns "H".= Left(AnyString, 7)        ' Returns "Hello W".= Left(AnyString, 20)        ' Returns "Hello World".


Left, Top Properties

Applies To

Bound Object Frame Control, Chart Control, Check Box Control, Combo Box Control, Command Button Control, Image Control, Label Control, Line Control, List Box Control, Option Button Control, Option Group Control, Page Break Control, Rectangle Control, Subform/Subreport Control, Text Box Control, Toggle Button Control, Unbound Object Frame Control.

Description

You can use the Left and Top properties to specify an object’s location on a form or report. For example, you might want a control to be always aligned at the upper-right corner of a section.

Setting

A control’s location is the distance measured from its left or top border to the left or top edge of the section containing the control. Setting the Left or Top property to 0 places the control’s edge at the very left or top of the section. To use a unit of measurement different from the setting in the Regional Settings section of the Windows Control Panel, specify the unit, such as cm or in (for example, 3 cm or 2 in).

In Visual Basic, use a numeric expression to set the value of this property. Values are expressed in twips.

For controls, you can set these properties using control’s property sheet, a macro, or Visual Basic.

For reports, you can set these properties only in an event procedure while the report is in the Print Preview window or being printed.

Remarks

When you move a control, its new Left and Top property settings are automatically entered in the property sheet. When you view a form or report in Print Preview or when you print a form, a control’s location is determined by its Left and Top property settings along with the margin settings in the Print Setup dialog box.

For reports, the Top property setting is the amount the current section is offset from the top of the page; the Left property setting is the amount the current section is offset from the left edge of the page. Both property settings are expressed in twips. You can use these properties to specify how far down the page you want a section to print in the section’s Format event procedure.

Note To set the bottom and right margins, use the Height and Width properties.

See Also

Height, Width Properties.

Example

The following example checks the Left property setting for the current report. If the value is less than the minimum margin setting, the intNextRecord and intPrintSection variables are set to False (0).

Sub Detail1_Format(Cancel As Integer, FormatCount As Integer)conLeftMargin = 1880intNextRecord As Integer, intPrintSection As Integer
' Don't advance to next record or print next section
' if Left property setting is more than 1880 twips.
    If Me.Left < conLeftMargin Then
        intNextRecord = False
        intPrintSection = False
    End IfSub


Len Function

Description

Returns the number of characters in a string or the number of bytes required to store a variable.

Syntax

Len(string | varname)

The Len function syntax has these parts:

Part | Description
string | Any valid string expression. If string contains Null, Null is returned.
varname | Any valid variable name. If varname contains Null, Null is returned. If varname is a Variant, Len treats it the same as a String and always returns the number of characters it contains.

Caution Len may not be able to determine the actual number of storage bytes required when used with user-defined data types.

Note Another function (LenB) is provided for use with byte data contained in a string. Instead of returning the number of characters in a string, LenB returns the number of bytes used to represent that string.

See Also

Data Type Summary, InStr Function.

Example

This example uses the Len function to return the number of characters in a string or the number of bytes required to store a variable. The Type...End Type block defining CustomerRecord must be preceded by the keyword Private if it appears in a Class module. In a standard module, a Type statement can be Public. To create a standard Module, choose Module from the Insert menu (your host application may differ, for example in Microsoft Excel, select Macro from the Insert menu and then choose Module).

Type CustomerRecord                    ' Define user-defined type.
    ID As Integer                    ' Place this definition in a
    Name As String * 10                ' standard module.
    Address As String * 30Type
Customer As CustomerRecord        ' Declare variables.MyInt As Integer, MyCur As Currency= "Hello World"                ' Initialize variable.= Len(MyInt)                    ' Returns 2.= Len(Customer)                ' Returns 42.= Len(MyString)                ' Returns 11.= Len(MyCur)                    ' Returns 8.


Let Statement

Description

Assigns the value of an expression to a variable or property.

Syntax

[Let] varname = expression

The Let statement syntax has these parts:

Part | Description
varname | Name of the variable or property; follows standard variable naming conventions.
expression | Value assigned to the variable or property.

Remarks

To simplify Visual Basic code, the optional Let keyword is most often omitted.

A value expression can be assigned to a variable or property only if it is of a data type that is compatible with the variable. You can’t assign string expressions to numeric variables, and you can’t assign numeric expressions to string variables. If you do, an error occurs at compile time.

Variant variables can be assigned either string or numeric expressions. However, the reverse is not always true. Any Variant except a Null can be assigned to a string variable, but only a Variant whose value can be interpreted as a number can be assigned to a numeric variable. Use the IsNumeric function to determine if the Variant can be converted to a number.

Caution Assigning an expression of one numeric data type to a variable of a different numeric data type coerces the value of the expression into the data type of the resulting variable.

Let statements can be used to assign one record variable to another only when both variables are of the same user-defined type. Use the LSet statement to assign record variables of different user-defined types. Use the Set statement to assign object references to variables.

See Also

Const Statement, Data Type Summary, IsNumeric Function, LSet Statement, Set Statement, Variant Data Type.

Example

This example assigns the values of expressions to variables using both the explicit and implicit Let statement.

' The following variable assignments use the Let statement.MyStr = "Hello World"MyInt = 5

The following are the same assignments without the Let statement.

MyStr = "Hello World"= 5


Like Operator

Description

Used to compare two strings.

Syntax

result = string Like pattern

The Like operator syntax has these parts:

Part | Description
result | Any numeric variable.
string | Any string expression.
pattern | Any string expression conforming to the pattern-matching conventions described in Remarks.

Remarks

If string matches pattern, result is True; if there is no match, result is False; and if either string or pattern is Null, result is also Null.

The behavior of the Like operator depends on the Option Compare statement. Unless otherwise specified, the default string-comparison method for each module is Option Compare Binary.

Option Compare Binary results in string comparisons based on a sort order derived from the internal binary representations of the characters. Sort order is determined by the code page. In the following example, a typical binary sort order is shown:

A < B < E < Z < a < b < e < z < À < Ê < Ø < à < ê < ø

Option Compare Text results in string comparisons based on a case-insensitive textual sort order determined by your system’s locale. The same characters shown above, when sorted using Option Compare Text, produce the following text sort order:

(A=a) < (À=à) < (B=b) < (E=e) < (Ê=ê) < (Z=z) < (Ø=ø)

Built-in pattern matching provides a versatile tool for string comparisons. The pattern-matching features allow you to use wildcard characters, character lists, or character ranges, in any combination, to match strings. The following table shows the characters allowed in pattern and what they match:

Character(s) in pattern | Matches in string
? | Any single character.
* | Zero or more characters.
# | Any single digit (0 – 9).
[charlist] | Any single character in charlist.
[!charlist] | Any single character not in charlist.

A group of one or more characters (charlist) enclosed in brackets ([ ]) can be used to match any single character in string and can include almost any character code, including digits.

Note The special characters left bracket ([), question mark (?), number sign (#), and asterisk (*) can be used to match themselves directly only by enclosing them in brackets. The right bracket (]) can’t be used within a group to match itself, but it can be used outside a group as an individual character.

In addition to a simple list of characters enclosed in brackets, charlist can specify a range of characters by using a hyphen (-) to separate the upper and lower bounds of the range. For example, [A-Z] in pattern results in a match if the corresponding character position in string contains any of the uppercase letters in the range A through Z. Multiple ranges are included within the brackets without any delimiters.

The meaning of a specified range depends on the character ordering valid at run time (as determined by Option Compare and the locale setting of the system the code is running on). Using the same example shown above with Option Compare Binary, the range [A–E] matches A, B and E. With Option Compare Text, [A–E] matches A, a, À, à, B, b, E, e. Note that it does not match Ê or ê because accented characters fall after unaccented characters in the sort order.

Other important rules for pattern matching include the following:

  • An exclamation point (!) at the beginning of charlist means that a match is made if any character except the ones in charlist is found in string. When used outside brackets, the exclamation point matches itself.
  • The hyphen (-) can appear either at the beginning (after an exclamation point if one is used) or at the end of charlist to match itself. In any other location, the hyphen is used to identify a range of characters.
  • When a range of characters is specified, they must appear in ascending sort order (from lowest to highest). [A-Z] is a valid pattern, but [Z-A] is not.
  • The character sequence [] is ignored; it is considered a zero-length string.

In some languages, there are special characters in the alphabet that actually represent two separate characters. For example, several languages use the character “æ” to represent the characters “a” and “e” when they appear together. The Like operator recognizes that the single special character and the two individual characters are equivalent.

When a language that uses one of these special characters is specified in the system locale settings, an occurrence of the single special character in either pattern or string matches the equivalent 2-character sequence in the other string. Similarly, a single special character in pattern enclosed in brackets (by itself, in a list, or in a range) matches the equivalent 2-character sequence in string.

See Also

Comparison Operators, InStr Function, Operator Precedence, Option Compare Statement, StrComp Function.

Example

This example uses the Like operator to compare a string to a pattern.

MyCheck = "aBBBa" Like "a*a"                ' Returns True.= "F" Like "[A-Z]"                ' Returns True.= "F" Like "[!A-Z]"                ' Returns False.= "a2a" Like "a#a"                ' Returns True.= "aM5b" Like "a[L-P]#[!c-e]"    ' Returns True.= "BAT123khg" Like "B?T*"        ' Returns True.= "CAT123khg" Like "B?T*"        ' Returns False.


LimitToList Property

Applies To

Combo Box Control, Table Fields.

Description

You can use the LimitToList property to limit a combo box’s values to the listed items.

Setting

The LimitToList property has the following settings.

Setting | Description | Visual Basic
Yes | If the user selects an item from the list in the combo box or enters text that matches a listed item, Microsoft Access accepts it. Entered text that doesn’t match a listed item isn’t accepted. The user must retype the entry, select a listed item, press ESC, or click Undo on the Edit menu. | True (-1)
No | (Default) Microsoft Access accepts any text that conforms to the ValidationRule property. | False (0)

You can set the LimitToList property in the combo box’s property sheet, a macro, or Visual Basic.

For table fields, you can set this property in table Design view for fields with the DisplayControl property set to Combo Box or List Box.

Note Microsoft Access sets this property automatically when you select Lookup Wizard as the data type for a field in table Design view.

Remarks

When the LimitToList property of a bound combo box is set to No, you can enter a value in the combo box that isn’t included in the list. Microsoft Access stores the new value in the form’s underlying table or query, not the table or query set for the combo box by the RowSource property. To have newly entered values appear in the combo box, you must add the new value to the table or query set in the RowSource property using a macro or Visual Basic event procedure.

Setting both the LimitToList property and the AutoExpand property to Yes lets Microsoft Access find matching values from the list as the user enters characters in the text box portion of the combo box.. When the LimitToList property is set to Yes and the user enters a combo box initialized with a non-Null value, Microsoft Access will not allow the user to exit the combo box without having made a selection. If the combo box is initialized with a Null value, the user may make a selection, clear that selection and exit the control leaving a Null value.

Note If you set the combo box’s BoundColumn property to any column other than the first visible column, then the LimitToList property is automatically set to Yes.

See Also

NotInList Event.


Line Input # Statement

Description

Reads a line from an open sequential file and assigns it to a string variable.

Syntax

Line Input #filenumber, varname

The Line Input # statement syntax has these parts:

Part | Description
filenumber | Any valid file number.
varname | Valid string variable name.

Remarks

The Line Input # statement reads from a file one character at a time until it encounters a carriage return (Chr(13)) or carriage return-linefeed (Chr(13) + Chr(10)) sequence. Carriage return-linefeed sequences are skipped rather than appended to the character string.

See Also

Chr Function, Input # Statement.

Example

This example uses the Line Input # statement to read a line from a sequential file and assign it to a variable. This example assumes that TESTFILE is a text file with a few lines of sample data.

Open "TESTFILE" For Input As #1            ' Open file.While Not EOF(1)                        ' Loop until end of file.
    Line Input #1, TextLine                ' Read line into variable.
    Debug.Print TextLine                    ' Print to Debug window.#1                                    ' Close file.


Line Method

Applies To

Report Object.

The Line method draws lines and rectangles on a Report object when the Print event occurs.

Syntax

object.Line [[Step](x1, y1)] - [Step](x2, y2)[, [color][, B[F]]]

You can use this method only in an event procedure or a macro specified by the event properties OnPrint or OnFormat for a report section, or OnPage for a report.

The Line method uses the following arguments.

Argument | Description
object | The Report object on which the line or rectangle is to be drawn.
Step | A key word that indicates the starting point coordinates are relative to the current graphics position given by the settings for the CurrentX and CurrentY properties of object.
x1, y1 | Single values indicating the coordinates of the starting point for the line or rectangle. The Scale properties (ScaleMode, ScaleLeft, ScaleTop, ScaleHeight, and ScaleWidth) of object determine the unit of measure used. If this argument is omitted, the line begins at the position indicated by the CurrentX and CurrentY properties.
Step | A key word that indicates the end-point coordinates are relative to the line’s starting point.
x2, y2 | Single values indicating the coordinates of the end point for the line to draw. These coordinates are required.

Argument | Description
color | A Long value indicating the RGB (red-green-blue) color used to draw the line. If this argument is omitted, the ForeColor property is used. You can also use the RGB function or QBColor function to specify the color.
B | An option that creates a rectangle using the coordinates as opposite corners of the rectangle.
F | F cannot be used without B. If the B option is used, the F option specifies that the rectangle is filled with the same color used to draw the rectangle. If B is used without F, the rectangle is filled with the color specified by the current settings of the FillColor and BackStyle properties. The default value for the BackStyle property is Normal for rectangles and lines.

Remarks

To connect two drawing lines, make sure that one line begins at the end point of the previous line.

The width of the line drawn depends on the DrawWidth property setting. The way a line or rectangle is drawn on the background depends on the settings of the DrawMode and DrawStyle properties.

When you apply the Line method, the CurrentX and CurrentY properties are set to the end point specified by the x2 and y2 arguments.

See Also

Current X, Current Y Properties; DrawMode Property; DrawStyle Property; DrawWidth Property; Event Property; FillColor Property; FillStyle Property; ForeColor Property; Print Event; QBColor Function; RGB Function; ScaleHeight, ScaleWidth Properties; ScaleLeft, ScaleTop Properties; ScaleModel Property.

Example

The following example uses the Line method to draw a red rectangle five pixels inside the edge of a report named EmployeeReport. The RGB function is used to make the line red.

To try this example in Microsoft Access, create a new report by clicking the New button on the Reports tab of the Database window. Set the OnPrint property of the Detail section to [Event Procedure]. Enter the following code in the report’s module, then switch to Print Preview.

Sub DrawLine()
    Dim rpt As Report, intColor As Integer
    Dim sngTop As Single, sngLeft As Single
    Dim sngWidth As Single, sngHeight As Single

    Set rpt = Reports!EmployeeReport
    rpt.ScaleMode = 3                    ' Set scale to pixels.
    sngTop = rpt.ScaleTop + 5            ' Top inside edge.
    sngLeft = rpt.ScaleLeft + 5            ' Left inside edge.
    sngWidth = rpt.ScaleWidth - 10        ' Width inside edge.
    sngHeight = rpt.ScaleHeight - 10        ' Height inside edge.
    intColor = RGB(255,0,0)                ' Make color red.
    ' Draw line as a box.
    rpt.Line(sngTop, sngLeft) - (sngWidth, sngHeight), intColor, BSub


LineSlant Property

Applies To

Line Control.

Description

You use the LineSlant property to specify whether a line slants from upper left to lower right or from upper right to lower left.

Setting

The LineSlant property uses the following settings.

Setting | Description | Visual Basic
\ | (Default) Upper left to lower right | False (0)
/ | Upper right to lower left | True (-1)

You can set this property using the control’s property sheet, a macro, or Visual Basic.

Remarks

Use the LineSlant property to change a line’s direction. To position and size the line on your form or report, use the mouse.

See Also

Line Method.


LinkChildFields, LinkMasterFields Properties

Applies To

Chart Control, Subform/Subreport Control, Unbound Object Frame Control.

Description

You can use the LinkChildFields and LinkMasterFields properties together to specify how Microsoft Access links records in a form or report to records in a subform, subreport, or embedded object, such as a chart. If these properties are set, Microsoft Access automatically updates the related record in the subform when you change to a new record in a main form.

Setting

You can set the LinkChildFields and LinkMasterFields properties for the subform, subreport, or embedded object as follows:

  • LinkChildFields — Enter the name of one or more linking fields in the subform, subreport, or embedded object.
  • LinkMasterFields — Enter the name of one or more linking fields or controls in the main form or report.

You can use the Subform\Subreport Field Linker to set these properties by clicking the Build button to the right of the property in the property sheet.

You can also set these properties using a string expression in a macro or Visual Basic.

The properties can only be set in Design view or during the Open event of a form or report.

Remarks

The fields or controls you use to set these properties don’t need to have the same names, but they must contain the same kind of data and have the same or a compatible data type and field size. For example, an AutoNumber field is compatible with a Number field if the FieldSize property for the Number field is set to Long Integer.

You can use the name of a control (including the name of a calculated control) to set the LinkMasterFields property, but you can’t use the name of a control to set the LinkChildFields property. If you want to use a calculated value as the link for a subform, subreport, or embedded object, define a calculated field in the child object’s underlying query and set the LinkChildFields property to the field.

When you specify more than one field or control name for these property settings, you must enter the same number of fields or controls for each property setting and separate the names with a semicolon (;).

When you create a subform or subreport by dragging a form or report from the Database window onto another form or report or by using the Form Wizard, Microsoft Access automatically sets the LinkChildFields and LinkMasterFields properties under the following conditions:

  • Both the main form or report and the child object are based on tables, and a relationship has been defined with the Relationships command. Microsoft Access uses the fields that relate the two tables as the linking fields.
  • The main form or report is based on a table with a primary key, and the subform or subreport is based on a table or query that contains a field with the same name and the same or a compatible data type as the primary key. Microsoft Access uses the primary key from the main object’s underlying table and the identically named field from the child object’s underlying table or query as the linking fields.

Note The linking fields don’t have to be included in the main object or in the child object. As long as they are contained in the objects’ underlying tables or queries, you can use the fields to link the objects. When you use a wizard, Microsoft Access automatically includes the linking fields.


ListCount Property

Applies To

Combo Box Control, List Box Control.

Description

You can use the ListCount property to determine the number of rows in a list box or the list box portion of a combo box.

Setting

The ListCount property holds the number of rows in the list box or the list box portion of the combo box. The value of the ListCount property is read-only and can’t be set by the user.

This property is available only in Visual Basic. You can read this property only in Form view and Datasheet view.

Remarks

You can use the ListCount property with the ListRows property to specify how many rows you want to display in the list box portion of a combo box.

See Also

ListIndex Property, ListRows Property, ListWidth Property, Selected Property.

Example

This example uses the ListCount property to find the number of rows in the list box portion of the CustomerList combo box on a Customers form. It then sets the ListRows property to display a specified number of rows in the list.

Sub SizeCustomerList()
    Dim ListControl As Control
    Set ListControl = Forms![Customers]![CustomerList]
    If ListControl.ListCount < 8 Then
        ListControl.ListRows = ListControl.ListCount
    Else
        ListControl.ListRows = 8
    End IfSub


ListIndex Property

Applies To

Combo Box Control, List Box Control.

Description

You can use the ListIndex property to determine which item is selected in a list box or combo box.

Setting

The ListIndex property is an integer from 0 to the total number of items in a list box or combo box. Microsoft Access sets the ListIndex property value when an item is selected in a list box or list box portion of a combo box. The ListIndex property value of the first item in a list is 0, the value of the second item is 1, and so on.

This property is available only in Visual Basic. You can read this property in Form view and Datasheet view.

Remarks

The ListIndex property value is also available by setting the BoundColumn property to 0 for a combo box or list box. If the BoundColumn property is set to 0, the underlying table field to which the combo box or list box is bound will contain the same list index value as the ListIndex property.

List boxes also have a MultiSelect property that allows the user to select multiple items from the control. When multiple selections are made in a list box, you can determine which items are selected using the Selected property of the control. The Selected property is an array of values from 0 to the ListCount property value minus one. For each item in the list box the Selected property will be True (-1) if the item is selected and False (0) if it is not selected.

See Also

ItemsSelected Collection, ListCount Property, ListRows Property, ListWidth Property, MultiSelect Property, Selected Property.


ListRows Property

Applies To

Combo Box Control, Table Fields.

Description

You can use the ListRows property to set the maximum number of rows to display in the list box portion of a combo box.

Setting

The ListRows property holds an integer that indicates the maximum number of rows to display. The default setting is 8.

You can set this property using the combo box’s property sheet, a macro, Visual Basic, or the Combo Box Wizard.

For table fields, you can set this property in table Design view for fields with the DisplayControl property set to Combo Box.

Note Microsoft Access sets this property automatically when you select Lookup Wizard as the data type for a field in table Design view.

In Visual Basic, use a numeric expression to set the value of this property.

You can also set this property using a combo box’s default control style.

Remarks

If the actual number of rows exceeds the number specified by the ListRows property setting, a vertical scroll bar appears in the list box portion of the combo box.

See Also

Height, Width Properties; ListCount Property; ListWidth Property.

Example

This example uses the ListCount property to find the number of rows in the list box portion of the CustomerList combo box on a Customers form. It then sets the ListRows property to display a specified number of rows in the list.

Sub SizeCustomerList()
    Dim ListControl As Control
    Set ListControl = Forms![Customers]![CustomerList]
    If ListControl.ListCount < 8 Then
        ListControl.ListRows = ListControl.ListCount
    Else
        ListControl.ListRows = 8
    End IfSub


ListWidth Property

Applies To

Combo Box Control, Table Fields.

Description

You can use the ListWidth property to set the width of the list box portion of a combo box.

Setting

The ListWidth property holds the width, in the current unit of measurement, of the list box portion of a combo box. To use a unit other than the default, include a measurement indicator, such as cm or in. The default setting (Auto) makes the list box portion of the combo box the same width as the combo box.

You can set the ListWidth property using the property sheet, a macro, or Visual Basic.

For table fields, you can set this property in table Design view for fields with the DisplayControl property set to Combo Box.

Note Microsoft Access sets this property automatically when you select Lookup Wizard as the data type for a field in table Design view.

In Visual Basic, use a numeric expression to set the value of this property. The default unit of measurement in Visual Basic is twips.

You can also set this property using a combo box’s default control style.

Remarks

The list portion of the combo box can be wider than the combo box but can’t be narrower.

If you want to display a multiple-column list, enter a value that will make the list box wide enough to fit all the columns.

Tip When designing combo boxes, be sure to leave enough space to display your data and for Microsoft Access to insert a vertical scroll bar.

See Also

ListRows Property.


Load, Unload Events

Applies To

Form.

Description

These events occur:

  • Load — When a form is opened and its records are displayed. The Load event can occur when an application starts, when the OpenForm action is used, or when the user opens a form by choosing the Open button in the Database window.
  • Unload — When a form is closed but before it’s removed from the screen. When the form is reloaded, Microsoft Access redisplays the form and reinitializes the contents of all its controls.

Remarks

The Unload event is caused by user actions such as:

  • Clicking Close on the File menu or a form’s Control menu.
  • Running the Close action in a macro.
  • Quitting an application by choosing the End Task button in the Microsoft Windows Task List.
  • Quitting Windows while an application is running.

By running a macro or executing an event procedure when a form’s Unload event occurs, you can verify that the form should be unloaded or specify actions that should take place when the form is unloaded. You can also open another form or display a dialog box requesting the user’s name to make a log entry indicating who used the form.

When you first open a form, the following events occur in this order:

Open [image] Load [image] Resize [image] Activate

If you’re trying to decide whether to use the Open or Load event for your macro or event procedure, one significant difference is that the Open event can be canceled, but the Load event can’t. For example, if you’re dynamically building a record source for a form in an event procedure for the form’s Open event, you can cancel opening the form if there are no records to display.

Note When you create macros or event procedures for events related to the Load event, such as Activate and GotFocus, be sure that they don’t conflict (for example, make sure you don’t cause something to happen in one macro or procedure that is canceled in another) and that they don’t cause cascading events.

The Unload event occurs before the Close event. The Unload event can be canceled, but the Close event can’t.

See Also

Activate, Deactivate Events; Close Action; Current Event; GotFocus, LostFocus Events; GoToRecord Action; Open, Close Events; OpenForm Action; Resize Event; SetFocus Method.


Load, Unload Events -- Event Procedures

Description

To create an event procedure that is executed when the Load or Unload event occurs, set the OnLoad or OnUnload property to [Event Procedure], and click the Build button.

Syntax

Private Sub Form_Load( )Private Sub Form_Unload(Cancel As Integer)

The Unload event uses the following argument.

Argument | Description
Cancel | The setting determining whether to unload the form. Setting Cancel to True (-1) prevents the form from being unloaded.

Remarks

You can place initialization code in a form’s Load event procedure. For example, you can specify default settings for controls and initialize form-level variables.

You can’t cancel the Load event.

In an Unload event procedure, you can include any form-level validation code you might need to close the form or save the data it contains to a file.

If Cancel is set to True for a form that is modal, you may not be able to return control to the rest of the application.

See Also

Load, Unload Events — Macros.

Example

The following example displays the current date in the form’s caption when the form is loaded.

Private Sub Form_Load()
    Me.Caption = DateSub

The next example prompts the user to verify that the form should close.

To try this example, add the following code to the Declarations section of a module for a form. In Form view, close the form to display the dialog box, and then choose Yes or No.

Private Sub Form_Unload(Cancel As Integer)
    If MsgBox("Close form?", vbYesNo) = vbYes Then
        Exit Sub
    Else
        Cancel = True
    End IfSub


Load, Unload Events -- Macros

Description

To run a macro when the Load or Unload event occurs, set the OnLoad or OnUnload property to the name of the macro.

Remarks

You can use a Load macro to carry out actions for the controls or records on a form after the form opens. For example, you can specify default settings for controls.

You can’t use the CancelEvent action in a Load macro.

You can use the CancelEvent action in an Unload macro to cancel unloading of the records. This also cancels closing of the form.

If a form’s Unload macro carries out a CancelEvent action, you won’t be able to close the form. You must either correct the condition that caused the CancelEvent action to be carried out or open the macro and delete the CancelEvent action. If the form is modal, you won’t be able to open the macro or work in any other windows in the application.

See Also

Load, Unload Events — Event Procedures.


LoadPicture Function

Description

The LoadPicture function loads a graphic into a custom control.

Syntax

LoadPicture(stringexpression)

The LoadPicture function uses the following argument.

Argument | Description
stringexpression | The filename of the graphic to be loaded. The graphic can be a bitmap file (.bmp), icon file (.ico), run-length encoded file (.rle), or metafile (.wmf).

Remarks

Assign the return value of the LoadPicture function to the Picture property of a custom control to dynamically load a graphic into the control. The following example loads a bitmap into a control called OLECustomControl on an Orders form.

Set Forms!Orders!OLECustomControl.Picture = LoadPicture("Stars.bmp")

The LoadPicture function returns an object of type Picture. You can assign this value to a variable of type Object using the Set statement.

The Picture object is not a Microsoft Access object, but it is available to procedures in Microsoft Access. If you wish to assign the return value of the LoadPicture function to an object variable of type Picture, you must first set a reference to the Standard OLE Types type library in the References dialog box, available by clicking References on the Tools menu. You can then declare an object variable of type Picture.

Note You can’t use the LoadPicture function to set the Picture property of an image control. This function works with custom controls only. To set the Picture property of an image control, simply assign to it a string specifying the filename and path of the desired graphic.

Example

The following example uses the LoadPicture function to load a metafile into a custom control on an Employees form. Note that in order to declare a variable of type Picture, you must set a reference to the Standard OLE Types type library in the References dialog, available by clicking References on the Tools menu.

Sub DisplayGraphic()
    ' Declare object variables of type Picture and Control.
    Dim pic As Picture, ctl As Control

    ' Set Control variable to refer to custom control on form.
    Set ctl = Forms!Employees!SomeCustomControl
    ' Assign return value of LoadPicture to Picture object.
    Set pic = LoadPicture("C:\MSOffice\Access\Bitmaps\Styles\Globe.wmf")
    ' Set Picture property of custom control.
    Set ctl.Picture = picSub


Loc Function

Description

Returns the current read/write position within an open file.

Syntax

Loc(filenumber)

The filenumber argument is any valid file number.

Remarks

The following describes the return value for each file access mode:

File Access | Return Value
Random | Number of the last record read from or written to the file.
Sequential | Current byte position in the file divided by 128. (Note that information returned by Loc for sequential files is neither used nor required.)
Binary | Position of the last byte read or written.

See Also

EOF Function, LOF Function.

Example

This example uses the Loc function to return the current read/write position within an open file. This example assumes that TESTFILE is a text file with a few lines of sample data.

Open "TESTFILE" For Binary As #1            ' Open file just created.While MyLocation < LOF(1)                ' Loop until end of file.
    MyLine = MyLine & Input(1, #1)        ' Read character into variable.
    MyLocation = Loc(1)                    ' Get current position within
                                        ' file.
    ' Print to Debug window.
    Debug.Print MyLine; Tab; MyLocation#1                                    ' Close file.


Lock, Unlock Statements

Description

Controls access by other processes to all or part of a file opened using the Open statement.

Syntax

Lock [#]filenumber[, recordrange]
. . .
Unlock [#]filenumber[, recordrange]

The Lock and Unlock statement syntax has these parts:

Part | Description
filenumber | Any valid file number.
recordrange | The range of records to lock or unlock.

Settings

The recordrange argument settings are:

recnumber | [start] To end

Setting | Description
recnumber | Record number (Random mode files) or byte number (Binary mode files) at which locking or unlocking begins.
start | Number of the first record or byte to lock or unlock.
end | Number of the last record or byte to lock or unlock.

Remarks

The Lock and Unlock statements are used in environments where several processes might need access to the same file.

Lock and Unlock statements are always used in pairs. The arguments to Lock and Unlock must match exactly.

The first record or byte in a file is at position 1, the second record or byte is at position 2, and so on. If you specify just one record, then only that record is locked or unlocked. If you specify a range of records and omit a starting record (start), all records from the first record to the end of the range (end) are locked or unlocked. Using Lock without recnumber locks the entire file; using Unlock without recnumber unlocks the entire file.

If the file has been opened for sequential input or output, Lock and Unlock affect the entire file, regardless of the range specified by start and end.

Caution Be sure to remove all locks with an Unlock statement before closing a file or quitting your program. Failure to remove locks produces unpredictable results.

See Also

Open Statement.

Example

This example illustrates the use of the Lock and Unlock statements. While a record is being modified, access by other processes to the record is denied. This example assumes that TESTFILE is a file containing five records of the user-defined type Record.

Type Record                            ' Define user-defined type.
    ID As Integer
    Name As String * 20TypeMyRecord As Record                ' Declare variable.
' Open sample file for random access."TESTFILE" For Random Shared As #1 Len = Len(MyRecord)= 4                        ' Define record number.#1, RecordNumber                ' Lock record.#1, RecordNumber, MyRecord        ' Read record..ID = 234                    ' Modify record..Name = "John Smith"#1, RecordNumber, MyRecord        ' Write modified record.#1, RecordNumber                ' Unlock current record.#1                                ' Close file.


Locked Property

See Enabled, Locked Properties.


LOF Function

Description

Returns the size, in bytes, of a file opened using the Open statement.

Syntax

LOF(filenumber)

The filenumber argument is any valid file number.

Remarks

To obtain the length of a file that is not open, use the FileLen function.

See Also

EOF Function, FileLen Function, Loc Function, Open Statement.

Example

This example uses the LOF function to determine the size of an open file. This example assumes that TESTFILE is a text file containing sample data.

Open "TESTFILE" For Input As #1            ' Open file.= LOF(1)                        ' Get length of file.#1                                    ' Close file.


Log Function

Description

Returns the natural logarithm of a number.

Syntax

Log(number)

The number argument can be any valid numeric expression greater than 0.

Remarks

The natural logarithm is the logarithm to the base e. The constant e is approximately 2.718282.

You can calculate base-n logarithms for any number x by dividing the natural logarithm of x by the natural logarithm of n as follows:

Logn(x) = Log(x) / Log(n)

The following example illustrates a custom Function that calculates base-10 logarithms:

Static Function Log10(X)
    Log10 = Log(X) / Log(10#)Function

See Also

Derived Math Functions, Exp Function.

Example

This example uses the Log function to return the natural logarithm of a number.

' Define angle in radians.= 1.3
' Calculate inverse hyperbolic sine.= Log(MyAngle + Sqr(MyAngle * MyAngle + 1))


Long Data Type

Description

Long (long integer) variables are stored as signed 32-bit (4-byte) numbers ranging in value from -2,147,483,648 to 2,147,483,647. The type-declaration character for Long is &.

See Also

CLng Function, Data Type Summary, Def type Statements, Integer Data Type.


LostFocus Event

See GotFocus, LostFocus Events.


lpOLEObject Property

Applies To

Bound Object Frame Control, Chart Control, Unbound Object Frame Control.

Description

You can use the lpOLEObject property in Visual Basic to determine the memory address of an OLE object. The lpOLEObject property returns a pointer to IOLEObject.

Setting

You can use the lpOLEObject property to refer to the address of the active OLE object. If no object is displayed, the setting is 0. The lpOLEObject property setting is a Long data type value specified by Microsoft Access.

This property setting isn’t available in Design view and is read-only in other views.

Remarks

In the OLE dynamic link libraries (DLLs), many function calls require the address of the OLE object as an argument. You can pass the value specified by the lpOLEObject property when making application programming interface (API) calls to the OLE DLLs.

Note If an API call is made to a function that makes a callback to the control, the results will be unpredictable.

See Also

hWnd Property.


LSet Statement

Description

Left aligns a string within a string variable, or copies a variable of one user-defined type to another variable of a different user-defined type.

Syntax

LSet stringvar = string LSet varname1 = varname2

The LSet statement syntax has these parts:

Part | Description
stringvar | Name of string variable.
string | String expression to be left-aligned within stringvar.
varname1 | Variable name of the user-defined type being copied to.
varname2 | Variable name of the user-defined type being copied from.

Remarks

LSet replaces any leftover characters in stringvar with spaces.

If string is longer than stringvar, LSet places only the leftmost characters, up to the length of the stringvar, in stringvar.

Warning Using LSet to copy a variable of one user-defined type into a variable of a different user-defined type is not recommended and should not be done without understanding that copying data of one data type into space reserved for a different data type can cause unpredictable results.

When you copy a variable from one user-defined type to another, the binary data from one variable is simply copied into the memory space of the other, without regard for the data types specified for the elements contained within.

See Also

RSet Statement.

Example

This example uses the LSet statement to left align a string within a string variable. Although LSet can also be used to copy a variable of one user-defined type to another variable of a different, but compatible, user-defined type, this practice is not recommended. Due to the varying implementations of data structures among platforms, such a use of LSet cannot be guaranteed to be portable.

MyString = "0123456789"    ' Initialize string.MyString = "<-Left"    ' MyString contains "<-Left    ".


LTrim, RTrim, and Trim Functions

Description

Returns a copy of a string without leading spaces (LTrim), trailing spaces (RTrim), or both leading and trailing spaces (Trim).

Syntax

LTrim(string)RTrim(string)Trim(string)

The string argument is any valid string expression. If string contains Null, Null is returned.

See Also

Left Function, Right Function.

Example

This example uses the LTrim and RTrim functions to strip leading and trailing spaces, respectively, from a string variable. It uses the Trim function alone to strip both types of spaces.

MyString = "  <-Trim->  "            ' Initialize string.= LTrim(MyString)            ' TrimString = "<-Trim->  ".= RTrim(MyString)            ' TrimString = "  <-Trim->".= LTrim(RTrim(MyString))    ' TrimString = "<-Trim->".
' Using the Trim function alone achieves the same result.= Trim(MyString)            ' TrimString = "<-Trim->".


Maximize Action

Description

You can use the Maximize action to enlarge the active window so that it fills the application window. This action will allow you want to see as much of the object in the active window as possible.

Setting

The Maximize action doesn’t use any arguments.

Remarks

This action has the same effect as clicking the Maximize button in the window’s upper-right corner or clicking Maximize on the Control menu.

You can use the Restore action to restore a maximized window to its previous size.

Tip You may need to use the SelectObject action if the window you want to maximize isn’t the active window.

To run the Maximize action in Visual Basic, use the Maximize method of the DoCmd object.

See Also

Maximize Method, Minimize Action, Restore Action, SelectObject Action.


Maximize Method

Applies To

DoCmd Object.

Description

The Maximize method carries out the Maximize action in Visual Basic. For more information on how the action works, see the action topic.

Syntax

DoCmd.Maximize

This method uses no arguments.

See Also

DoCmd Object, Maximize Action, Minimize Method, Restore Method, SelectObject Method.


Me

Description

The Me keyword in Visual Basic behaves like an implicitly declared variable. It is automatically available to every procedure in a class module. When a class can have more than one instance, Me provides a way to refer to the specific instance of the class where the code is executing. Using Me is particularly useful when you want to pass information about the currently executing instance of a class to a procedure in another module. For example, suppose you have the following procedure in a module:

Sub ChangeFormColor(FormName As Form)
    FormName.BackColor = RGB(Rnd * 256, Rnd * 256, Rnd * 256)Sub

You can call this procedure and pass the current instance of the Form class as an argument using the following statement in one of the procedures in your form code:

ChangeFormColor Me

See Also

Set Statement.


Me Property

Applies To

Form, Report.

Description

You can use the Me property in Visual Basic to refer to a form or report, or the form or report associated with a subform or subreport, where Visual Basic code is currently running.

Setting

The Me property is available only in Visual Basic and is read-only in all views.

Remarks

In most cases, the form or report referred to by the Me property is the same form or report referred to by the ActiveForm or ActiveReport properties of the Screen object. However, these properties refer to the form or report with the focus, whereas the Me property always refers to the form or report in which code is running. For example, a Timer event can occur in a form that doesn’t have the focus. When that happens, the code Screen.ActiveForm refers to the form with the focus, and the Me property refers to the form in which the Timer event occurred. Therefore, when creating generic procedures that operate on the current form, the preferred method is to pass the form to the procedure using the Me property rather than the ActiveForm property.

See Also

ActiveForm Property; ActiveReport Property; Form, Report Properties; Parent Property; Screen Object.

Example

The following example shows how to change the caption of the Customers form to the current company name whenever a new record is displayed. The form’s Current event procedure calls the ChangeCaption subroutine and passes it the Me property to specify the active form. The ChangeCaption procedure changes the caption of the form. Because the ChangeCaption procedure changes the caption of the active form (and not a specific form), it can be called from other procedures in an application.

Sub Form_Current()
    ChangeCaption Me        ' Pass current form name as argument.Sub
ChangeCaption(frmCurrentForm As Form)
    ' Move focus to Customer Name text box.     frmCurrentForm![CompanyName].SetFocus
    ' Change caption.
    frmCurrentForm.Caption = frmCurrentForm![CompanyName].TextSub


MenuBar Property

Applies To

Application Object, Form, Report.

Description

You can use the MenuBar property to specify the menu bar macro that will to display a custom menu bar for a database, form, or report.

Setting

Enter the name of the menu bar macro that displays a custom menu bar. If you leave the MenuBar property setting blank, Microsoft Access displays the built-in (default) menu bar or the application’s global menu bar.

You can set this property using the object’s property sheet, a macro, or Visual Basic.

In Visual Basic, set this property using a string expression that is the name of the menu bar macro you want to run.

To display the built-in menu bar for a database, form, or report using a macro or Visual Basic, set the property to a zero-length string (" ").

Tip To create a menu bar macro, you can use the Menu Builder by clicking the Build button in the MenuBar property box of the form or report you want to attach the menu to. The Menu Builder creates and names the menu bar macro and the macro group containing the actions for the menu commands on the menus you create. If you use the Menu Builder to create the menu bar macro and the macro group for the menus on this menu bar, you can also use the Menu Builder to edit this macro and macro group.

Remarks

When you use the MenuBar property with forms and reports, Microsoft Access runs the specified menu bar macro and displays the custom menu bar when the form or report is opened. This menu bar is displayed whenever the form or report has the focus.

The menu bar macro contains AddMenu actions that create the drop-down menus on the custom menu bar. For each drop-down menu, the menu bar macro names the macro group that defines the commands on the menu. If you make changes to the menu bar macro or the macro group that defines the commands on the drop-down menus while the form or report is open, you must close the form or report and reopen it to see the changes in the custom menu bar and its menus.

You can’t use any action except AddMenu in a menu bar macro.

When used with the Application object, the MenuBar property enables you to display a custom menu bar throughout the database. However, if you’ve set the MenuBar property for a form or report in the database, the custom menu bar of the form or report takes precedence over the database’s custom menu bar. You can display a different custom menu bar for a specific form or report by setting its MenuBar property to a different menu bar macro. When the form or report has the focus, the custom menu bar for the form or report is displayed; when the form or report loses the focus, the custom menu bar for the database is displayed.

Note You can switch between a database’s custom menu bar and the built-in menu bar by pressing CTRL+F11.

See Also

AddMenu Action, AllowFullMenus Property, Application Object, ShortcutMenuBar Property, StartupMenuBar Property.

Example

The following example sets the MenuBar property to a menu bar macro named CustomerMenu.

Forms![Customers].MenuBar = "CustomerMenu"

To display the built-in menu bar for the form or the application global menu, you set the MenuBar property to a zero-length string (" ").

Forms![Customers].MenuBar = ""


Mid Function

Description

Returns a specified number of characters from a string.

Syntax

Mid(string, start[, length])

The Mid function syntax has these named arguments:

Part | Description
string | String expression from which characters are returned. If string contains Null, Null is returned.
start | Character position in string at which the part to be taken begins. If start is greater than the number of characters in string, Mid returns a zero-length string.
length | Number of characters to return. If omitted or if there are fewer than length characters in the text (including the character at start), all characters from the start position to the end of the string are returned.

Remarks

To determine the number of characters in string, use the Len function.

Note Another function (MidB) is provided for use with byte data contained in a string. Instead of specifying the number of characters, the arguments specify numbers of bytes.

See Also

Left Function; Len Function; LTrim, RTrim, and Trim Functions; Mid Statement; Right Function.

Example

This example uses the Mid function to return a specified number of characters from a string.

MyString = "Mid Function Demo"        ' Create text string.= Mid(MyString, 1, 3)        ' Returns "Mid".= Mid(MyString, 14, 4)        ' Returns "Demo".= Mid(MyString, 5)            ' Returns "Function Demo".


Mid Statement

Description

Replaces a specified number of characters in a string variable with characters from another string.

Syntax

Mid(stringvar, start[, length]) = string

The Mid statement syntax has these parts:

Part | Description
stringvar | Name of string variable to modify.
start | Character position in stringvar where the replacement of text begins.
length | Number of characters to replace. If omitted, all of string is used.
string | String expression that replaces part of stringvar.

Remarks

The number of characters replaced is always less than or equal to the number of characters in stringvar.

Note Another statement (MidB) is provided for use with byte data contained in a string. In the MidB statement, start specifies the byte position within stringvar where replacement begins and length specifies the numbers of bytes to replace.

See Also

Mid Function.

Example

This example uses the Mid statement to replace a specified number of characters in a string variable with characters from another string.

MyString = "The dog jumps"                ' Initialize string.(MyString, 5, 3) = "fox"                ' MyString = "The fox jumps".(MyString, 5) = "cow"                    ' MyString = "The cow jumps".(MyString, 5) = "cow jumped over"        ' MyString = "The cow jumps".(MyString, 5, 3) = "duck"                ' MyString = "The duck jumps".


Minimize Action

Description

You can use the Minimize action to reduce the active window to an icon at the bottom of the Microsoft Access window.

Setting

The Minimize action doesn’t use any arguments.

Remarks

You can use this action to remove a window from the screen while leaving the object open. You can also use this action to open an object without displaying its window. To display the object, use the SelectObject action with either the Maximize or Restore action. The Restore action restores a minimized window to its previous size.

The Minimize action has the same effect as clicking the Minimize button in the window’s upper-right corner or clicking Minimize on the Control menu.

Note Tips

  • You may first need to use the SelectObject action if the window you want to minimize isn’t the active window.
  • To minimize the Database window, use the SelectObject action with the In Database Window argument set to Yes and then use the Minimize action.
  • You can use the Hide command on the Window menu to hide the active window. Instead of being reduced to an icon, the window becomes invisible. The Unhide command on the Window menu will make the window reappear. You can use the DoMenuItem action to carry out either of these commands from a macro.
  • You can also use the SetValue action to set a form’s Visible property to hide or show the form’s window.

To run the Minimize action in Visual Basic, use the Minimize method of the DoCmd object.

See Also

DoMenuItem Action, Maximize Action, Minimize Method, OpenForm Action, Restore Action, SelectObject Action.


Minimize Method

Applies To

DoCmd Object.

Description

The Minimize method carries out the Minimize action in Visual Basic. For more information on how the action works, see the action topic.

Syntax

DoCmd.Minimize

This method uses no arguments.

See Also

DoCmd Object, Maximize Method, Minimize Action, OpenForm Method, Restore Method, SelectObject Method.


MinMaxButtons Property

Applies To

Form.

Description

You can use the MinMaxButtons property to specify whether Maximize or Minimize buttons will be available on a form.

Setting

The MinMaxButtons property uses the following settings.

Setting | Description | Visual Basic
None | The form will not have Maximize or Minimize buttons. | 0
Min Enabled | Only the Minimize button is available. | 1
Max Enabled | Only the Maximize button is available. | 2
Both Enabled | (Default) Both the Minimize and Maximize buttons are available. | 3

You can set these properties using the form’s property sheet, a macro, or Visual Basic.

You can set the MinMaxButtons property only in form Design view.

Remarks

Clicking a form’s Maximize button enlarges the form so it fills the Microsoft Access window. Clicking a form’s Minimize button reduces the form to an icon at the bottom of the Microsoft Access window.

To display Maximize and Minimize buttons on a form, you must set the form’s BorderStyle property to Thin or Sizable and the ControlBox property to Yes. If you set the BorderStyle property to None or Dialog, or if you set the ControlBox property to No, the form won’t have Maximize or Minimize buttons, regardless of the MinMaxButtons property setting.

Even when the MinMaxButtons property is set to None, a form always has Maximize and Minimize buttons in Design view.

If a form’s MinMaxButtons property is set to None, the Maximize and Minimize commands aren’t available on the form’s Control menu.

See Also

BorderStyle Property, ControlBox Property, Maximize Action, Minimize Action, Modal Property, PopUp Property.


Minute Function

Description

Returns a whole number between 0 and 59, inclusive, representing the minute of the hour.

Syntax

Minute(time)

The time argument is any numeric or string expression, or any combination, that can represent a time. If time contains Null, Null is returned.

See Also

Day Function, Hour Function, Now Function, Second Function, Time Function, Time Statement.

Example

This example uses the Minute function to obtain the minute of the hour from a specified time. In the development environment, the time (date literal) is displayed in short time format using the locale settings of your code.

MyTime = #4:35:17 PM#        ' Assign a time.= Minute(MyTime)    ' MyMinute contains 35.


MIRR Function

Description

Returns the modified internal rate of return for a series of periodic cash flows (payments and receipts).

Syntax

MIRR(values(), finance_rate, reinvest_rate)

The MIRR function has these named arguments:

Part | Description
values() | Array of cash flow values. The array must contain at least one negative value (a payment) and one positive value (a receipt).
finance_rate | Interest rate paid as the cost of financing.
reinvest_rate | Interest rate received on gains from cash reinvestment.

Remarks

The modified internal rate of return is the internal rate of return when payments and receipts are financed at different rates. The MIRR function takes into account both the cost of the investment (finance_rate) and the interest rate received on reinvestment of cash (reinvest_rate).

The arguments finance_rate and reinvest_rate are percentages expressed as decimal values. For example, 12 percent is expressed as 0.12.

The MIRR function uses the order of values within the array to interpret the order of payments and receipts. Be sure to enter your payment and receipt values in the correct sequence.

Example

This example uses the MIRR function to return the modified internal rate of return for a series of cash flows contained in the array Values(). LoanAPR represents the financing interest, and InvAPR represents the interest rate received on reinvestment.

Static Values(5) As Double                    ' Set up array.= .1                                    ' Loan rate.= .12                                    ' Reinvestment rate.= "#0.00"                                ' Define money format.(0) = -70000                            ' Business start-up costs.
' Positive cash flows reflecting income for four successive years.(1) = 22000 : Values(2) = 25000(3) = 28000 : Values(4) = 31000= MIRR(Values(), LoanAPR, InvAPR)    ' Calculate internal rate.= "The modified internal rate of return for these five cash to "& _
    "flows is"= Msg & Format(Abs(RetRate) * 100, Fmt) & "%."Msg                                    ' Display internal return
                                            ' rate.


MkDir Statement

Description

Creates a new directory or folder.

Syntax

MkDir path

The path argument is a string expression that identifies the directory or folder to be created. The path may include the drive. If no drive is specified, MkDir creates the new directory or folder on the current drive.

Remarks

In Microsoft Windows, if you use MkDir to create a directory whose name contains an embedded space, you may be able to access it with some applications, but you can’t remove it using standard operating system commands. To remove such a directory, use the RmDir statement.

See Also

ChDir Statement, CurDir Function, RmDir Statement.

Example

This example uses the MkDir statement to create a directory or folder. If the drive is not specified, the new directory or folder is created on the current drive.

MkDir "MYDIR"            ' Make new directory or folder.


Mod Operator

Description

Used to divide two numbers and return only the remainder.

Syntax

result = number1 Mod number2

The Mod operator syntax has these parts:

Part | Description
result | Any numeric variable.
number1 | Any numeric expression.
number2 | Any numeric expression.

Remarks

The modulus, or remainder, operator divides number1 by number2 (rounding floating-point numbers to integers) and returns only the remainder as result. For example, in the following expression, A (which is result) equals 5.

A = 19 Mod 6.7

Usually, the data type of result is a Byte, Byte variant, Integer, Integer variant, Long, or Variant containing a Long, regardless of whether or not result is a whole number. Any fractional portion is truncated. However, if any expression is Null, result is also Null. Any expression that is Empty is treated as 0.

Example

This example uses the Mod operator to divide two numbers and return only the remainder. If either number is a floating-point number, it is first rounded to an integer.

MyResult = 10 Mod 5            ' Returns 0.= 10 Mod 3            ' Returns 1.= 12 Mod 4.3        ' Returns 0.= 12.6 Mod 5        ' Returns 3.


Modal Property

Applies To

Form.

Description

You can use the Modal property to specify whether a form opens as a modal form. When a form opens as a modal form, you must close the form before you can move the focus to another object.

Setting

The Modal property uses the following settings.

Setting | Description | Visual Basic
Yes | The form opens as a modal form in Form view. | True (-1)
No | (Default) The form isn’t a modal form when it opens. | False (0)

You can set this property using the form’s property sheet, a macro, or Visual Basic.

Remarks

When you open a modal form, other windows are disabled until you close it. To disable menus and toolbars in addition to other windows, set both the form’s Modal and PopUp properties to Yes.

You can use the BorderStyle property to specify the kind of border for a form. Typically, modal forms have the BorderStyle property set to Dialog.

Tip You can use the Modal, PopUp and BorderStyle properties to create a custom dialog box. You can set Modal to Yes, PopUp to Yes and BorderStyle to Dialog for custom dialog boxes.

Setting the Modal property to Yes makes the form modal only when you open it in Form view from the Database window or using a macro or Visual Basic. When the form is modal, you can’t switch to other views of the form from Form view. You must close the form and reopen it in Design view or Datasheet view.

Note You can use the Dialog setting of the Window Mode argument of the OpenForm action to open a form with its Modal and PopUp properties set to Yes.

See Also

BorderStyle Property, ControlBox Property, MinMaxButtons Property, OpenForm Action, PopUp Property.


Module Property

Applies To

Form, Report.

Description

You can use the Module property to specify a form module or report module.

Setting

The Module property is available only in Visual Basic and is read-only in all views.

Remarks

You can use this property only with the InsertText method to specify the module you want to insert code into.

See Also

InsertText Method.

Example

The following example uses the Module property to insert the Beep method into the form Open event.

Dim strFormOpenCode As String= "Sub Form_Open(Cancel As Integer)" & vbCrLf & _
    "Beep" & strCRLF & "End Sub"![MyForm].Module.InsertText strFormOpenCode


Month Function

Description

Returns a whole number between 1 and 12, inclusive, representing the month of the year.

Syntax

Month(date)

The date argument is any numeric or string expression, or any combination, that can represent a date. If date contains Null, Null is returned.

See Also

Date Function, Date Statement, Day Function, Now Function, Weekday Function, Year Function.

Example

This example uses the Month function to obtain the month from a specified date. In the development environment, the date literal is displayed in short date format using the locale settings of your code.

MyDate = #February 12, 1969#        ' Assign a date.= Month(MyDate)            ' MyMonth contains 2.

The following example uses the Month function to set criteria in a query showing which orders were placed in December. Suppose you have an Orders table that includes an OrderID field and an OrderDate field. For example, you can create a new query on the Orders in the Query window, drag the OrderID field onto the query design grid from the Orders table, and enter the following expression in the Criteria cell under the OrderID field.

(Month([OrderDate]) = 12)


MouseDown, MouseUp Events

Applies To

Bound Object Frame Control, Chart Control, Check Box Control, Combo Box Control, Command Button Control, Form, Form Section, Image Control, Label Control, List Box Control, Option Button Control, Option Group Control, Rectangle Control, Text Box Control, Toggle Button Control, Unbound Object Frame Control.

Description

These events occur:

  • MouseDown — When the user presses a mouse button.
  • MouseUp — When the user releases a mouse button.

Note Notes

  • The MouseDown and MouseUp events apply only to forms, form section, and controls on a form.
  • These events don’t apply to a label attached to another control, such as the label for a text box. They apply only to “freestanding” labels. Pressing and releasing a mouse button in an attached label has the same effect as pressing and releasing the button in the associated control. The normal events for the control occur; no separate events occur for the attached label.

Remarks

You can use a MouseDown or MouseUp event to specify what happens when a particular mouse button is pressed or released. Unlike the Click and DblClick events, the MouseDown and MouseUp events enable you to distinguish between the left, right, and middle mouse buttons. You can also write code for mouse-keyboard combinations that use the SHIFT, CTRL, and ALT keys.

To cause a MouseDown or MouseUp event for a form to occur, press the mouse button in a blank area, record selector, or scroll bar on the form. To cause a MouseDown or MouseUp event for a form section to occur, press the mouse button in a blank area of the form section after selecting the section. To select the form section, click the section header.

The following apply to both MouseDown and MouseUp events:

  • If a mouse button is pressed while the pointer is over a form or control, that object receives all mouse events up to and including the last MouseUp event.
  • If mouse buttons are pressed in succession, the object that receives the mouse event after the first press receives all mouse events until all buttons are released.

To respond to an event caused by moving the mouse, you use a MouseMove event.

See Also

Click Event; DblClick Event; Enter, Exit Events; GotFocus, LostFocus Events; MouseMove Event.


MouseDown, MouseUp Events -- Event Procedures

Description

To create an event procedure that is executed when the MouseDown or MouseUp event occurs, set the OnMouseDown or OnMouseUp property to [Event Procedure], and click the Build button.

Syntax

Private Sub Form_MouseDown(Button As Integer, Shift As Integer, X As åSingle, Y As Single)Private Sub controlname_MouseDown(Button As Integer, Shift As Integer, X åAs Single, Y As Single)Private Sub Form_MouseUp(Button As Integer, Shift As Integer, X As Single, åY As Single)Private Sub controlname_MouseUp(Button As Integer, Shift As Integer, X As åSingle, Y As Single)

The MouseDown and MouseUp events use the following arguments.

Argument | Description
controlname | A string that is the name of the control affected by the MouseDown and MouseUp event procedures.

Argument | Description
Button | The button that was pressed (MouseDown) or released (MouseUp) to trigger the event. If you need to test for the Button argument, you can use one of the following intrinsic constants as bit masks: Constant Description acLeftButton Bit mask for the left mouse button. acRightButton Bit mask for the right mouse button. acMiddleButton Bit mask for the middle mouse button.
Shift | The state of the SHIFT, CTRL, and ALT keys when the button specified by the Button argument was pressed or released. If you need to test for the Shift argument, you can use one of the following intrinsic constants as bit masks: Constant Description acShiftMask Bit mask for the SHIFT key. acCtrlMask Bit mask for the CTRL key. acAltMask Bit mask for the ALT key.
X, Y | The x and y coordinates for the current location of the mouse pointer. X and Y are always expressed in twips.

Note If a mouse button is pressed while the pointer is over a form or control, that object receives all mouse events up to and including the last MouseUp event. This means that the X and Y arguments may not always be relative to the object that receives them.

Remarks

You test for a condition by first assigning each result to a temporary Integer variable and then comparing the Shift or Button argument to a intrinsic constant. Use the And operator with the Button argument to test whether the condition is greater than 0, indicating that the left, middle, or right mouse button was pressed, as in the following example.

LeftDown = (Button And acLeftButton) > 0

In an event procedure, you can test for any combination of conditions, as in the following example.

If ShiftDown And CtrlDown Then
    .    ' Do this if SHIFT and CTRL keys are pressed.
    .
    .

Note The Button argument for the MouseDown and MouseUp events differs from the Button argument used for the MouseMove event. For the MouseDown and MouseUp events, the Button argument indicates exactly one button per event; that is, if you press two mouse buttons, two MouseDown (and MouseUp) events will occur, each with a different Button argument setting. For the MouseMove event, the Button argument indicates the current state of all buttons.

You can use the arguments for the KeyDown, KeyPress, and KeyUp events, in conjunction with the arguments for the MouseDown, MouseUp, and MouseMove events, to make your application work smoothly for both keyboard and mouse users.

You can’t cancel the MouseDown or MouseUp events.

See Also

MouseDown, MouseUp Events — Macros.

Example

The following example shows how you can find out which mouse button caused a MouseDown event.

To try this example, add the following code to the Declarations section of a module for a form.

Private Sub Form_MouseDown(Button As Integer, Shift As Integer, _
    X As Single, Y As Single)
    If Button = acLeftButton Then MsgBox "You pressed the left button."
    If Button = acRightButton Then _
        MsgBox "You pressed the right button."
    If Button = acMiddleButton Then _
        MsgBox "You pressed the middle button."Sub


MouseDown, MouseUp Events -- Macros

Description

To run a macro when the MouseDown or MouseUp event occurs, set the OnMouseDown or OnMouseUp event property to the name of the macro.

Remarks

You can use a MouseDown or MouseUp macro to respond whenever the user presses or releases a mouse button in a form or control. However, macros can’t return the button code and determine which mouse button was pressed, so you typically use event procedures with this event.

You can’t use the CancelEvent action in a MouseDown or MouseUp macro, with one exception: You can use the CancelEvent action in a MouseDown macro to cancel the event that occurs when you press the right mouse button. For example, you can cancel the display of a shortcut menu and display your own custom shortcut menu.

See Also

MouseDown, MouseUp Events — Event Procedures.


MouseMove Event

Applies To

Bound Object Frame Control, Chart Control, Check Box Control, Combo Box Control, Command Button Control, Form, Form Section, Image Control, Label Control, List Box Control, Option Button Control, Option Group Control, Rectangle Control, Text Box Control, Toggle Button Control, Unbound Object Frame Control.

Description

The MouseMove event occurs when the user moves the mouse.

Notes

  • The MouseMove event applies only to forms, form sections, and controls on a form.
  • This event doesn’t apply to a label attached to another control, such as the label for a text box. It applies only to “freestanding” labels. Moving the mouse pointer over an attached label has the same effect as moving the pointer over the associated control. The normal events for the control occur; no separate events occur for the attached label.

Remarks

The MouseMove event is generated continually as the mouse pointer moves over objects. Unless another object generates a mouse event, an object recognizes a MouseMove event whenever the mouse pointer is positioned within its borders.

To cause a MouseMove event for a form to occur, move the mouse pointer over a blank area, record selector, or scroll bar on the form. To cause a MouseMove event for a form section to occur, move the mouse pointer over a blank area of the form section after selecting the section. To select the form section, click the section header.

Notes

  • Moving a form can trigger a MouseMove event even if the mouse is stationary. MouseMove events are generated when the form moves underneath the pointer. If a macro or event procedure moves a form in response to a MouseMove event, the event can cascade (that is, continually generate MouseMove events).
  • If two controls are very close together, and you move the mouse pointer quickly over the space between them, the MouseMove event may not occur for the space (for example, this might be the MouseMove event for the form section). In such cases, you may need to respond to the MouseMove event in the contiguous control. as well as in the form section.

To run a macro or execute an event procedure in response to pressing and releasing the mouse buttons, you use the MouseDown and MouseUp events.

See Also

Click Event; DblClick Event; Enter, Exit Events; GotFocus, LostFocus Events; MouseDown, MouseUp Events.


MouseMove Event -- Event Procedures

Description

To create an event procedure that is executed when the MouseMove event occurs, set the OnMouseMove property to [Event Procedure], and click the Build button.

Syntax

Private Sub Form_MouseMove(Button As Integer, Shift As Integer, X As åSingle, Y As Single)Private Sub controlname_MouseMove(Button As Integer, Shift As Integer, X åAs Single, Y As Single)

The MouseMove event uses the following arguments.

Argument | Description
controlname | A string that is the name of the control affected by the MouseMove event procedure.

Argument | Description
Button | The state of the mouse buttons when the event occurs. If you need to test for the Button argument, you can use one of the following intrinsic constants as bit masks: Constant Description acLeftButton Bit mask for the left mouse button. acRightButton Bit mask for the right mouse button. acMiddleButton Bit mask for the middle mouse button.
Shift | The state of the SHIFT, CTRL, and ALT keys when the button specified by the Button argument was pressed or released. If you need to test for the Shift argument, you can use one of the following intrinsic constants as bit masks: Constant Description acShiftMask Bit mask for the SHIFT key. acCtrlMask Bit mask for the CTRL key. acAltMask Bit mask for the ALT key.
X, Y | The x and y coordinates of the current location of the mouse pointer. X and Y are always expressed in twips.

You test for a condition by first assigning each result to a temporary Integer variable and then comparing the Shift or Button argument to as intrinsic constant. Use the And operator with the Button argument to test whether the condition is greater than 0, indicating that the left, middle, or right mouse button was pressed, as in the following example.

LeftDown = (Button And acLeftButton) > 0

In a procedure, you can test for any combination of conditions, as in the following example.

If ShiftDown And CtrlDown Then
    .    ' Do this if SHIFT and CTRL keys are pressed.
    .
    .

Note The Button argument for the MouseDown and MouseUp events differs from the Button argument for MouseMove. For the MouseMove event, the Button argument indicates the current state of all buttons; a single MouseMove event can indicate that some, all, or no button is pressed. For example, if you press both the left and right buttons while moving the mouse, the Button argument is set to 3 (1 + 2). For the MouseDown and MouseUp events, the Button argument indicates one button per event.

Remarks

You can use the arguments for the KeyDown, KeyPress, and KeyUp events, in conjunction with the arguments for the MouseDown, MouseUp, and MouseMove events, to make your application work smoothly for both keyboard and mouse users. For example, you may need to coordinate the keyboard focus with the mouse focus. Normally, these are the same. For example, if you move the mouse pointer to a text box and click the mouse button, both the keyboard focus and the mouse focus move to the text box. However, moving the mouse pointer over a control does not move the keyboard focus to that control. You need to click a mouse button, use one of the keyboard navigation keys, or set the focus to the control in the MouseMove event procedure.

Since the MouseMove event occurs for each area of the form it moves over, you can end up with a multitude of MouseMove events if you don’t control them. You may want to make sure that if a control or section has received a MouseMove event, the event doesn’t occur for the control or section again while the mouse pointer is still on this area of the form. To do this, set and check a module variable that indicates whether the MouseMove event has already occurred for this control or form section.

You can’t cancel the MouseMove event.

See Also

MouseMove Event — Macros.

Example

The following example determines where the mouse is and whether the left mouse button and/or the SHIFT key is pressed. The X and Y coordinates of the mouse pointer position are displayed in a label control as you move the mouse.

To try this example, add the following code to the Declarations section of a module for a form that contains a label named Coordinates.

Private Sub Detail_MouseMove(Button As Integer, Shift As Integer, _
        X As Single, Y As Single)
    Dim intShiftDown As Integer, intLeftButton As Integer

    Coordinates.Caption = X & " , " & Y
    ' Use bit masks to determine state of SHIFT key and left button.
    intShiftDown = Shift And acLeftButton
    intLeftButton = Button And acShiftMask
    ' Check that SHIFT key and left button are both pressed.
    If intShiftDown And intLeftButton > 0 Then
        MsgBox "Shift key and left mouse button were pressed."
    End IfSub


MouseMove Event -- Macros

Description

To run a macro when the MouseMove event occurs, set the OnMouseMove property to the name of the macro.

Remarks

You can use a MouseMove macro to respond whenever the user moves the mouse over a form or control. However, macros can’t return the button code and determine the state of the mouse buttons or determine the coordinates of the mouse pointer when the movement occurs, so you typically use event procedures with this event.

You can’t use the CancelEvent action in a MouseMove macro.

See Also

MouseMove Event — Event Procedures.


MouseUp Event

See MouseDown, MouseUp Events.


MoveLayout, NextRecord, PrintSection Properties

Applies To

Report.

Description

You can use combinations of these property settings in Visual Basic to specify or change a report’s layout when the report is previewed, printed, or saved to a file:

  • MoveLayout — This property specifies whether Microsoft Access should move to the next printing location on the page.
  • NextRecord — This property specifies whether a section should advance to the next record.
  • PrintSection — This property specifies whether a section should be printed on the page.

Setting

The MoveLayout property uses the following settings.

Setting | Description
True (-1) | (Default) The section’s Left and Top properties are advanced to the next print location.
False (0) | The section’s Left and Top properties are unchanged.

The NextRecord property uses the following settings.

Setting | Description
True | (Default) The section advances to the next record.
False | The section doesn’t advance to the next record.

The PrintSection property uses the following settings.

Setting | Description
True | (Default) The section is printed on the page.
False | The section isn’t printed.

To set these properties, specify a macro or event procedure for a section’s OnFormat property.

Microsoft Access sets these properties to True before each section’s Format event.

Remarks

These properties are useful when you want to use a report as a template into which you write data from a macro or Visual Basic as you print.

The following table shows the result of different setting combinations for these properties.

MoveLayout | NextRecord | PrintSection | Description
True | True | True | (Default) Move to the next print location, get the next record, and print the data.
True | False | True | Move to the next print location, don’t advance to the next record, but print the data. This combination is typically used when the data in a section requires more space than the layout allows and you want to print the remaining data in the space that would otherwise be occupied by the next section.
False | True | False | Skip a record without leaving a blank space on the page.

MoveLayout | NextRecord | PrintSection | Description
True | True | False | Skip a record and leave a blank space on the page.
True | False | False | Leave a blank space without skipping a record, as in a sparse matrix.
False | True | True | Print the current record on top of the last record as an overlay.
False | False | True | Not allowed.
False | False | False | Not allowed.

See Also

Event Properties; Format Event; Left, Top Properties; NewRowOrCol Property.


MoveSize Action

Description

You can use the MoveSize action to move or resize the active window.

Setting

The MoveSize action uses the following arguments.

Action argument | Description
Right | The new horizontal position of the window’s upper-left corner, measured from the left edge of its containing window.
Down | The new vertical position of the window’s upper-left corner, measured from the top edge of its containing window.
Width | The window’s new width.
Height | The window’s new height.

If you leave an argument blank, Microsoft Access uses the window’s current setting.

You must enter a value for at least one argument.

Note Each measurement is in inches or centimeters, depending on the units set for Measurement system in the Number tab of the Regional Settings Properties dialog box in the Microsoft Windows Control Panel.

Remarks

This action is similar to clicking Move or Size on the window’s Control menu. With the menu commands, you use the keyboard’s arrow keys to move or resize the window. With the MoveSize action, you enter the position and size measurements directly. You can also use the mouse to move and size windows.

You can use this action on any window, in any view.

Note Tips

  • To move a window without resizing it, enter values for Right and Down argument but leave Width and Height arguments blank.
  • To resize a window without moving it, enter values for Width and Height arguments but leave Right and Down arguments blank.

To run the MoveSize action in Visual Basic, use the MoveSize method of the DoCmd object.

See Also

Event Properties, MoveSize Method, Resize Event, Restore Action, SelectObject Action.


MoveSize Method

Applies To

DoCmd Object.

Description

The MoveSize method carries out the MoveSize action in Visual Basic. For more information on how the action and its arguments work, see the action topic.

Syntax

DoCmd.MoveSize [ right] [, down] [, width] [, height]

The MoveSize method uses the following arguments.

Argument | Description
right | Numeric expression
down | Numeric expression
width | Numeric expression
height | Numeric expression

Remarks

You must include at least one argument for the MoveSize method. If you leave an argument blank, the current setting for the window is used.

You can leave an optional argument blank in the middle of the syntax, but you must include the argument’s comma. If you leave one or more trailing arguments blank, don’t use a comma following the last argument you specify.

The units for the arguments are twips.

See Also

DoCmd Object, MoveSize Action, Resize Event, Restore Method, SelectObject Method.

Example

This example moves the active window and changes its height, but leaves its width unchanged.

DoCmd.MoveSize 1440, 2400, , 2000


MsgBox Action

Description

You can use the MsgBox action to display a message box containing a warning or an informational message. For example, you can use the MsgBox action with validation macros. When a control or record fails a validation condition in the macro, a message box can display an error message and provide instructions about the kind of data that should be entered.

Setting

The MsgBox action uses the following arguments.

Action argument | Description
Message | The text in the message box. You can type up to 256 characters or enter an expression (preceded by an equal sign).
Beep | Specifies whether your computer’s speaker sounds a beep tone once when the message displays. Click Yes to sound the speaker once. Click No if you don’t want a beep. The default is Yes.
Type | The type of message box. Each type has a different icon. Click None, Critical, Warning?, Warning!, or Information. The default is None.
Title | The text displayed in the message box title bar. For example, you can have the title bar display “Customer ID Validation”. If you leave this argument blank, “Microsoft Access” is displayed.

Remarks

You can use the MsgBox action to create a formatted error message similar to built-in error messages displayed by Microsoft Access. The MsgBox action permits you to supply a message in three sections for the Message argument. You separate the sections with the “@” character.

The following example displays a formatted message box with a sectioned message. The first section of text in the message is displayed as a bold heading. The second section is displayed as plain text beneath that heading. The third section is displayed as plain text beneath the bold heading “Solution”, which is provided for you.

Enter the following in the Message argument:

Wrong button!@This button doesn’t work.@Try another.

Microsoft Windows 95 and Windows NT display slightly different icons for the Type argument settings.

You can’t run the MsgBox action in Visual Basic. Use the MsgBox function instead.

See Also

CancelEvent Action; ValidationRule, ValidationText Properties.


MsgBox Function

Description

Displays a message in a dialog box, waits for the user to choose a button, and returns a value indicating which button the user has chosen.

Syntax

MsgBox(prompt[, buttons][, title][, helpfile, context])

The MsgBox function syntax has these named arguments:

Part | Description
prompt | String expression displayed as the message in the dialog box. The maximum length of prompt is approximately 1024 characters, depending on the width of the characters used. If prompt consists of more than one line, you can separate the lines using either a carriage return character (Chr(13)), a linefeed character (Chr(10)), or carriage return-linefeed character combination (Chr(13) & Chr(10)) between each line.
buttons | Numeric expression that is the sum of values specifying the number and type of buttons to display, the icon style to use, the identity of the default button, and the modality of the message box. If omitted, the default value for buttons is 0.

Part | Description
title | String expression displayed in the title bar of the dialog box. If you omit title, the application name is placed in the title bar.
helpfile | String expression that identifies the Help file to use to provide context-sensitive Help for the dialog box. If helpfile is provided, context must also be provided.
context | Numeric expression that is the Help context number the Help author assigned to the appropriate Help topic. If context is provided, helpfile must also be provided.

Settings

The buttons argument settings are:

Constant | Value | Description
vbOKOnly | 0 | Display OK button only.
vbOKCancel | 1 | Display OK and Cancel buttons.
vbAbortRetryIgnore | 2 | Display Abort, Retry, and Ignore buttons.
vbYesNoCancel | 3 | Display Yes, No, and Cancel buttons.
vbYesNo | 4 | Display Yes and No buttons.
vbRetryCancel | 5 | Display Retry and Cancel buttons.
vbCritical | 16 | Display Critical Message icon.
vbQuestion | 32 | Display Warning Query icon.
vbExclamation | 48 | Display Warning Message icon.
vbInformation | 64 | Display Information Message icon.
vbDefaultButton1 | 0 | First button is default.
vbDefaultButton2 | 256 | Second button is default.
vbDefaultButton3 | 512 | Third button is default.
vbApplicationModal | 0 | Application modal; the user must respond to the message box before continuing work in the current application.
vbSystemModal | 4096 | System modal; all applications are suspended until the user responds to the message box.

The first group of values (0 – 5) describes the number and type of buttons displayed in the dialog box; the second group (16, 32, 48, 64) describes the icon style; the third group (0, 256, 512) determines which button is the default; and the fourth group (0, 4096) determines the modality of the message box. When adding numbers to create a final value for the argument buttons, use only one number from each group.

Note These constants are specified by Visual Basic for applications. As a result, the names can be used anywhere in your code in place of the actual values.

Return Values

Constant | Value | Button chosen
vbOK | 1 | OK
vbCancel | 2 | Cancel
vbAbort | 3 | Abort
vbRetry | 4 | Retry
vbIgnore | 5 | Ignore
vbYes | 6 | Yes
vbNo | 7 | No

Remarks

When both helpfile and context are provided, the user can press F1 to view the Help topic corresponding to the context. Some host applications (for example Microsoft Excel) also automatically add a Help button to the dialog box.

If the dialog box displays a Cancel button, pressing the ESC key has the same effect as choosing Cancel. If the dialog box contains a Help button, context-sensitive Help is provided for the dialog box. However, no value is returned until one of the other buttons is chosen.

Note If you want to specify more than the first named argument, you must use MsgBox in an expression. If you want to omit some positional arguments, you must include the corresponding comma delimiter.

See Also

InputBox Function.

Specifics (Microsoft Access)

You can use the MsgBox function in Microsoft Access to create a formatted error message similar to built-in error messages displayed by Microsoft Access. This function permits you to supply a string in three sections for the prompt argument. You separate the sections with the at sign (@).

The following example displays a formatted dialog box with a sectioned string. The first section of text in the string is displayed as a bold heading. The second section is displayed as plain text beneath that heading. The third section is displayed as plain text beneath the heading “Solution”, which the function provides for you.

MsgBox "Wrong button!@This button doesn't work.@Try another.", _
    vbOKOnly + vbExclamation

Note To display a message box without an icon in Microsoft Access, simply omit any constant that would denote an icon, or supply a value of zero for the buttons argument, as in the following example.

MsgBox "No icons included.", 0

Example

This example uses the MsgBox function to display a critical-error message in a dialog box with Yes and No buttons. The No button is specified as the default response. The value returned by the MsgBox function depends on the button chosen by the user. This example assumes that DEMO.HLP is a Help file that contains a topic with a Help context number equal to 1000.

Msg = "Do you want to continue ?"                ' Define message.= vbYesNo + vbCritical + vbDefaultButton2    ' Define buttons.= "MsgBox Demonstration"                    ' Define title.= "DEMO.HLP"                                ' Define Help file.= 1000                                        ' Define topic'
                                                ' context.
' Display message.= MsgBox(Msg, Style, Title, Help, Ctxt)Response = vbYes Then                            ' User chose Yes.
    MyString = "Yes"    ' Perform some action.    ' User chose No.
    MyString = "No"                                ' Perform some action.If

The following example uses the MsgBox function to create a formatted error message in Microsoft Access. Note the use of the at sign (@) to denote the different sections of the string.

Sub CustomMessage()
    Dim strMsg As String, strInput As String

    ' Initialize string.
    strMsg = "Number outside range.@You entered a number that is " _
        & "less than 1 or greater than 10.@Press OK to enter " _
        & "the number again."
    ' Prompt user for input.
    strInput = InputBox("Enter a number between 1 and 10.")
    ' Test value of user input.
    Do While strInput < 0 or strInput > 10
        If MsgBox (strMsg, vbOkCancel, "Error!") = vbOk Then
            strInput = InputBox("Enter a number between 1 and 10.")
        End If
    Loop
    ' Display user's correct input.
    MsgBox "You entered the number " & strInputSub


MultiSelect Property

Applies To

List Box Control.

Description

You can use the MultiSelect property to specify whether a user can make multiple selections in a list box and how the multiple selections can be made.

Setting

The MultiSelect property uses the following settings.

Setting | Description | Visual Basic
None | (Default) Multiple selection isn’t allowed. | 0
Simple | Multiple items are selected or deselected by choosing them with the mouse or pressing the spacebar. | 1
Extended | Multiple items are selected by pressing SHIFT+CLICK or SHIFT+ARROW to extend the selection from the previously selected item to the current item. Holding down CTRL and clicking an item selects or deselects that item. | 2

You can set the MultiSelect property in the list box’s property sheet, a macro, or using Visual Basic. You can also set this property in a list box’s default control style.

This property can be set in any view.

Remarks

You can use the ListIndex property to return the index for the selected item. When the MultiSelect property is set to Extended or Simple, you can use the list box’s Selected property or ItemsSelected collection to determine the items that are selected.

See Also

Column Property, ItemsSelected Collection, ListIndex Property, Selected Property.


Name Property

Applies To

Bound Object Frame Control, Chart Control, Check Box Control, Combo Box Control, Command Button Control, Form, Form Section, Image Control, Label Control, Line Control, List Box Control, Option Button Control, Option Group Control, Page Break Control, Rectangle Control, Report, Report Section, Subform/Subreport Control, Text Box Control, Toggle Button Control, Unbound Object Frame Control.

Description

You can use the Name property to specify a string expression that identifies the name of a form, report, section, or control.

Setting

A valid name must start with a letter and can include numbers, underscore characters (_), or any punctuation except brackets ([ ]). Spaces are allowed in form, report, and control names. For forms and reports, the name may be up to 64 characters long. For controls, the name may be as long as 255 characters.

For forms and reports, set the Name property by clicking Save on the File menu in Design view and entering a valid name. To change the name of an existing form or report in the Database window, click the name, then either click Rename on the Edit menu or click the name again. You can also change the name by clicking it with the right mouse button and clicking Rename on the shortcut menu. To change the name of an existing form or report when the object is open, click Save As/Export on the File menu.

For a section or control, you can set this property using the property sheet, a macro, or Visual Basic. You can use the Name property in expressions for forms and reports.

You can set this property only in Design view.

Remarks

The default name for new forms and reports is the object name plus a unique Integer. For example, the first new form is Form1, the second new form is Form2, and so on. A form can’t have the same name as another system object, such as the Screen object.

For an unbound control, the default name is the type of control plus a unique Integer. For example, if the first control you add to a form is a text box, its Name property setting is Text1.

For a bound control, the default name is the name of the field in the underlying source of data. If you create a control by dragging a field from the field list, the field’s FieldName property setting is copied to the control’s Name property box.

You can’t use “Form” or “Report” to name a control or section.

Controls on the same form or report can’t have the same name, but controls on different forms or reports can have the same name. A control and a section on the same form can’t share the same name.

See Also

Name Property (Microsoft Office 95 Data Access Reference), Screen Object.


Name Statement

Description

Renames a disk file, directory, or folder.

Syntax

Name oldpathname As newpathname

The Name statement syntax has these parts:

Part | Description
oldpathname | String expression that specifies the existing filename and location — may include directory or folder, and drive.
newpathname | String expression that specifies the new filename and location — may include directory or folder, and drive. The filename specified by newpathname can’t already exist.

Remarks

Both newpathname and oldpathname must be on the same drive. If the path in newpathname exists and is different from the path in oldpathname, the Name statement moves the file to the new directory or folder and renames the file, if necessary. If newpathname and oldpathname have different paths and the same filename, Name moves the file to the new location and leaves the filename unchanged. Using Name, you can move a file from one directory or folder to another, but you can’t move a directory or folder.

Using Name on an open file produces an error. You must close an open file before renaming it.

See Also

Kill Statement.

Example

This example uses the Name statement to rename a file. For purposes of this example, assume that the directories or folders that are specified already exist.

OldName = "OLDFILE": NewName = "NEWFILE"        ' Define filenames.OldName As NewName                        ' Rename file. = "C:\MYDIR\OLDFILE": NewName = "C:\YOURDIR\NEWFILE"OldName As NewName                        ' Move and rename file.


NavigationButtons Property

Applies To

Form.

Description

You can use the NavigationButtons property to specify whether navigation buttons and a record number box are displayed on a form.

Setting

The NavigationButtons property uses the following settings.

Setting | Description | Visual Basic
Yes | (Default) The form has navigation buttons and a record number box. | True (-1)
No | The form doesn’t have navigation buttons or a record number box. | False (0)

You can set this property using the form’s property sheet, a macro, or Visual Basic.

Remarks

Navigation buttons provide an efficient way to move to the first, previous, next, or last record. A record number box displays the number of the current record and the total number of records.


NewCurrentDatabase Method

Description

You can use the NewCurrentDatabase method to create a new database in the Microsoft Access window. You can use the this method to create a new database from another application that is controlling Microsoft Access through OLE Automation. For example, you can use the NewCurrentDatabase method from Microsoft Excel to create a new database in the Microsoft Access window.

Syntax

application.NewCurrentDatabase dbname

The NewCurrentDatabase method uses the following arguments.

Argument | Description
application | The Application object.
dbname | A string expression that is the name of a new database file, including the path name and the filename extension. If your network supports it, you can also specify a network path in the following form.
 | \\Server\Share\Directory\Filename.mdb

Remarks

The NewCurrentDatabase method enables you to create a new Microsoft Access database from another application through OLE Automation. Once you have created an instance of Microsoft Access from another application, you must also create a new database or specify a particular database to open. This database opens in the Microsoft Access window.

If the database identified by dbname already exists, an error occurs.

The new database is opened under the Admin user account.

See Also

OpenCurrentDatabase Method.

Example

The following example creates a new Microsoft Access database from another application through OLE Automation, then creates a new table in that database.

You can enter this code in a Visual Basic module in any application that can act as an OLE Automation controller. For example, you might run the following code from Microsoft Excel or Microsoft Visual Basic, or even Microsoft Access.

When the variable pointing to the Application object goes out of scope, the instance of Microsoft Access that it represents closes as well. Therefore, you should declare this variable at the module level.

' Include following in Declarations section of module.
' From Microsoft Excel, use "Dim appAccess As Object".appAccess As Access.Application
NewAccessDatabase()
    Dim dbs As Database, tdf As TableDef, fld As Field
    Dim strDB As String

    ' Initialize string to database path.
    strDB = "C:\My Documents\Newdb.mdb"
    ' Create new instance of Microsoft Access.
    Set appAccess = CreateObject("Access.Application.7")
    ' Open database in Microsoft Access window.
    appAccess.NewCurrentDatabase(strDB)
    ' Get Database variable.
    Set dbs = appAccess.CurrentDb
    ' Create new table.
    Set tdf = dbs.CreateTableDef("Contacts")
    ' Create field in new table.
    Set fld = tdf.CreateField("Name", dbText, 20)
    ' Append Field and TableDef objects.
    tdf.Fields.Append fld
    dbs.TableDefs.Append tdfSub

Note From some applications, such as Microsoft Visual Basic 4.0, you can include the New keyword when declaring the Application object variable. This keyword automatically creates a new instance of Microsoft Access, without requiring you to use the CreateObject function. Check your application’s documentation to determine whether it supports this syntax.


NewRecord Property

Applies To

Form.

Description

You can use the NewRecord property to determine whether the current record is a new record.

Setting

The NewRecord property has the following settings.

The NewRecord property is read-only in Form view and Datasheet view. It is not available in Design view. This property is available only in macros, or Visual Basic.

Remarks

When a user has moved to a new record, the NewRecord property setting will be True whether the user has started to edit the record or not.

See Also

CurrentRecord Property.

Example

The following example shows how to use the NewRecord property to determine if the current record is a new record. The NewRecordMark procedure sets the current record to the variable newrec. If the record is new, a string is assigned to the string variable newmsg.

Sub NewRecordMark(frm As Form)
    Dim newrec As Integer
    Dim newmsg As String
    newrec = frm.NewRecord
    If newrec = True Then
        newmsg = "new record"
    End IfSub


NewRowOrCol Property

Applies To

Form Section, Report Section.

Description

You can use the NewRowOrCol property to specify whether a section and its associated data is printed in a new row or column within a multiple-column report. For example, you can use this property to print each group header at the top of a new column in a multiple-column report.

Note The NewRowOrCol property does not apply to page headers or page footers.

Setting

The NewRowOrCol property uses the following settings.

You can set this property using the section’s property sheet, a macro, or Visual Basic.

You can set the NewRowOrCol property only in report Design view.

Remarks

The following items are some sample settings for a group header section in a multiple-column report. The Layout Items option in the Layout tab of the Page Setup dialog box (available by clicking Page Setup on the File menu) should be set to Down, Then Across.

Report sections in a form or report are normally printed vertically down a page. The default Layout Items option is Across, Then Down. You can print the sections in multiple columns across a page by setting the Layout Items option in the Layout tab of the Page Setup dialog box to Down, Then Across.

When you set the NewRowOrCol property to Before Section, the vertical or horizontal orientation of the page affects how the section is printed. If you select Across, Then Down in the Layout Items option in the Layout tab of the Page Setup dialog box, Microsoft Access starts printing the section at the beginning of a new row; if you select Down, Then Across, Microsoft Access starts printing the section at the beginning of a new column.

See Also

Event Properties, ForceNewPage Property.

Example

The following example returns the NewRowOrCol property setting and assigns it to the intGetVal variable.

Dim intGetVal As Integer= Reports!MyReport.Section(1).NewRowOrCol

The next example presents two layouts for a report that divides data into four groups (Head1 to Head4). Each group includes three to six records, and each record has field a and field b. The layouts differ only in their Layout Items option in the Layout tab of the Page Setup dialog box and the values of their NewRowOrCol properties.

· Layout Items — Across, Then Down

· Grid Settings — Items Across set to 4

· NewRowOrCol property setting for group header section — Before & After

Head1

1a 1b 2a 2b 3a 3b 4a 4b 5a 5b

Head2

1a 1b 2a 2b 3a 3b 4a 4b

Head3

1a 1b 2a 2b 3a 3b

Head4

1a 1b 2a 2b 3a 3b 4a 4b

5a 5b 6a 6b

· Layout Items — Down, Then Across

· Grid Settings — Items Across set to 4

· NewRowOrCol property setting for group header section — Before Section

Head1 Head2 Head3 Head4

1a 1b 1a 1b 1a 1b 1a 1b

2a 2b 2a 2b 2a 2b 2a 2b

3a 3b 3a 3b 3a 3b 3a 3b

4a 4b 4a 4b 4a 4b

5a 5b 5a 5b

6a 6b


NewValues Property

Applies To

Table.

Description

You can use the NewValues property to specify how AutoNumber fields increment when new records are added to a table.

Note The NewValues property applies only to AutoNumber fields.

Setting

The NewValues property uses the following settings.

You can set this property in the table’s property sheet in table Design view by clicking the General tab under Field Properties.

Remarks

When you replicate a database, AutoNumber field settings are set to Random to ensure that new records entered in different replicas will have unique values.


NoData Event

Applies To

Report.

Description

The NoData event occurs after Microsoft Access formats a report for printing that has no data (the report is bound to an empty recordset), but before the report is printed. You can use this event to cancel printing of a blank report.

Remarks

If the report is not bound to a table or query (using the report’s RecordSource property), the NoData event does not occur.

This event occurs after the Format events for the report, but before the first Print event.

This event does not occur for subreports. If you want to hide controls on a subreport when the subreport has no data, so that the controls don’t print in this case, you can use the HasData property in a macro or event procedure that runs when the Format or Print event occurs.

The NoData event occurs before the first Page event for the report.

See Also

Format Event, HasData Property, Print Event, Retreat Event.


NoData Event -- Event Procedures

Description

To create an event procedure that is executed when the NoData event occurs, set the OnNoData property to [Event Procedure], and click the Build button.

Syntax

Private Sub Report_NoData(Cancel As Integer)

The NoData event procedure uses the following argument.

Argument | Description
Cancel | The setting determining whether to print the report. Setting Cancel to True (-1) prevents the report from printing. You can also use the CancelEvent method of the DoCmd object to cancel printing the report.

See Also

NoData Event — Macros.

Example

The following example shows how to cancel printing a report when it is blank. A message box notifying the user that the printing has been canceled is also displayed.

Private Sub Report_NoData(Cancel As Integer)
    MsgBox "The report has no data." & _
    "@Printing the report is canceled. " & _
    "@Check the source of data for the report to make sure you " & _
    "entered the correct criteria (for example, a valid range " & _
    "of dates).", vbOKOnly + vbInformation
    Cancel = TrueSub


NoData Event -- Macros

Description

To run a macro when the NoData event occurs, set the OnNoData property to the name of the macro.

Remarks

You can use the CancelEvent action in a NoData macro to cancel printing of the blank report.

See Also

NoData Event — Event Procedures.


Not Operator

Description

Used to perform logical negation on an expression.

Syntax

result = Not expression

The Not operator syntax has these parts:

Part | Description
result | Any numeric variable.
expression | Any expression.

Remarks

The following table illustrates how result is determined:

If expression is | Then result is
True | False
False | True
Null | Null

In addition, the Not operator inverts the bit values of any variable and sets the corresponding bit in result according to the following truth table:

TR>
Bit in expression | Bit in result
0 | 1
1 | 0

See Also

Operator Precedence.

Example

This example uses the Not operator to perform logical negation on an expression.

A = 10: B = 8: C = 6: D = Null    ' Initialize variables.= Not(A > B)                ' Returns False.= Not(B > A)                ' Returns True.= Not(C > D)                ' Returns Null.= Not A                    ' Returns -11 (bit-wise comparison).


Nothing

Description

The Nothing keyword in Visual Basic is used to disassociate an object variable from any actual object. Use the Set statement to assign Nothing to an object variable. For example:

Set MyObject = Nothing

Several object variables can refer to the same actual object. When Nothing is assigned to an object variable, that variable no longer refers to any actual object. When several object variables refer to the same object, memory and system resources associated with the object to which the variables refer are released only after all of them have been set to Nothing, either explicitly using Set, or implicitly after the last object variable set to Nothing goes out of scope.

See Also

Dim Statement, Private Statement, Public Statement, Set Statement.


NotInList Event

Applies To

Combo Box Control.

Description

The NotInList event occurs when the user enters a value in the text box portion of a combo box that isn’t in the combo box list.

Note The NotInList event applies only to controls on a form, not controls on a report.

Remarks

This event enables the user to add a new value to the combo box list.

The LimitToList property must be set to Yes for the NotInList event to occur.

The NotInList event doesn’t trigger the Error event.

The NotInList event occurs for combo boxes whose LimitToList property is set to Yes after you enter a value that is not in the list and attempt to move to another control or save the record. It occurs after all the Change events for the combo box.

See Also

BeforeUpdate, AfterUpdate Events; Change Event; LimitToList Property.


NotInList Event -- Event Procedures

Description

To create an event procedure that is executed when the NotInList event occurs, set the OnNotInList property to [Event Procedure], and click the Build button.

Syntax

Private Sub controlname_NotInList(NewData As String, Reponse As Integer)

The NotInList event procedure uses the following arguments

Argument | Description
controlname | A string that is the name of the control affected by the NotInList event procedure.
NewData | A string that Microsoft Access uses to pass the text the user entered in the text box portion of the combo box to the event procedure.

Argument | Description
Response | An intrinsic constant that indicates how the NotInList event was handled. The Response argument can have the following constants.

Constant acDataErrDisplay | Description (Default) Displays the default message to the user. You can use this when you don’t want to allow the user to add a new value to the combo box list.
acDataErrContinue | Doesn’t display the default message to the user. You can use this when you want to display a custom message to the user. For example, the event procedure could display a custom dialog box asking if the user wanted to save the new entry. If the response is Yes, the event procedure would add the new entry to the list and set the Response argument to acDataErrAdded. If the response is No, the event procedure would set the Response argument to acDataErrContinue.
acDataErrAdded | Doesn’t display a message to the user but enables you to add the entry to the combo box list in the NotInList event procedure. After the entry is added, Microsoft Access updates the list by requerying the combo box. Microsoft Access then rechecks the string against the combo box list, and saves the value in NewData in the field the combo box is bound to. If the string is not in the list, then Microsoft Access displays an error message.

Remarks

You can create an event procedure for the NotInList event that provides a way for the user to add a new item to the combo box list. For example, you can add a record to the table that supplies the list’s values, or add a value to the value list that is the source for the combo box list.

To add a new entry to a combo box list, your event procedure must add the value in the NewData argument to the source of the combo box list. How you do this depends on the type of source the combo box list uses, as determined by the RowSourceType and RowSource properties of the combo box. In the Example in this topic, the event procedure adds the new value to a value list for the combo box.

If you let the user change the value originally typed in the combo box (for example, in a custom dialog box), you must set the combo box value to the new entry entered in the custom dialog box. This saves the new value in the field the combo box is bound to. Set the Response argument to acDataErrContinue, and Microsoft Access will add the new value to the combo box list.

See Also

NotInList Event — Macros.

Example

The following example uses the NotInList event to add an item to a combo box.

To try this example, create a combo box called Colors on a form. Set the LimitToList property of the combo box to Yes. To populate the combo box, set the RowSourceType property of the combo box to Value List, and supply a list of values separated by semicolons as the setting for the RowSource property. For example, you might supply the following values as the setting for this property: Red; Green; Blue.

Next add the following code to the Declarations section of the form. Switch to Form view and enter a new value in the text portion of the combo box.

Private Sub Colors_NotInList(NewData As String, _
        Response As Integer)
    Dim ctl As Control

    ' Return Control object that points to combo box.
    Set ctl = Me!Colors
    ' Prompt user to verify they wish to add new value.
    If MsgBox("Value is not in list. Add it?", vbOKCancel) = vbOK Then
        ' Set Response argument to indicate that data is being added.
        Response = acDataErrAdded
        ' Add string in NewData argument to row source.
        ctl.RowSource = ctl.RowSource & ";" & NewData
    Else
    ' If user chooses Cancel, suppress error message and undo changes.
        Response = acDataErrContinue
        ctl.Undo
    End IfSub

Note The above example adds an item to an unbound combo box. When you add an item to a bound combo box, you add a value to a field in the underlying data source. In most cases you can’t simply add one field in a new record — depending on the structure of data in the table, you probably will need to add one or more fields to fulfill data requirements. For instance, a new record must include values for any fields comprising the primary key. If you need to add items to a bound combo box dynamically, you must prompt the user to enter data for all required fields, save the new record, and then requery the combo box to display the new value.


NotInList Event -- Macros

Description

To run a macro when the NotInList event occurs, set the OnNotInList property to the name of the macro.

Remarks

You can use a NotInList macro to add a new value to the combo box list. When the NotInList event occurs, open a custom dialog box and set the value of one of its controls to the new value. This control should be bound to the field in the table or query that is the source for the combo box. Save the record in the custom dialog box, then requery the combo box.

You can’t use the CancelEvent action in a NotInList macro.

See Also

NotInList Event — Event Procedures.


Now Function

Description

Returns the current date and time according to the setting of your computer’s system date and time.

Syntax

Now

See Also

Date Function, Date Statement, Day Function, Hour Function, Minute Function, Month Function, Second Function, Time Function, Time Statement, Weekday Function, Year Function.

Example

This example uses the Now function to return the current system date and time.

Today = Now            ' Assign current system date and time.

You can use the Now function in a calculated control to return the current system date and time. For example, you can create a text box and set its ControlSource property to the following expression.

= Now()


NPer Function

Description

Returns the number of periods for an annuity based on periodic, constant payments and a constant interest rate.

Syntax

NPer(rate, pmt, pv[, fv[, type]])

The NPer function has these named arguments:

Part | Description
rate | Interest rate per period. For example, if you get a car loan at an annual percentage rate (APR) of 10 percent and make monthly payments, the rate per period is 0.1/12, or 0.0083.
pmt | Payment to be made each period. Payments usually contain principal and interest that doesn’t change over the life of the annuity.
pv | Present value, or value today, of a series of future payments or receipts. For example, when you borrow money to buy a car, the loan amount is the present value to the lender of the monthly car payments you will make.
fv | Future value or cash balance you want after you’ve made the final payment. For example, the future value of a loan is $0 because that’s it value after the final payment. However, if you want to save $50,000 for your child’s education over 18 years, then $50,000 is the future value. If omitted, 0 is assumed.
type | Number indicating when payments are due. Use 0 if payments are due at the end of the payment period, or use 1 if payments are due at the beginning of the period. If omitted, 0 is assumed.

Remarks

An annuity is a series of constant cash payments made over a period of time. An annuity can be a loan (such as a home mortgage) or an investment (such as a monthly savings plan).

For all arguments, cash paid out (such as deposits to savings) is represented by negative numbers; cash received (such as dividend checks) is represented by positive numbers.

Example

This example uses the NPer function to return the number of periods over which payments must be made to pay off a loan whose value is contained in PVal. Also provided are the interest percentage rate per period (APR / 12), the payment (Payment), the future value of the loan (FVal), and a number that indicates whether the payment is due at the beginning or end of the payment period (PayType).

Const ENDPERIOD = 0, BEGINPERIOD = 1            ' When payments are made.= 0                                        ' Usually 0 for a loan.= InputBox("How much do you want to borrow?")= InputBox("What is the annual percentage rate of your loan?")APR > 1 Then APR = APR / 100                ' Ensure proper form.= InputBox("How much do you want to pay each month?")= MsgBox("Do you make payments at the end of month?", vbYesNo)PayType = vbNo Then PayType = BEGINPERIOD Else PayType = ENDPERIOD= NPer(APR / 12, -Payment, PVal, FVal, PayType)Int(TotPmts) <> TotPmts Then TotPmts = Int(TotPmts) + 1"It will take you " & TotPmts & " months to pay off your loan."


NPV Function

Description

Returns the net present value of an investment based on a series of periodic cash flows (payments and receipts) and a discount rate.

Syntax

NPV(rate, values())

The NPV function has these named arguments:

Part | Description
rate | Discount rate over the length of the period, expressed as a decimal.
values( ) | Array of cash flow values. The array must contain at least one negative value (a payment) and one positive value (a receipt).

Remarks

The net present value of an investment is the current value of a future series of payments and receipts.

The NPV function uses the order of values within the array to interpret the order of payments and receipts. Be sure to enter your payment and receipt values in the correct sequence.

The NPV investment begins one period before the date of the first cash flow value and ends with the last cash flow value in the array.

The net present value calculation is based on future cash flows. If your first cash flow occurs at the beginning of the first period, the first value must be added to the value returned by NPV and must not be included in the cash flow values of values().

The NPV function is similar to the PV function (present value) except that the PV function allows cash flows to begin either at the end or the beginning of a period. Unlike the variable NPV cash flow values, PV cash flows must be constant throughout the investment.

Example

This example uses the NPV function to return the net present value for a series of cash flows contained in the array Values(). RetRate represents the fixed internal rate of return.

Static Values(5) As Double                ' Set up array.= "###,##0.00"                        ' Define money format.= .1                                ' Guess starts at 10 percent.= .0625                            ' Set fixed internal rate.(0) = -70000                        ' Business start-up costs.
' Positive cash flows reflecting income for four successive years.(1) = 22000 : Values(2) = 25000(3) = 28000 : Values(4) = 31000= NPV(RetRate, Values())            ' Calculate net present value.= "The net present value of these cash flows is "= Msg & Format(NetPVal, Fmt) & "."Msg                                ' Display net present value.


Number Property

Applies To

Err Object.

Description

Returns or sets a numeric value specifying an error. Number is the Err object’s default property.

Syntax

object.Number [= errornumber]

The Number property syntax has these parts:

Part | Description
object | Always the Err object.
errornumber | A Long integer representing a Basic error number or an OLE SCode error value.

Remarks

Because the Number property is the Err object’s default property, existing code that uses the Err function does not have to be revised. All of the following correctly return or set the Number property:

Err.Number = 5            ' Set the Err object's Number property to 5.= 5                    ' Set the Err object's Number property to 5..Print Err            ' Display the Err object's Number property..Print Err.Number    ' Display the Err object's Number property.

When returning a user-defined error from an OLE Automation object, set Err.Number by adding the number you’ve chosen as an error code to the constant vbObjectError. For example, you use the following code to return the number 1051 as an error code:

Err.Raise Number := vbObjectError + 1051, Source:= "SomeClass"

Not all Visual Basic host applications can create OLE Automation objects. See your host application’s documentation to determine whether it can create classes and OLE Automation objects. However, all host applications can create OLE Automation controllers, and should use code like the following when interpreting error codes returned from objects:

' Code to trap a specific VB object error.Err.Number = vbObjectError + 1051 Then
...    Err.Number - vbObjectError > 0 Then
    ' Other Visual Basic object-generated errors are between 0-65535.
    If Err.Number - vbObjectError < 65535 Then
        ...        ' Code to handle Visual
    End If        ' Basic object errors.Err.Number > 0 Then
' If a VB object returns a system-defined error,there is no need to
' strip vbObjectError.
    If Err.Number < 65535 Then
        ...
    End IfIf

The first If traps a specific object-defined error by combining it with the constant vbObjectError. Action can then be taken for the object’s error number 1051. The first ElseIf traps a range of object-defined errors. It subtracts vbObjectError from Err.Number, then examines the result to see if it is in the range for an object-defined error. If it is, the action taken should depend on the documentation of the error provided by the object. The final ElseIf checks to see if the error is simply a Visual Basic trappable runtime error (a system error), for example File not found (Error 53) that may have been passed back by the object. Note that although the range for these is 0–65535, the actual number of defined errors is currently fewer than 1000.

Since Number is a property, it behaves like a function call, and this may be significant if Err is passed to a procedure. If you have existing code in which you rely on a change in Err being copied back to the caller through the procedure’s parameter, it may fail even if Err is passed ByRef. However, since Err is a global object, there is no need to pass it as an argument at all. Make any desired changes directly to Err or Err.Number in the called procedure.

See Also

Description Property, Err Object, HelpContext Property (Visual Basic), HelpFile Property (Visual Basic), LastDLLError Property, Source Property.

Example

This example examines the Number property of the Err object to determine whether an error returned by an object was defined by the object, or whether it was mapped to an error defined by Visual Basic. Note that the constant vbObjectError is a very large negative number that an object adds to its own error code to indicate that the error is defined by the server. Therefore, subtracting it from Err.Number strips it out of the result. If the error is object-defined, the base number is left in MyError, which is displayed in a message box along with the original source of the error. If Err.Number represents a Visual Basic error, then the Visual Basic error number is displayed in the message box.

' First, strip off the constant added by the object to indicate one
' of its own errors.= Err.Number - vbObjectError
' If you subtract the vbObjectError constant, and the number is still
' in the range 0-65,535, it is an object-defined error code.MyError > 0 and MyError < 65535 Then
    Msg = "The object you accessed assigned this number " & _
        "to the error: " & MyError & ". " & _
        "The originator of the error was: " & Err.Source & ". " & _
        "Press F1 to see the originator’s Help topic. "
'Otherwise it is a Visual Basic error number.
    Msg = "This error (#" & Err.Number & ") " & _
        "is a Visual Basic error number. Press Help button " & _
        "or F1 for the Visual Basic Help topic for this error. "If
    MsgBox Msg, , "Object Error", Err.HelpFile, Err.HelpContext


Nz Function

Description

Use the Nz function to return zero, a zero-length string (" "), or another specified value when a Variant is Null. For example, you can use this function to convert a Null value to another value and prevent it from propagating through an expression.

Syntax

Nz(variant[, valueifnull])

The Nz function uses the following arguments.

Argument | Description
variant | A variable of data type Variant.
valueifnull | Optional. A Variant that supplies a value to be returned if the variant argument is Null. This argument enables you to return aother than zero or a zero-length string.

If the value of variant is Null, the Nz function returns the number zero or a zero-length string, depending on whether the context indicates the value should be a number or a string. If the optional argument valueifnull is included, then the Nz function will return the value specified by that argument if variant is Null.

If the value of variant is not Null, then the Nz function returns the value of variant.

Remarks

The Nz function is useful for expressions that may include Null values. To force an expression to evaluate to a non-Null value even when it contains a Null value, use the Nz function to return a zero, a zero-length string, or a custom return value.

For example, the expression 2 + varX will always return a Null value when the Variant varX is Null. However, 2 + Nz(varX) returns 2.

You can often use the Nz function as an alternative to the IIf function. For example, in the following code, two expressions including the IIf function are necessary to return the desired result. The first expression including the IIf function is used to check the value of a variable and convert it to zero if it is Null.

varTemp = IIf(IsNull(varFreight), 0, varFreight)= IIf(varTemp > 50, "High", "Low")

In the next example, the Nz function provides the same functionality as the first expression, and the desired result is achieved in one step rather than two.

varResult = IIf(Nz(varFreight) > 50, "High", "Low")

If you supply a value for the optional argument valueifnull, that value will be returned when variant is Null. By including this optional argument, you may be able to avoid using an expression containing the IIf function. For example, the following expression uses the IIf function to return a string if the value of varFreight is Null.

varResult = IIf(IsNull(varFreight), "No Freight Charge", varFreight)

In the next example, the optional argument supplied to the Nz provides the string to be returned if varFreight is Null.

varResult = Nz(varFreight, "No Freight Charge")

See Also

Is Operator, IsEmpty Function, IsNull Function.

Example

The following example evaluates a control on a form and returns one of two strings based on the control’s value. If the value of the control is Null, the procedure uses the Nz function to convert a Null value to a zero-length string.

Sub CheckValue()
    Dim frm As Form, ctl As Control
    Dim varResult As Variant

    ' Return Form variable pointing to Orders form.
    Set frm = Forms!Orders
    ' Return Control variable pointing to ShipRegion.
    Set ctl = frm!ShipRegion
    ' Choose result based on value of control.
    varResult = IIf(Nz(ctl.Value) = "", "No value", _
        "Value is " & ctl.Value)
    ' Display result.
    MsgBox varResultSub


Object Data Type

Description

Object variables are stored as 32-bit (4-byte) addresses that refer to OLE Automation objects within an application. A variable declared as an Object is one that can subsequently be assigned (using the Set statement) to refer to any object produced by the application.

See Also

Data Type Summary, Def type Statements, IsObject Function, Variant Data Type.


Object Properties

Applies To

Form, Query, Report, Table.

Description

The Object properties provide general information about objects contained in the database window.

Setting

You can view the Object properties, and set the Description or Attributes properties, by clicking the Properties icon on the Database toolbar, clicking the Properties command on the View menu, or choosing the Properties command from the popup menu that appears when you right click on an object in the database window.

You can also specify or determine the Object properties using Visual Basic.

Note You can only enter or edit the Description or Attributes properties. The other Object properties are set by Microsoft Access and are read-only.

Remarks

The objects in the database window are: Tables, Queries, Forms, Reports, Macros, and Modules. Each class of objects in the database is represented by a separate Document object within the Containers collection. For example, the Containers collection contains a Document object that represents all the forms in the database.

The Object properties available from the database window are:

Name

This is the name of the object and contains the setting from the object’s Name property.

Type

This is the object type. Microsoft Access object types are: Form, Macro, Module, Query, Report, and Table.

Description

This is the object’s description and is the same as the Description property. For tables or queries, you can also set the object’s Description property in the object’s property sheet. An object’s description also appears next to the object’s name in the database window if the Details command is selected from the View menu.

Created

This is the date that the object was created. For tables or queries, this property is the same as the DateCreated property.

Modified

This is the date that the object was last modified. For tables or queries this property is the same as the LastUpdated property.

Owner

This is the owner of the object. For more information, see the Owner property.

Attributes

This property specifies whether the object is hidden or visible and whether the object is replicable in a database replica.

If you set the hidden attribute to True, the object will not appear in the database window. To display hidden objects in the database window choose the Options command on the Tools menu, click the View tab, and then select the Hidden objects check box. The icons for hidden objects will be displayed with a dimmed outline in the database window. You can then turn the hidden attribute off, making the object visible in the database window.

See Also

Containers Collection; DateCreated, LastUpdate Properties; Description Property; Documents Collection; Name Property; Microsoft Office 95 Data Access Reference: Description Property; Name Property.

Example

The following example uses the PrintObjectProperties subroutine to print the values of an object’s Object properties to the Debug Window. The subroutine requires the object type and object name as arguments.

Dim strObjectType As StringstrObjectName As StringstrMsg As String
= "Enter object type (e.g., Forms, Macros, " & _
    "Modules, Queries, Reports, Tables)"
' Get object type.= InputBox(strMsg)= "Enter the name of a Form, Macro, Module, " & _
    "Query, Report, or Table"
' Get object name from user.= InputBox(strMsg)
' Pass object type and object name to the PrintObjectProperties
' subroutine.strObjectType, strObjectName
PrintObjectProperties(strObjectType As String, _
        strObjectName As String)
    Dim dbs As Database, cnt As Container, doc As Document
    Dim intI As Integer
    Dim strTabChar As String
    Set dbs = CurrentDb
    strTabChar = Chr$(9)
    ' Set container object variable.
    Set cnt = dbs.Containers(strObjectType)
    ' Set document object variable.
    Set doc = cnt.Documents(strObjectName)
    doc.Properties.Refresh
    ' Print the object name to the Debug window.
    Debug.Print doc.Name
    ' Print each object property to Debug window.
    For intI = 0 to doc.Properties.Count - 1
        Debug.Print strTabChar & doc.Properties(intI).Name & " = " _
            & doc.Properties(intI).Value
    Next intISub


Object Property

Applies To

Bound Object Frame Control, Chart Control, Unbound Object Frame Control.

Description

You can use the Object property in Visual Basic to specify a linked or embedded OLE Automation object in a control.

Setting

The Object property setting is a Object data type value that specifies an OLE Automation object used in OLE Automation tasks.

The Object property setting is read-only in all views.

Remarks

You perform OLE Automation tasks on an OLE Automation object using properties and methods the object supports. For information on which properties and methods an OLE Automation object supports, see the documentation for the application that created the object.

See Also

OLE Automation.

Example

The following example uses the Object property of an unbound object frame named OLE1. Customer name and address information is inserted into an embedded word document formatted as a form letter with placeholders for the name and address information and boilerplate text in the body of the letter. The procedure replaces the address information for each record and prints the form letter. It doesn’t save copies of the printed form letter.

Sub PrintFormLetter_Click()
    Dim objWord As Object
    Dim strCustomer As String, strAddress As String
    Dim strCity As String, strRegion As String
    ' Assign the object property of control to variable.
    Set objWord = Me!OLE1.Object.Application.Wordbasic
    ' Assign customer address information to variables.
    Me!CompanyName.SetFocus
    strCustomer = Me!CompanyName.Text
    Me!Address.SetFocus
    strAddress = Me!Address.Text
    Me!City.SetFocus
    strCity = Me!City.Text & ", "
    Me!Region.SetFocus
    If Not IsNull(Me!Region.Text) Then
        strRegion = Me!Region.Text
    Else
        Me!Country.Setfocus
        strRegion = Me!Country.Text
    End If
    Me!OLE1.Action = acOLEActivate        ' Activate OLE control.
    objWord.StartOfDocument
    objWord.LineDown 2
    objWord.EndOfLine 1
    objWord.Insert strCustomer            ' Insert customer name.
    objWord.LineDown
    objWord.StartOfLine
    objWord.EndOfLine 1
    objWord.Insert strAddress            ' Insert address.
    objWord.LineDown
    objWord.StartOfLine
    objWord.EndOfLine 1
    objWord.Insert strCity & strRegion    ' Insert City and Region.
    objWord.FilePrint                    ' Print Word document.
    objWord.FileClose
    Set objWord = NothingSub


ObjectPalette Property

Applies To

Bound Object Frame Control, Chart Control, Command Button Control, Form, Report, Toggle Button Control, Unbound Object Frame Control.

Description

You can use the ObjectPalette property with the PaintPalette property to specify which palette is used by the application to create:

  • An OLE object contained in a bound object frame, chart, or unbound object frame.
  • A bitmap that is loaded into a command button or a toggle button using the Picture property.

Setting

Microsoft Access uses a String data type in the ObjectPalette property to set the value of the PaintPalette property for a form or report.

For the following objects, views, and controls, the Object Palette property setting is read-only.

Object | View | Control
Forms | Design view and Form view | Command button, chart, toggle button, and unbound object frame
 | Form view | Bound object frame
Reports | Design view | Command button, chart, toggle button, and unbound object frame

You can use this property only in a macro or Visual Basic.

Remarks

The setting of the ObjectPalette property makes the palette of the application associated with the OLE object available to the PaintPalette property of a form or report. For example, to make the palette used in Microsoft Graph available when you’re designing a form in Microsoft Access, you set the form’s PaintPalette property to the ObjectPalette value of an existing chart control.

Note Windows can have only one color palette active at a time. Microsoft Access allows you to have multiple graphics on a form, each using a different color palette. The PaletteSource property lets you specify which color palette a form should use when displaying graphics.

See Also

PaintPalette Property, PaletteSource Property, Picture Property.

Example

The following example sets the PaintPalette property of the Seascape form to the ObjectPalette property of the Ocean control on the DisplayPictures form. (Ocean can be a bound object frame, command button, chart, toggle button, or unbound object frame.)

Forms![Seascape].PaintPalette = _     Forms![DisplayPictures]![Ocean].ObjectPalette

The ObjectPalette and PaintPalette properties are useful for programmatically altering the color palette in use by an open form at run time. A common use of these properties is to set the current form PaintPalette property to that of a graphic displayed in a control that has the focus.

For example, you can have a form with an ocean picture, showing many shades of blue, and a sunset picture, showing many shades of red. Since Windows only allows one color palette active at a time, one picture will look much better than the other. The following example uses a control’s Enter event for setting the form’s PaintPalette property to the control’s ObjectPalette property so the graphic that has the focus will have an optimal appearance.

Sub OceanPicture_Enter()
    Me.PaintPalette = Me![OceanPicture].ObjectPaletteSub
SunsetPicture_Enter()
    Me.PaintPalette = Me![SunsetPicture].ObjectPaletteSub


ObjectVerbs Property

Applies To

Bound Object Frame Control, Chart Control, Unbound Object Frame Control.

Description

You can use the ObjectVerbs property in Visual Basic to determine the list of verbs an OLE object supports. A verb, such as edit or play, specifies an operation a user can perform on an OLE object.

Setting

The ObjectVerbs property setting is a zero-based string array.

This property setting isn’t available in Design view and is read-only in other views.

Remarks

You can use the ObjectVerbs property with the ObjectVerbsCount property to display a list of the verbs supported by an OLE object. The Verb property uses this list of verbs to determine which operation to perform when an OLE object is activated (when the Action property is set to acOLEActivate).

The Verb property setting is the position of a particular verb in the list of verbs returned by the ObjectVerbs property. For example, 1 specifies the first verb in the list (the Visual Basic command ObjectVerbs(0), or the first verb in the ObjectVerbs property array), 2 specifies the second verb in the list (the Visual Basic command ObjectVerbs(1), or the second verb in the ObjectVerbs property array), and so on.

The first verb in the ObjectVerbs property array, called by the Visual Basic command ObjectVerbs(0), is the default verb. If the Verb property hasn’t been set, this verb specifies the operation performed when the OLE object is activated.

Applications that expose OLE objects typically include the Object command on the Edit menu. When the user clicks this command, a submenu displays the object’s verbs. You can use the ObjectVerbs and ObjectVerbsCount properties to display a list of verbs in a form or report instead of on a menu.

The list of verbs an object supports varies, depending on the state of the object. To update the list of verbs an object supports, set the control’s Action property to acOLEFetchVerbs. Be sure to update the list of verbs before presenting it to the user.

See Also

Action Property, ObjectVerbsCount Property, Verb Property.

Example

The following example returns the verbs supported by the OLE object in the OLE1 control and displays each verb in a message box.

Function GetVerbList(frm As Form) As Integer
    Dim intX As Integer, intNumVerbs As Integer
    Dim strVerbListArray() As String
    frm!OLE1.Action = acOLEFetchVerbs    ' Update verb list.
    intNumVerbs = frm!OLE1.ObjectVerbsCount
    ReDim strVerbListArray(intNumVerbs)
        For intX = 0 To intNumVerbs - 1    ' For each verb.
        ' Return verb.
        strVerbListArray(intX) = frm!OLE1.ObjectVerbs(intX)
        MsgBox strVerbListArray(intX)    ' Display verb in message box.
    Next intXFunction


ObjectVerbsCount Property

Applies To

Bound Object Frame Control, Chart Control, Unbound Object Frame Control.

Description

You can use the ObjectVerbsCount property in Visual Basic to determine the number of verbs supported by an OLE object. A verb, such as edit or play, specifies an operation a user can perform on an OLE object.

Setting

The ObjectVerbsCount property setting is an Integer data type value that specifies the number of elements in the ObjectVerbs property array.

This property setting isn’t available in Design view and is read-only in other views.

Remarks

The list of verbs an OLE object supports may vary, depending on the state of the object. To update the list of supported verbs, set the control’s Action property to acOLEFetchVerbs.

See Also

Action Property, ObjectVerbs Property, Verb Property.

Example

See the ObjectVerb property example.


Oct Function

Description

Returns a string representing the octal value of a number.

Syntax

Oct(number)

The number argument is any valid numeric or string expression.

Remarks

If number is not already a whole number, it is rounded to the nearest whole number before being evaluated.

If number is | Oct returns
Null | Null.
Empty | Zero (0).
Any other number | Up to 11 octal characters.

You can represent octal numbers directly by preceding numbers in the proper range with &O. For example, &O10 is the octal notation for decimal 8.

See Also

Hex Function.

Example

This example uses the Oct function to return the octal value of a number.

MyOct = Oct(4)         ' Returns 4.= Oct(8)        ' Returns 10.= Oct(459)        ' Returns 713.


ODBCConnectStr Property

Applies To

Query.

Description

You can use the ODBCConnectStr property in an SQL pass-through query to specify the Open Database Connectivity (ODBC) connection string for the query.

Note The ODBCConnectStr property applies only to pass-through queries.

Setting

Enter the ODBC connection string that defines the connection to the SQL database you want to use.

You can set this property using the query property sheet or Visual Basic.

You can also use the ODBC Connection String Builder to create the ODBC connection string for this property. This builder establishes a connection to the SQL database server and then ends the connection after the ODBC connection string is created.

Remarks

The default setting for this property is the string “ODBC;”, which Microsoft Access restores if you delete an existing setting. When the ODBCConnectStr property is set to “ODBC;”, Microsoft Access will prompt you for a connection string whenever the query is used but won’t store the connect string. You must enter a connection string in the ODBCConnectStr property box if you want Microsoft Access to store the connection string.

Tip If you know the full connection string for the SQL database, enter it in the ODBCConnectStr property box. This way you will avoid the need to enter the connection string in the ODBC connection dialog box each time you use the query.

The connection string is different for different types of ODBC data sources. For example, to connect to the Human Resources data source on the HRSRVR server (a Microsoft SQL Server) using the logon identification (ID) Smith and the password Sesame, you can use the following connection string.

ODBC;DSN=Human Resources;SERVER=HRSRVR;UID=Smith;PWD=Sesame

See Also

Connect Property (Microsoft Office 95 Data Access Reference), ODBCTimeout Property.


OldValue Property

Applies To

Bound Control, Bound Object Frame Control, Check Box Control, Combo Box Control, List Box Control, Option Button Control, Option Group Control, Text Box Control, Toggle Button Control.

Description

You can use the OldValue property to determine the unedited value of a bound control.

Setting

The OldValue property contains the unedited data from a bound control and is read-only in all views.

You can access this property only in a macro or Visual Basic.

The OldValue property can be assigned to a variable using the following syntax.

OriginalValue = Forms!Customers!AmountPaid.OldValue

Remarks

Microsoft Access uses the OldValue property to retrieve the value of a control as it exists in the underlying record. When you edit a bound control on a form, your changes aren’t saved until you move to another record. The OldValue property contains the unedited version of the underlying data.

You can provide your own undo capability by assigning the OldValue property setting to a control. The following example shows how you can restore the unedited contents of the control Date.

Forms!Orders!Date = Forms!Orders!Date.OldValue

If the control hasn’t been edited, this example has no effect. When you move to another record, the database is updated, so the current value and the OldValue property will be the same.

The OldValue property setting has the same data type as the field to which the control is bound.

See Also

ControlSource Property, Value Property.

Example

The following example checks to determine if new data entered in a field is within 10 percent of the value of the original data. If the change is greater than 10 percent, the OldValue property is used to restore the original value.

Sub Validate_Field()
    Dim curNewValue As Currency, curOriginalValue As Currency
    Dim curChange As Currency, strMsg As String
    curNewValue = Forms!Employees!RaiseAmount
    curOriginalValue = Forms!Employees!RaiseAmount.OldValue
    curChange = Abs(curNewValue - curOriginalValue)
    If curChange > (curOriginalValue * .1) Then
        strMsg = "Change is more than 10 percent of original."
        strMsg = strMsg & vbCrLf & "Restoring original value."
        MsgBox strMsg, vbExclamation, "Invalid change"
        Forms!Employees!RaiseAmount = curOriginalValue
    End IfSub


OLEClass Property

Applies To

Chart Control, Unbound Object Frame Control.

Description

You can use the OLEClass property to obtain a description of the kind of OLE object contained in a chart or an unbound object frame.

Setting

This property is set automatically in the property sheet to a string expression when you click Object on the Insert menu to add an OLE object to a form. The OLEClass property setting is read-only in all views.

Remarks

The OLEClass property and the Class property are similar but not identical. The OLEClass property setting is a general description of the OLE object while the Class property setting is the name used to refer to the OLE object in Visual Basic. Examples of OLEClass property settings are Microsoft Excel Chart, Microsoft Word Document, and Paintbrush Picture.

See Also

Class Property.


OLEType Property

Applies To

Bound Object Frame Control, Chart Control, Unbound Object Frame Control.

Description

You can use the OLEType property to determine if a control contains an OLE object, and, if so, whether the object is linked or embedded.

Setting

The OLEType property uses the following settings.

Setting | Description | Visual Basic
Linked | The control contains a linked object. All the object’s data is managed by the application that created it. | 0
Embedded | The control contains an embedded object. All the object’s data is managed by Microsoft Access. | 1
None | The control doesn’t contain an OLE object. | 3

The OLEType property is read-only in all views.

Remarks

When creating an OLE object, use the OLETypeAllowed property to determine what type of object a control can contain.

See Also

Action Property, OLETypeAllowed Property.

Example

The following example illustrates how to display the Insert Object dialog box and how to display an error message if the Cancel button in the Insert Object dialog box is clicked, so no object will be created.

Sub InsertObject_Click()
    Dim conUserCancelled As Integer
    conUserCancelled = 2001                ' Error message returned
                                        ' when user cancels.Error GoTo ButtonErr                    ' Set up error handler.
    If OLE1.OLEType = 3 Then                ' No OLE Object created.
        OLE1.Action = acOLEInsertObjDlg    ' Display Insert Object
                                        ' dialog box.
    End If
    Exit Sub:
    If Err = conUserCancelled Then    ' Display message.
    MsgBox "You pressed the Cancel button, no object was created."
    End If
    Resume NextSub


OLETypeAllowed Property

Applies To

Bound Object Frame Control, Chart Control, Unbound Object Frame Control.

Description

You can use the OLETypeAllowed property to specify the type of OLE object a control can contain.

Setting

The OLETypeAllowed property uses the following settings.

Setting | Description | Visual Basic
Linked | The control can contain only a linked object. | 0
Embedded | The control can contain only an embedded object. | 1
Either | (Default) The control can contain either a linked or an embedded object. | 2

You can set the OLETypeAllowed property using the property sheet, a macro, or Visual Basic. You can also set this property in a control’s default control style.

Note For unbound object frames, you can’t change the OLETypeAllowed setting after an object is created. For bound object frames, you can change the setting after the object is created. Changing the OLETypeAllowed property setting only affects new objects that you add to the control.

Remarks

To determine the type of OLE object a control already contains, you can use the OLEType property.

See Also

Action Property, OLEType Property.

Example

See the Action property example.


On Error Statement

Description

Enables an error-handling routine and specifies the location of the routine within a procedure; can also be used to disable an error-handling routine.

Syntax

On Error GoTo line On Error Resume NextOn Error GoTo 0

The On Error statement syntax can have any of the following forms:

Statement | Description
On Error GoTo line | Enables the error-handling routine that starts at line, which is any line label or line number. Thereafter, if a run-time error occurs, control branches to line, making the error handler active. The specified line must be in the same procedure as the On Error statement; otherwise, a compile-time error occurs.
On Error Resume Next | Specifies that when a run-time error occurs, control goes to the statement immediately following the statement where the error occurred; that is, execution continues. It’s recommended to use this form rather than On Error GoTo when accessing objects.
On Error GoTo 0 | Disables any enabled error handler in the current procedure.

Remarks

If you don’t use an On Error statement, any run-time error that occurs is fatal; that is, an error message is displayed and execution stops.

An “enabled” error handler is one that has been turned on by an On Error statement; an “active” error handler is an enabled handler that is in the process of handling an error. If an error occurs while an error handler is active (between the occurrence of the error and a Resume, Exit Sub, Exit Function, or Exit Property statement), the current procedure’s error handler can’t handle the error. Control returns to the calling procedure; if the calling procedure has an enabled error handler, it is activated to handle the error. If the calling procedure’s error handler is also active, control passes back through previous calling procedures until an enabled, but inactive, error handler is found. If no inactive, enabled error handler is found, the error is fatal at the point at which it actually occurred. Each time the error handler passes control back to the calling procedure, that procedure becomes the current procedure. Once an error is handled by an error handler in any procedure, execution resumes in the current procedure at the point designated by the Resume statement.

Note An error-handling routine is not a Sub or Function procedure. It is a section of code marked by a line label or line number.

Error-handling routines rely on the value in the Err object’s Number property to determine the cause of the error. The error-handling routine should test or save relevant Err object property values before any other error can occur or before a procedure that could cause an error is called. The values in the Err object’s properties reflect only the most recent error. The error message associated with Err.Number is contained in Err.Description.

On Error Resume Next causes execution to continue with the statement immediately following the statement that caused the run-time error, or with the statement immediately following the most recent call out of the procedure containing the On Error Resume Next statement. This allows execution to continue despite a run-time error. You can then build the error-handling routine inline within the procedure, rather than transfer control to another location within the procedure. An On Error Resume Next statement becomes inactive when another procedure is called, so you should execute an On Error Resume Next statement in each called routine if you want inline error handling within that routine.

Note The On Error Resume Next construct may be preferable to On Error GoTo when dealing with errors generated during access to other objects, since it permits unambiguous identification of the object whose error code is being returned. Checking Err after each interaction with an object removes ambiguity about which object your code was accessing when the error occurred because the context is immediate. Thus, you can be sure of which object placed the error code in Err.Number, as well as which object originally generated the error (the one specified in Err.Source).

On Error GoTo 0 disables error handling in the current procedure. It doesn’t specify line 0 as the start of the error-handling code, even if the procedure contains a line numbered 0. Without an On Error GoTo 0 statement, an error handler is automatically disabled when a procedure is exited.

To prevent error-handling code from running when no error has occurred, place an Exit Sub, Exit Function, or Exit Property statement, as appropriate, immediately before the error-handling routine, as in the following example:

Sub InitializeMatrix(Var1, Var2, Var3, Var4)
    On Error GoTo ErrorHandler
    . . .
    Exit Sub:
    . . .
    Resume NextSub

Here, the error-handling code follows the Exit Sub statement and precedes the End Sub statement to separate it from the normal procedure flow. This is only one possible solution — error-handling code can be placed anywhere in a procedure.

Untrapped errors in OLE Automation objects are returned to the controlling application when the OLE Automation object is running as an executable file. Within the development environment, they are only returned to the OLE Automation controller if the proper options are set. See your host application’s documentation for a description of which options should be set during debugging, how to set them, and whether the host can create classes and OLE Automation objects.

When writing an OLE Automation object, if your object accesses other objects, you should try to handle errors passed back from them unhandled. If you cannot handle such errors, your object should pass them back to the caller of your object, but should first map the error code in Err.Number to one of your own errors. You should specify your error by adding your error code to the constant vbObjectError. For example, if your error code is 1052, assign it as follows:

Err.Number = vbObjectError + 1052

Note On 32-bit Microsoft Windows operating systems, system errors during calls to dynamic-link libraries (DLL), do not raise exceptions and cannot be trapped with Visual Basic error trapping. When calling DLL functions, you should check each return value for success or failure (according to the API specifications), and in the event of a failure, check the value in the Err object’s LastDLLError property.

See Also

End Statement, Err Object, Exit Statement, LastDLLError Property, Resume Statement.

Example

This example first uses the On Error GoTo statement to specify the location of an error-handling routine within a procedure. In the example, an attempt to delete an open file generates error number 55. The error is handled in the error-handling routine and control is then returned to the statement that caused it. The On Error GoTo 0 statement turns off error trapping. Then the On Error Resume Next statement is used to defer error trapping so that the context for the error generated by the next statement can be known for certain. Note that Err.Clear is used to clear the Err object’s properties after the error is handled.

Sub OnErrorStatementDemo()
        On Error GoTo ErrorHandler        ' Enable error-handling
                                        ' routine.
        Open "TESTFILE" For Output As #1    ' Open file for output.
        Kill "TESTFILE"                    ' Attempt to delete open
                                        ' file.
        On Error Goto 0                    ' Turn off error trapping.
        On Error Resume Next                ' Defer error trapping.
        ObjectRef = GetObject("MyWord.Basic")    ' Try to start
                                                ' nonexistent object,
                                                ' then test for OLE
        If Err.Number = 440 Then                    ' Automation error.
            ' Tell user what happened. Then clear the Err object.
            Msg = "There was an error attempting to open the " & _
                "OLE object!"
            MsgBox Msg, , "Deferred Error Test"
            Err.Clear                    ' Clear Err object fields
        End If
    Exit Sub                                ' Exit to avoid handler.
    ErrorHandler:                        ' Error-handling routine.
        Select Case Err.Number            ' Evaluate error number.
            Case 55                        ' "File already open" error.
                Close #1    ' Close open file.
            Case Else
                ' Handle other situations here...
        End Select
        ' Resume execution at same line that caused the error.
        Resume    Sub


On...GoSub, On...GoTo Statements

Description

Branch to one of several specified lines, depending on the value of an expression.

Syntax

On expression GoSub destinationlist On expression GoTo destinationlist

The On...GoSub and On...GoTo statement syntax has these parts:

Part | Description
expression | Any numeric expression that evaluates to a whole number between 0 and 255, inclusive. If expression is any number other than a whole number, it is rounded before it is evaluated.
destinationlist | List of line numbers or line labels separated by commas.

Remarks

The value of expression determines which line in destinationlist is branched to. If the value of expression is less than 1 or greater than the number of items in the list, one of the following results occurs:

If expression is | Then
Equal to 0 | Control drops to the statement following On...GoSub or On...GoTo.
Greater than number of items in list | Control drops to the statement following On...GoSub or On...GoTo.
Negative | An error occurs.
Greater than 255 | An error occurs.

You can mix line numbers and line labels in the same list. There is no practical limit to the number of line labels and line numbers you can use with On...GoSub and On...GoTo. However, if you use more labels or numbers than fit on a single line, you must use the line-continuation character to continue the logical line onto the next physical line.

Tip Select Case provides a more structured and flexible way to perform multiple branching.

See Also

GoSub...Return Statement, GoTo Statement, Select Case Statement.

Example

This example uses the On...GoSub and On...GoTo statements to branch to subroutines and line labels, respectively.

Sub OnGosubGotoDemo()
    Number = 2                    ' Initialize variable.
    ' Branch to Sub2.
    On Number GoSub Sub1, Sub2    ' Execution resumes here after
                                ' On...GoSub.
    On Number GoTo Line1, Line2    ' Branch to Line2.
    ' Execution does not resume here after On...GoTo.
    Exit Sub:
    MyString = "In Sub1" : Return:
    MyString = "In Sub2" : Return:
    MyString = "In Line1":
    MyString = "In Line2"Sub


Open Statement

Description

Enables input/output (I/O) to a file.

Syntax

Open pathname [For mode] [Access access] [lock] As [#]filenumber å[Len=reclength]

The Open statement syntax has these parts:

Part | Description
pathname | String expression that specifies a filename — may include directory or folder, and drive.
mode | Keyword specifying the file mode: Append, Binary, Input, Output, or Random.
access | Keyword specifying the operations permitted on the open file: Read, Write, or Read Write.
lock | Keyword specifying the operations permitted on the open file by other processes: Shared, Lock Read, Lock Write, and Lock Read Write.
filenumber | A valid file number in the range 1 to 511, inclusive. Use the FreeFile function to obtain the next available file number.
reclength | Number less than or equal to 32,767 (bytes). For files opened for random access, this value is the record length. For sequential files, this value is the number of characters buffered.

Remarks

You must open a file before any I/O operation can be performed on it. Open allocates a buffer for I/O to the file and determines the mode of access to use with the buffer.

If the file specified by pathname doesn’t exist, it is created when a file is opened for Append, Binary, Output, or Random modes.

If the file is already opened by another process and the specified type of access is not allowed, the Open operation fails and an error occurs.

The Len clause is ignored if mode is Binary.

Important In Binary, Input, and Random modes, you can open a file using a different file number without first closing the file. In Append and Output modes, you must close a file before opening it with a different file number.

See Also

Close Statement, FreeFile Function.

Example

This example illustrates various uses of the Open statement to enable input and output to a file.

The following code opens the file TESTFILE in sequential-input mode.

Open "TESTFILE" For Input As #1
' Close before reopening in another mode.#1

This example opens the file in Binary mode for writing operations only.

Open "TESTFILE" For Binary Access Write As #1
' Close before reopening in another mode.#1

The following example opens the file in Random mode. The file contains records of the user-defined type Record.

Type Record                ' Define user-defined type.
    ID As Integer
    Name As String * 20TypeMyRecord As Record    ' Declare variable."TESTFILE" For Random As #1 Len = Len(MyRecord)
' Close before reopening in another mode.#1

This code example opens the file for sequential output; any process can read or write to file.

Open "TESTFILE" For Output Shared As #1
' Close before reopening in another mode.#1

This code example opens the file in Binary mode for reading; other processes cannot read file.

Open "TESTFILE" For Binary Access Read Lock Read As #1


Open, Close Events

Applies To

Form, Report.

Description

These events occur:

  • Open — for forms, the Open event occurs when a form is opened, but before the first record is displayed. For reports, the event occurs before a report is previewed or printed.
  • Close — occurs when a form or report is closed and removed from the screen.

Remarks

By running a macro or an event procedure when a form’s Open event occurs, you can close another window or move the focus to a particular control on a form. You can also run a macro or an event procedure that asks for information needed before the form or report is opened or printed. For example, an Open macro or event procedure can open a custom dialog box in which the user enters the criteria for the set of records to display on a form or the date range to include for a report.

The Open event doesn’t occur when you open a form that’s already open — for example, when you switch to the form from another window in Microsoft Access or use the OpenForm action in a macro to bring the open form to the top.

When you open a form, Microsoft Access runs the underlying query for the form before it runs the Open macro or event procedure. However, when you open a report, Microsoft Access runs the Open macro or event procedure before it runs the underlying query for the report. This enables the user to specify criteria for the report before it opens — for example, in a custom dialog box you display when the Open event occurs.

If your application can have more than one form loaded at a time, use the Activate and Deactivate events instead of the Open event to display and hide custom toolbars when the focus moves to a different form.

The Open event occurs before the Load event, which is triggered when a form is opened and its records are displayed.

When you first open a form, the following events occur in this order:

Open [image] Load [image] Resize [image] Activate [image] Current

The Close event occurs after the Unload event, which is triggered after the form is closed but before it is removed from the screen.

When you close a form, the following events occur in this order:

Unload [image] Deactivate [image] Close

When you close a report, the following events occur in this order:

Unload [image] Close [image] Deactivate

When the Close event occurs, you can open another window or request the user’s name to make a log entry indicating who used the form or report.

If you’re trying to decide whether to use the Open or Load event for your macro or event procedure, one significant difference is that the Open event can be canceled, but the Load event can’t. For example, if you’re dynamically building a record source for a form in an event procedure for the form’s Open event, you can cancel opening the form if there are no records to display. Similarly, the Unload event can be canceled, but the Close event can’t.

See Also

Activate, Deactivate Events; GotFocus, LostFocus Events; GoToRecord Action; Load, UnLoad Events; Resize Event; SetFocus Method.


Open, Close Events -- Event Procedures

Description

To create an event procedure that is run when the Open or Close event occurs, set the OnOpen or OnClose property to [Event Procedure], and click the Build button.

Syntax

Private Sub Form_Open (Cancel As Integer)Private Sub Report_Open (Cancel As Integer)Private Sub Form_Close ( )Private Sub Report_Close ( )

The Open event procedure uses the following argument.

Argument | Description
Cancel | The setting determines if the opening of a form or report occurs. Setting Cancel to True (-1) cancels the opening of a form or report.

Remarks

You can’t cancel the Close event.

If you want to refer to controls in an Open event procedure, you must first move the focus to the appropriate control or record using the SetFocus method or the GoToRecord or GoToControl method of the DoCmd object.

If an application has only one form loaded at a time, you can place code for displaying or hiding a toolbar in the Open event procedure for a form. The following example displays the toolbar MyToolbar when the form is opened:

Sub Form_Open(Cancel As Integer)
    DoCmd.ShowToolbar "MyToolbar", acToolbarYesSub

See Also

Open, Close Events — Macros.

Example

This example shows how you can cancel the opening of a form when the user chooses a Cancel button. A message box prompts the user to enter order details. If the user chooses Cancel, the Order Details form isn’t opened.

To try the following example, add the following code to the Declarations section of a form.

Private Sub Form_Open (Cancel As Integer)
    Dim intReturn As Integer
    intReturn = MsgBox("Enter order details now?", vbYesNoCancel)
    Select Case intReturn
        Case vbYes
            DoCmd.OpenForm "Order Details"    ' Open Order Details form.
        Case vbNo
            MsgBox "Remember to enter order details by 5pm."
        Case vbCancel
            Cancel = True                    ' Cancel Open event.
    End SelectSub


Open, Close Events -- Macros

Description

To run a macro when the Open or Close event occurs, set the OnOpen or OnClose property to the name of the macro.

Remarks

You can use the CancelEvent action in an Open macro to cancel opening of the form or report. You can’t use the CancelEvent action in a Close macro. However, you can use the CancelEvent action in a macro that runs when the Unload event occurs on a form. This cancels closing of the form.

If you want to refer to controls from an Open macro, you must first move the focus to the appropriate control or record. For example, to use a SetValue action in an Open macro to set the value of a control on a form, you must first use the GoToControl or GoToRecord action to access the control or the record containing the control.

See Also

Open, Close Events — Event Procedures.


OpenArgs Property

Applies To

Form.

Description

You can use the OpenArgs property to determine the string expression specified by the openargs argument of the OpenForm method that opens a form.

Setting

This property is available only in a macro or Visual Basic using the DoCmd.OpenForm method. This property setting is read-only in all views.

Remarks

To use the OpenArgs property, open a form using the DoCmd.OpenForm method, and set the openargs argument to the desired string expression. The OpenArgs property setting can then be used in code for the form, such as an Open event procedure. You can also refer to the property setting in a macro, such as an Open macro, or an expression, such as an expression that sets the ControlSource property for a control on the form.

For example, suppose that the form you open is a continuous-form list of clients. If you want the focus to move to a specific client record when the form opens, you can set the OpenArgs property to the client name, and then use the FindRecord action in an Open macro to move the focus to the record for the client with the specified name.

See Also

DoCmd Object; Open, Close Events; OpenForm Action.

Example

The following example uses the OpenArgs property to open an Employees form to a specific employee record and demonstrates how the OpenForm action sets the OpenArgs property. You can run this procedure in an appropriate instance — for example, when the AfterUpdate event occurs for a custom dialog box used to enter new information on an employee. The Open event procedure for the Employees form uses the OpenArgs property to open the form to the specific employee record.

Sub OpenToCallahan()
    DoCmd.OpenForm "Employees", acNormal, , , acReadOnly, , "Callahan"Sub
Form_Open(Cancel As Integer)
    Dim strEmployeeName As String
    ' If OpenArgs property contains employee name,
    ' find corresponding employee record
    ' and display it on form. For example, if the
    ' OpenArgs property contains "Callahan",
    ' move to first "Callahan" record.
    strEmployeeName = Forms![Employees].OpenArgs
    If Len(strEmployeeName) > 0 Then
        DoCmd.GoToControl "LastName"
        DoCmd.FindRecord strEmployeeName, ,True, , True, , True
    End IfSub

The next example uses the FindFirst method to locate the employee named in the OpenArgs property.

Private Sub Form_Open(Cancel As Integer)
    If Not IsNull(Me.OpenArgs) Then
        Dim strEmployeeName As String
        strEmployeeName = Me.OpenArgs
        Dim RS As Recordset
        Set RS = Me.RecordsetClone
        RS.FindFirst "[LastName] = '" & strEmployeeName & "'"
        If Not RS.NoMatch Then
            Me.Bookmark = RS.Bookmark
        End If
    End IfSub


OpenCurrentDatabase Method

Description

You can use the OpenCurrentDatabase method to open an existing database as the current database. You can use the this method to open a database from another application that is controlling Microsoft Access through OLE Automation. For example, you can use the OpenCurrentDatabase method from Microsoft Excel to open the Northwind sample database in the Microsoft Access window.

Syntax

application.OpenCurrentDatabase dbname[, exclusive]

The OpenCurrentDatabase method uses the following arguments.

Argument | Description
application | The Application object.
dbname | A string expression that is the name of an existing database file, including the path name and the filename extension. If your network supports it, you can also specify a network path in the following form.
 | \\Server\Share\Directory\Filename.mdb
exclusive | Optional. An Integer value that specifies whether you want to open the database in exclusive mode. By default the database opens in shared mode.

Remarks

The OpenCurrentDatabase method enables you to open a Microsoft Access database from another application through OLE Automation. Once you have created an instance of Microsoft Access from another application, you must also create a new database or specify a particular database to open. This database opens in the Microsoft Access window.

If you have already opened a database and wish to open another database in the Microsoft Access window, you can use the CloseCurrentDatabase method to close the first database before opening another.

Set the exclusive argument to True (-1) to open the database in exclusive mode. If you omit this argument, the database will open in the shared mode.

If the database identified by dbname does not exist, an error occurs.

Note Don’t confuse the OpenCurrentDatabase method with the data access OpenDatabase method. The OpenCurrentDatabase method opens a database in the Microsoft Access window. The OpenDatabase method returns a Database object variable that represents a particular database, but doesn’t actually open that database in the Microsoft Access window.

See Also

CloseCurrentDatabase Method, NewCurrentDatabase Method.

Example

The following example opens a Microsoft Access database from another application through OLE Automation, then opens a form in that database.

You can enter this code in a Visual Basic module in any application that can act as an OLE Automation controller. For example, you might run the following code from Microsoft Excel, Microsoft Visual Basic, or even Microsoft Access.

When the variable pointing to the Application object goes out of scope, the instance of Microsoft Access that it represents closes as well. Therefore, you should declare this variable at the module level.

' Include following in Declarations section of module.
' From Microsoft Excel, use "Dim appAccess As Object".appAccess As Access.Application
DisplayForm()
    Dim strDB As String

    ' Initialize string to database path.
    strDB = "C:\Office95\Access\Samples\Northwind.mdb"
    ' Create new instance of Microsoft Access.
    Set appAccess = CreateObject("Access.Application.7")
    ' Open database in Microsoft Access window.
    appAccess.OpenCurrentDatabase strDB
    ' Open Orders form.
    appAccess.DoCmd.OpenForm "Orders"Sub

Note From some applications, such as Microsoft Visual Basic 4.0, you can include the New keyword when declaring the Application object variable. This keyword automatically creates a new instance of Microsoft Access, without requiring you to use the CreateObject function. Check your application’s documentation to determine whether it supports this syntax.


OpenForm Action

Description

You can use the OpenForm action to open a form in Form view, form Design view, Print Preview, or Datasheet view. You can select data entry and window modes for the form and restrict the records the form displays.

Setting

The OpenForm action uses the following arguments.

Action argument | Description
Form Name | The name of the form to open. The Form Name box in the Action Arguments section of the Macro window shows all forms in the current database. This is a required argument.
 | If you run a macro containing the OpenForm action in a library database, Microsoft Access looks for the form with this name first in the library database, then in the current database.

Action argument | Description
View | The view in which the form will open. Click Form, Design, Print Preview, or Datasheet from the View box. The default is Form.

Filter Name | A filter that restricts or sorts the form’s records. You can enter the name of either an existing query or a filter that was saved as a query. However, the query must include all the fields in the form you are opening or have its OutputAllFields property set to Yes.
Where Condition | A valid SQL WHERE clause (without the word WHERE) or expression that Microsoft Access uses to select records from the form’s underlying table or query. If you select a filter with the Filter Name argument, Microsoft Access applies this WHERE clause to the filter. To open a form and restrict its records to those specified by the value of a control on another form, use the following expression. [fieldname] = Forms![formname]![controlname on other form] The fieldname argument is the name of a field in the underlying table or query of the form you want to open. The controlname on other form argument is the name of the control on the other form that contains the value you want records in the first form to match.

Action argument | Description
Data Mode | The data entry mode for the form. This applies only to forms opened in Form view or Datasheet view. Click Add (the user can add new records but can’t edit existing records), Edit (the user can edit existing records and add new records), or Read Only (the user can only view records). The default is Edit. Note The Data Mode argument setting overrides the settings of the form’s AllowEdits, AllowDeletions, AllowAdditions, and DataEntry properties. For example, if a form’s AllowEdits property is set to No, you can still use the OpenForm action to open the form in Edit mode.
Window Mode | The window mode in which the form opens. Click Normal (the form is in the mode set by its properties), Hidden (the form is hidden), Icon (the form opens minimized as an icon at the bottom of the screen), or Dialog (the form’s Modal and PopUp properties are set to Yes). The default is Normal.

Remarks

This action is similar to choosing the Open button or Design button in the Database window after selecting a form in the Forms tab.

A form can be modal (it must be closed or hidden before the user can perform any other action) or modeless (the user can move to other windows while the form is open). It can also be a pop-up form (a form used to collect or display information that remains on top of all other Microsoft Access windows). You set the Modal and PopUp properties when you design the form. If you click Normal for the Window Mode argument, the form opens in the mode specified by these property settings. If you click Dialog for the Window Mode argument, these properties are both set to Yes. A form opened as hidden or as an icon returns to the mode specified by its property settings when you show or restore it.

When you open a form with the Window Mode argument set to Dialog, Microsoft Access suspends the macro until the form is closed or hidden. You can hide a form by setting its Visible property to No using the SetValue action.

Tip You can select a form in the Database window and drag it to a macro action row. This automatically creates an OpenForm action that opens the form in Form view.

Switching to Design view while the form is open removes most of the argument settings for the form, such as the Data Mode and Window Mode argument settings. They aren’t in effect even if the user returns to Form view or Datasheet view.

See Also

Close Action; Open, Close Events; OpenArgs Property; OpenForm Method; SelectObject Action; SetValue Action.


OpenForm Method

Applies To

DoCmd Object.

Description

The OpenForm method carries out the OpenForm action in Visual Basic. For more information on how the action and its arguments work, see the action topic.

Syntax

DoCmd.OpenForm formname [, view] [, filtername] [, wherecondition] [, ådatamode] [, windowmode] [, openargs]

The OpenForm method uses the following arguments.

Argument | Description
formname | A string expression that is the valid name of a form in the current database. If you execute Visual Basic code containing the OpenForm method in a library database, Microsoft Access looks for the form with this name first in the library database, then in the current database.
view | One of the following intrinsic constants: acNormal acDesign acPreview acFormDS acNormal opens the form in Form view. If you leave this argument blank, the default (acNormal) is assumed.
filtername | A string expression that is the valid name of a query in the current database.
wherecondition | A string expression that is a valid SQL WHERE clause without the word WHERE.
datamode | One of the following intrinsic constants: acAdd acEdit acReadOnly If you leave this argument blank, the default (acEdit) is assumed.
windowmode | One of the following intrinsic constants: acNormal If you leave this argument blank, the default (acNormal) is assumed.

Argument | Description
openargs | A string expression. This expression is used to set the form’s OpenArgs property. This setting can then be used by code in a form module, such as the Open event procedure. The OpenArgs property can also be referred to in macros and expressions. For example, suppose that the form you open is a continuous-form list of clients. If you want the focus to move to a specific client record when the form opens, you can specify the client name with openargs. This argument is available only in Visual Basic.

Remarks

The maximum length of the wherecondition argument is 32,768 characters (unlike the Where Condition action argument in the Macro window, whose maximum length is 256 characters).

You can leave an optional argument blank in the middle of the syntax, but you must include the argument’s comma. If you leave a trailing argument blank, don’t use a comma following the last argument you specify.

See Also

Close Method; DoCmd Object; Open, Close Events; OpenArgs Property; OpenForm Action; SelectObject Method.

Example

This example opens the Employees form in Form view and displays only records with King in the LastName field. The displayed records can be edited, and new records can be added.

DoCmd.OpenForm "Employees", , ,"[LastName] = 'King'"


OpenModule Action

Description

You can use the OpenModule action to open a specified Visual Basic module at a specified procedure. This can be a Sub procedure, a Function procedure, or an event procedure.

Setting

The OpenModule action uses the following arguments.

Action argument | Description
Module Name | The name of the module you want to open. You can leave this box blank if you want to search all the standard modules in the database for a procedure, and open the appropriate module at that procedure.

Action argument | Description
 | If you run a macro containing the OpenModule action in a library database, Microsoft Access looks for the module with this name first in the library database, then in the current database.
Procedure Name | The name of the procedure you want to open the module to. If you leave this box blank, the module opens to the Declarations section.

Note You must enter a valid name in either the Module Name or Procedure Name argument.

Remarks

You can use this action to open an event procedure by specifying the event procedure in the Procedure Name argument. However, you must also specify a module name, because event procedures are private and don’t appear in the global name space. For example, to open the Click event procedure of the PrintInvoice button on the form Orders, set the Module Name argument to Form.Orders and set the Procedure Name argument to PrintInvoice_Click. To view the event procedure for a form or report, the form or report must be open.

To open a private procedure, the module containing it must be open.

This action has the same effect as selecting a module in the Database window, and then pressing the Design button. This action also enables you to specify a procedure name and to search the standard modules in a database for procedures.

Tip You can select a module in the Database window and drag it to a macro action row. This automatically creates an OpenModule action that opens the module to the Declarations section.

To run the OpenModule action in Visual Basic, use the OpenModule method of the DoCmd object.

See Also

OpenModule Method, RunCode Action.


OpenModule Method

Applies To

DoCmd Object.

Description

The OpenModule method carries out the OpenModule action in Visual Basic. For more information on how the action and its arguments work, see the action topic.

Syntax

DoCmd.OpenModule [modulename] [, procedurename]

The OpenModule method uses the following arguments.

Argument | Description
modulename | A string expression that is the valid name of the Visual Basic module you want to open. If you leave this argument blank, Microsoft Access searches all the standard modules in the database for the procedure you selected with the procedurename argument and opens the module containing the procedure to that procedure. If you execute Visual Basic code containing the OpenModule method in a library database, Microsoft Access looks for the module with this name first in the library database, then in the current database.
procedurename | A string expression that is the valid name for the procedure you want to open the module to. If you leave this argument blank, the module opens to the Declarations section.

Remarks

You must include at least one of the two OpenModule arguments. If you enter a value for both arguments, Microsoft Access opens the specified module at the specified procedure.

If you leave the procedurename argument blank, don’t use a comma following the modulename argument.

See Also

DoCmd Object, OpenModule Action, RunCode Action.

Example

This example opens the Utility Functions module to the IsLoaded( ) Function procedure.

DoCmd.OpenModule "Utility Functions","IsLoaded"


OpenQuery Action

Description

You can use the OpenQuery action to open a select or crosstab query in Datasheet view, Design view, or Print Preview. This action runs an action query. You can also select a data entry mode for the query.

Setting

The OpenQuery action uses the following arguments.

Action argument | Description
Query Name | The name of the query to open. The Query Name box in the Action Arguments section of the Macro window shows all queries in the current database. This is a required argument. If you run a macro containing the OpenQuery action in a library database, Microsoft Access looks for the query with this name first in the library database, then in the current database.
View | The view in which the query will open. Click Datasheet, Design, or Print Preview in the View box. The default is Datasheet.
Data Mode | The data entry mode for the query. This applies only to queries opened in Datasheet view. Click Add (the user can add new records but can’t edit existing records), Edit (the user can edit existing records and add new records), or Read Only (the user can only view records). The default is Edit.

Remarks

If you click Datasheet for the View argument, Microsoft Access displays the result set if the query is a select, crosstab, union, or pass-through query whose ReturnsRecords property is set to Yes; and it runs the query if it’s an action, data-definition, or pass-through query whose ReturnsRecords property is set to No.

The OpenQuery action is similar to choosing the Open button or Design button in the Database window after selecting a query in the Queries tab. With this action you can select additional options.

Tip You can select a query in the Database window and drag it to a macro action row. This automatically creates an OpenQuery action that opens the query in Datasheet view.

Switching to Design view while the query is open removes the Data Mode argument setting for the query. This setting isn’t in effect even if the user returns to Datasheet view.

Tip If you don’t want to display the system messages that normally appear when an action query is run (indicating it is an action query and showing how many records will be affected), you can use the SetWarnings action to suppress the display of these messages.

To run the OpenQuery action in Visual Basic, use the OpenQuery method of the DoCmd object.

See Also

OpenQuery Method, RunSQL Action, SetWarnings Action


OpenQuery Method

Applies To

DoCmd Object.

Description

The OpenQuery method carries out the OpenQuery action in Visual Basic. For more information on how the action and its arguments work, see the action topic.

Syntax

DoCmd.OpenQuery queryname [, view] [, datamode]

The OpenQuery method uses the following arguments.

Argument | Description
queryname | A string expression that is the valid name of a query in the current database. If you execute Visual Basic code containing the OpenQuery method in a library database, Microsoft Access looks for the query with this name first in the library database, then in the current database.
view | One of the following intrinsic constants: acNormal acDesign acPreview If queryname is the name of a select, crosstab, union, or pass-through query whose ReturnsRecords property is set to -1, acNormal displays the query’s result set. If queryname refers to an action, data-definition, or pass-through query whose ReturnsRecords property is set to 0, acNormal runs the query. If you leave this argument blank, the default (acNormal) is assumed.

Argument | Description
datamode | One of the following intrinsic constants: acAdd If you leave this argument blank, the default (acEdit) is assumed.

Remarks

If you specify the datamode argument and leave the view argument blank, you must include the view argument’s comma. If you leave a trailing argument blank, don’t use a comma following the last argument you specify.

See Also

DoCmd Object, OpenQuery Method, RunSQL Method.

Example

This example opens Sales Totals Query in Datasheet view and enables the user to view but not to edit or add records.

DoCmd.OpenQuery "Sales Totals Query", , acReadOnly


OpenReport Action

Description

The OpenReport action opens a report in Design view or Print Preview, or it prints the report immediately. You can also restrict the records that are printed in the report.

Setting

The OpenReport action uses the following arguments.

Action argument | Description
Report Name | The name of the report to open. The Report Name box in the Action Arguments section of the Macro window shows all reports in the current database. This is a required argument.
 | If you run a macro containing the OpenReport action in a library database, Microsoft Access looks for the report with this name first in the library database, then in the current database.
View | The view in which the report will open. Click Print (to print the report immediately), Design, or Print Preview in the View box. The default is Print Preview.
Filter Name | A filter that restricts the report’s records. You can enter the name of either an existing query or a filter that was saved as a query. However, the query must include all the fields in the report you are opening or have its OutputAllFields property set to Yes.

Action argument | Description
Where Condition | A valid SQL WHERE clause (without the word WHERE) or expression that Microsoft Access uses to select records from the report’s underlying table or query. If you select a filter with the Filter Name argument, Microsoft Access applies this WHERE clause to the filter.
 | To open a report and restrict its records to those specified by the value of a control on a form, use the following expression.
 | [fieldname] = Forms![formname]![controlname on form]
 | The fieldname argument is the name of a field in the underlying table or query of the report you want to open. The controlname on form argument is the name of the control on the form that contains the value you want records in the report to match.
 | Note The maximum length of the Where Condition argument is 256 characters. If you need to enter a more complex SQL WHERE clause longer than this, use the OpenForm method of the DoCmd object in Visual Basic instead. You can enter SQL WHERE clause statements of up to 32,768 characters in Visual Basic.

Remarks

The Print setting for the View argument prints the report immediately using the current printer settings without bringing up the Print dialog box. You can also use the OpenReport action to open and set up a report and then use the PrintOut action to print it. For example, you may want to modify the report or use the PrintOut action to change the printer settings before you print.

The OpenReport action is similar to clicking the Design button, the Preview button, or the Print command on the File menu in the Database window after selecting a report.

Note Tips

  • To print similar reports for different sets of data, use a filter or a WHERE clause to restrict the records printed in the report. Then edit the macro to apply a different filter or change the Where Condition argument.
  • You can select a report in the Database window and drag it to a macro action row. This automatically creates an OpenReport action that opens the report in Print Preview.

See Also

OpenReport Method.


OpenReport Method

Applies To

DoCmd Object.

Description

The OpenReport method carries out the OpenReport action in Visual Basic. For more information on how the action and its arguments work, see the action topic.

Syntax

DoCmd.OpenReport reportname [, view] [, filtername] [, wherecondition]

The OpenReport method uses the following arguments.

Argument | Description
reportname | A string expression that is the valid name of a report in the current database. If you execute Visual Basic code containing the OpenReport method in a library database, Microsoft Access looks for the report with this name first in the library database, then in the current database.
view | One of the following intrinsic constants: acNormal acDesign acPreview acNormal prints the report immediately. If you leave this argument blank, the default (acNormal) is assumed.
filtername | A string expression that is the valid name of a query in the current database.
wherecondition | A string expression that is a valid SQL WHERE clause without the word WHERE.

Remarks

The maximum length of the wherecondition argument is 32,768 characters (unlike the Where Condition action argument in the Macro window, whose maximum length is 256 characters).

You can leave an optional argument blank in the middle of the syntax, but you must include the argument’s comma. If you leave one or more trailing arguments blank, don’t use a comma following the last argument you specify.

See Also

DoCmd Object, OpenReport Action, PrintOut Method.

Example

This example prints Sales Report using the existing query Report Filter.

DoCmd.OpenReport "Sales Report", acNormal, "Report Filter"


OpenTable Action

Description

You can use the OpenTable action to open a table in Datasheet view, Design view, or Print Preview. You can also select a data entry mode for the table.

Setting

The OpenTable action uses the following arguments.

Action argument | Description
Table Name | The name of the table to open. The Table Name box in the Action Arguments section of the Macro window shows all tables in the current database. This is a required argument. If you run the macro containing the OpenTable action in a library database, Microsoft Access looks for the table with this name first in the library database, then in the current database.
View | The view in which the table will open. Click Datasheet, Design, or Print Preview from the View box. The default is Datasheet.
Data Mode | The data entry mode for the table. This applies only to tables opened in Datasheet view. Click Add (the user can add new records but can’t edit existing records), Edit (the user can edit existing records and add new records), or Read Only (the user can only view records). The default is Edit.

Remarks

This action is similar to clicking the Open button or Design button in the Database window after selecting a table in the Tables tab.

Tip You can select a table in the Database window and drag it to a macro action row. This automatically creates an OpenTable action that opens the table in Datasheet view.

Switching to Design view while the table is open removes the table’s Data Mode argument setting. This setting won’t be in effect even if the user returns to Datasheet view.

To run the OpenTable action in Visual Basic, use the OpenTable method of the DoCmd object.

See Also

OpenTable Method.


OpenTable Method

Applies To

DoCmd Object.

Description

The OpenTable method carries out the OpenTable action in Visual Basic. For more information on how the action and its arguments work, see the action topic.

Syntax

DoCmd.OpenTable tablename [, view] [, datamode]

The OpenTable method uses the following arguments.

Argument | Description
tablename | A string expression that is the valid name of a table in the current database.
 | If you execute Visual Basic code containing the OpenTable method in a library database, Microsoft Access looks for the table with this name first in the library database, then in the current database.
view | One of the following intrinsic constants:
 | acNormal acDesign acPreview
 | acNormal opens the table in Datasheet view.
 | If you leave this argument blank, the default (acNormal) is assumed.
datamode | One of the following intrinsic constants:
 | acAdd acEdit acReadOnly
 | If you leave this argument blank, the default (acEdit) is assumed.

Remarks

If you specify the datamode argument and leave the view argument blank, you must include the view argument’s comma. If you leave a trailing argument blank, don’t use a comma following the last argument you specify.

See Also

DoCmd Object, OpenTable Action.

Example

This example opens the Employees table in Print Preview.

DoCmd.OpenTable "Employees", acPreview


Operator Precedence

Description

When several operations occur in an expression, each part is evaluated and resolved in a predetermined order. That order is known as operator precedence. Parentheses can be used to override the order of precedence and force some parts of an expression to be evaluated before others. Operations within parentheses are always performed before those outside. Within parentheses, however, normal operator precedence is maintained.

When expressions contain operators from more than one category, arithmetic operators are evaluated first, comparison operators are evaluated next, and logical operators are evaluated last. Comparison operators all have equal precedence; that is, they are evaluated in the left to right order in which they appear. Arithmetic and logical operators are evaluated in the following order of precedence:

Arithmetic

Comparison

Logical

Exponentiation (^) | Equality (=) | Not
Negation (-) | Inequality (<>) | And
Multiplication and division (*, /) | Less than (<) | Or
Integer division (\) | Greater than (>) | Xor
Modulo arithmetic (Mod) | Less than or Equal to (<=) | Eqv
Addition and subtraction (+,-) | Greater than or Equal to (>=) | Imp
String concatenation (&) | Like |
 | Is |

When multiplication and division occur together in an expression, each operation is evaluated as it occurs from left to right. Likewise, when addition and subtraction occur together in an expression, each operation is evaluated in order of appearance from left to right.

The string concatenation operator (&) is not an arithmetic operator, but in precedence it does fall after all arithmetic operators and before all comparison operators. Similarly, the Like operator, while equal in precedence to all comparison operators, is actually a pattern-matching operator. The Is operator is an object reference comparison operator. It does not compare objects or their values; it checks only to determine if two object references refer to the same object.

See Also

^ Operator, * Operator, / Operator, \ Operator, Mod Operator, + Operator,
- Operator, & Operator, And Operator, Eqv Operator, Imp Operator, Not Operator, Or Operator, Xor Operator, Is Operator, Like Operator.


Option Base Statement

Description

Used at module level to declare the default lower bound for array subscripts.

Syntax

Option Base {0 | 1}

Remarks

If used, the Option Base statement must appear in a module before any statements that declare variables or define constants.

Since the default base is 0, the Option Base statement is never required. However, if used, it can appear only once in a module and must precede array declarations that include dimensions.

Tip The To clause in the Dim, Private, Public, ReDim, and Static statements provides a more flexible way to control the range of an array’s subscripts. However, if you don’t explicitly set the lower bound with a To clause, you can use Option Base to change the default lower bound to 1.

The Option Base statement only affects the lower bound of arrays in the module where the statement is located.

See Also

Dim Statement, LBound Function, Option Compare Statement, Option Explicit Statement, Option Private Statement, Private Statement, Public Statement, ReDim Statement, Static Statement.

Example

This example uses the Option Base statement to override the default base array subscript value of 0. The LBound function returns the smallest available subscript for the indicated dimension of an array. The Option Base statement is used at the module level only.

Option Base 1                    ' Set default array subscripts to 1.MyArray(20), TwoDArray(3, 4)    ' Declare array variables.ZeroArray(0 To 5)            ' Override default base subscript.
' Use LBound function to test lower bounds of arrays.= LBound(MyArray)            ' Returns 1.= LBound(TwoDArray, 2)        ' Returns 1.= LBound(ZeroArray)        ' Returns 0.


Option Compare Statement

Description

Used at module level to declare the default comparison method to use when string data is compared.

Syntax

Option Compare {Binary | Text | Database}

Remarks

If used, the Option Compare statement must appear in a module before any statements that declare variables or define constants.

The Option Compare statement specifies the string comparison method (Binary, Text, or Database) for a module. If a module doesn’t include an Option Compare statement, the default text comparison method is Binary.

Option Compare Binary results in string comparisons based on a sort order derived from the internal binary representations of the characters. Sort order is determined by the code page. In the following example, a typical binary sort order is shown:

A < B < E < Z < a < b < e < z < À < Ê < Ø < à < ê < ø

Option Compare Text results in string comparisons based on a case-insensitive text sort order determined by your system’s locale. The same characters shown above, when sorted using Option Compare Text, produce the following text sort order:

(A=a) < ( À=à) < (B=b) < (E=e) < (Ê=ê) < (Z=z) < (Ø=ø)

Option Compare Database can only be used within Microsoft Access. This results in string comparisons based on the sort order that is determined by the locale ID of the database where the string comparisons occur.

See Also

InStr Function, Option Base Statement, Option Explicit Statement, Option Private Statement, StrComp Function.

Specifics (Microsoft Access)

In Microsoft Access, all modules by default contain the Option Compare Database statement in the Declarations section. This statement sets the string comparison method for the module to the one specified for the entire database.

You can change the string comparison method for all new databases by clicking Options on the Tools menu and changing the value in the New Database Sort Order box on the General tab of the Options dialog box. By default this value is set to General, which specifies a case-insensitive sort order based on the English alphabet.

Changing the New Database Sort Order option doesn’t affect the string comparison method for the current database. It only affects databases that are created after the option has been set.

To specify a string comparison method for an individual module that is different from the one specified for the database, change Option Compare Database to Option Compare Binary or Option Compare Text. The Option Compare Binary statement compares strings by evaluating the ASCII values corresponding to the characters they contain, so the statement is case-sensitive. Option Compare Text is case-insensitive.

Note If you are using the Bookmark property of a Recordset object, you must include an Option Compare Binary statement in the Declarations section of the module. The setting and return value for the Bookmark property is a Variant array of Byte data. If you use a case-insensitive string comparison method, the Bookmark property may point you to the wrong record.

Example

This example uses the Option Compare statement to set the default string comparison method. The Option Compare statement is used at the module level only.

' Set the string comparison method to Binary.Compare Binary         ' That is, "AAA" is less than "aaa".
' Set the string comparison method to Text.Compare Text            ' That is, "AAA" is equal to "aaa".


Option Explicit Statement

Description

Used at module level to force explicit declaration of all variables in that module.

Syntax

Option Explicit

Remarks

If used, the Option Explicit statement must appear in a module before any statements that declare variables or define constants.

If you don’t use the Option Explicit statement, all undeclared variables are of Variant type unless the default type is otherwise specified with a Def type statement.

When you use the Option Explicit statement, you must explicitly declare all variables using the Dim, Private, Public, ReDim, or Static statements. If you attempt to use an undeclared variable name, an error occurs at compile time.

Tip Use Option Explicit to avoid incorrectly typing the name of an existing variable or to avoid risking confusion in code where the scope of the variable is not clear.

See Also

Const Statement, Def type Statements, Dim Statement, Function Statement, Option Base Statement, Option Compare Statement, Option Private Statement, Private Statement, Public Statement, ReDim Statement, Static Statement, Sub Statement.

Specifics (Microsoft Access)

In Microsoft Access, you can ensure that all new form modules, report modules, and standard modules will automatically include the Option Explicit statement. On the Tool menu, click Options, then click the Module tab, and select the Require Variable Declaration option.

Once you select this option, it will automatically be set for all other databases which you create or open with Microsoft Access.

Note When you select this option, only new modules will have the Option Explicit setting. You must enter the Option Explicit statement into the Declarations section of any existing modules; or when the module is open, on the Tools menu click Options, click the Module tab, and select the Require Variable Declaration option.

Example

This example uses the Option Explicit statement to force you to explicitly declare all variables. Attempting to use an undeclared variable causes an error at compile time. The Option Explicit statement is used at the module level only.

Option Explicit        ' Force explicit variable declaration.MyVar            ' Declare variable.= 10            ' Undeclared variable generates error.= 10            ' Declared variable does not generate error.


Option Private Statement

Description

Used at module level to indicate that an entire module is private.

Syntax

Option Private Module

Remarks

If used, the Option Private statement must appear in a module before any statements that declare variables or define constants.

The public parts (variables, objects, and user-defined types declared at module level) of modules declared private using the Option Private statement are still available within the project containing the module, but they are not available to other applications or projects.

Note Option Private is only useful for host applications that support simultaneous loading of multiple projects and permit references between the loaded projects. For example, Microsoft Excel version 5.0 permits loading of multiple projects, while Microsoft Visual Basic does not.

See Also

Option Base Statement, Option Compare Statement, Option Explicit Statement, Private Statement, Public Statement.

Specifics (Microsoft Access)

When you include the Option Private statement in a standard module in Microsoft Access, any public identifiers in the module are still available to all other procedures in the current database. However, they are not available to other databases.

Note If a standard module includes the Option Private statement, it will not be visible in the Object Browser from any other referencing Microsoft Access database.

You cannot have an Option Private statement in form modules or report modules because they are always private.

Example

The following example demonstrates the Option Private statement, which is used at the module level in a standard module to indicate that the entire module is private. If a module contains an Option Private Module statement, any public procedures can be called from other modules in the database, but not from another database.

Option Private Module        ' Indicates that module is private.


Or Operator

Description

Used to perform a logical disjunction on two expressions.

Syntax

result = expression1 Or expression2

The Or operator syntax has these parts:

Part | Description
result | Any numeric variable.
expression1 | Any expression.
expression2 | Any expression.

Remarks

If either or both expressions evaluate to True, result is True. The following table illustrates how result is determined:

If expression1 is | And expression2 is | The result is
True | True | True
True | False | True
True | Null | True
False | True | True
False | False | False
False | Null | Null
Null | True | True
Null | False | Null
Null | Null | Null

The Or operator also performs a bit-wise comparison of identically positioned bits in two numeric expressions and sets the corresponding bit in result according to the following truth table:

If bit in expression1 is | And bit in expression2 is | The result is
0 | 0 | 0
0 | 1 | 1
1 | 0 | 1
1 | 1 | 1

See Also

Operator Precedence.

Example

This example uses the Or operator to perform logical disjunction on two expressions.

A = 10: B = 8: C = 6: D = Null        ' Initialize variables.= A > B Or B > C                ' Returns True.= B > A Or B > C                ' Returns True.= A > B Or B > D                ' Returns True.= B > D Or B > A                ' Returns Null.= A Or B                        ' Returns 10 (bit-wise comparison).


OrderBy Property

Applies To

Form, Query, Report, Table.

Description

You can use the OrderBy property to specify how you want to sort records in a form, query, report, or table.

Setting

The OrderBy property is a string expression that is the name of the field or fields on which you want to sort records. When you use more than one field name, separate the names with a comma (,).

When you set the OrderBy property by entering one or more field names, the records will be sorted in ascending order. Similarly, Visual Basic will sort these fields in ascending order by default.

If you want to sort records in descending order, type DESC at the end of the string expression. For example, to sort customer records in descending order by contact name, set the OrderBy property to “ContactName DESC”.

You can set the OrderBy property in the object’s property sheet, a macro, or using Visual Basic.

Remarks

For reports, the OrderByOn property must be set to Yes to apply the sort order specified by the object’s OrderBy property. For forms, select the field on which you want to order the records and either click the appropriate Sort button on the toolbar, or point to Sort on the Records menu and click the appropriate command on the submenu. You can also set the OrderByOn property for either forms or reports using Visual Basic.

Note When a new object is created, it inherits the RecordSource, Filter, OrderBy, and OrderByOn properties of the table or query it was created from. For forms and reports, inherited filters aren’t automatically applied an object is opened.

See Also

AllowFilters Property, ApplyFilter Action, ApplyFilter Method, Filter Property, OrderByOn Property.


OrderByOn Property

Applies To

Form, Query Types, Report, Table.

Description

You can use the OrderByOn property to specify whether an object’s OrderBy property setting is applied.

Setting

The OrderByOn property uses the following arguments.

Setting | Description | Visual Basic
Yes | (Default) The OrderBy property setting is applied when the object is opened. | True (-1)
No | The OrderBy property setting isn’t applied when the object is opened. | False (0)

For reports, you can set the OrderByOn property in the report’s property sheet, a macro, or using Visual Basic.

For all other objects, you can set the OrderByOn property by clicking the sort button from the toolbar or using Visual Basic.

Remarks

When a new object is created, it inherits the RecordSource, Filter, OrderBy, OrderByOn, and FilterOn properties of the table or query it was created from.

See Also

AllowFilters Property, ApplyFilter Action, ApplyFilter Method, Filter Property, FilterOn Property, OrderBy Property.


OutputAllFields Property

Applies To

Query.

Description

You can use the OutputAllFields property to show all fields in the query’s underlying data source and in the field list of a form or report. Setting this property is an easy way to show all fields without having to check the Show box in the query design grid for each field in the query.

Note The OutputAllFields property applies only to append, make-table, and select queries.

Setting

The OutputAllFields property uses the following settings.

Setting | Description
Yes | Displays all the fields in the underlying tables and in the field list of a form or report.
No | (Default) Displays only fields having the Show box selected in the query design grid.

You can set this property in the query property sheet or in SQL view of the Query window.

Note An asterisk (*) in the SQL statement in place of a field name is the equivalent of setting the OutputAllFields property to Yes.

Remarks

When OutputAllFields is set to Yes, the only fields you need to include in the query design grid are those that you want to sort on or specify criteria for.

When you save a filter as a query, Microsoft Access sets OutputAllFields to Yes.

Example

The following example uses an asterisk in an SQL statement to select all the fields in the Shippers table. It then displays the fields in text boxes on a form by setting the ControlSource property for the text boxes to the names of the individual fields in the query.

Dim strGetSQL AS String= "SELECT * FROM Shippers"!Form1.RecordSource = strGetSQL.ControlSource = "ShipperID".ControlSource = "CompanyName"

In the output for the next SQL statement, the values in the CompanyName and ProductName fields are sorted in ascending order, and all the fields in the Suppliers and Products tables are displayed in the field lists and in Datasheet view. You can enter this SQL statement in SQL view of the Query window.

SELECT DISTINCTROW *Suppliers JOIN Products ON Suppliers.[SupplierID] = Products.[SupplierID]BY Suppliers.[CompanyName], Products.[ProductName];


OutputTo Action

Description

You can use the OutputTo action to output the data in the specified Microsoft Access database object (a datasheet, form, report, or module) to a file in Microsoft Excel (.xls) version 7.0, rich-text (.rtf), or MS-DOS Text (.txt) format.

Setting

The OutputTo action uses the following arguments.

Action argument | Description
Object Type | The type of object containing the data to output. Click Table (for a table datasheet), Query (for a query datasheet), Form (for a form or form datasheet), Report, or Module in the Object Type box in the Action Arguments section of the Macro window. You can’t output a macro. If you want to output the active object, select its type with this argument, but leave the Object Name box blank. The default is Table. This is a required argument.
Object Name | The name of the object containing the data to output. The Object Name box shows all objects in the database of the type selected by the Object Type argument. If you run a macro containing the OutputTo action in a library database, Microsoft Access looks for the object with this name first in the library database, then in the current database.
Output Format | The type of format you want used to output the data. You can click Microsoft Excel (*.xls), Rich Text Format (*.rtf), or MS-DOS Text (*.txt) in the box. Modules can be output only to MS-DOS Text format. If you leave this box blank, Microsoft Access prompts you for the output format.
Output File | The file you want to output the data to, including the full path. You can include the standard filename extension (.xls, .rtf, or .txt) for the output format you select by the Output Format argument, but it’s not required. If you leave the Output File box blank, Microsoft Access prompts you for an output filename.
Auto Start | Indicator whether you want the appropriate application to start immediately after the OutputTo action runs, with the file specified in the Output File argument opened. If you select Yes, one of the following applications starts with the output file from the Microsoft Access object opened: Microsoft Excel (for .xls files), Microsoft Word for Windows (for .rtf files), or Microsoft Windows Notepad (for .txt files). If you select No, the application doesn’t start. The default is No.

Remarks

The Microsoft Access data is output in the selected format and can be read by any application that uses the same format. For example, you can output a Microsoft Access report with its formatting to a rich-text format document and then open the document in Word for Windows.

The following rules apply when you use the OutputTo action to output a database object:

  • You can output data in table, query, and form datasheets. In the output file, all fields in the datasheet look as they do in Microsoft Access, except fields containing OLE objects. The columns for these fields are included in the output file, but the fields are blank.
  • For a control bound to a Yes/No field (a toggle button, option button, or check box), the output file displays the value -1 (Yes) or 0 (No).
  • If you output the data in a form in Form view, the output file always contains the form’s Datasheet view.
  • If you output the data in a report, the only controls that are included in the output file are text boxes (for .xls output files) or text boxes and labels (for .rtf and .txt output files). All other controls are ignored. Header and footer information is also not included in the output file. The only exception to this is that when you output the data in a report to a Microsoft Excel file, a text box in a group footer containing an expression using the Sum function is included in the output file. No other control in a header or footer (and no aggregate function other than the Sum function) is included in the output file.
  • Subreports are included in the output file (for any of the output file formats), but subforms aren’t.

If you output the data in a report to an output file and the columns and rows of data in the output file do not align as in the report, the following tips may help:

  • You can point to Size on the Format menu, then click To Fit to size the controls.
  • You can avoid overlapping controls or placing controls too close together.
  • You can point to Align on the Format menu, then click the appropriate command to align the controls on the report. Controls that are not aligned in the same row may be placed in separate rows, causing additional spacing.

The OutputTo action is similar to clicking Save As/Export on the File menu, selecting the To An External File Or Database option, and selecting the Save Formatted check box in the dialog box that is displayed. The action arguments correspond to the settings in the Save As/Export dialog boxes. The Save As/Export command, however, applies only to the object selected in the Database window. By using the OutputTo action, you can specify the object you want to output.

Note You can output the selected data with the Save As/Export command. However, this functionality is not available with the OutputTo action.

You can also point to Office Links on the Tools menu, then click Analyze It With MS Excel or Publish It With MS Word to output a database object, and open the output file immediately in Microsoft Excel or Microsoft Word for Windows.

To run the OutputTo action in Visual Basic, use the OutputTo method of the DoCmd object.

See Also

OutputTo Method, SendObject Action.


OutputTo Method

Applies To

DoCmd Object.

Description

The OutputTo method carries out the OutputTo action in Visual Basic. For more information on how the action and its arguments work, see the action topic.

Syntax

DoCmd.OutputTo objecttype [, objectname] [, outputformat] [, outputfile] [,autostart]

The OutputTo method uses the following arguments.

Argument | Description
objecttype | One of the following intrinsic constants:
 | acTable
objectname | A string expression that is the valid name of an object of the type selected with the objecttype argument. If you want to output the active object, specify the object’s type for the objecttype argument and leave this argument blank. If you execute Visual Basic code containing the OutputTo method in a library database, Microsoft Access looks for the object with this name first in the library database, then in the current database.
outputformat | One of the following intrinsic constants:
 | acFormatXLS
 | If you leave this argument blank, Microsoft Access prompts you for the output format.

Argument | Description
outputfile | A string expression that is the full name, including the path, of the file you want to output the object to. If you leave this argument blank, Microsoft Access prompts you for an output file name.
autostart | Use True (-1) to start the appropriate Windows-based application immediately, with the file specified by outputfile loaded. Use False (0) if you don’t want to start the application. If you leave this argument blank, the default (False) is assumed.

Remarks

Modules can be output only in MS-DOS Text format, so if you specify acModule for objecttype, you must specify acFormatTXT for outputformat.

You can leave an optional argument blank in the middle of the syntax, but you must include the argument’s comma. If you leave a trailing argument blank, don’t use a comma following the last argument you specify.

See Also

DoCmd Object, OutputTo Action, SendObject Method.

Example

This example outputs the Employees table in rich-text format (.rtf) to the Employee.rtf file and immediately opens the file in Microsoft Word for Windows.

DoCmd.OutputTo acTable, "Employees", acFormatRTF, "Employee.rtf", True


Page Event

Applies To

Report.

Description

The Page event occurs after Microsoft Access formats a page of a report for printing, but before the page is printed. You can use this event to draw a border around the page, or add other graphic elements to the page.

Remarks

This event occurs after all the Format events for the report, and after all the Print events for the page, but before the page is actually printed.

You normally use the Line, Circle, or PSet methods in the Page event procedure to create the desired graphics for the page.

The NoData event occurs before the first Page event for the report.

See Also

Circle Method; Format Event; Line Method; NoData Event; Page, Pages Properties; Print Event; PSet Method; Retreat Event.


Page Event -- Event Procedures

Description

To create an event procedure that is executed when the Page event occurs, set the OnPage property to [Event Procedure], and click the Build button.

Syntax

Private Sub Report_Page( )

Remarks

You can’t cancel the Page event.

See Also

Page Event — Macros.

Example

The following example shows how to draw a rectangle around a report page, using the Line method. The ScaleWidth and ScaleHeight properties by default return the internal width and height of the report.

Private Sub Report_Page()
    Me.Line(0, 0)-(Me.ScaleWidth, Me.ScaleHeight), , BSub


Page Event -- Macros

Description

To run a macro when the Page event occurs, set the OnPage property to the name of the macro.

Remarks

Since you normally use the Line, Circle, or PSet methods in the Page event procedure to create the desired graphics for the page, you typically use the Page event procedure with this event rather than the Page macro.

You can’t use the CancelEvent action in a Page macro.

See Also

Page Event — Event Procedures.


Page, Pages Properties

Applies To

Form, Report.

Description

You can use the Page and Pages properties to return information needed to print page numbers in a form or report. For example, you could use these properties to print “Page n of nn” in the page footer of a report.

  • Page — This property specifies the current page number when a form or report is being printed.
  • Pages — This property specifies the total number of pages in a form or report.

Setting

Although you can set the Page property to an Integer value, you most often use these properties to return information about page numbers. Both properties return an Integer value when used in an expression.

You can use the Page and Pages properties in an expression, a macro, or an event procedure.

These properties are only available in Print Preview or when printing.

The Pages property is read-only at all times.

Remarks

To refer to the Pages property in a macro or Visual Basic, the form or report must include a text box whose ControlSource property is set to an expression that uses Pages. For example, you can use the following expressions as the ControlSource property setting for a text box in a page footer.

This expression | Prints
=Page | A page number (for example, 1, 2, 3) in the page footer.
="Page " & Page & " of " & Pages | “Page n of nn” (for example, Page 1 of 5, Page 2 of 5) in the page footer.
=Pages | The total number pages in the form or report (for example, 5).

See Also

PageHeader, PageFooter Properties.

Example

The following example displays a message that tells how many pages the report contains. For this example to work, the report must include a text box for which the ControlSource property is set to the expression =Pages.

Dim intTotalPages As Integer, strMsg As String= Reports![Report1].Pages= "This report contains " & intTotalPages & " pages."strMsg


PageHeader, PageFooter Properties

Applies To

Report.

Description

You can use the PageHeader and PageFooter properties to specify whether a report’s page header or page footer are printed on the same page as a report header or report footer. For example, you might not want to print a page header containing the page number on the first page of a report if the report header is a cover sheet.

Setting

The PageHeader and PageFooter properties use the following settings.

Setting | Description | Visual Basic
All Pages | (Default) The page header or footer is printed on all pages of a report. | 0
Not With Rpt Hdr | The page header or footer isn’t printed on the same page as the report header. Microsoft Access prints the report header on a new page. | 1
Not With Rpt Ftr | The page header or footer isn’t printed on the same page as the report footer. Microsoft Access prints the report footer on a new page. | 2
Not With Rpt Hdr/Ftr | The page header or footer isn’t printed on a page that has either a report header or a report footer. Microsoft Access prints the report header or footer on a new page. | 3

You can set these properties using the report’s property sheet, a macro or Visual Basic.

You can set the PageHeader and PageFooter properties only in report Design view.

Remarks

Microsoft Access normally prints report page headers or page footers on every page in a report, including the first and last.

In report Design view, click Page Header/Footer on the View menu to display the page header and page footer sections.

Note When forms are printed, page headers and page footers are always printed on all pages.

Example

The following example sets the PageHeader property for a report to Not With Rpt Hdr. To run this example, type the following line in the Debug window for a report named Report1.

Reports![Report1].PageHeader = 1


Painting Property

Applies To

Form, Report.

Description

You can use the Painting property to specify whether forms or reports are repainted.

Setting

The Painting property uses the following settings.

Setting | Description
True | (Default) The form or report is repainted.
False | The form or report isn’t repainted.

You can set this property using only a macro or Visual Basic.

This property applies only in Form view and is unavailable in other views.

Remarks

The Painting property is similar to the Echo action. However, the Painting property prevents repainting of a single form or report, whereas the Echo action prevents repainting of all open windows in an application.

Setting the Painting property for a form or report to False also prevents all controls (except subform or subreport controls) on a form or report from being repainted. To prevent a subform or subreport control from being repainted, you must set the Painting property for the subform or subreport to False. (Note that you set the Painting property for the subform or subreport, not the subform or subreport control.)

See Also

Echo Action.

Example

The following example uses the Painting property to enable or disable form painting depending on whether the SetPainting variable is set to True or False. If form painting is turned on, Microsoft Access displays the hourglass icon while repainting.

Function EnablePaint(frmName As Form, ByVal SetPainting As Integer) As _
        Integer
    frmName.Painting = SetPainting
    If SetPainting = False Then        ' Form painting is turned off.
        DoCmd.Hourglass True            ' Display icon.
    Else
        DoCmd.Hourglass False        ' Don't display icon.
    End IfFunction


PaintPalette Property

Applies To

Form, Report.

Description

You can use the PaintPalette property to specify a palette that can be used by the PaletteSource property of a form or report.

Setting

You can set the PaintPalette property using a macro or Visual Basic. The property setting must be a String data type.

For a form, you can set the PaintPalette property in Design view and Form view.

For a report, you can set the PaintPalette property in Design view only.

Remarks

When you set the PaintPalette property, Microsoft Access makes a copy of the palette that you specify and saves it with the form or report. The palette is then available if you modify that form or report.

Changes to the palette you specified when you set the PaintPalette property don’t affect the copy of the palette stored with the form or report. If you want to update the copy of the palette stored with the form or report, you must rerun the code or macro that sets the PaintPalette property or reset the PaletteSource property when the form or report is open.

When you set the PaintPalette property for a form or report, Microsoft Access automatically updates its PaletteSource property. Conversely, when you set the PaletteSource property for a form or report, the PaintPalette property is also updated. For example, when you specify a custom palette with the PaintPalette property, the PaletteSource property setting is changed to Custom.

Note Windows can have only one color palette active at a time. Microsoft Access allows you to have multiple graphics on a form, each using a different color palette. The PaletteSource property lets you specify which color palette a form should use when displaying graphics.

See Also

ObjectPalette Property, PaletteSource Property, Picture Property.

Example

See the ObjectPalette property example.


PaletteSource Property

Applies To

Form, Report.

Description

You can use the PaletteSource property to specify the palette for a form or report.

Setting

Enter the path and filename of one of the following file types:

  • .dib (device independent bitmap file)
  • .pal (Windows palette file)
  • .ico (Windows icon file)
  • .bmp (Windows bitmap file)

The default setting is (Default), which specifies the palette included with Microsoft Access. If you change this setting by entering a path and filename, the property setting displays the word Custom.

You can set this property using the property sheet, a macro, or Visual Basic.

For a form, you can set the PaletteSource property in Design view and Form view.

For a report, you can set the PaletteSource property only in Design view.

Remarks

Windows can have only one color palette active at a time. Microsoft Access allows you to have multiple graphics on a form, each using a different color palette. The PaletteSource property lets you specify which color palette a form uses when displaying graphics.

When you set the PaletteSource property for a form or report, Microsoft Access automatically updates its PaintPalette property. Conversely, when you set a form’s or report’s PaintPalette property, the PaletteSource property is also updated. For example, when you specify a custom palette with the PaintPalette property, the PaletteSource property setting changes to Custom.

See Also

ObjectPalette Property, PaintPalette Property.


Parent Property

Applies To

Bound Object Frame Control, Chart Control, Check Box Control, Combo Box Control, Command Button Control, Form Section, Image Control, Label Control, Line Control, List Box Control, Option Button Control, Option Group Control, Page Break Control, Rectangle Control, Report Section, Subform/Subreport Control, Text Box Control, Toggle Button Control, Unbound Object Frame Control.

Description

You can use the Parent property to refer to the parent of a control, section, or control that contains other controls. The Parent property returns a control object if the parent is a control; it returns a form object or report object if the parent is a form or report.

Setting

The Parent property refers to a form, report, or control object and is read-only in all views.

Remarks

You can use the Parent property to determine which form or report is currently the parent when you have a subform or subreport that has been inserted in multiple forms or reports.

For instance, you might insert an OrderDetail subform into both a form and a report. The following example uses the Parent property to refer to the OrderID field, which is present on the main form and report. You can enter this expression in a bound control on the subform.

= Parent![OrderID]

The Parent property of a label control is the control the label is linked to. The Parent property for a check box, option button, or toggle button in an option group is the name of the option group control. The Parent property of an option group control will be the name of the form.

See Also

Form, Report Properties; Forms Collection; Me Property.

Example

The following example uses the Parent property to examine the parent of the Speedy Label label control, the Speedy check box control, and the ShipVia option group.

Dim frm As Formctl As Controlfrm = Forms!Ordersctl = frm.[Speedy Label]
' Returns name of control attached to label."The parent control is " & ctl.Parent.Namectl = frm.[Speedy]
' Returns name of control containing control."The parent control is " & ctl.Parent.Namectl = frm.[ShipVia]
' Returns name of form containing option group control."The parent control is " & ctl.Parent.Name

The next example also returns the name of the form containing the option group control.

MsgBox Forms!Orders[Speedy Label].Parent.Parent.Parent.Name


Partition Function

Description

Returns a string indicating where a number occurs within a calculated series of ranges.

Syntax

Partition(number, start, stop, interval)

The Partition function syntax has these named arguments:

Part | Description
number | Whole number that you want to evaluate against the ranges.
start | Whole number that is the start of the overall range of numbers. It can’t be less than 0.
stop | Whole number that is the end of the overall range of numbers. It can’t be equal to or less than start.
interval | Whole number that is the interval spanned by each range in the series from start to stop. It can’t be less than 1.

Remarks

The Partition function identifies the particular range in which number falls and returns a string describing that range. The Partition function is most useful in queries. You can create a select query that shows how many orders fall within various ranges (for example, order values from 1 to 1000, 1001 to 2000, and so on).

The following table shows how the ranges are determined using three sets of start, stop, and interval parts. The First Range and Last Range columns show what Partition returns. The ranges are represented by lowervalue:uppervalue, where the low end (lowervalue) of the range is separated from the high end (uppervalue) with a colon ( : ).

start | stop | interval | Before First | First Range | Last Range | After Last
0 | 99 | 5 | “ :–1” | “ 0: 4” | “ 95: 99” | “ 100: ”
20 | 199 | 10 | “ : 19” | “ 20: 29” | “ 190: 199” | “ 200: ”
100 | 1010 | 20 | “ : 99” | “ 100: 119” | “ 1000: 1010” | “ 1011: ”

In the table shown above, the third line shows the result when start and stop define a set of numbers that can’t be evenly divided by interval. The last range extends to stop (11 numbers) even though interval is 20.

If necessary, Partition returns a range with enough leading spaces so that there are the same number of characters to the left and right of the colon as there are characters in stop, plus one. This ensures that if you use Partition with other numbers, the resulting text will be handled properly during any subsequent sort operation.

If interval is 1, the range is number:number, regardless of the start and stop arguments. For example, if interval is 1, number is 100 and stop is 1000, Partition returns “ 100: 100”.

If any of the parts is Null, Partition returns a Null.

Example

This example assumes you have an Orders table that contains a Freight field. It creates a select that counts the number of orders for which freight cost falls into each of several ranges. The Partition function is used first to establish these ranges, then the SQL Count function counts the number of orders in each range. In this example, the arguments to the Partition function are start = 0, stop = 500, interval = 50. The first range would therefore be 0:49, and so on up to 500

SELECT DISTINCTROW Partition([freight],0, 500, 50) AS Range,(Orders.Freight) AS CountOrdersBY Partition([freight],0,500,50);

You can use the Partition function in the query design grid as well as in the SQL view of the Query window. In the query design grid, you can use the Partition function in a calculated field or to specify criteria for a select query.

The following example shows how you can use the Partition function to create a calculated field that lists how many records fall into each specified range. Suppose you have an Orders table that contains a Freight field. In the Query window, create a new Totals query by adding the Orders table and clicking on the Totals button in the Query toolbar. Drag the Freight field to the first Field cell on the query design grid, and set the value of the Total cell to Count. In another field cell, enter the following expression.

Range: Partition([Freight], 0, 1000, 50)

Set the Total cell below this field to Group By, and run the query. The Partition function returns eleven ranges (0:99, 100:199, 200:299, and so on). The query shows the number of orders with freight charges falling into each range.

The next example shows how you can use the Partition function in the SQL view of the Query window. It creates a crosstab query that evaluates a Freight field in an Orders table. It calculates the number of orders for each customer for which freight cost falls within one of several ranges. The ranges are defined by the arguments to the Partition function: start = 0, stop = 1000, interval = 50.

Enter the following expression in SQL view. When you run this query, each range will appear as a column heading.

TRANSFORM Count(Orders.[OrderID]) AS [CountOfOrderID]Orders.[CustomerID]OrdersBY Orders.[CustomerID]Partition(Int([Freight]), 0, 1000, 50);


Picture Property

Applies To

Command Button Control, Form, Image Control, Report, Toggle Button Control.

Description

You can use the Picture property to specify a bitmap to be displayed on a form, report, command button, image frame, or toggle button. Buttons can display either a caption or a picture.

Setting

The Picture property contains the path and filename of a bitmap to be displayed on command button, image frame, or toggle button or as a background picture on a form or report.

You can also use the Picture Builder to select a bitmap by clicking the Build button to the right of the Picture property in the property sheet. If the PictureType property is set to Embedded, the bitmap is stored with the object.

The default setting is “(none)”. After the bitmap is loaded into the object, the property setting displays “(bitmap)”. If you delete “(bitmap)” from the property setting, the picture is deleted from the object and the property setting is again “(none)”.

You can set this property in the property sheet, a macro, or Visual Basic.

In Visual Basic, you can set this property using a string expression that includes the path and the name of the bitmap, as in the following example.

btnShowLogo.Picture = "c:\Windows\Winlogo.bmp"

Remarks

You can create custom bitmaps using Microsoft Paintbrush or another application that creates bitmap files. A bitmap file must have a .bmp, .ico, or .dib extension.

Buttons can display either a caption or a picture. If you assign both to a button, the picture will be visible, the caption will not. If the picture is deleted, the caption reappears. Microsoft Access displays the picture centered on the button and clipped, if the picture is larger than the button.

Tip To create a command button or toggle button with a caption and a picture, you could include the desired caption as part of the bitmap and assign the bitmap to the Picture property of the control.

See Also

PictureAlignment Property, PictureData Property, PictureSizeMode Property, PictureTiling Property, PictureType Property.


PictureAlignment Property

Applies To

Form, Image Control, Report.

Description

You can use the PictureAlignment property to specify where a background picture will appear in an image control or on a form or report.

Setting

The PictureAlignment property uses the following settings.

Setting | Description | Visual Basic
Top-left | The picture is displayed at the top left corner of the image control, Form window, or page of a report. | 0
Top-right | The picture is displayed at the top right corner of the image control, Form window, or page of a report. | 1
Center | (Default) The picture is centered in the image control, Form window, or page of a report. | 2
Bottom-left | The picture is displayed at the bottom left corner of the image control, Form window, or page of a report. | 3
Bottom-right | The picture is displayed at the bottom right corner of the image control, Form window, or page of a report. | 4
Form Center | (Forms only) The form’s picture is centered horizontally in relation to the width of the form and vertically in relation to the height the entire form. | 5

You can set the PictureAlignment property in the form or report’s property sheet, a macro, or using Visual Basic.

This property can be set in any view.

Remarks

The Form Center setting aligns a form’s picture in the center of the form itself. All other PictureAlignment property settings align a form’s picture in relation to the Form window. If you want to make sure that a form’s picture is displayed only on the form or tiled only across the form, set the PictureAlignment property to Form Center.

For reports, the picture appears relative to a full page and not in relation to the size of the actual report. If your report is less than a full page and you want a picture to appear at a location not available through the PictureAlignment property settings, use an image control instead.

When you set the PictureTiling property to Yes, tiling of the picture will begin from the PictureAlignment property setting.

See Also

Picture Property, PictureData Property, PicturePages Property, PictureSizeMode Property, PictureTiling Property, PictureType Property.


PictureData Property

Applies To

Command Button Control, Form, Image Control, Report, Toggle Button Control.

Description

You can use the PictureData property in Visual Basic to copy the picture in one form, report, or control to another object that supports the Picture property.

Setting

The PictureData property setting is the PictureData property of another image control, command button, toggle button, form, or report.

You set this property using Visual Basic.

Remarks

You can use this property to open a form using a different background picture, depending on actions taken by the user. For example, you might open a Customers form using a different background picture depending on whether the form is opened for data entry or for browsing.

You can also use the PictureData property together with the Timer event and the TimerInterval property to perform simple animation on a form.

See Also

Picture Property, PictureAlignment Property, PicturePages Property, PictureSizeMode Property, PictureTiling Property, PictureType Property.

Example

The following example uses three image controls to animate a butterfly image across a form. The Hidden1 image control contains a picture of a butterfly with its wings up and the Hidden2 image control contains a picture of the same butterfly with its wings down. Both image controls have their Visible property set to False. The TimerInterval property is set to 200. Each time the Timer event occurs, the picture in the image control Visible1 is changed using the PictureData property of the hidden image controls, and the visible image control is moved 200 twips to the right. The visible image control is moved back to the left side of the form when its Left property value is greater than the width of the form stored in the global variable gfrmWidth. The value of gfrmWidth is set to Me.Width in the form’s open event.

Private Sub Form_Timer()
    Static picNum As Integer
    Select Case picNum
        Case Is = 1
            Me!Visible1.PictureData = Me!Hidden1.PictureData
        Case Is = 2
            Me!Visible1.PictureData = Me!Hidden2.PictureData
        Case Else
    End Select
    If picNum = 2 Then picNum = 0
    picNum = picNum + 1
    If (Me!Visible1.Left > gfrmWidth) Then Me!Visible1.Left = 0
    Me!Visible1.Left = Me!Visible1.Left + 200Sub


PicturePages Property

Applies To

Report.

Description

You can use the PicturePages property to specify on which page or pages of a report a picture will be displayed.

Setting

The PicturePages property uses the following settings.

Setting | Description | Visual Basic
All Pages | (Default) The picture appears on all pages of the report. | 0
First Page | The picture appears only on the first page of the report. | 1
No Pages | The picture does not appear on the report. | 2

You can set the PicturePages property in a report’s property sheet, a macro, or using Visual Basic.

See Also

Picture Property, PictureData Property, PictureSizeMode Property, PictureTiling Property.


PictureSizeMode Property

Applies To

Form, Report.

Description

You can use the PictureSizeMode property to specify how a picture for a form or report is sized.

Setting

The PictureSizeMode property uses the following settings.

Setting | Description | Visual Basic
Clip | (Default) The picture is displayed in its actual size. If the picture is larger than the form or report then the picture is clipped. | 0
Stretch | The picture is stretched horizontally and vertically to fill the entire form, even if its original ratio of height to width is distorted. | 1
Zoom | The picture is enlarged to the maximum extent possible while keeping its original ratio of height to width. | 3

You can set the PictureSizeMode property in the form or report’s property sheet, a macro, or using Visual Basic.

Remarks

When a small picture is used for the Picture property of a form or report, setting the PictureSizeMode to Stretch or Zoom can cause substantial distortion of its resolution. Smaller pictures can be tiled across the entire form or report using the PictureTiling property.

See Also

Picture Property, PictureAlignment Property, PictureData Property, PictureTiling Property, PictureType Property, SizeMode Property.


PictureTiling Property

Applies To

Form, Image Control, Report.

Description

You can use the PictureTiling property to specify whether a background picture is tiled across the entire image control, form window, form, or page of a report.

Setting

The PictureTiling property uses the following settings.

Setting | Description | Visual Basic
Yes | The picture is tiled. | True (-1)
No | (Default) The picture isn’t tiled. | False (0)

You can set the PictureTiling property in the object’s property sheet, a macro, or using Visual Basic.

Remarks

You can create interesting effects by placing a picture on a form or report and setting the PictureTiling property to Yes. The alignment of the tiled images is affected by the PictureAlignment property setting. For example, if the PictureAlignment property is set to Top-left, tiling begins at the top left of the image control, Form, or Report window.

Note If the PictureAlignment property is set to Form Center and the PictureTiling property is set to Yes, the background picture of a form will be tiled across the form, not across the Form window.

See Also

Picture Property, PictureAlignment Property, PictureData Property, PicturePages Property, PictureSizeMode Property, PictureType Property.


PictureType Property

Applies To

Command Button Control, Form, Image Control, Report, Toggle Button Control.

Description

You can use the PictureType property to specify whether Microsoft Access stores an object’s picture as a linked object or an embedded object.

Setting

The PictureType property uses the following settings.

Setting | Description | Visual Basic
Embedded | (Default) The picture is embedded in the object and becomes part of the database file. | 0
Linked | The picture is linked to the object. Microsoft Access stores a pointer to the location of the picture on the disk. | 1

You can set the PictureType property in the object’s property sheet, a macro, or using Visual Basic.

This property can be set only in form or report Design view.

For controls, you can also set this property using the default control style.

Remarks

When the PictureType property is set to Embedded, the size of the database increases by the size of the picture file and, with some .wmf files, the size may increase as much as twice the size of the picture file. When the PictureType property is set to Linked, there is no increase in the size of the database because Microsoft Access only saves a pointer to the picture’s location on the disk.

Note If a linked file is moved to another location on the disk, you must re-establish the link using the object’s Picture property.

The individual bits that make up a picture’s image are stored in the object’s PictureData property.

You can modify a linked picture using a separate application and changes to the picture will appear the next time the object containing that picture is displayed in the database.

See Also

Picture Property, PictureData Property.


Pmt Function

Description

Returns the payment for an annuity based on periodic, constant payments and a constant interest rate.

Syntax

Pmt(rate, nper, pv[, fv[, type]])

The Pmt function has these named arguments:

Part | Description
rate | Interest rate per period. For example, if you get a car loan at an annual percentage rate (APR) of 10 percent and make monthly payments, the rate per period is 0.1/12, or 0.0083.
nper | Total number of payment periods in the annuity. For example, if you make monthly payments on a four-year car loan, your loan has a total of 4 * 12 (or 48) payment periods.
pv | Present value (or lump sum) that a series of payments to be paid in the future is worth now. For example, when you borrow money to buy a car, the loan amount is the present value to the lender of the monthly car payments you will make.
fv | Future value or cash balance you want after you’ve made the final payment. For example, the future value of a loan is $0 because that’s it value after the final payment. However, if you want to save $50,000 for your child’s education over 18 years, then $50,000 is the future value. If omitted, 0 is assumed.
type | Number indicating when payments are due. Use 0 if payments are due at the end of the payment period, or use 1 if payments are due at the beginning of the period. If omitted, 0 is assumed.

Remarks

An annuity is a series of constant cash payments made over a period of time. An annuity can be a loan (such as a home mortgage) or an investment (such as a monthly savings plan).

The arguments rate and nper must be calculated using payment periods expressed in the same units. For example, if rate is calculated using months, nper must also be calculated using months.

For all arguments, cash paid out (such as deposits to savings) is represented by negative numbers; cash received (such as dividend checks) is represented by positive numbers.

Example

This example uses the Pmt function to return the payment for a loan over a fixed period. Given are the interest percentage rate per period (APR / 12), the total number of payments (TotPmts), the present value or principal of the loan (PVal), the future value of the loan (FVal), and a number that indicates whether the payment is due at the beginning or end of the payment period (PayType).

Const ENDPERIOD = 0, BEGINPERIOD = 1        ' When payments are made.= "###,###,##0.00"                    ' Define money format.= 0                                    ' Usually 0 for a loan.= InputBox("How much do you want to borrow?")= InputBox("What is the annual percentage rate of your loan?")APR > 1 Then APR = APR / 100            ' Ensure proper form.= InputBox("How many monthly payments will you make?")= MsgBox("Do you make payments at the end of month?", vbYesNo)PayType = vbNo Then PayType = BEGINPERIOD Else PayType = ENDPERIOD= Pmt(APR / 12, TotPmts, -PVal, FVal, PayType)"Your payment will be " & Format(Payment, Fmt) & " per month."


PopUp Property

Applies To

Form.

Description

You can use the PopUp property to specify whether a form opens as a pop-up. For example, you set a form’s PopUp and Modal properties to Yes to create a custom dialog box.

Setting

The PopUp property uses the following settings.

Setting | Description | Visual Basic
Yes | The form opens as a pop-up form in Form view. It remains on top of all other Microsoft Access windows. | True (-1)
No | (Default) The form is not a pop-up form. | False (0)

You can set this property using the form’s property sheet, a macro, or Visual Basic.

The PopUp property can be set only in Design view.

Remarks

To specify the type of border you want on a pop-up form, use the BorderStyle property. You typically set the BorderStyle property to Thin for pop-up forms.

Tip You can use the PopUp, Modal and BorderStyle properties to create a custom dialog box. Set Modal to Yes, PopUp to Yes and BorderStyle to Dialog for custom dialog boxes.

Setting the PopUp property to Yes makes the form a pop-up only when you open it in Form view from the Database window or when using a macro or Visual Basic. When the PopUp property is set to Yes, you can’t switch to other views from Form view. You must close the form and reopen it in Design view or Datasheet view.

Note You can use the Dialog setting of the Window Mode argument of the OpenForm action to open a form with its PopUp and Modal properties set to Yes.

See Also

BorderStyle Property, ControlBox Property, MinMaxButtons Property, Modal Property, OpenForm Action.


PPmt Function

Description

Returns the principal payment for a given period of an annuity based on periodic, constant payments and a constant interest rate.

Syntax

PPmt(rate, per, nper, pv[, fv[, type]])

The PPmt function has these named arguments:

Part | Description
rate | Interest rate per period. For example, if you get a car loan at an annual percentage rate (APR) of 10 percent and make monthly payments, the rate per period is 0.1/12, or 0.0083.
per | Payment period in the range 1 through nper.
nper | Total number of payment periods in the annuity. For example, if you make monthly payments on a four-year car loan, your loan has a total of 4 * 12 (or 48) payment periods.

Part | Description
pv | Present value, or value today, of a series of future payments or receipts. For example, when you borrow money to buy a car, the loan amount is the present value to the lender of the monthly car payments you will make.
fv | Future value or cash balance you want after you’ve made the final payment. For example, the future value of a loan is $0 because that’s it value after the final payment. However, if you want to save $50,000 for your child’s education over 18 years, then $50,000 is the future value. If omitted, 0 is assumed.
type | Number indicating when payments are due. Use 0 if payments are due at the end of the payment period, or use 1 if payments are due at the beginning of the period. If omitted, 0 is assumed.

Remarks

An annuity is a series of constant cash payments made over a period of time. An annuity can be a loan (such as a home mortgage) or an investment (such as a monthly savings plan).

The arguments rate and nper must be calculated using payment periods expressed in the same units. For example, if rate is calculated using months, nper must also be calculated using months.

For all arguments, cash paid out (such as deposits to savings) is represented by negative numbers; cash received (such as dividend checks) is represented by positive numbers.

Example

This example uses the PPmt function to calculate how much of a payment for a specific period is principal when all the payments are of equal value. Given are the interest percentage rate per period (APR / 12), the payment period for which the principal portion is desired (Period), the total number of payments (TotPmts), the present value or principal of the loan (PVal), the future value of the loan (FVal), and a number that indicates whether the payment is due at the beginning or end of the payment period (PayType).

Const ENDPERIOD = 0, BEGINPERIOD = 1            ' When payments are made.= Chr(13) & Chr(10)                        ' Define newline.= Chr(9)                                    ' Define tab.= "###,###,##0.00"                        ' Define money format.= 0                                        ' Usually 0 for a loan.= InputBox("How much do you want to borrow?")= InputBox("What is the annual percentage rate of your loan?")APR > 1 Then APR = APR / 100                ' Ensure proper form.= InputBox("How many monthly payments do you have to make?")= MsgBox("Do you make payments at the end of month?", vbYesNo)PayType = vbNo Then PayType = BEGINPERIOD Else PayType = ENDPERIOD= Abs(-Pmt(APR / 12, TotPmts, PVal, FVal, PayType))= "Your monthly payment is " & Format(Payment, Fmt) & ". "= Msg & "Would you like a breakdown of your principal and "= Msg & "interest per period?"= MsgBox(Msg, vbYesNo)                ' See if chart is desired.MakeChart <> vbNo Then
    If TotPmts > 12 Then MsgBox "Only first year will be shown."
    Msg = "Month  Payment  Principal  Interest" & NL
    For Period = 1 To TotPmts
        If Period > 12 Then Exit For            ' Show only first 12.
        P = PPmt(APR / 12, Period, TotPmts, -PVal, FVal, PayType)
        P = (Int((P + .005) * 100) / 100)    ' Round principal.
        I = Payment - P
        I = (Int((I + .005) * 100) / 100)    ' Round interest.
        Msg = Msg & Period & TB & Format(Payment, Fmt)
        Msg = Msg & TB & Format(P, Fmt) & TB & Format(I, Fmt) & NL
    Next Period
    MsgBox Msg                            ' Display amortization table.If


PreviousControl Property

Applies To

Screen Object.

Description

You can use the PreviousControl property with the Screen object to determine the control that last received the focus.

Setting

The PreviousControl property setting is a String value that is the name of a control.

This property is available only in a macro or Visual Basic and is read-only.

Remarks

You can’t use the PreviousControl property until more than one control on any form has received the focus after a form is opened. Microsoft Access generates an error if you attempt to access this property when only one control on a form has received the focus.

See Also

GotFocus, LostFocus Events.

Example

The following example displays a message if the control that last received the focus was not the txtFinalEntry text box.

Function ProcessData() As Integer
    Const conNoPreviousControl = 2483    ' No previous control error.
    On Error GoTo Process_Err
    If Screen.PreviousControl.Name = "txtFinalEntry" Then
        .                                ' Process Data Here.
        .
        .
        ProcessData = True
    Else
        ' Set Focus to txtFinalEntry and display message.
        Me!txtFinalEntry.Setfocus
        MsgBox "Please enter a value here for further processing."
        ProcessData = False
    End If_Bye:
    Exit Function_Err:
    If Err = conNoPreviousControl Then
        Me!txtFinalEntry.Setfocus
        MsgBox "Please enter value to process"
        ProcessData = False
    End If
    Resume Process_ByeFunction


Primary Property

Applies To

Index, Index Object.

Description

You can use the Primary property to specify whether the index is the primary key for the table. A primary key uniquely identifies each record in a table and prevents you from entering duplicate values in a primary key field.

Setting

The Primary property uses the following settings.

Setting | Description | Visual Basic
Yes | The selected index is the primary key. | True (-1)
No | The selected index isn’t the primary key. | False (0)

You can set the Primary property in three ways:

  • In table Design view, select the field or fields in the order you want for the primary key and then click Primary Key on the Edit menu or click the Primary Key button on the toolbar.
  • In the Indexes window, select or enter the name of an index in the Index Name column and set the Primary property to Yes in the Index Properties list.
  • In Visual Basic to access the Primary property of an index in Visual Basic, use the Data Access Objects Primary property.

Remarks

Microsoft Access creates an index on the primary key of the table and uses it to find records and to create joins between tables. The primary key index requires an entry in each primary key field and allows no duplicates. The order of the fields determines the default sort order for the table.

If there is no primary key when you save a table design, Microsoft Access will display a dialog box asking whether you want a primary key to be created. If you choose Yes, an AutoNumber data type field will be added to the table (with its NewValues property set to Increment) and set as the primary key. If you choose No, no primary key will be created.

A table with no primary key can’t be used in a relationship and can be slower to sort and search.

See Also

Indexed Property, Primary Property (Microsoft Office 95 Data Access Reference), Unique Property.


Print # Statement

Description

Writes display-formatted data to a sequential file.

Syntax

Print #filenumber, [outputlist]

The Print # statement syntax has these parts:

Part | Description
filenumber | Any valid file number.
outputlist | Expression or list of expressions to print.

Settings

The outputlist argument settings are:

[{Spc(n) | Tab[(n)]}][expression][charpos]

Setting | Description
Spc(n) | Used to insert space characters in the output, where n is the number of space characters to insert.
Tab(n) | Used to position the insertion point to an absolute column number, where n is the column number. Use Tab with no argument to position the insertion point at the beginning of the next print zone.

Setting | Description
expression | Numeric or string expressions to print.
charpos | Specifies the insertion point for the next character. Use a semicolon to specify the insertion point to be immediately after the last character displayed. Use Tab(n) to position the insertion point to an absolute column number. Use Tab with no argument to position the insertion point at the beginning of the next print zone. If charpos is omitted, the next character is printed on the next line.

Remarks

If you omit outputlist and include only a list separator after filenumber, a blank line is printed to the file. Multiple expressions can be separated with either a space or a semicolon. A space has the same effect as a semicolon.

All data written to the file using Print # is internationally aware; that is, the data is properly formatted (using the appropriate decimal separator) and the keywords are written in the language appropriate for the locale specified for your system.

For Boolean data, either True or False is printed. The True and False keywords are translated, as appropriate, according to the locale setting specified for your system.

Date data is written to the file using the standard short date format recognized by your system. When either the date or the time component is missing or zero, only the part provided gets written to the file.

Nothing is written to the file if outputlist data is Empty. However, if outputlist data is Null, Null is written to the file. Again, the Null keyword is translated, as appropriate.

For Error data, the output appears as Error errorcode. The Error keyword is translated, as appropriate, when written to the file.

Because Print # writes an image of the data to the file, you must delimit the data so it prints correctly. If you use Tab with no arguments to move the print position to the next print zone, Print # also writes the spaces between print fields to the file.

Note If, at some future time, you want to read the data from a file using the Input # statement, use the Write # statement instead of the Print # statement to write the data to the file. Using Write # ensures the integrity of each separate data field by properly delimiting it, so that it can be read back in using Input #. Using Write # also ensures that it can be correctly read in any locale.

See Also

Open Statement, Print Method, Spc Function, Tab Function, Write # Statement.

Example

This example uses the Print # statement to write data to a file.

Open "TESTFILE" For Output As #1            ' Open file for output.#1, "This is a test"                ' Print text to file.#1,                                ' Print blank line to file.#1, "Zone 1"; Tab ; "Zone 2"        ' Print in two print zones.#1, "Hello" ; " " ; "World"        ' Separate strings with space.#1, Spc(5) ; "5 leading spaces "    ' Print five leading spaces.#1, Tab(10) ; "Hello"                ' Print word at column 10.

' Assign Boolean, Date, Null and Error values.= False : MyDate = #February 12, 1969# : MyNull = Null= CVErr(32767)
' True, False, Null, and Error are translated using locale settings of
' your system. Date literals are written using standard short date
' format.#1, MyBool ; " is a Boolean value"#1, MyDate ; " is a date"#1, MyNull ; " is a null value"#1, MyError ; " is an error value"#1                                    ' Close file.


Print Event

Applies To

Report Section.

Description

The Print event occurs when data in a report section is formatted for printing, but before the section is printed.

Remarks

For a report detail section, the Print event occurs for each record in the section just before Microsoft Access prints the data in the record. A Print event procedure or macro has access to data in the current record.

For report group headers, the Print event occurs for each new group, and a Print macro or event procedure has access to data in the group header and the first record in the detail section. For report group footers, the Print event occurs for each new group, and a Print macro or event procedure has access to data in the group footer and the data in the last record in the detail section.

You can use the Print event to run a macro or execute an event procedure only after Microsoft Access has prepared data for printing on a page. For example, you can calculate running page totals that are printed in the page header or footer.

For changes that affect page layout, such as displaying or hiding controls, use the Format event.

The Print event occurs only for sections that are actually printed. If you need access to data from sections that aren’t printed (for example, you are keeping a running sum, but are only printing certain pages), use the Format event instead.

The Page event occurs after all the Format events for the report, and after all the Print events for a page, but before the page is actually printed.

See Also

Format Event; FormatCount Property; NoData Event; Page Event; Page, Pages Properties; PrintCount Property; Retreat Event.


Print Event -- Event Procedures

Description

To create an event procedure that is run when the Print event occurs, set the OnPrint property to [Event Procedure], and click the Build button.

Syntax

Private Sub sectionname_Print (Cancel As Integer, PrintCount As Integer)

The Print event procedure uses the following arguments.

Argument | Description
sectionname | A string that is the name of the section affected by the Print event procedure.
Cancel | The setting determines if the printing of the section occurs. Setting the Cancel argument to True (-1) cancels printing of the section.
PrintCount | An integer value that specifies whether the Print event has occurred more than once for a record. For example, if part of a record is printed on one page and the rest is printed on the next page, the Print event occurs twice, and the PrintCount argument is set to 2.

Remarks

To cancel printing of the section, you set the Cancel argument to True (-1) or use the CancelEvent method of the DoCmd object. Microsoft Access prints a blank area on the page where the section would have been. You can use CancelEvent to skip a record in a report and leave a blank area on the page in its place when the report is printed.

Note You can’t use a Print event procedure to set properties for any object.

See Also

Print Event — Macros.

Example

This example checks the PrintCount argument to determine the number of times the Print event has occurred. If it has occurred more than once, the Print event is canceled for the section.

To try the following example, add the following code to the Declarations section of a report that contains a section named CustomerDetail.

Private Sub CustomerDetail_Print (Cancel As Integer, _
        PrintCount As Integer)
    If PrintCount > 1 Then Cancel = TrueSub


Print Event -- Macros

Description

To run a macro when the Print event occurs, set the OnPrint property to the name of the macro.

Remarks

You can use the PrintCount property to check whether the Print event has occurred more than once for a record. For example, if part of a record is printed on one page and the rest is printed on the next page, the Print event occurs twice, and the PrintCount property is set to 2. You can check the PrintCount value for Print macros that should run only once for a record, such as a macro that shows totals for the records on a page in a page footer.

You can use the CancelEvent action in a Print macro to cancel printing of a section. Microsoft Access prints a blank area on the page where the section would have been when the report is printed. You can use CancelEvent to skip a record in a report and leave a blank area on the page in its place when the report is printed.

A Print macro runs only for sections that are actually printed.

Note You can’t use a Print macro to set properties for any object.

See Also

Print Event — Event Procedures.


Print Method

Applies To

Debug Object.

Description

Prints text in the Immediate pane of the Debug window.

Syntax

object.Print outputlist

The Print method syntax has the following object qualifier and part:

Part | Description
object | Optional. An object expression that evaluates to an object in the Applies To list.
outputlist | Optional. Expression or list of expressions to print. If omitted, a blank line is printed.

The outputlist argument has the following syntax and parts:

{Spc(n) | Tab(n)} expression charpos

Part | Description
Spc(n) | Optional. Used to insert space characters in the output, where n is the number of space characters to insert.
Tab(n) | Optional. Used to position the insertion point at an absolute column number where n is the column number. Use Tab with no argument to position the insertion point at the beginning of the next print zone.
expression | Optional. Numeric or string expressions to print.
charpos | Optional. Specifies the insertion point for the next character. Use a semicolon to position the insertion point immediately following the last character displayed. Use Tab(n) to position the insertion point at an absolute column number. Use Tab with no argument to position the insertion point at the beginning of the next print zone. If charpos is omitted, the next character is printed on the next line.

Remarks

Multiple expressions can be separated with either a space or a semicolon. A space has the same effect as a semicolon.

All data printed to the Immediate pane is internationally aware; that is, the data is properly formatted (using the appropriate decimal separator) and the keywords are output in the language appropriate for the international locale specified for your system.

For Boolean data, either True or False is printed. The True and False keywords are translated, as appropriate, according to the locale setting specified for your system.

Date data is written using the standard short date format recognized by your system. When either the date or the time component is missing or zero, only the data provided is written.

Nothing is written if outputlist data is Empty. However, if outputlist data is Null, Null is output. Again, the Null keyword is translated, as appropriate, when output.

For error data, the output is written as Error errorcode. The Error keyword is translated, as appropriate, when output.

Note Because the Print method normally prints with proportionally-spaced characters, it is important to remember that there is no correlation between the number of characters printed and the number of fixed-width columns those characters occupy. For example, a wide letter, such as a “W”, occupies more than one fixed-width column, whereas a narrow letter, such as an “i”, occupies less. To account for cases where wider than average characters are used, you must ensure that your tabular columns are positioned far enough apart. Alternatively, you can print using a fixed-pitch font (such as Courier) to ensure that each character uses only one column.

See Also

Print # Statement, Spc Function, Tab Function.

Example

Using the Print method, this example displays the value of the variable MyVar in the Immediate pane of the Debug window. Note that the Print method only applies to objects that can display text.

Dim MyVar= "Come see me in the Immediate pane.".Print MyVar


PrintCount Property

Applies To

Report.

Description

You can use the PrintCount property to identify the number of times the OnPrint property has been evaluated for the current section of a report.

Setting

You can use this property only in a macro or an event procedure specified by a section’s OnPrint property setting.

The PrintCount property setting has a Long data type value.

This property isn’t available in Design view and is read-only in all other views.

Remarks

Microsoft Access increments the PrintCount property each time the OnPrint property setting is evaluated for the current section. As the next section is printed, Microsoft Access resets PrintCount property to 0.

The PrintCount property is incremented, for example, when the KeepTogether property is set to No for the current section and the section is printed on more than one page. If you print a report containing order information, you might keep a running total of the order amounts. The following example shows how you can use the PrintCount property to make sure the value of each order is added only once.

If Reports![MyReport].PrintCount = 1 Then
    RunningTotal = RunningTotal + OrderAmountIf

See Also

Event Properties, FormatCount Property, Print Event.


PrintOut Action

Description

You can use the PrintOut action to print the active object in the open database. You can print datasheets, reports, forms, and modules.

Setting

The PrintOut action uses the following arguments.

Action argument | Description
Print Range | The range to print. Click All (the user can print all of the object), Selection (the user can print the part of the object that is selected), Pages (the user can specify a range of pages in the Page From and Page To arguments). The default is All.
Page From | The first page to print. Printing starts at the top of this page. This argument is required if you click Pages in the Print Range box.
Page To | The last page to print. Printing stops at the bottom of this page. This argument is required if you click Pages for the Print Range box.
Print Quality | The print quality. Click High, Medium, Low, or Draft. The lower the quality, the faster the object prints. The default is High.
Copies | The number of copies to print. The default is 1.
Collate Copies | Click Yes to collate the printed copies. Click No if you don’t need to collate the copies. The object may print faster if this argument is set to No. The default is Yes.

Remarks

This action is similar to selecting an object and then clicking Print on the File menu. With the action, however, no Print dialog box appears.

Tip If you have particular print settings you use frequently, create a macro containing a PrintOut action with these settings in its arguments.

The arguments for this action correspond to options in the Print dialog box. However, unlike the FindRecord action and Find In Field dialog box, the argument settings aren’t shared with the Print dialog box options.

To run the PrintOut action in Visual Basic, use the PrintOut method of the DoCmd object.

See Also

OpenForm Action, OpenQuery Action, OpenReport Action, OpenTable Action, PrintOut Method.


PrintOut Method

Applies To

DoCmd Object.

Description

The PrintOut method carries out the PrintOut action in Visual Basic. For more information on how the action and its arguments work, see the action topic.

Syntax

DoCmd.PrintOut [printrange] [, pagefrom, pageto] [, printquality] [, copies] [,collatecopies]

The PrintOut method uses the following arguments.

Argument | Description
printrange | One of the following intrinsic constants:
 | acPrintAll
 | If you leave this argument blank, the default (acPrintAll) is assumed.
pagefrom | A numeric expression that is a valid page number in the active form or datasheet. This argument is required if you specify acPages for the printrange argument.
pageto | A numeric expression that is a valid page number in the active form or datasheet. This argument is required if you specify acPages for the printrange argument.
printquality | One of the following intrinsic constants:
 | acHigh
 | If you leave this argument blank, the default (acHigh) is assumed.

Argument | Description
copies | A numeric expression. If you leave this argument blank, the default (1) is assumed.
collatecopies | Use True (-1) to collate copies and False (0) to print without collating. If you leave this argument blank, the default (True) is assumed.

Remarks

You can leave an optional argument blank in the middle of the syntax, but you must include the argument’s comma. If you leave one or more trailing arguments blank, don’t use a comma following the last argument you specify.

See Also

DoCmd Object, OpenForm Method, OpenModule Method, OpenQuery Method, OpenReport Method, OpenTable Method, Print Method, PrintOut Action.

Example

This example prints two collated copies of the first four pages of the active form or datasheet.

DoCmd.PrintOut acPages, 1, 4, , 2


PrintSection Property

See MoveLayout, NextRecord, PrintSection Properties.


Private Statement

Description

Used at module level to declare private variables and allocate storage space.

Syntax

Private varname[([subscripts])][As [New] type][, varname[([subscripts])][As[New] type]] . . .

The Private statement syntax has these parts:

Part | Description
varname | Name of the variable; follows standard variable naming conventions.
subscripts | Dimensions of an array variable; up to 60 multiple dimensions may be declared. The subscripts argument uses the following syntax: [lower To] upper[,[lower To] upper] . . . When not explicitly stated in lower, the lower bound of an array is controlled by the Option Base statement. The lower bound is zero if no Option Base statement is present.
New | Keyword used to indicate that a declared object variable is a new instance of a Visual Basic object or an externally creatable OLE Automation object. The New keyword can’t be used to create variables of any intrinsic data type and can’t be used to create dependent OLE Automation objects.
type | Data type of the variable; may be Byte, Boolean, Integer, Long, Currency, Single, Double, Date, String (for variable-length strings), String * length (for fixed-length strings), Object, Variant, a user-defined type, or an object type. Use a separate As type clause for each variable being defined.

Remarks

Private variables are available only to the module in which they are declared.

Use the Private statement to declare the data type of a variable. For example, the following statement declares a variable as an Integer:

Private NumberOfEmployees As Integer

Also use a Private statement to declare the object type of a variable. The following declares a variable for a new instance of a worksheet.

Private X As New Worksheet

If the New keyword is not used when declaring an object variable, no instance of the object actually exists. A variable that refers to an object must be assigned an existing object using the Set statement before it can be used. Until it is assigned an object, the declared object variable has the special value Nothing, which indicates that it does not refer to any particular instance of an object.

You can also use the Private statement with empty parentheses to declare a dynamic array. After declaring a dynamic array, use the ReDim statement within a procedure to define the number of dimensions and elements in the array. If you try to redeclare a dimension for an array variable whose size was explicitly specified in a Private, Public, or Dim statement, an error occurs.

If you do not specify a data type or object type, and there is no Def type statement in the module, the variable is Variant by default.

When variables are initialized, a numeric variable is initialized to 0, a variable-length string is initialized to a zero-length string, and a fixed-length string is filled with zeros. Variant variables are initialized to Empty. Each element of a user-defined type variable is initialized as if it were a separate variable.

Tip When you use the Private statement in a procedure, it is a generally accepted programming practice to put the Private statement at the beginning of the procedure.

See Also

Array Function, Const Statement, Dim Statement, Function Statement, Option Base Statement, Option Private Statement, Property Get Statement, Property Let Statement, Property Set Statement, Public Statement, ReDim Statement, Set Statement, Static Statement, Sub Statement, Type Statement.

Example

This example shows the Private statement being used at the module level to declare variables as private; that is, they are available only to the module in which they are declared.

Private Number As Integer                    ' Private Integer variable.NameArray(1 To 5) As String            ' Private array variable.
' Multiple declarations, two Variants and one Integer, all Private.MyVar, YourVar, ThisVar As Integer


Property Get Statement

Description

Declares the name, arguments, and code that form the body of a Property procedure, which gets the value of a property.

Syntax

[Public | Private][Static] Property Get name [(arglist)][As type]
[statements]
[name = expression]
[Exit Property]
[statements]
[name = expression]
End Property

The Property Get statement syntax has these parts:

Part | Description
Public | Indicates that the Property Get procedure is accessible to all other procedures in all modules. If used in a private module (one that contains an Option Private statement) the procedure is not available outside the project.

Part | Description
Private | Indicates that the Property Get procedure is accessible only to other procedures in the module where it is declared.
Static | Indicates that the Property Get procedure’s local variables are preserved between calls. The Static attribute doesn’t affect variables that are declared outside the Property Get procedure, even if they are used in the procedure.
name | Name of the Property Get procedure; follows standard variable naming conventions, except that the name can be the same as a Property Let or Property Set procedure in the same module.
arglist | List of variables representing arguments that are passed to the Property Get procedure when it is called. Multiple arguments are separated by commas. The name and data type of each argument in a Property Get procedure must be the same as the corresponding arguments in a Property Let procedure (if one exists).
type | Data type of the value returned by the Property Get procedure; may be Byte, Boolean, Integer, Long, Currency, Single, Double, Date, String (except fixed length), Object, Variant, or user-defined type. Arrays of any type can’t be returned, but a Variant containing an array can.
 | The return type of a Property Get procedure must be the same data type as the last (or sometimes the only) argument in a corresponding Property Let procedure (if one exists) that defines the value assigned to the property on the right-hand side of an expression.
statements | Any group of statements to be executed within the body of the Property Get procedure.
expression | Value of the property returned by the procedure defined by the Property Get statement.

The arglist argument has the following syntax and parts:

[ByVal | ByRef] varname[( )][As type]

Part | Description
ByVal | Indicates that the argument is passed by value.
ByRef | Indicates that the argument is passed by reference.
varname | Name of the variable representing the argument; follows standard variable naming conventions.
type | Data type of the argument passed to the Property Get procedure; may be Byte, Boolean, Integer, Long, Currency, Single, Double, Date, String (variable length only), Object, Variant, a user-defined type, or an object type.

Remarks

If not explicitly specified using either Public or Private, Property procedures are public by default. If Static is not used, the value of local variables is not preserved between calls.

All executable code must be in procedures. You can’t define a Property Get procedure inside another Property, Sub, or Function procedure.

The Exit Property keywords cause an immediate exit from a Property Get procedure. Program execution continues with the statement following the statement that called the Property Get procedure. Any number of Exit Property statements can appear anywhere in a Property Get procedure.

Like a Sub and Property Let procedure, a Property Get procedure is a separate procedure that can take arguments, perform a series of statements, and change the values of its arguments. However, unlike a Sub or Property Let procedure, you can use a Property Get procedure on the right-hand side of an expression in the same way you use a Function or a property name when you want to return the value of a property.

See Also

Function Statement, Property Let Statement, Property Set Statement, Sub Statement.

Specifics (Microsoft Access)

You can use the Property Get statement to define a property procedure that gets the value of a property for a user-defined object. You will probably want to use the Property Let and Property Get statements together to create a property for an object. For example, you could define a Property Let procedure in a form module to set a new property for an object, and a Property Get procedure to return the value of that setting.

Usually you will define property procedures within a form or report module. Property procedures in a form or report module are public by default, and will be available to procedures in other modules in the current database. However, they will not be available to other databases.

You can use the property procedures to create new properties on a user-defined object. You can also use them to combine a set of properties for a custom form or report object. For example, you could create a custom property called CustomFormType. Using the Property Get statement, you could construct the CustomFormType property procedures so that one setting would display a white form with scroll bars, navigation buttons, and caption “Type1”, while another setting would display a blue form with neither scroll bars nor navigation buttons, and caption “Type2”. Then you could set the CustomFormType property for new form objects that you create for this form. Using the Property Get statement, you could create a property procedure to return the value of this property once it has been set.

Example

This example uses the Property Get Statement to define a property procedure that gets the value of a property. The property identifies, as a string, the current color of a pen in a drawing package.

Dim CurrentColor As IntegerBLACK = 0, RED = 1, GREEN = 2, BLUE = 3

' Returns the current color of the pen as a string.Get PenColor() As String
    Select Case CurrentColor
        Case RED
            PenColor = "Red"
        Case GREEN
            PenColor = "Green"
        Case BLUE
            PenColor = "Blue"
    End SelectProperty
' The following code gets the color of the pen
' calling the Property Get procedure.= PenColor()

The following example shows how to use the Property Let and Property Get statements to create a custom property, CustomFormType, for a user-defined object. By setting the CustomFormType property, you apply a set of predefined characteristics to a user-defined form object. You can also read the property to determine its current setting.

To test this example, create a new form and save it as CustomFormTemplate. In the Declarations section of the form’s module, enter the following code.

Public intCurrent As IntegerconType1 = 1conType2 = 2

Enter the following procedures in the form module. The Property Let procedure defines the characteristics that will be applied to the form when the CustomFormType property is set. The Property Get procedure returns the current setting of the CustomFormType property.

Static Property Let CustomFormType(intCustomType As Integer)
    Select Case intCustomType
        Case conType1
            With Me
                .Section(0).BackColor = RGB(255, 255, 255)
                .ScrollBars = 3
                .NavigationButtons = True
                .Caption = "Type1"
                intCurrent = conType1
            End With
        Case conType2
            With Me
                .Section(0).BackColor = RGB(127, 127, 127)
                .ScrollBars = 0
                .NavigationButtons = False
                .Caption = "Type2"
                intCurrent = conType2
            End With
        Case Else
            MsgBox "Error!"
    End SelectProperty
Property Get CustomFormType() As Integer
    Select Case intCurrent
        Case conType1
            CustomFormType = conType1
        Case conType2
            CustomFormType = conType2
        Case Else
            MsgBox "Error!"
    End SelectProperty

' Define custom method to display form.Show()
    Me.Visible = TrueSub

Create a new instance of the CustomFormTemplate object in a standard module. Now you can set and read the value of the CustomFormType property just as you would any built-in property.

Sub SetFormProperty()
    Dim frmObject as New Form_CustomFormTemplate
    ' Call Show method to display form.
    frmObject.Show
    ' Set value of property.
    frmObject.CustomFormType = 1
    ' Return value of property.
    Debug.Print frmObject.CustomFormTypeSub


Property Let Statement

Description

Declares the name, arguments, and code that form the body of a Property Let procedure, which assigns a value to a property.

Syntax

[Public | Private][Static] Property Let name [(arglist)]
[statements]
[Exit Property]
[statements]
End Property

The Property Let statement syntax has these parts:

Part | Description
Public | Indicates that the Property Let procedure is accessible to all other procedures in all modules. If used in a private module (one that contains an Option Private statement), the procedure is not available outside the project.
Private | Indicates that the Property Let procedure is accessible only to other procedures in the module where it is declared.
Static | Indicates that the Property Let procedure’s local variables are preserved between calls. The Static attribute doesn’t affect variables that are declared outside the Property Let procedure, even if they are used in the procedure.
name | Name of the Property Let procedure; follows standard variable naming conventions, except that the name can be the same as a Property Get or Property Set procedure in the same module.
arglist | List of variables representing arguments that are passed to the Property Let procedure when it is called. Multiple arguments are separated by commas. The name and data type of each argument in a Property Let procedure (except the last one) must be the same as the corresponding arguments in a Property Get procedure. The last argument is the value assigned to the property on the right-hand side of an expression. The data type of the last (or sometimes the only) argument must be the same as the return type of the corresponding Property Get procedure.
statements | Any group of statements to be executed within the body of the Property Let procedure.

The arglist argument has the following syntax and parts:

[ByVal | ByRef] varname[( )][As type]

Part | Description
ByVal | Indicates that the argument is passed by value.
ByRef | Indicates that the argument is passed by reference.
varname | Name of the variable representing the argument; follows standard variable naming conventions.
type | Data type of the argument passed to the Property Let procedure; may be Byte, Boolean, Integer, Long, Currency, Single, Double, Date, String (variable length only), Object, Variant, a user-defined type, or an object type.

Note Every Property Let statement must define at least one argument for the procedure it defines. That argument (or the last argument if there is more than one) contains the actual value to be assigned to the property when the procedure defined by the Property Let statement is invoked.

Remarks

If not explicitly specified using either Public or Private, Property procedures are public by default. If Static is not used, the value of local variables is not preserved between calls.

All executable code must be in procedures. You can’t define a Property Let procedure inside another Property, Sub, or Function procedure.

The Exit Property keywords cause an immediate exit from a Property Let procedure. Program execution continues with the statement following the statement that called the Property Let procedure. Any number of Exit Property statements can appear anywhere in a Property Let procedure.

Like a Function and Property Get procedure, a Property Let procedure is a separate procedure that can take arguments, perform a series of statements, and change the value of its arguments. However, unlike a Function and Property Get procedure, both of which return a value, you can only use a Property Let procedure on the left-hand side of a property assignment expression or Let statement.

See Also

Function Statement, Let Statement, Property Get Statement, Property Set Statement, Sub Statement.

Specifics (Microsoft Access)

You can use the Property Let statement to define a property procedure that assigns the value of a property for a user-defined object. You will probably want to use the Property Let and Property Get statements together to create a property for an object. For example, you could define a Property Let procedure in a form module to set a new property for an object, and a Property Get procedure to return the value of that setting.

Usually you will define property procedures within a form module or report module. Property procedures in a form or report module are public by default, and will be available to procedures in other modules in the current database. However, they will not be available to other databases.

You can use the property procedures to create new properties on a user-defined object. You can also use them to combine a set of properties for a custom form or report object. For example, you could create a custom property called CustomFormType. Using the Property Get statement, you could construct the CustomFormType property procedures so that one setting would display a white form with scroll bars, navigation buttons, and caption “Type1”, while another setting would display a blue form with neither scroll bars nor navigation buttons, and caption “Type2”. Then you could set the CustomFormType property for new form objects that you create for this form. Using the Property Get statement, you could create a property procedure to return the value of this property once it has been set.

Example

This example uses the Property Let statement to define a procedure that assigns a value to a property. The property identifies the pen color for a drawing package.

Dim CurrentColor As IntegerBLACK = 0, RED = 1, GREEN = 2, BLUE = 3

' Set the pen color property for a Drawing package.
' The module-level variable CurrentColor is set to
' a numeric value that identifies the color used for drawing.Let PenColor(ColorName As String)
    Select Case ColorName                ' Check color name string.
        Case "Red"
            CurrentColor = RED            ' Assign value for Red.
        Case "Green"
            CurrentColor = GREEN            ' Assign value for Green.
        Case "Blue"
            CurrentColor = BLUE            ' Assign value for Blue.
        Case Else
            CurrentColor = BLACK            ' Assign default value.
    End SelectProperty
' The following code sets the PenColor property for a drawing package
' by calling the Property Let procedure.() = "Red"

See also the Property Get statement example.


Property Set Statement

Description

Declares the name, arguments, and code that form the body of a Property procedure, which sets a reference to an object.

Syntax

[Public | Private][Static] Property Set name [(arglist)]
[statements]
[Exit Property]
[statements]End Property

The Property Set statement syntax has these parts:

Part | Description
Public | Indicates that the Property Set procedure is accessible to all other procedures in all modules. If used in a private module (one that contains an Option Private statement), the procedure is not available outside the project.
Private | Indicates that the Property Set procedure is accessible only to other procedures in the module where it is declared.
Static | Indicates that the Property Set procedure’s local variables are preserved between calls. The Static attribute doesn’t affect variables that are declared outside the Property Set procedure, even if they are used in the procedure.
name | Name of the Property Set procedure; follows standard variable naming conventions, except that the name can be the same as a Property Get or Property Let procedure in the same module.
arglist | List of variables representing arguments that are passed to the Property Set procedure when it is called. Multiple arguments are separated by commas. The last argument is the object reference used on the right-hand side of an object reference assignment.
statements | Any group of statements to be executed within the body of the Property procedure.

The arglist argument has the following syntax and parts:

[ByVal | ByRef] varname[( )][As type]

Part | Description
ByVal | Indicates that the argument is passed by value.
ByRef | Indicates that the argument is passed by reference.
varname | Name of the variable representing the argument; follows standard variable naming conventions.
type | Data type of the argument passed to the Property Set procedure; may be Byte, Boolean, Integer, Long, Currency, Single, Double, Date, String (variable length only), Object, Variant, a user-defined type, or an object type.

Note Every Property Set statement must define at least one argument for the procedure it defines. That argument (or the last argument if there is more than one) contains the actual object reference for the property when the procedure defined by the Property Set statement is invoked.

Remarks

If not explicitly specified using either Public or Private, Property procedures are public by default. If Static is not used, the value of local variables is not preserved between calls.

All executable code must be in procedures. You can’t define a Property Set procedure inside another Property, Sub, or Function procedure.

The Exit Property keywords cause an immediate exit from a Property Set procedure. Program execution continues with the statement following the statement that called the Property Set procedure. Any number of Exit Property statements can appear anywhere in a Property Set procedure.

Like a Function and Property Get procedure, a Property Set procedure is a separate procedure that can take arguments, perform a series of statements, and change the value of its arguments. However, unlike a Function and Property Get procedure, both of which return a value, you can only use a Property Set procedure on the left-hand side of an object reference assignment (Set statement).

See Also

Function Statement, Property Get Statement, Property Let Statement, Set Statement, Sub Statement.

Example

This example uses the Property Set statement to define a property procedure that sets a reference to an object.

' The Pen property may be set to different Pen implementations.Set Pen(P As Object)
    Set CurrentPen = P                    ' Assign Pen to object.Property


PrtDevMode Property

Applies To

Form, Query, Report, Table.

Description

You can use the PrtDevMode property to set or return printing device mode information specified for a form, report, or module in the Print Setup dialog box.

Note It is strongly recommended that you consult the Win32® Software Development Kit for complete documentation on the PrtDevMode, PrtDevNames, and PrtMip properties.

The PrtDevMode property applies only to tables and queries in Datasheet view and reports and forms.

Setting

The PrtDevMode property setting is a 94-byte structure that mirrors the DEVMODE structure defined in the Win32 Software Development Kit. For complete information on the PrtDevMode property members, consult the Win32 Software Development Kit.

The PrtDevMode property uses the following members.

Member | Description
DeviceName | A 32-character string that specifies the name of the device the driver supports — for example, “HP LaserJet IIISi” if the Hewlett-Packard® LaserJet® IIISi is the specified printer. Each printer driver has a unique string.
SpecVersion | An Integer that specifies the version number of the DEVMODE structure in the Win32 Software Development Kit.
DriverVersion | An Integer that specifies the printer driver version number assigned by the printer driver developer.
Size | An Integer that specifies the size, in bytes, of the DEVMODE structure. (This value doesn’t include the optional dmDriverData member for device-specific data, which can follow this structure.) If an application manipulates only the driver-independent portion of the data, you can use this member to find out the length of this structure without having to account for different versions.

Member | Description
DriverExtra | An Integer that specifies the size, in bytes, of the optional dmDriverData member for device-specific data, which can follow this structure. If an application doesn’t use device-specific information, you set this member to 0.
Fields | A Long value that specifies which of the remaining members in the DEVMODE structure have been initialized. It can be any combination of specific constants or none of them. For available constants, see the Fields member constants.
Orientation | An Integer that specifies the orientation of the paper. It can be either 1 (portrait) or 2 (landscape).
PaperSize | An Integer that specifies the size of the paper to print on. You can set this member to 0 if the length and width of the paper are specified by the PaperLength and PaperWidth members, respectively. Otherwise, you can set the PaperSize member to a predefined value. For available values, see the PaperSize member values.
PaperLength | An Integer that specifies the paper length in units of 1/10 of a millimeter. This member overrides the paper length specified by the PaperSize member for custom paper sizes or for devices such as dot-matrix printers that can print on a variety of paper sizes.
PaperWidth | An Integer that specifies the paper width in units of 1/10 of a millimeter. This member overrides the paper width specified by the PaperSize member.
Scale | An Integer that specifies the factor by which the printed output will be scaled. The apparent page size is scaled from the physical page size by a factor of Scale/100. For example, a piece of paper measuring 8.5 by 11 inches (letter-size) with a Scale value of 50 would contain as much data as a page measuring 17 by 22 inches because the output text and graphics would be half their original height and width.
Copies | An Integer that specifies the number of copies printed if the printing device supports multiple-page copies.
DefaultSource | An Integer that specifies the default bin from which the paper is fed. For available values, see the DefaultSource member values.
PrintQuality | An Integer that specifies the printer resolution. See the PrintQuality member values of appropriate device-independent values.

Member | Description
Color | An Integer. For a color printer, specifies whether the output is printed in color. For available values, see the Color member values.
Duplex | An Integer. For a printer capable of duplex printing, specifies whether the output is printed on both sides of the paper. For available values, see the Duplex member values.
YResolution | An Integer that specifies the y-resolution of the printer in dots per inch (dpi). If the printer initializes this member, the PrintQuality member specifies the x-resolution of the printer in dpi.
TTOption | An Integer that specifies how TrueType fonts will be printed. For available values, see the TTOption member values.
Collate | An Integer that specifies whether collation should be used when printing multiple copies. Using uncollated copies provides faster, more efficient output, since the data is sent to the printer just once.
FormName | A 16-character string that specifies the name of the form to use; for example, “Letter” or “Legal”.
Pad | A Long Integer value.
Bits | A Long value that specifies in bits per pixel the color resolution of the display device.
PW | A Long value that specifies the width, in pixels, of the visible device surface.
PH | A Long value that specifies the height, in pixels, of the visible device surface.
DFI | A Long value that specifies the device’s display mode.
DFR | A Long value that specifies the frequency, in hertz (cycles per second), of the display device in a particular mode.

You can set the PrtDevMode property using a macro or an event procedure.

This property setting is read/write in Design view and read-only in other views.

Caution Printer drivers can add device-specific data immediately following the DEVMODE structure. It is important that information that may be contained after the first 94 bytes not be overwritten.

Remarks

Only printer drivers that export the ExtDeviceMode function use the DEVMODE structure.

An application can retrieve the paper sizes and names supported by a printer by calling the DeviceCapabilities function with the DC_PAPERS, DC_PAPERSIZE, and DC_PAPERNAMES values.

Before setting the value of the dmTTOption member, applications should find out how a printer driver can use TrueType fonts by calling the DeviceCapabilities function using the DC_TRUETYPE value.

Constants for the Fields Member

A printer driver supports only those members that are appropriate for the printer technology.

Constant | Value
DM_ORIENTATION | &H0000001
DM_PAPERSIZE | &H0000002
DM_PAPERLENGTH | &H0000004
DM_PAPERWIDTH | &H0000008
DM_SCALE | &H0000010
DM_COPIES | &H0000100
DM_DEFAULTSOURCE | &H0000200
DM_PRINTQUALITY | &H0000400
DM_COLOR | &H0000800
DM_DUPLEX | &H0001000
DM_YRESOLUTION | &H0002000
DM_TTOPTION | &H0004000
DM_COLLATE | &H0008000
DM_FORMNAME | &H0010000

Values for the PaperSize Member

Value | Paper size
1 | Letter (8.5 x 11 in.)
2 | Letter Small (8.5 x 11 in.)
3 | Tabloid (11 x 17 in.)
4 | Ledger (17 x 11 in.)
5 | Legal (8.5 x 14 in.)
6 | Statement (5.5 x 8.5 in.)
7 | Executive (7.25 x 10.5 in.)
8 | A3 (297 x 420 mm)
9 | A4 (210 x 297 mm)
10 | A4 Small (210 x 297 mm)
11 | A5 (148 x 210 mm)
12 | B4 (250 x 354)
13 | B5 (182 x 257 mm)
14 | Folio (8.5 x 13 in.)
15 | Quarto (215 x 275 mm)
16 | 11 x 17 in.
18 | Note (8.5 x 11 in.)
19 | Envelope #9 (3.875 x 8.875 in.)
20 | Envelope #10 (4.125 x 9.5 in.)
21 | Envelope #11 (4.5 x 10.375 in.)
22 | Envelope #12 (4.25 x 11 in.)
23 | Envelope #14 (5 x 11.5 in.)
24 | C size sheet
25 | D size sheet
26 | E size sheet
27 | Envelope DL (110 x 220 mm)
28 | Envelope C5 (162 x 229 mm)
29 | Envelope C3 (324 x 458 mm)
30 | Envelope C4 (229 x 324 mm)
31 | Envelope C6 (114 x 162 mm)
32 | Envelope C65 (114 x 229 mm)
33 | Envelope B4 (250 x 353 mm)
34 | Envelope B5 (176 x 250 mm
35 | Envelope B6 (176 x 125 mm)
36 | Envelope (110 x 230 mm)

Value | Paper size
37 | Envelope Monarch (3.875 x 7.5 in.)
38 | 6-3/4 Envelope (3.625 x 6.5 in.)
39 | US Std Fanfold (14.875 x 11 in.)
40 | German Std Fanfold (8.5 x 12 in.)
41 | German Legal Fanfold (8.5 x 13 in.)
256 | User-defined

Values for the DefaultSource Member

Value | Meaning
1 | Upper or only one bin
2 | Lower bin
3 | Middle bin
4 | Manual bin
5 | Envelope bin
6 | Envelope manual bin
7 | Automatic bin
8 | Tractor bin
9 | Small-format bin
10 | Large-format bin
11 | Large-capacity bin
14 | Cassette bin
256 | Device-specific bins start here

Values for the PrintQuality Member

Value | Resolution
-4 | High
-3 | Medium
-2 | Low
-1 | Draft

Values for the Color Member

Value | Meaning
1 | Color
2 | Monochrome

Values for the Duplex Member

Value | Meaning
1 | Simplex
2 | Horizontal
3 | Vertical

Values for the TTOption Member

Value | Meaning
1 | Print TrueType fonts as graphics. This is the default for dot-matrix printers.
2 | Download TrueType fonts as soft fonts. This is the default for Hewlett-Packard printers that use Printer Control Language (PCL).
3 | Substitute device fonts for TrueType fonts. This is the default for PostScript printers.

See Also

PrtDevNames Property, PrtMip Property.

Example

The following example uses the PrtDevMode property to check the user-defined page size for a report.

Type str_DEVMODE
    RGB As String * 94Type
type_DEVMODE
    dmDeviceName As String * 16
    dmSpecVersion As Integer
    dmDriverVersion As Integer
    dmSize As Integer
    dmDriverExtra As Integer
    dmFields As Long
    dmOrientation As Integer
    dmPaperSize As Integer
    dmPaperLength As Integer
    dmPaperWidth As Integer
    dmScale As Integer
    dmCopies As Integer
    dmDefaultSource As Integer
    dmPrintQuality As Integer
    dmColor As Integer
    dmDuplex As Integer
    dmResolution As Integer
    dmTTOption As Integer
    dmCollate As Integer
    dmFormName As String * 16
    dmPad As Long
    dmBits As Long
    dmPW As Long
    dmPH As Long
    dmDFI As Long
    dmDFr As LongType
CheckCustomPage(rptName As String)
    Dim DevString As str_DEVMODE
    Dim DM As type_DEVMODE
    Dim DevModeExtra As String
    Dim rpt As Report
    Dim response
    ' Opens report in Design view.
    DoCmd.OpenReport rptName, acDesign
    Set rpt = Reports(rptName)
    If Not IsNull(rpt.PrtDevMode) Then
        DevModeExtra = rpt.PrtDevMode  ' Gets current DEVMODE structure.
        DevString.RGB = DevModeExtra
        LSet DM = DevString
        If DM.dmPaperSize = 256 Then
            ' Display user-defined size.
            response = MsgBox("The current Custom Page Size is " _
                & DM.dmPaperWidth / 254 & " in wide by " _
                & DM.dmPaperLength / 254 _
                & " in long. Do you want to change the settings?", 4)
        Else
            ' Currently not user-defined.
            response = MsgBox("The report does not have a custom" _
                & " page. Do you want to define one?", 4)
        End If
        If response = 6 Then
            ' User wants to change settings.
            ' Initialize fields.
            DM.dmFields = DM.dmFields Or DM_PAPERSIZE _
                Or DM_PAPERLENGTH Or DM_PAPERWIDTH
            DM.dmPaperSize = 256                    ' Set custom page.
            ' Prompt for length and width.
            DM.dmPaperLength = InputBox("Please enter Page Length" _
                & " in inches") * 254
            DM.dmPaperWidth = InputBox("Please enter Page Width" _
                & " in inches") * 254
            LSet DevString = DM                    ' Update property.
            Mid$(DevModeExtra, 1, 94) = DevString.RGB
            rpt.PrtDevMode = DevModeExtra
        End If
    End IfSub

The following example shows how to change the orientation of the report. This example will switch the orientation from portrait to landscape or landscape to portrait depending on the report’s current orientation.

Sub SwitchOrient(rptName As String)
    Const DM_PORTRAIT = 1
    Const DM_LANDSCAPE = 2
    Dim DevString As str_DEVMODE
    Dim DM As type_DEVMODE
    Dim DevModeExtra As String
    Dim rpt As Report
    DoCmd.OpenReport rptName, acDesign    ' Opens report in Design view.
    Set rpt = Reports(rptName)
    If Not IsNull(rpt.PrtDevMode) Then
        DevModeExtra = rpt.PrtDevMode
        DevString.RGB = DevModeExtra
        LSet DM = DevString
        DM.dmFields = DM.dmFields Or DM_ORIENTATION ' Initialize fields.
        If DM.dmOrientation = DM_PORTRAIT Then
            DM.dmOrientation = DM_LANDSCAPE
        Else
            DM.dmOrientation = DM_PORTRAIT
        End If
        LSet DevString = DM                ' Update property.
        Mid$(DevModeExtra, 1, 94) = DevString.RGB
        rpt.PrtDevMode = DevModeExtra
    End IfSub


PrtDevNames Property

Description

You can use the PrtDevNames property to set or return information about the printer selected in the Print Setup dialog box.

Note It is strongly recommended that you consult the Win32 Software Development Kit for complete documentation on the PrtDevMode, PrtDevNames, and PrtMip properties.

The PrtDevNames property applies only to tables and queries in Datasheet view and reports and forms.

Setting

The PrtDevNames property is a variable-length structure that mirrors the DEVNAMES structure defined in the Win32 Software Development Kit.

The PrtDevNames property uses the following members.

Member | Description
DriverOffset | Specifies the offset from the beginning of the structure to a Null-terminated string that specifies the filename (without an extension) of the device driver. This string is used to specify which printer is initially displayed in the Print Setup dialog box.
DeviceOffset | Specifies the offset from the beginning of the structure to the Null-terminated string that specifies the name of the device. This string can’t be longer than 32 bytes (including the null character) and must be identical to the DeviceName member of the DEVMODE structure. You can determine the driver name and device name by looking at the [devices] section of the Win.ini file.
OutputOffset | Specifies the offset from the beginning of the structure to the Null-terminated string that specifies the MS-DOS device name for the physical output medium (output port); for example, “LPT1:”.
Default | Specifies whether the strings specified in the DEVNAMES structure identify the default printer. Before the Print Setup dialog box is displayed, if Default is set to 1 and all of the values in the DEVNAMES structure match the current default printer, the selected printer is set to the default printer. Default is set to 1 if the current default printer has been selected.

Microsoft Access sets the PrtDevNames property when you make selections in the Printer section of the Print Setup dialog box. You can also set the property using Visual Basic.

Remarks

Microsoft Access uses the DEVNAMES structure to initialize the Print Setup dialog box. When the user chooses OK to close the dialog box, information about the selected printer is returned by the PrtDevNames property.

See Also

PrtDevMode Property, PrtMip Property.


PrtMip Property

Applies To

Form, Query, Report, Table.

Description

You can use the PrtMip property in Visual Basic to set or return the device mode information specified for a form, report, or module in the Print Setup dialog box.

Setting

The PrtMip property setting is a 28-byte structure that maps to settings for the Margins options and the Data Only option for a form, report, or module in the Print Setup dialog box. The structure also maps to the options displayed after you choose the More button in the Print Setup dialog box. (The More button is enabled only for a form in Form view or a report.)

The PrtMip property uses the following members.

Member | Description
LeftMargin, RightMargin, TopMargin, BottomMargin | An Integer that specifies the distance between the edge of the page and the item to be printed in twips.
DataOnly | An Integer that specifies the elements to be printed. When True (-1), prints only the data in a table or query in Datasheet view, form, or report, and suppresses labels, control borders, gridlines, and display graphics such as lines and boxes. When False (0), prints data, labels, and graphics.
ItemsAcross | An Integer that specifies the number of columns across for multiple-column reports or labels.
RowSpacing | An Integer that specifies the horizontal space between detail sections in units of 1/20 of a point.
ColumnSpacing | An Integer that specifies the vertical space between detail sections in twips.
DefaultSize | An Integer. When True, uses the size of the detail section in Design view. When False, uses the values specified by the ItemSizeWidth and ItemSizeHeight members.
ItemSizeWidth | An Integer that specifies the width of the detail section in twips.
ItemSizeHeight | An Integer that specifies the height of the detail section twips.
ItemLayout | An Integer that specifies horizontal (1953) or vertical (1954) layout of columns.
FastPrint | Reserved
Datasheet | Reserved

The PrtMip property setting is read/write in Design view and read-only in other views.

See Also

PrtDevMode Property, PrtDevNames Property.

Example

The following PrtMip property example demonstrates how to setup the report with 2 horizontal columns.

Type str_PRTMIP
    RGB As String * 56Typetype_PRTMIP
    xLeftMargin As Long
    yTopMargin As Long
    xRightMargin As Long
    yBotMargin As Long
    fDataOnly As Long
    xWidth As Long
    yHeight As Long
    fDefaultSize As Long
    cxColumns As Long
    yColumnSpacing As Long
    xRowSpacing As Long
    rItemLayout As Long
    fFastPrint As Long
    fDatasheet As LongType
PrtMipCols(rptName As String)
    Dim PrtMipString As str_PRTMIP
    Dim PM As type_PRTMIP
    Dim rpt As Report
    Const PM_HORIZONTALCOLS = 1953
    Const PM_VERTICALCOLS = 1954
    DoCmd.OpenReport rptName, acDesign    ' Open report in Design view.
    Set rpt = Reports(rptName)
    PrtMipString.RGB = rpt.PrtMip
    LSet PM = PrtMipString
    PM.cxColumns = 2                        ' Create two columns.
    PM.xRowSpacing = 0.25 * 1440            ' Set 0.25 inch between rows.
    PM.yColumnSpacing = 0.5 * 1440        ' Set 0.5 inch between columns.
    PM.rItemLayout = PM_HORIZONTALCOLS

    LSet PrtMipString = PM                ' Update property.
    rpt.PrtMip = PrtMipString.RGBSub

The next PrtMip property example shows how to set all margins to 1 inch.

Sub SetMarginsToDefault(rptName As String)
    Dim PrtMipString As str_PRTMIP
    Dim PM As type_PRTMIP
    Dim rpt As Report
    DoCmd.OpenReport rptName, acDesign      ' Open report in Design view.
    Set rpt = Reports(rptName)
    PrtMipString.RGB = rpt.PrtMip
    LSet PM = PrtMipString
    PM.xLeftMargin = 1 * 1440              ' Set margins.
    PM.yTopMargin = 1 * 1440
    PM.xRightMargin = 1 * 1440
    PM.yBotMargin = 1 * 1440
    LSet PrtMipString = PM                  ' Update property.
    rpt.PrtMip = PrtMipString.RGBSub


PSet Method

Applies To

Report Object.

Description

The PSet method sets a point on a Report object to a specified color when the Print event occurs.

Syntax

object.PSet [Step](x, y)[, color]

You can use this method only in an event procedure or a macro specified by the event properties OnPrint or OnFormat for a report section, or OnPage for a report.

The PSet method uses the following arguments.

Argument | Description
object | The Report object on which the point is to be drawn.
Step | A key word that indicates the coordinates are relative to the current graphics position given by the settings for the CurrentX and CurrentY properties of object.
x, y | Single values indicating the horizontal and vertical coordinates of the point to set.
color | An RGB (red-green-blue) color to set the point to. If this argument is omitted, the current foreground color is used. You can also use the RGB function or the QBColor function to specify the color.

Remarks

The size of the point depends on the DrawWidth property setting. When the DrawWidth property is set to 1, the PSet method sets a single pixel to the specified color. When the DrawWidth property is greater than 1, the point is centered on the specified coordinates.

The way the point is drawn depends on the settings of the DrawMode and DrawStyle properties.

When you apply the PSet method, the CurrentX and CurrentY properties are set to the point specified by the x and y arguments.

To clear a single pixel with the PSet method, specify the coordinates of the pixel and use white (&HFFFFFF) as the color argument.

See Also

CurrentX, CurrentY Properties; DrawMode Property; DrawStyle Property; DrawWidth Property; Event Properties; Print Event; QBColor Function; RGB Function.

Example

The following example uses the PSet method to draw a line through the horizontal axis of a report.

To try this example in Microsoft Access, create a new report by clicking the New button on the Reports tab of the Database window. Set the OnPrint property of the Detail section to [Event Procedure]. Enter the following code in the report’s module, then switch to Print Preview.

Sub Detail_Print(Cancel As Integer, PrintCount As Integer)
    Dim sngMidPt As Single, intI As Integer

    rpt.ScaleMode = 3                        ' Set scale to pixels.
    sngMidPt = rpt.ScaleHeight / 2            ' Calculate midpoint.
    ' Loop to draw line down horizontal axis pixel by pixel.
    For intI = 1 To rpt.ScaleWidth
        rpt.PSet(intI, sngMidPt)
    Next intISub

Tip It’s faster to draw a line using the Line method rather than the PSet method.


Public Statement

Description

Used at module level to declare public variables and allocate storage space.

Syntax

Public varname[([subscripts])][As [New] type][, varname[([subscripts])][As[New] type]] . . .

The Public statement syntax has these parts:

Part | Description
varname | Name of the variable; follows standard variable naming conventions.
subscripts | Dimensions of an array variable; up to 60 multiple dimensions may be declared. The argument subscripts uses the following syntax:
 | [lower To] upper [,[lower To] upper] . . . When not explicitly stated in lower, the lower bound of an array is controlled by the Option Base statement. The lower bound is zero if no Option Base statement is present.
New | Keyword used to indicate that a declared object variable is a new instance of a Visual Basic object or an externally creatable OLE Automation object. The New keyword can’t be used to create variables of any intrinsic data type and can’t be used to create dependent OLE Automation objects.
type | Data type of the variable; may be Byte, Boolean, Integer, Long, Currency, Single, Double, Date, String (for variable-length strings), String * length (for fixed-length strings), Object, Variant, a user-defined type, or an object type. Use a separate As type clause for each variable being defined.

Remarks

Variables declared using the Public statement are available to all procedures in all modules in all applications unless Option Private Module is in effect; in which case, the variables are public only within the project in which they reside.

Caution The Public statement can’t be used in a class module to declare a fixed-length string variable.

Use the Public statement to declare the data type of a variable. For example, the following statement declares a variable as an Integer:

Public NumberOfEmployees As Integer

Also use a Public statement to declare the object type of a variable. The following declares a variable for a new instance of a worksheet.

Public X As New Worksheet

If the New keyword is not used when declaring an object variable, no instance of the object actually exists. A variable that refers to an object must be assigned an existing object using the Set statement before it can be used. Until it is assigned an object, the declared object variable has the special value Nothing, which indicates that it does not refer to any particular instance of an object.

You can also use the Public statement with empty parentheses to declare a dynamic array. After declaring a dynamic array, use the ReDim statement within a procedure to define the number of dimensions and elements in the array. If you try to redeclare a dimension for an array variable whose size was explicitly specified in a Private, Public, or Dim statement, an error occurs.

If you do not specify a data type or object type and there is no Def type statement in the module, the variable is Variant by default.

When variables are initialized, a numeric variable is initialized to 0, a variable-length string is initialized to a zero-length string, and a fixed-length string is filled with zeros. Variant variables are initialized to Empty. Each element of a user-defined type variable is initialized as if it were a separate variable.

Tip When you use the Public statement in a procedure, it is a generally accepted programming practice to put the Public statement at the beginning of the procedure.

See Also

Array Function, Const Statement, Dim Statement, Option Base Statement, Option Private Statement, Private Statement, Property Get Statement, Property Let Statement, Property Set Statement, ReDim Statement, Set Statement, Static Statement, Type Statement.

Specifics (Microsoft Access)

By default, module-level variables are private to that module. You must explicitly declare a variable as public with the Public statement.

In a standard module, module-level variables declared with the Public statement are available to all other procedures in all modules in all Microsoft Access databases. However, they are not visible in the Object Browser, and they are not available to any other applications other than Microsoft Access.

If a public variable is declared in a standard module that contains the Option Private statement, the variable is available to all procedures in the current database, but not to procedures in other databases.

A public variable declared in a form module or report module is visible to all procedures in the current database, but not to procedures in other databases. To refer to a public variable declared in a form or report module from another module, you must qualify the variable with the class name of the form or report.

For example, if you declare the public variable varPublic in the module of a form called OrderForm, you can refer to that variable from a standard module as follows.

Form_OrderForm.varPublic

Note The Public statement can’t be used in a form or report module to declare a fixed-length string or an array.

Example

This example uses the Public statement at the module level (General section) of a standard module to explicitly declare variables as public; that is, they are available to all procedures in all modules in all applications unless Option Private Module is in effect.

Public Number As Integer                        ' Public Integer variable.NameArray(1 To 5) As String            ' Public array variable.
' Multiple declarations, two Variants and one Integer, all Public.MyVar, YourVar, ThisVar As Integer

The following example uses the Public statement at the module level to explicitly declare variables as public. Public variables are available to all procedures in all modules within the current database. If they are declared in a standard module, then they are also available to a referencing database.

Public intNum As IntegerobjApplication As Object


Put Statement

Description

Writes from a variable to a disk file.

Syntax

Put [#]filenumber, [recnumber], varname

The Put statement syntax has these parts:

Part | Description
filenumber | Any valid file number.
recnumber | Record number (Random mode files) or byte number (Binary mode files) at which writing begins.
varname | Name of variable containing data to be written to disk.

Remarks

The first record or byte in a file is at position 1, the second record or byte is at position 2, and so on. If you omit recnumber, the next record or byte (the one after the last Get or Put statement or the one pointed to by the last Seek function) is written. You must include delimiting commas, for example:

Put #4,,FileBuffer

For files opened in Random mode, the following rules apply:

  • If the length of the data being written is less than the length specified in the Len clause of the Open statement, Put still writes subsequent records on record-length boundaries. The space between the end of one record and the beginning of the next record is padded with the existing contents of the file buffer. Because the amount of padding data can’t be determined with any certainty, it is generally a good idea to have the record length match the length of the data being written. If the length of the data being written is greater than that specified in the Len clause of the Open statement, an error occurs.
  • If the variable being written is a variable-length string, Put writes a 2-byte descriptor containing the string length and then the variable. The record length specified by the Len clause in the Open statement must be at least 2 bytes greater than the actual length of the string.
  • If the variable being written is a Variant of a numeric type, Put writes 2 bytes identifying the VarType of the Variant and then the variable. For example, when writing a Variant of VarType 3, Put writes 6 bytes: 2 bytes identifying the Variant as VarType 3 (Long) and 4 bytes containing the Long data. The record length specified by the Len clause in the Open statement must be at least 2 bytes greater than the actual number of bytes required to store the variable.

Note You can use the Put statement to write a Variant array to disk but you cannot use Put to write a scalar Variant containing an array to disk. You also cannot use Put to write objects to disk.

  • If the variable being written is a String Variant (VarType 8), Put writes 2 bytes identifying the VarType, 2 bytes indicating the length of the string, and then the string data. The record length specified by the Len clause in the Open statement must be at least 4 bytes greater than the actual length of the string.
  • If the variable being written is a dynamic array, Put writes a descriptor whose length equals 2 plus 8 times the number of dimensions, that is, 2 + 8 * NumberOfDimensions. The record length specified by the Len clause in the Open statement must be greater than or equal to the sum of all the bytes required to write the array data and the array descriptor. For example, the following array declaration requires 118 bytes when the array is written to disk.

Dim MyArray(1 To 5,1 To 10) As Integer

The 118 bytes are distributed as follows: 18 bytes for the descriptor (2 + 8 * 2), and 100 bytes for the data (5 * 10 * 2).

  • If the variable being written is a fixed-size array, Put writes only the data. No descriptor is written to disk.
  • If the variable being written is any other type of variable (not a variable-length string or a Variant), Put writes only the variable data. The record length specified by the Len clause in the Open statement must be greater than or equal to the length of the data being written.
  • Put writes elements of user-defined types as if each were written individually, except there is no padding between elements. On disk, a dynamic array in a user-defined type written with Put is prefixed by a descriptor whose length equals 2 plus 8 times the number of dimensions, that is, 2 + 8 * NumberOfDimensions. The record length specified by the Len clause in the Open statement must be greater than or equal to the sum of all the bytes required to write the individual elements, including any arrays and their descriptors.

For files opened in Binary mode, all of the Random rules apply except:

  • The Len clause in the Open statement has no effect. Put writes all variables to disk contiguously; that is, with no padding between records.
  • For any array other than an array in a user-defined type, Put writes only the data. No descriptor is written.
  • Put writes variable-length strings that are not elements of user-defined types without the 2-byte length descriptor. The number of bytes written equals the number of characters in the string. For example, the following statements write 10 bytes to file number 1:

VarString$ = String$(10," ")#1,,VarString$

See Also

Get Statement, Open Statement, Seek Function, VarType Function.

Example

This example uses the Put statement to write data to a file. Five records of the user-defined type Record are written to the file.

Type Record                                    ' Define user-defined type.
    ID As Integer
    Name As String * 20TypeMyRecord As Record                        ' Declare variable.
' Open file for random access."TESTFILE" For Random As #1 Len = Len(MyRecord)RecordNumber = 1 To 5                    ' Loop 5 times.
    MyRecord.ID = RecordNumber                ' Define ID.
    MyRecord.Name = "My Name" & RecordNumber    ' Create a string.
    Put #1, RecordNumber, MyRecord            ' Write record to file.RecordNumber#1                                        ' Close file.


PV Function

Description

Returns the present value of an annuity based on periodic, constant payments to be paid in the future and a constant interest rate.

Syntax

PV(rate, nper, pmt[, fv[, type]])

The PV function has these named arguments:

Part | Description
rate | Interest rate per period. For example, if you get a car loan at an annual percentage rate (APR) of 10 percent and make monthly payments, the rate per period is 0.1/12, or 0.0083.
nper | Total number of payment periods in the annuity. For example, if you make monthly payments on a four-year car loan, your loan has a total of 4 * 12 (or 48) payment periods.
pmt | Payment to be made each period. Payments usually contain principal and interest that doesn’t change over the life of the annuity.
fv | Future value or cash balance you want after you’ve made the final payment. For example, the future value of a loan is $0 because that’s it value after the final payment. However, if you want to save $50,000 for your child’s education over 18 years, then $50,000 is the future value. If omitted, 0 is assumed.
type | Number indicating when payments are due. Use 0 if payments are due at the end of the payment period, or use 1 if payments are due at the beginning of the period. If omitted, 0 is assumed.

Remarks

An annuity is a series of constant cash payments made over a period of time. An annuity can be a loan (such as a home mortgage) or an investment (such as a monthly savings plan).

The arguments rate and nper must be calculated using payment periods expressed in the same units. For example, if rate is calculated using months, nper must also be calculated using months.

For all arguments, cash paid out (such as deposits to savings) is represented by negative numbers; cash received (such as dividend checks) is represented by positive numbers.

Example

In this example, the PV function returns the present value of an $1,000,000 annuity that will provide $50,000 a year for the next 20 years. Provided are the expected annual percentage rate (APR), the total number of payments (TotPmts), the amount of each payment (YrIncome), the total future value of the investment (FVal), and a number that indicates whether each payment is made at the beginning or end of the payment period (PayType). Note that because YrIncome represents cash paid out from the annuity each year, it’s a negative number.

Const ENDPERIOD = 0, BEGINPERIOD = 1       ' When payments are made.= "###,##0.00"                       ' Define money format.= .0825                               ' Annual percentage rate.= 20                               ' Total number of payments.= 50000                           ' Yearly income.= 1000000                           ' Future value.= BEGINPERIOD                   ' Payment at beginning of month.= PV(APR, TotPmts, -YrIncome, FVal, PayType)"The present value is " & Format(PVal, Fmt) & "."


QBColor Function

Description

Returns the RGB color code corresponding to a color number.

Syntax

QBColor(color)

The color argument is a whole number in the range 0 to 15, as described in Settings.

Settings

The color argument has these settings:

Number | Color | Number | Color
0 | Black | 8 | Gray
1 | Blue | 9 | Light Blue
2 | Green | 10 | Light Green
3 | Cyan | 11 | Light Cyan
4 | Red | 12 | Light Red
5 | Magenta | 13 | Light Magenta
6 | Yellow | 14 | Light Yellow
7 | White | 15 | Bright White

Remarks

The color argument represents color values used by other versions of Basic (such as Microsoft Visual Basic for MS-DOS and the Basic Compiler). Starting with the least-significant byte, the returned value specifies the red, green, and blue values used to set the appropriate color in the RGB system used by Visual Basic for applications.

See Also

RGB Function.

Example

This example uses the QBColor function to change the BackColor property of the form passed in as MyForm to the color indicated by ColorCode. QBColor accepts integer values between 0 and 15.

Sub ChangeBackColor (ColorCode As Integer, MyForm As Form)
    MyForm.BackColor = QBColor(ColorCode)Sub


Quit Action

Description

You can use the Quit action to exit Microsoft Access. The Quit action can also specify one of several options for saving database objects prior to exiting Microsoft Access.

Setting

The Quit action uses the following argument.

Action argument | Description
Options | Specifies what happens to unsaved objects when you quit Microsoft Access. Click Prompt to display dialog boxes that ask whether to save each object. Click Save All to save all objects without prompting by dialog boxes. Click Exit to quit without saving any objects. The default is Save All.

Remarks

Microsoft Access doesn’t run any actions that follow the Quit action in a macro.

You can use this action to quit Microsoft Access without prompts from Save dialog boxes by using a custom menu command or a button on a form. For example, you might have a master form that you use to display the objects in your custom workspace. This form could have a Quit button that runs a macro containing the Quit action with the Options argument set to Save All.

This action has the same effect as choosing the Exit command from the File menu. If you have any unsaved objects when you choose this command, the dialog boxes that appear are the same as those displayed when you select Prompt for the Options argument of the Quit action.

You can use the Save action in a macro to save a specified object without having to quit Microsoft Access or close the object.

To run the Quit action in Visual Basic, use the Quit method of the DoCmd object.

See Also

Close Action, Quit Method (DoCmd Object), StopAllMacros Action, StopMacro Action.


Quit Method (Application Object)

Applies To

Application Object

Description

Use the Quit method to quit Microsoft Access. You can select one of several options for saving a database object before quitting.

Syntax

Application.Quit [option]

The Quit method uses the following argument.

Argument | Description
option | An intrinsic constant that specifies what happens to unsaved objects when you quit Microsoft Access. It can be any of the following constants: · (Default) acSaveYes saves all objects without displaying a dialog box · acPrompt displays a dialog box that asks whether you want to save any database objects that have been changed but not saved. · acExit quits Microsoft Access without saving any objects.

Remarks

The Quit method has the same effect as clicking Exit on the File menu. You can create a custom menu command or a button on a form with a procedure that includes the Quit method. For example, you can place a Quit button on a form and include a procedure in the button’s Click event that uses the Quit method with option set to acSaveYes.

See Also

Quit Action.

Example

The following example shows the Click event procedure for a command button named AppExit. After clicking the AppExit button, a dialog box prompts the user to save changes, and the procedure quits Microsoft Access.

Private Sub AppExit_Click()
    Application.Quit acPromptSub


Quit Method (DoCmd Object)

Applies To

DoCmd Object.

Description

The Quit method of the DoCmd object carries out the Quit action in Visual Basic. For more information on how the action and its arguments work, see the action topic.

Syntax

DoCmd.Quit [options]

The Quit method uses the following arguments.

Argument | Description
options | One of the following intrinsic constants:
 | acPrompt acSaveYes acSaveNo acExit
 | If you leave this argument blank, the default (acSaveYes) is assumed.

Remarks

The Quit method of the DoCmd object was added to provide backwards compatibility for running the Quit action in Visual Basic code in Microsoft Access version 7.0. It is recommended that you use the existing Quit method of the Application object instead.

Example

This example displays a dialog box that asks if you want to save any changed objects before you quit Microsoft Access.

DoCmd.Quit acPrompt


Raise Method

Applies To

Err Object.

Description

Generates a run-time error.

Syntax

object.Raise(Number, Source, Description, HelpFile, HelpContext)

The Raise method has the following object qualifier and named arguments:

Argument | Description
object | Always the Err object.
Number | Required. A Long integer that identifies the nature of the error. Visual Basic errors (both Visual Basic-defined and user-defined errors) are in the range 0– 65535. When setting the Number property to your own error code in an OLE Automation object, you add your error code number to the constant vbObjectError. For example, to generate the error number 1050, assign vbObjectError + 1050 to the Number property. (Not all Visual Basic host applications can create OLE Automation objects. See your host application’s documentation to determine whether it can create classes and OLE Automation objects.)
Source | Optional. A string expression naming the object or application that originally generated the error. When setting this property for an OLE Automation object, use the form project.class. If nothing is specified, the programmatic ID of the current Visual Basic project is used.
Description | Optional. A string expression describing the error. If unspecified, the value in Number is examined. If it can be mapped to a Visual Basic run-time error code, the string that would be returned by the Error function is used as Description. If there is no Visual Basic error corresponding to Number, “Application-defined or object-defined error” is used.
HelpFile | Optional. The fully qualified path to the Microsoft Windows Help file in which help on this error can be found. If unspecified, Visual Basic uses the fully qualified drive, path, and filename of the Visual Basic Help file.
HelpContext | Optional. The context ID identifying a topic within HelpFile that provides help for the error. If omitted, the Visual Basic Help file context ID for the error corresponding to the Number property is used, if it exists.

Remarks

All the arguments are optional except Number. If you use Raise, however, without specifying some arguments, and the property settings of the Err object contain values that have not been cleared, those values serve as the values for your error.

Raise is used for generating run-time errors, and can be used instead of the Error statement (Error still works the same in existing code, and may be appropriate in new code). Raise is useful for generating errors when writing OLE Automation objects, since the Err object gives the programmer and user richer information than is possible if you generate errors with the Error statement. For example, with the Raise method the original generator of the error can be specified in the Source property, online Help for the error can be referenced, and so forth.

See Also

Clear Method, Description Property, Err Object, Error Statement, HelpContext Property, HelpFile Property, LastDLLError Property, Number Property, Source Property.

Example

This example uses the Err object’s Raise method to generate an error within an OLE Automation object written in Visual Basic. It has the programmatic ID MyProj.MyObject.

Const MyContextID = 1010407            ' Define a constant for contextID.TestName(CurrentName, NewName)
    If Instr(NewName, "bob") Then    ' Test the validity of NewName.
        ' Raise the exception.
        Err.Raise vbObjectError + 27, "MyProj.MyObject", _
            "No ""bob"" allowed in your name", "c:\MyProj\MyHelp.Hlp", _
            MyContextID
    End IfFunction


Randomize Statement

Description

Initializes the random-number generator.

Syntax

Randomize [number]

The number argument can be any valid numeric expression.

Remarks

Randomize uses number to initialize the Rnd function’s random-number generator, giving it a new seed value. If you omit number, the value returned by the system timer is used as the new seed value.

If Randomize is not used, the Rnd function (with no arguments) uses the same number as a seed the first time it is called, and thereafter uses the last generated number as a seed value.

Note To repeat sequences of random numbers, call Rnd with a negative argument immediately before using Randomize with a numeric argument. Using Randomize with the same value for number does not repeat the previous sequence.

See Also

Rnd Function, Timer Function.

Example

This example uses the Randomize statement to initialize the random-number generator. Because the number argument has been omitted, Randomize uses the return value from the Timer function as the new seed value.

Randomize                        ' Initialize random-number generator.= Int((6 * Rnd) + 1)        ' Generate random value between 1 and 6.


Rate Function

Description

Returns the interest rate per period for an annuity.

Syntax

Rate(nper, pmt, pv[, fv[, type[, guess]]])

The Rate function has these named arguments:

Part | Description
nper | Total number of payment periods in the annuity. For example, if you make monthly payments on a four-year car loan, your loan has a total of 4 * 12 (or 48) payment periods.
pmt | Payment to be made each period. Payments usually contain principal and interest that doesn’t change over the life of the annuity.
pv | Present value, or value today, of a series of future payments or receipts. For example, when you borrow money to buy a car, the loan amount is the present value to the lender of the monthly car payments you will make.
fv | Future value or cash balance you want after you’ve made the final payment. For example, the future value of a loan is $0 because that’s it value after the final payment. However, if you want to save $50,000 for your child’s education over 18 years, then $50,000 is the future value. If omitted, 0 is assumed.
type | Number indicating when payments are due. Use 0 if payments are due at the end of the payment period, or use 1 if payments are due at the beginning of the period. If omitted, 0 is assumed.
guess | Value you estimate will be returned by Rate. If omitted, guess is 0.1 (10 percent).

Remarks

An annuity is a series of constant cash payments made over a period of time. An annuity can be a loan (such as a home mortgage) or an investment (such as a monthly savings plan).

For all arguments, cash paid out (such as deposits to savings) is represented by negative numbers; cash received (such as dividend checks) is represented by positive numbers.

Rate is calculated by iteration. Starting with the value of guess, Rate cycles through the calculation until the result is accurate to within 0.00001 percent. If, after 20 tries, it can’t find a result, Rate fails. If your guess is 10 percent and Rate fails, try a different value for guess.

Example

This example uses the Rate function to calculate the interest rate of a loan given the total number of payments (TotPmts), the amount of the loan payment (Payment), the present value or principal of the loan (PVal), the future value of the loan (FVal), a number that indicates whether the payment is due at the beginning or end of the payment period (PayType), and an approximation of the expected interest rate (Guess).

Const ENDPERIOD = 0, BEGINPERIOD = 1            ' When payments are made.= "##0.00"                                ' Define percentage format.= 0                                        ' Usually 0 for a loan.= .1                                    ' Guess of 10 percent.= InputBox("How much did you borrow?")= InputBox("What's your monthly payment?")= InputBox("How many monthly payments do you have to make?")= MsgBox("Do you make payments at the end of the month?", _
    vbYesNo)PayType = vbNo Then PayType = BEGINPERIOD Else PayType = ENDPERIOD= (Rate(TotPmts, -Payment, PVal, FVal, PayType, Guess) * 12) * 100"Your interest rate is " & Format(CInt(APR), Fmt) & " percent."


Recalc Method

Description

The Recalc method immediately updates all calculated controls on a form.

Syntax

form.Recalc

The Recalc method uses the following argument.

Argument | Description
form | A Form object representing the form that contains the controls for which you want to recalculate the values.

Remarks

Using this method is equivalent to pressing the F9 key when a form has the focus. You can use this method to recalculate the values of controls that depend on other fields for which the contents may have changed.

See Also

Form Object, Refresh Method, Repaint Method, Requery Method.

Example

The following example uses the Recalc method to update controls on an Orders form. This form includes the Freight text box, which displays the freight cost, and a calculated control that displays the total cost of an order including freight. If the statement containing the Recalc method is placed in the AfterUpdate event procedure for the Freight text box, the total cost of an order is recalculated every time a new freight amount is entered.

Sub Freight_AfterUpdate()
    Forms!Orders.RecalcSub


RecordLocks Property

Applies To

Form, Query, Report.

Description

You can use the RecordLocks property to determines how records are locked and what happens when two users try to edit the same record at the same time. When you edit a record, Microsoft Access can automatically lock that record to prevent other users from changing it before you are finished.

  • Forms — You can use this property to specify how records in the underlying table or query are locked when data in a multiuser database is updated.
  • Reports — You can use this property to specify whether records in the underlying table or query are locked while a report is previewed or printed.
  • Queries — You can use this property to specify whether records in a query (typically an action query in a multiuser database) are locked while the query is run.

Setting

The RecordLocks property uses the following settings.

Setting | Description | Visual Basic
No Locks | (Default) In forms, two or more users can edit the same record simultaneously. This is also called “optimistic” locking. If two users attempt to save changes to the same record, Microsoft Access displays a message to the user who tries to save the record second. This user can then discard the record, copy the record to the Clipboard, or replace the changes made by the other user. This setting is typically used on read-only forms or in single-user databases. It is also used in multiuser databases to permit more than one user to be able to make changes to the same record at the same time. In reports, records aren’t locked while the report is previewed or printed. In queries, records aren’t locked while the query is run. | 0
All Records | All records in the underlying table or query are locked while the form is open in Form view or Datasheet view, while the report is previewed or printed, or while the query is run. Although users can read the records, no one can edit, add, or delete any records until the form is closed, the report has finished printing, or the query has finished running. | 1
Edited Record | (Forms and queries only) A page of records is locked as soon as any user starts editing any field in the record and stays locked until the user moves to another record. Consequently, a record can be edited by only one person at a time. This is also called “pessimistic” locking. | 2

You can set this property using the objects property sheet, a macro, or Visual Basic.

Remarks

You can use the No Locks setting for forms if only one person uses the underlying tables or queries or makes all the changes to the data.

In a multiuser database, you can use the No Locks setting if you want to use optimistic locking and warn users attempting to edit the same record on a form. You can use the Edited Record setting if you want to prevent two or more users editing data at the same time.

You can use the All Records setting when you need to ensure that no changes are made to data after you start to preview or print a report or run an append, delete, make-table, or update query.

In Form view or Datasheet view, each locked record has a locked symbol in its record selector.

Note To change the default RecordLocks property setting for forms, click Options on the Tools menu. Click the Advanced tab on the Options dialog box and select the Default Record Locking option.

Data in a form, report, or query from an Open Database Connectivity (ODBC) database is treated as if the No Locks setting were chosen, regardless of which setting is actually chosen.


RecordSelectors Property

Applies To

Form.

Description

You can use the RecordSelectors property to specify whether a form displays record selectors in Form view.

Setting

The RecordSelectors property uses the following settings.

Setting | Description | Visual Basic
Yes | (Default) Each record has a record selector. | True (-1)
No | No record has a record selector. | False (0)

You can set this property using the form’s property sheet, a macro, or Visual Basic.

Remarks

You can use this property to remove record selectors when you create or use a form as a custom dialog box or a palette.

The record selector displays an icon when a record is being edited. When the RecordSelectors property is set to No and the RecordLocks property is set to Edited Record (record locking is pessimistic), there is no visual clue that the record is locked.

See Also

NavigationButtons Property, PopUp Property.


RecordsetClone Property

Applies To

Form.

Description

You can use the RecordsetClone property to refer to a form’s Recordset object specified by the form’s RecordSource property.

Setting

The RecordsetClone property setting is a copy of the underlying query or table specified by the form’s RecordSource property. If a form is based on a query, for example, referring to the RecordsetClone property is the equivalent of cloning a Recordset object using the same query. If you then apply a filter to the form, the Recordset object reflects the filtering.

The RecordsetClone property is available only in Visual Basic and is read-only in all views.

Remarks

You use the RecordsetClone property to navigate or operate on a form’s records independent of the form itself. For example, you can use the RecordsetClone property when you want to use a method, such as the FindFirst method, that can’t be used with forms. The RecordsetClone property provides access to all the methods and properties that apply to a Recordset object.

When a new Recordset object is opened, its first record is the current record. If you use one of the Find or Move methods to make any record in the Recordset object current, you must synchronize the current record in the Recordset object with the form’s current record by assigning the value of the form’s Bookmark property to a string variable, and then assign the string variable to the data access Bookmark property of the Recordset object.

You can use the RecordCount property to count the number of records in a Recordset object. The following example shows how you can combine the RecordCount property and the RecordsetClone property to count the records in a form.

Forms!Orders.RecordsetClone.MoveLast= "My form contains " & Forms!Orders.RecordsetClone.RecordCount= Msg & " records.", vbInformation, "Record Count"Msg

Note If you close the form or if you change the form’s RecordSource property, the Recordset object is no longer valid. If you subsequently refer to the Recordset object or to previously saved bookmarks in the form or the Recordset object, an error will occur.

See Also

FindFirst, FindLast, FindNext, FindPrevious Methods; MoveFirst, MoveLast, MoveNext, MovePrevious Methods; Recordset Object.

Example

The following example uses the RecordsetClone property to create a Recordset object from the Orders form and then prints the names of the fields in the Debug window.

Sub Print_Field_Names()
    Dim rs As Recordset, intI As Integer
    Set rs = Me.RecordsetClone
    For intI = 0 To rs.Fields.Count - 1
        Debug.Print rs.Fields(intI).Name        ' Print field names.
    Next intISub

The next example uses the RecordsetClone property and the Recordset object to synchronize a recordset’s record with the form’s current record. When a company name is selected from a combo box, the FindFirst method is used to locate the record for that company and the Recordset object’s Bookmark property is assigned to the form’s Bookmark property causing the form to display the found record.

Sub CompanyName_AfterUpdate()
    Dim rs As Recordset
    Dim strSearchName As String
    Set rs = Me.RecordsetClone
    strSearchName = Me!CompanyName
    rs.FindFirst "[CompanyName] = '" & strSearchName & "'"
        If rs.NoMatch Then
            MsgBox "Record not found"
        Else
            Me.Bookmark = rs.Bookmark
        End If
    rs.CloseSub


RecordsetType Property

Applies To

Form.

Description

You can use the RecordsetType property to specify what kind of recordset is made available to a form. For example, if you don’t want data in bound controls to be edited when a form is in Form view or Datasheet view, you can set the RecordsetType property to Snapshot.

Note For forms, the RecordsetType property replaces the AllowUpdating property found in Microsoft Access 2.0. Microsoft Access for Windows 95 supports the AllowUpdating property for backwards compatibility only. It is recommended that you use the RecordsetType property.

Setting

The RecordsetType property uses the following settings.

Setting | Description | Visual Basic
Dynaset | (Default) You can edit bound controls based on a single table or tables with a one-to-one relationship. For controls bound to fields based on tables with a one-to-many relationship, you can’t edit data from the join field on the “one” side of the relationship unless cascade update is enabled between the tables. | 0
Dynaset (Inconsistent Updates) | All tables and controls bound to their fields can be edited. | 1
Snapshot | No tables or the controls bound to their fields can be edited. | 2

You can set this property using the form’s property sheet, a macro, or Visual Basic.

Remarks

You can create forms based on multiple underlying tables with fields bound to controls on the forms. Depending on the RecordsetType property setting, you can limit which of these bound controls can be edited.

In addition to the editing control provided by RecordsetType, each control on a form has a Locked property that you can set to specify whether the control and its underlying data can be edited. If the Locked property is set to Yes, you can’t edit the data.

See Also

AllowAdditions Property; AllowDeletions Property; AllowEdits Property; Enabled, Locked Properties.

Example

In the following example, only if the user ID is ADMIN can records be updated. This code sample sets the RecordsetType property to Snapshot if the global variable gstrUserID value is not ADMIN.

Sub Form_Open(Cancel As Integer)
    Const conSnapshot = 2
    If gstrUserID <> "ADMIN" Then
        Forms!Employees.RecordsetType = conSnapshot
    End IfSub


RecordSource Property

Applies To

Form, Report.

Description

You can use the RecordSource property to specify the source of the data for a form or report. You can display data from a table, query, or SQL statement. For example, to display and edit data from the Employees table in a form, you set the form’s RecordSource property to Employees. Then you can bind controls on the form or report to specific fields in the Employees table by setting the control’s ControlSource property to the name of a field in the table.

Setting

The RecordSource property setting can be a table name, a query name, or an SQL statement. For example, you can use the following settings.

TR>
Sample Setting | Description
A table or query name | You can bind a control on the form or report to the LastName field in the Employees table by setting the control’s ControlSource property to LastName.
An SQL statement | You can bind a control on the form or report to the OrderDate field in the Orders table by setting the control’s ControlSource property to OrderDate, as in the following example. SELECT DISTINCTROW Orders.[OrderDate] Orders;

You can set the RecordSource property using the form or report’s property sheet, a macro, or Visual Basic.

In Visual Basic, use a string expression to set this property.

Note Changing the record source of an open form or report causes an automatic requery of the underlying data.

Remarks

After you have created a form or report, you can change its source of data by changing the RecordSource property. The RecordSource property is also useful if you want to create a reusable form or report. For example, you could create a form that incorporates a standard design, then copy the form and change the RecordSource property to display data from a different table, query, or SQL statement.

Limiting the number of records contained in a form’s record source can enhance performance, especially when your application is running on a network. For example, you can set a form’s RecordSource property to a single record and change the form’s record source depending on criteria selected by the user.

You can also achieve improved performance by setting the RecordSource property to the name of a table or saved query instead of an SQL statement.

See Also

ControlSource Property; RowSourceType, RowSource Properties.

Example

The following example sets the RecordSource property for a form to the Customers table.

Forms![frmCustomers].RecordSource = "Customers"

The next example changes a form’s record source to a single record in the Customers table, depending on the company name selected in the cmboCompanyName combo box control. The combo box is filled by an SQL statement that returns the customer ID in the bound column and the company name.

Sub cmboCompanyName_AfterUpdate()
    Dim strNewRecord As String
    strNewRecord = "SELECT DISTINCTROW * FROM Customers "
    strNewRecord = strNewRecord & "WHERE [CustomerID] = '" _
        & Me!cmboCompanyName.Value & "'"
    Me.RecordSource = strNewRecordSub


ReDim Statement

Description

Used at procedure level to declare dynamic-array variables and allocate or reallocate storage space.

Syntax

ReDim [Preserve] varname(subscripts) [As type][, varname(subscripts) [As type]] . . .

The ReDim statement syntax has these parts:

Part | Description
Preserve | Preserves the data in an existing array when you change the size of the last dimension.
varname | Name of the variable; follows standard variable naming conventions.

Part | Description
subscripts | Dimensions of an array variable; up to 60 multiple dimensions may be declared. The subscripts argument uses the following syntax: [lower To] upper[,[lower To] upper] . . . When not explicitly stated in lower, the lower bound of an array is controlled by the Option Base statement. The lower bound is zero if no Option Base statement is present.
type | Data type of the variable; may be Byte, Boolean, Integer, Long, Currency, Single, Double, Date, String (for variable-length strings), String * length (for fixed-length strings), Object, Variant, a user-defined type, or an object type. Use a separate As type clause for each variable being defined. For a Variant containing an array, type describes the type of each element of the array, but does not change the Variant to some other type.

Remarks

The ReDim statement is usually used to size or resize a dynamic array that has already been formally declared using a Private, Public, or Dim statement with empty parentheses (without dimension subscripts).

You can use the ReDim statement repeatedly to change the number of elements and dimensions in an array. However, you can’t declare an array of one data type and later use ReDim to change the array to another data type, unless the array is contained in a Variant. If the array is contained in a Variant, the type of the elements can be changed using an As type clause.

If you use the Preserve keyword, you can resize only the last array dimension and you can’t change the number of dimensions at all. For example, if your array has only one dimension, you can resize that dimension because it is the last and only dimension. However, if your array has two or more dimensions you can change the size of only the last dimension and still preserve the contents of the array. The following example shows how you can increase the size of the last dimension of a dynamic array without erasing any existing data contained in the array.

ReDim X(10, 10, 10)
. . .Preserve X(10, 10, 15)

Caution If you make an array smaller than it was, data in the eliminated elements will be lost.

When variables are initialized, a numeric variable is initialized to 0, a variable-length string is initialized to a zero-length string, and a fixed-length string is filled with zeros. Variant variables are initialized to Empty. Each element of a user-defined type variable is initialized as if it were a separate variable. A variable thatrefers to an object must be assigned an existing object using the Set statement before it can be used. Until it is assigned an object, the declared object variable has the special value Nothing, which indicates that it does not refer to any particular instance of an object.

Note To resize an array contained in a Variant, you must explicitly declare the Variant variable before attempting to resize its array.

See Also

Array Function, Dim Statement, Option Base Statement, Private Statement, Public Statement, Set Statement, Static Statement.

Example

This example uses the ReDim statement to allocate and reallocate storage space for dynamic-array variables. It assumes the Option Base is 1.

Dim MyArray() As Integer    ' Declare dynamic array.MyArray(5)    ' Allocate 5 elements.I = 1 To 5    ' Loop 5 times.
    MyArray(I) = I    ' Initialize array.I

The next statement resizes the array and erases the elements.

ReDim MyArray(10)    ' Resize to 10 elements.I = 1 To 10    ' Loop 10 times.
    MyArray(I) = I    ' Initialize array.I

The following statement resizes the array but does not erase elements.

ReDim Preserve MyArray(15)            ' Resize to 15 elements.


Refresh Method

Description

The Refresh method immediately updates the records in the underlying record source for a specified form or datasheet to reflect changes made to the data by you and other users in a multiuser environment.

Syntax

form.Refresh

The Refresh method uses the following argument.

Argument | Description
form | A Form object that represents the form to refresh

Remarks

Using this method is equivalent to clicking Refresh on the Records menu.

Microsoft Access refreshes records automatically, based on the Refresh Interval setting on the Advanced tab of the Options dialog box, available by clicking Options on the Tools menu. ODBC data sources are refreshed based on the ODBC Refresh Interval setting on the Advanced tab of the Options dialog box. You can use the Refresh method to view changes that have been made to the current set of records in a form or datasheet since the record source underlying the form or datasheet was last refreshed.

The Refresh method shows only changes made to records in the current set. Since the Refresh method doesn’t actually requery the database, the current set will not include records that have been added or exclude records that have been deleted since the database was last requeried. Nor will it exclude records that no longer satisfy the criteria of the query or filter. To requery the database, use the Requery method. When the record source for a form is requeried, the current set of records will accurately reflect all data in the record source.

Notes

  • It’s often faster to refresh a form or datasheet than to requery it. This is especially true if the initial query was slow to run.
  • Don’t confuse the Refresh method with the Repaint method, which updates the screen with any pending visual changes.

See Also

Event Properties; Form Object; GetOption, SetOption Methods; Recalc Method; Requery Method.

Example

The following example uses the Refresh method to update the records in the underlying record source for the form Customers whenever the form receives the focus.

Private Sub Form_Activate()
    Forms!Customers.RefreshSub


RefreshTitleBar Method

Applies To

Application Object.

Description

The RefreshTitleBar method refreshes the Microsoft Access title bar after the AppTitle or AppIcon property has been set in Visual Basic. For example, you can change the caption in the Microsoft Access title bar to “Contacts Database” by setting the AppTitle property. In order for this change to take effect, you must subsequently use the RefreshTitleBar method.

Syntax

Application.RefreshTitleBar

The RefreshTitleBar method uses the following argument.

Argument | Description
Application | The Application object.

Remarks

The AppTitle and AppIcon properties enable you to customize your application by changing the title and icon that appear in the Microsoft Access title bar. The title bar is not automatically updated after you have set these properties. In order for the change to the title bar to appear, you must use the RefreshTitleBar method.

You can reset the AppTitle and AppIcon properties to their default value by deleting them from the Properties collection of the Database object representing the current database. After you delete these properties, you must use the RefreshTitleBar method to restore the Microsoft Access defaults to the title bar.

Example

The following example sets the AppTitle property of the current database and applies the RefreshTitleBar method to update the title bar.

Sub ChangeTitle()
    Dim dbs As Database, prp As Property
    Const conPropNotFoundError = 3270

    On Error GoTo ErrorHandler
    ' Return Database variable pointing to current database.
    Set dbs = CurrentDb
    ' Change title bar.
    dbs.Properties!AppTitle = "Contacts Database"
    ' Update title bar on screen.
    Application.RefreshTitleBar
    Exit Sub
    :
    If Err.Number = conPropNotFoundError Then
        Set prp = dbs.CreateProperty("AppTitle", dbText, _
            "Contacts Database")
        dbs.Properties.Append prp
    Else
        MsgBox "Error: " & Err.Number & vbCrLf & Err.Description
    End If
    Resume NextSub


Rem Statement

Description

Used to include explanatory remarks in a program.

Syntax

Rem comment

You can also use the following syntax:

' comment

The comment argument is the text of any comment you want to include. After the Rem keyword, a space before comment is required.

Remarks

If you use line numbers or line labels, you can branch from a GoTo or GoSub statement to a line containing a Rem statement. Execution continues with the first executable statement following the Rem statement.

As shown in the syntax examples, you can use a single quotation mark or apostrophe (') instead of the Rem keyword. If the Rem keyword follows other statements on a line, it must be separated from the statements by a colon. However, when you use a single quotation mark, the colon is not required after other statements.

Example

This example illustrates the various forms of the Rem statement, which is used to include explanatory remarks in a program.

Rem This is the first form of the syntax.

The following shows the second form of the syntax.

MyStr1 = "Hello": Rem Comment after a statement separated by a colon.= "Goodbye"         ' This is also a comment; no colon is needed.


Remove Method

Applies To

Collection Object.

Description

Removes a member from a Collection object.

Syntax

object.Remove(index)

The Remove method syntax has the following object qualifier and part:

Part | Description
object | Required. An object expression that evaluates to an object in the Applies To list.
index | Required. An expression that specifies the position of a member of the collection. If a numeric expression, index must be a number from 1 to the value of the collection’s Count property. If a string expression, index must correspond to the key specified when the member being referred to was added to the collection.

Remarks

If the value provided as index does not match any existing member of the collection, an error occurs.

See Also

Add Method.

Example

This example illustrates the use of the Remove method to remove objects from a Collection object, MyClasses. This code removes the object whose index is 1 on each iteration of the loop.

Dim NumNum = 1 To MyClasses.Count
    MyClasses.Remove 1    ' Remove the first object each time
                ' through the loop until there are
                ' no objects left in the collection.Num

Example

The following example shows how to use the Remove method to delete items from a Collection object colThings. User-defined collections are indexed numerically. For a user-defined collection, the default base index is 1. Since collections are automatically reindexed when an item is removed, the following code removes the first member on each iteration.

Note that you can use the For Each...Next syntax to manipulate items in a collection.

For Each objMine in colThings
    objThings.Remove 1objMine


Rename Action

Description

You can use the Rename action to rename a specified database object.

Setting

The Rename action uses the following arguments.

Action argument | Description
New Name | A new name for the database object. This is a required argument.
Object Type | The type of object you want to rename. Click Table, Query, Form, Report, Macro, or Module in the Object Type box in the Action Arguments section of the Macro window. To rename the object selected in the Database window, leave this argument blank.
Old Name | The name of the object to be renamed. The Old Name box shows all objects in the database of the type selected by the Object Type argument. If you leave Object Type blank, leave this argument blank also.

Note If you run a macro containing the Rename action in a library database, Microsoft Access looks for the object with this name first in the library database, then in the current database.

Remarks

The new name of the database object must follow the standard naming conventions for Microsoft Access objects.

You cannot rename an open object.

If you leave the Object Type and Old Name arguments blank, Microsoft Access renames the object selected in the Database window. To select an object in the Database window, you can use the SelectObject action with the In Database Window argument set to Yes. You can also select an object by clicking it the Database window, clicking it again so you can edit its name, and entering a new name. With the Rename action, you don’t have to select the object first in the Database window, and you don’t have to stop the macro to enter the new name.

This action differs from the CopyObject action, which creates a copy of the object under a new name.

To run the Rename action in Visual Basic, use the Rename method of the DoCmd object.

See Also

CopyObject Action, Rename Method, SelectObject Action.


Rename Method

Applies To

DoCmd Object.

Description

The Rename method carries out the Rename action in Visual Basic. For more information on how the action and its arguments work, see the action topic.

Syntax

DoCmd.Rename newname [, objecttype, oldname]

The Rename method uses the following arguments.

Argument | Description
newname | A string expression that is the new name for the object you want to rename. The name must follow the object-naming rules for Microsoft Access objects.
objecttype | One of the following intrinsic constants:

 | acTable
oldname | A string expression that is the valid name of an object of the type specified by the objecttype argument.
 | If you execute Visual Basic code containing the Rename method in a library database, Microsoft Access looks for the object with this name first in the library database, then in the current database.

Remarks

If you leave the objecttype and oldname arguments blank, Microsoft Access renames the object selected in the Database window. To select an object in the Database window, you can use the SelectObject action or SelectObject method with the In Database Window argument set to Yes (True).

If you leave the objecttype and oldname arguments blank, don’t use a comma following the newname argument.

See Also

CopyObject Method, DoCmd Object, Rename Action, Save Method, SelectObject Method.

Example

This example renames the Employees table using the specified name.

DoCmd.Rename "Old Employees Table", acTable, "Employees"


Repaint Method

Description

The Repaint method completes any pending screen updates for a specified form. When performed on a form, the Repaint method also completes any pending recalculations of the form’s controls.

Syntax

form.Repaint

The Repaint method uses the following argument.

Argument | Description
form | A Form object that represents the form to repaint

Remarks

Microsoft Access sometimes waits to complete pending screen updates until it finishes other tasks. With the Repaint method, you can force immediate repainting of the controls on the specified form. You can use the Repaint method:

  • When you change values in a number of fields. Unless you force a repaint, Microsoft Access might not display the changes immediately, especially if other fields, such as those in an expression in a calculated control, depend on values in the changed fields.
  • When you want to make sure that a form displays data in all of its fields. For example, fields containing OLE objects often don’t display their data immediately after you open a form.

This method doesn’t cause a requery of the database, nor does it show new or changed records in the form’s underlying record source. You can use the Requery method to requery the source of data for the form or one of its controls.

Note Notes

  • Don’t confuse the Repaint method with the Refresh method, or with the Refresh command on the Records menu. The Refresh method and Refresh command show changes you or other users have made to the underlying record source for any of the currently displayed records in forms and datasheets. The Repaint method simply updates the screen when repainting has been delayed while Microsoft Access completes other tasks.
  • The Repaint method differs from the Echo method in that the Repaint method forces a single immediate screen update, while the Echo method turns screen updating on or off.

See Also

Form Object, Recalc Method, RepaintObject Action.

Example

The following example uses the Repaint method to repaint a Customer form when the form receives the focus.

Private Sub Form_Activate()
    Forms!Customers.RepaintSub


RepaintObject Action

Description

You can use the RepaintObject action to complete any pending screen updates for a specified database object or the active database object, if none is specified. Such updates include any pending recalculations for the object’s controls.

Setting

The RepaintObject action uses the following arguments.

Action argument | Description
Object Type | The type of object to repaint. Click Table, Query, Form, Report, Macro, or Module from the Object Type box in the Action Arguments section of the Macro window. Leave this argument blank to select the active object.
Object Name | The name of the object to repaint. The Object Name box shows all objects in the database of the type selected by the Object Type argument. If you leave the Object Type argument blank, leave this argument blank also.

Remarks

Microsoft Access waits to complete pending screen updates until it finishes other pending tasks. With this action, you can force immediate repainting of the controls in the specified object. You can use this action:

  • When you use the SetValue action to change values in a number of controls. Microsoft Access might not show the changes immediately, especially if other controls (such as calculated controls) depend on values in the changed controls.
  • When you want to make sure that the form you’re viewing displays data in all of its controls. For example, controls containing OLE objects don’t display their data immediately after you open a form.

This action doesn’t cause a requery of the database, so it doesn’t show new and changed records, or remove deleted records from the object’s underlying table or query. Use the Requery action to requery the source of the object or one of its controls. Use the ShowAllRecords action to display the most recent records and remove any applied filters.

Note The RepaintObject action doesn’t have the same effect as choosing the Refresh command from the Records menu, which shows any changes you or other users have made to the currently displayed records in forms and datasheets.

To run the RepaintObject action in Visual Basic, use the RepaintObject method of the DoCmd object.

See Also

RepaintObject Method, Requery Action, SetValue Action, ShowAllRecords Action.


RepaintObject Method

Applies To

DoCmd Object.

Description

The RepaintObject method carries out the RepaintObject action in Visual Basic. For more information on how the action and its arguments work, see the action topic.

Syntax

DoCmd.RepaintObject [objecttype, objectname]

The RepaintObject method uses the following arguments.

Argument | Description
objecttype | One of the following intrinsic constants:

 | acTable
objectname | A string expression that is the valid name of an object of the type selected with the objecttype argument.

Remarks

Using the RepaintObject method with no arguments repaints the active window.

The RepaintObject method of the DoCmd object was added to provide backwards compatibility for running the RepaintObject action in Visual Basic code in Microsoft Access for Windows 95. If you want to repaint a form, it is recommended that you use the existing Repaint method of the Form object instead.

See Also

DoCmd Object, Recalc Method, Refresh Method, Repaint Method, RepaintObject Action, Requery Method, Requery Method (DoCmd Object), ShowAllRecords Method.

Example

This example repaints the form Customers.

DoCmd.RepaintObject acForm, "Customers"


RepeatSection Property

Applies To

Report.

Description

You can use the RepeatSection property to specify whether a group header is repeated on the next page or column when a group spans more than one page or column.

Setting

The RepeatSection property uses the following settings.

Setting | Description | Visual Basic
Yes | The group header is repeated. | True (-1)
No | (Default) The group header isn’t repeated. | False (0)

You can set the RepeatSection property in the group header section’s property sheet, a macro, or using Visual Basic.

Remarks

When printing a report that contains a subreport, the subreport’s RepeatSection property will determine if the subreport group headers are repeated across pages or columns.


Report Object

Description

A Report object refers to a particular Microsoft Access report.

Remarks

A Report object is a member of the Reports collection. Within the Reports collection, individual reports are numbered by an index beginning with zero. You can refer to an individual Report object in the Reports collection either by referring to the report by name, or by referring to its index within the collection. If the report name includes a space, the name must be surrounded by brackets.

Syntax | Example
Reports!reportname | Reports!OrderReport
Reports![report name] | Reports![Order Report]
Reports("reportname") | Reports("OrderReport")
Reports(index) | Reports(0)

Each Report object has a Controls collection, which contains all controls on the report. You can refer to a control on a report either by implicitly or explicitly referring to the Controls collection. Your code will be faster if you refer to the Controls collection implicitly. The following examples show two of the ways you might refer to a NewData control on a report called OrderReport.

Reports!OrderReport!NewData           ' Implicit reference.

Reports!OrderReport.Controls!NewData       ' Explicit reference.

Many of the properties of a Report object can also be set from a report’s property sheet. For information on how to set individual properties, see those properties.

You can’t add or delete a Report object from the Reports collection.

Properties

ActiveControl Property, ActiveReport Property.

See Also

Controls Collection, Reports Collection.

Example

The following example creates a new report and sets certain properties.

Sub NewReport()
    Dim rpt As Report

    ' Return variable of data type Report pointing to new Report object.
    Set rpt = CreateReport
    ' Set properties for new report.
    rpt.RecordSource = "Products"
    rpt.Caption = "Products Report"
    ' Restore new report.
    DoCmd.RestoreSub

The next example enumerates the Reports collection and prints the name of each report in the Reports collection. It then enumerates the Controls collection of each report and prints the name of each control on the report.

Sub AllOpenReports()
    Dim rpt As Report, ctl As Control

    ' Enumerate Reports collection.
    For Each rpt In Reports
        ' Print name of report.
        Debug.Print rpt.Name
        ' Enumerate Controls collection of each report.
        For Each ctl In rpt.Controls
            ' Print name of each control.
            Debug.Print ">>>"; ctl.Name
        Next ctl
    Next rptSub


Reports Collection

Description

The Reports collection contains all of the currently open reports in a Microsoft Access database.

Remarks

You can use the Reports collection in Visual Basic or in an expression to refer to reports that are currently open. For example, you can enumerate the Reports collection to set or return the values of properties of individual reports in the collection.

Tip The For Each...Next statement is useful for enumerating a collection.

You can’t add or delete a Report object from the Reports collection.

You can refer to an individual Report object in the Reports collection either by referring to the report by name, or by referring to its index within the collection.

The Reports collection is indexed beginning with zero. If you refer to a report by its index, the first report is Reports(0), the second report is Reports(1), and so on.

Note To list all reports in the database, whether open or closed, enumerate the Documents collection of the Reports Container object. You can then use the Name property of each individual Document object to return the name of a report.

Properties

Count Property (Microsoft Access).

See Also

Application Object, Container Object, Document Object, Documents Collection, For Each...Next Statement, Report Object.

Example

See the Report object example.


Requery Action

Description

You can use the Requery action to update the data in a specified control on the active object by requerying the source of the control. If no control is specified, this action requeries the source of the object itself. Use this action to ensure that the active object or one of its controls displays the most current data.

Setting

The Requery action uses the following argument.

Action argument | Description
Control Name | The name of the control you want to update. You should use only the name of the control, not the fully qualified identifier, such as Forms!formname!controlname. Leave this argument blank to requery the source of the active object. If the active object is a datasheet or a query result set, you must leave this argument blank.

Remarks

The Requery action does one of the following:

  • Reruns the query on which the control or object is based.
  • Displays any new or changed records, and removes any deleted records from the table on which the control or object is based.
  • List boxes and combo boxes.
  • Subform controls.
  • OLE objects, such as charts.
  • Controls containing domain aggregate functions, such as DSum.

If the specified control is not based on a query or table, this action forces a recalculation of the control.

If you leave the Control Name argument blank, the Requery action has the same effect as pressing SHIFT+F9 when the object has the focus. If a subform control has the focus, this action requeries only the source of the subform (just as pressing SHIFT+F9 does).

Note The Requery action requeries the source of the control or object. In contrast, the RepaintObject action repaints controls in the specified object but doesn’t requery the database or display new records. The ShowAllRecords action not only requeries the active object, but it also removes any applied filters, which the Requery action does not do.

If you want to requery a control that is not on the active object, you must use the Requery method in Visual Basic, not the Requery action or its corresponding Requery method of the DoCmd object. The Requery method in Visual Basic is faster than the Requery action or the DoCmd Requery method. In addition, when you use the Requery action or the DoCmd Requery method, Microsoft Access closes the query and reloads it from the database, but when you use the Requery method, Microsoft Access reruns the query without closing and reloading it. Note that the data access Requery method works the same way as the Microsoft Access Requery method.

See Also

RepaintObject Action, Requery Method (DoCmd Object), ShowAllRecords Action.


Requery Method

Applies To

Control Object, Form Object.

Description

The Requery method updates the data underlying a specified form, or a control that is on the active form, by requerying the source of data for the form or control.

Syntax

object.Requery

The Requery method uses the following argument.

Argument | Description
object | A Form or Control object representing the form or control you want to update. Omit this argument to requery the source of data for the active object.

Remarks

Use this method to ensure that a form or control displays the most recent data.

The Requery method does one of the following:

  • Reruns the query on which the form or control is based.
  • Displays any new or changed records or removes deleted records from the table on which the form or control is based.
  • Updates records displayed based on any changes to the Filter property of the form.

Controls based on a query or table include:

  • List boxes and combo boxes.
  • Subform controls.
  • OLE objects, such as charts.
  • Controls for which the ControlSource property setting includes domain aggregate functions or SQL aggregate function.

If you specify any other type of control for object, the record source for the form is requeried.

If the control specified by object isn’t bound to a field in a table or query, the Requery method forces a recalculation of the control.

If you omit object, the Requery method requeries the underlying source of data for the form or control that has the focus. If the control that has the focus has a record source or row source, it will be requeried; otherwise the control’s data will simply be refreshed.

If a subform control has the focus, this method only requeries the record source for the subform, not the parent form.

Note Notes

  • The Requery method updates the data underlying a form or control to reflect records that are new to or have been deleted from the record source since it was last requeried. The Refresh method shows only changes that have been made to the current set of records; it does not reflect new records or deleted records in the record source. The Repaint method simply repaints the specified form and its controls.
  • The Requery method doesn’t pass control to the operating system to allow Windows to continue processing messages. Use the DoEvents function if you need to relinquish temporary control to the operating system.
  • The Requery method is faster than the Requery action. When you use the Requery action, Microsoft Access closes the query and reloads it from the database. When you use the Requery method, Microsoft Access reruns the query without closing and reloading it.

See Also

Control Object, Form Object, Recalc Method, Refresh Method, Repaint Method.

Example

This example uses the Requery method to requery the data from the EmployeeList list box on an Employees form.

Sub RequeryList()
    Dim ctlList As Control

    ' Return Control object pointing to list box.
    Set ctlList = Forms!Employees!EmployeeList
    ' Requery source of data for list box.
    ctlList.RequerySub


Requery Method (DoCmd Object)

Applies To

DoCmd Object.

Description

The Requery method of the DoCmd object carries out the Requery action in Visual Basic. For more information on how the action and its argument work, see the action topic.

Syntax

DoCmd.Requery [controlname]

The Requery method uses the following arguments.

Argument | Description
controlname | A string expression that is the name of a control on the active object

Remarks

Use only the name of the control for the controlname argument, not the full syntax.

You can also use a variable declared as a Control data type for this argument:

Dim LstBox As ControlLstBox = Forms!Form1!Field3.Requery LstBox.Name

The Requery method of the DoCmd object is different from the Requery method in Visual Basic. The Requery method of the DoCmd object was added to provide backwards compatibility for running the Requery action in Visual Basic code in Microsoft Access for Windows 95. If you want to requery a control that is not on the active object, you must use the Requery method in Visual Basic, not the Requery action or its corresponding Requery method of the DoCmd object. The Requery method in Visual Basic is faster than the Requery action or the DoCmd Requery method. In addition, when you use the Requery action or the DoCmd Requery method, Microsoft Access closes the query and reloads it from the database, but when you use the Requery method, Microsoft Access reruns the query without closing and reloading it. Note that the Requery method for DAO objects works the same way as the Microsoft Access Requery method.

Example

This example uses the Requery method to update the EmployeeList control.

DoCmd.Requery "EmployeeList"


Required Property

Applies To

Table Fields.

Description

You can use the Required property to specify whether or not a value is required in a field. If this property is set to Yes, when you enter data in a record you must enter a value in the field or in any control bound to the field, and the value cannot be Null. For example, you might want to be sure that a LastName control has a value for each record. When you want to permit Nulls in a field you must not only set the Required property to No but if there is a Validation Rule it must explicitly state “Null Or (...other validation rules...)”.

Note The Required property doesn’t apply to AutoNumber fields.

Setting

The Required property uses the following settings.

Setting | Description | Visual Basic
Yes | The field requires a value. | True (-1)
No | (Default) The field doesn’t require a value. | False (0)

You can set this property for all table fields (except AutoNumber data type fields) in the table’s property sheet or Visual Basic.

Note To access a field’s Required property in Visual Basic, use the Data Access Object’s Required property.

Remarks

The Required property is enforced at the table level by the Microsoft Jet database engine. If you set this property to Yes, the field must receive or already contain a value when it has the focus — when a user enters data in a table (or in a form or datasheet based on the table), when a macro or Visual Basic sets the value of the field, or when data is imported into the table.

You can use the Required and AllowZeroLength properties to differentiate between information that doesn’t exist (stored as a zero-length string (" ") in the field) and information that may exist but is unknown (stored as a Null value in the field). If you set the AllowZeroLength property to Yes, a zero-length string will be a valid entry in the field regardless of the Required property setting. If you set Required to Yes and AllowZeroLength to No, you must enter a value in the field, and a zero-length string won’t be a valid entry.

Note You need to use an input mask when data is entered in a field to distinguish between the display of a Null value and a zero-length string. For example, the string “None” could be displayed when a zero-length string is entered.

The following table shows the results you can expect when you combine the settings of the Required and AllowZeroLength properties.

Required | AllowZeroLength | User's action | Value stored
No | No | Presses ENTERSPACEBARa zero-length string | Null Null (not allowed)
No | Yes | Presses ENTERSPACEBARa zero-length string | Null Nullstring
Yes | No | Presses ENTERSPACEBARa zero-length string | (not allowed) (not allowed) (not allowed)
Yes | Yes | Presses ENTERSPACEBARa zero-length string | (not allowed)stringstring

If you set the Required property to Yes for a field in a table that already contains data, Microsoft Access gives you the option to check whether the field has a value in all existing records. However, you can require that a value be entered in this field in all new records even if there are existing records with Null values in the field.

Note To enforce a relationship between related tables that do not allow Null values, set the Required property of the foreign key field in the related table to Yes. The Jet database engine then ensures that you have a related record in the parent table before you can create a record in the child table. If the foreign key field is part of the primary key of the child table, this is unnecessary, because a primary key field can’t contain a Null value.

See Also

AllowZeroLength Property; InputMask Property; ValidationRule, ValidationText Properties.


Reset Statement

Description

Closes all disk files opened using the Open statement.

Syntax

Reset

Remarks

The Reset statement syntax closes all active files opened by the Open statement and writes the contents of all file buffers to disk.

See Also

Close Statement, End Statement, Open Statement.

Example

This example uses the Reset statement to close all open files and write the contents of all file buffers to disk. Note the use of the Variant variable FileNumber as both a string and a number.

For FileNumber = 1 To 5            ' Loop 5 times.
    ' Open file for output. FileNumber is concatenated into the string
    ' TEST for the filename, but is a number following a #.
    Open "TEST" & FileNumber For Output As #FileNumber
    Write #FileNumber, "Hello World"    ' Write data to file.FileNumber                            ' Close files and write contents
                                ' to disk.


Resize Event

Applies To

Form.

Description

The Resize event occurs when a form is opened and whenever the size of a form changes.

Remarks

This event occurs if you change the size of the form in a macro or event procedure; for example, if you use the MoveSize action in a macro to resize the form.

By running a macro or executing an event procedure when a Resize event occurs, you can move or resize a control when the form it’s on is resized. You can also use a Resize event to recalculate variables or reset properties that may depend on the size of the form.

When you first open a form, the following events occur in this order:

Open [image] Load [image] Resize [image] Activate [image] Current

See Also

Activate, Deactivate Events; Current Event; GotFocus, LostFocus Events; Load, Unload Events; MoveSize Action; Open, Close Events; OpenForm Action; Repaint Method; RepaintObject Action; SetFocus Method.


Resize Event -- Event Procedures

Description

To create an event procedure that is executed when the Resize event occurs, set the OnResize property to [Event Procedure], and click the Build button.

Syntax

Private Sub Form_Resize( )

Remarks

To repaint the screen every time a form is resized, use the Repaint method in a Resize event procedure.

You can’t cancel the Resize event.

See Also

Resize Event — Macros.

Example

The following example shows how a Resize event procedure can be used to repaint a form when it is maximized. When the user clicks a command button labeled “Maximize,” the form is maximized and the Resize event is triggered.

To try this example, add the code to the Declarations section of a module for a form called Contacts that contains a command button named Maximize.

Private Sub Maximize_Click()
    DoCmd.MaximizeSub
Sub Form_Resize()
    Forms!Contacts.RepaintSub


Resize Event -- Macros

Description

To run a macro when the Resize event occurs, set the OnResize property to the name of the macro.

Remarks

To repaint the screen every time a form is resized, use the RepaintObject action in the macro you specify for the Resize event.

You can’t use the CancelEvent action in a Resize macro.

See Also

Resize Event — Event Procedures.


Restore Action

Description

You can use the Restore action to restore a maximized or minimized window to its previous size.

Setting

The Restore action doesn’t use any arguments.

Remarks

This action works on the selected object. If an object has been minimized to an icon, you can first select it using the SelectObject action and then restore it to its previous size using the Restore action.

You can use the MoveSize action to move or size a window that you have restored.

The Restore action has the same effect as clicking the Restore button in the window’s upper-right corner or clicking the Restore command on the window’s Control menu.

To run the Restore action in Visual Basic, use the Restore method of the DoCmd object.

See Also

Maximize Action, Minimize Action, MoveSize Action, Restore Method, SelectObject Action.


Restore Method

Applies To

DoCmd Object.

Description

The Restore method carries out the Restore action in Visual Basic. For more information on how the action works, see the action topic.

Syntax

DoCmd.Restore

This method uses no arguments.

See Also

DoCmd Object, Maximize Method, Minimize Method, MoveSize Method, Restore Action, SelectObject Method.


Resume Statement

Description

Resumes execution after an error-handling routine is finished.

Syntax

Resume [0]Resume Next Resume line

The Resume statement syntax can have any of the following forms:

Statement | Description
Resume [0] | If the error occurred in the same procedure as the error handler, execution resumes with the statement that caused the error. If the error occurred in a called procedure, execution resumes at the statement that last called out of the procedure containing the error-handling routine.
Resume Next | If the error occurred in the same procedure as the error handler, execution resumes with the statement immediately following the statement that caused the error. If the error occurred in a called procedure, execution resumes with the statement immediately following the statement that last called out of the procedure containing the error-handling routine (or On Error Resume Next statement).
Resume line | Execution resumes at line, which is a line label or line number. The argument line must be in the same procedure as the error handler.

Remarks

If you use a Resume statement anywhere except in an error-handling routine, an error occurs.

When an error-handling routine is active and the end of a procedure (an End Sub, End Function, or End Property statement) is encountered before a Resume statement is encountered, an error occurs because a logic error is assumed to have been made inadvertently. However, if an Exit Sub, Exit Function, or Exit Property statement is encountered while an error handler is active, no error occurs because it is considered a deliberate redirection of execution.

See Also

End Statement, Err Object, Exit Statement, On Error Statement.

Example

This example uses the Resume statement to end error handling in a procedure and resume execution with the statement that caused the error. Error number 55 is generated to illustrate using the Resume statement.

Sub ResumeStatementDemo()
    On Error GoTo ErrorHandler        ' Enable error-handling routine.
    Open "TESTFILE" For Output As #1    ' Open file for output.
    Kill "TESTFILE"                    ' Attempt to delete open file.
    Exit Sub                            ' Exit Sub to avoid error handler.:                        ' Error-handling routine.
    Select Case Err.Number            ' Evaluate error number.
        Case 55                        ' "File already open" error.
            Close #1                    ' Close open file.
        Case Else
                                    ' Handle other situations here....
    End Select
    Resume                            ' Resume execution at same line
                                    ' that caused the error.Sub


Retreat Event

Applies To

Report Section.

Description

The Retreat event occurs when Microsoft Access returns to a previous report section during report formatting.

Remarks

Under certain circumstances, Microsoft Access must return to a previous report section to determine where certain controls and sections are on a report and whether they will fit in a given space. Examples include:

  • Groups (except for page headers and footers) for which the KeepTogether property is set to either Whole Group or With First Detail.
  • Subreports or subforms for which the CanGrow and/or CanShrink properties are set to Yes.
  • Sections on the last page of a report.

In these situations, the Format event occurs as Microsoft Access determines how the sections will fit on the printed page (however, a Print event doesn’t occur because the sections aren’t being printed yet). If the sections can’t be printed, Microsoft Access backs up to the necessary location so that the sections can actually be printed on the following page. The Retreat event occurs for each section past which Microsoft Access retreats. The Format event for each section then occurs again as Microsoft Access prepares to reprint the sections.

For example, whenever Microsoft Access reaches the end of the last page while formatting a report, the Retreat event occurs for each previous section until Microsoft Access reaches the first section at the top of the last page. Then the Format event occurs again for each section on the page, followed by the Print events.

You can run an event procedure or macro when the Retreat event occurs to undo any changes that you made when the Format event occurred for the section. This is useful when your Format event procedure or macro carries out actions, such as calculating page totals or controlling the size of a section, that you only want to perform once for each section.

The Retreat event is also useful for maintaining the positioning of report items. For example, the Sales By Year report in the Northwind sample database uses this event to determine if a page header is printed or not (the page header is printed on pages following a page where the group header has been printed, and the page header isn’t printed on the page following a page where the group footer has been printed).

See Also

Format Event, FormatCount Property, NoData Event, Page Event, Print Event, PrintCount Property.


Retreat Event -- Event Procedures

Description

To create an event procedure that is executed when the Retreat event occurs, set the OnRetreat property to [Event Procedure], and click the Build button.

Syntax

Private Sub sectionname_Retreat( )

The Retreat event procedure uses the following argument.

Argument | Description
sectionname | A string that is the name of the section affected by the Retreat event procedure.

Remarks

You can’t cancel the Retreat event.

See Also

Retreat Event — Macros.


Retreat Event -- Macros

Description

To run a macro when the Retreat event occurs, set the OnRetreat property to the name of the macro.

Remarks

You can’t use the CancelEvent action in a Retreat macro.

See Also

Retreat Event — Event Procedures.


ReturnsRecords Property

Applies To

Query.

Description

You can use the ReturnsRecords property in an SQL pass-through query to specify whether the query returns records. For example, if your pass-through query is SELECT * FROM EMPLOYEES, you can set the ReturnRecords property to Yes to display all employee records in the query’s datasheet.

Note The ReturnsRecords property applies only to pass-through queries.

Setting

The ReturnsRecords property uses the following settings.

Setting | Description | Visual Basic
Yes | (Default) The query returns records (like a select query). | True (-1)
No | The query doesn’t return records (like an action query). | False (0)

You can set this property in the query property sheet or in Visual Basic.

Tip You can access a pass-through query’s ReturnsRecords property in Visual Basic, but the preferred method is to use the data access ReturnsRecords property.

Remarks

A pass-through query can return records, or it can be used to change data, create a database object, or perform an action like an action query.

When you set the ReturnsRecords property to Yes, you can use the pass-through query in another query or as the basis for a combo box, list box, form, or report. If you set the ReturnsRecords property to No, you can’t use the query as the basis for an object or control because no records are returned.

See Also

ReturnRecords Property (Microsoft Office 95 Data Access Reference).


RGB Function

Description

Returns a whole number representing an RGB color value.

Syntax

RGB (red, green, blue)

The RGB function syntax has these named arguments:

Part | Description
red | Number in the range 0 to 255, inclusive, that represents the red component of the color.
green | Number in the range 0 to 255, inclusive, that represents the green component of the color.
blue | Number in the range 0 to 255, inclusive, that represents the blue component of the color.

Remarks

Application methods and properties that accept a color specification expect that specification to be a number representing an RGB color value. An RGB color value specifies the relative intensity of red, green, and blue to cause a specific color to be displayed.

The value for any argument to RGB that exceeds 255 is assumed to be 255.

The following table lists some standard colors and the red, green, and blue values they include:

Color | Red Value | Green Value | Blue Value
Black | 0 | 0 | 0
Blue | 0 | 0 | 255
Green | 0 | 255 | 0
Cyan | 0 | 255 | 255
Red | 255 | 0 | 0
Magenta | 255 | 0 | 255
Yellow | 255 | 255 | 0
White | 255 | 255 | 255

See Also

QBColor Function.

Example

This example shows how the RGB function is used to return a whole number representing an RGB color value. It is used for those application methods and properties that accept a color specification. The object MyObject and its property are used for illustration purposes only. If MyObject does not exist, or if it does not have a Color property, an error occurs.

Red = RGB(255, 0, 0)                    ' Return the value for Red.= 75                                ' Initialize offset.= RGB(I, 64 + I, 128 + I)     ' Same as RGB(75, 139, 203)..Color = RGB(255, 0, 0)        ' Set the Color property of
                                    ' MyObject to Red.


Right Function

Description

Returns a specified number of characters from the right side of a string.

Syntax

Right(string, length)

The Right function syntax has these named arguments:

Part | Description
string | String expression from which the rightmost characters are returned. If string contains Null, Null is returned.
length | Numeric expression indicating how many characters to return. If 0, a zero-length string is returned. If greater than or equal to the number of characters in string, the entire string is returned.

Remarks

To determine the number of characters in string, use the Len function.

Note Another function (RightB) is provided for use with byte data contained in a string. Instead of specifying the number of characters to return, length specifies the number of bytes.

See Also

Left Function, Len Function, Mid Function.

Example

This example uses the Right function to return a specified number of characters from the right side of a string.

AnyString = "Hello World"            ' Define string.= Right(AnyString, 1)            ' Returns "d".= Right(AnyString, 6)            ' Returns " World".= Right(AnyString, 20)            ' Returns "Hello World".


RmDir Statement

Description

Removes an existing directory or folder.

Syntax

RmDir path

The path argument is a string expression that identifies the directory or folder to be removed. The path may include the drive. If no drive is specified, RmDir removes the directory or folder on the current drive.

Remarks

An error occurs if you try to use RmDir on a directory or folder containing files. Use the Kill statement to delete all files before attempting to remove a directory or folder.

See Also

ChDir Statement, CurDir Function, Kill Statement, MkDir Statement.

Example

This example uses the RmDir statement to remove an existing directory or folder.

' Assume that MYDIR is an empty directory or folder."MYDIR"                ' Remove MYDIR.


Rnd Function

Description

Returns a random number.

Syntax

Rnd[(number)]

The number argument can be any valid numeric expression.

Remarks

The Rnd function returns a value less than 1 but greater than or equal to 0.

The value of number determines how Rnd generates a random number:

If number is | Rnd generates
Less than zero | The same number every time, using number as the seed.
Greater than zero | The next random number in the sequence.
Equal to zero | The most recently generated number.
Not supplied | The next random number in the sequence.

For any given initial seed, the same number sequence is generated because each successive call to the Rnd function uses the previous number as a seed for the next number in the sequence.

Before calling Rnd, use the Randomize statement without an argument to initialize the random-number generator with a seed based on the system timer.

To produce random integers in a given range, use this formula:

Int((upperbound - lowerbound + 1) * Rnd + lowerbound)

Here, upperbound is the highest number in the range, and lowerbound is the lowest number in the range.

Note To repeat sequences of random numbers, call Rnd with a negative argument immediately before using Randomize with a numeric argument. Using Randomize with the same value for number does not repeat the previous sequence.

See Also

Randomize Statement, Timer Function.

Example

This example uses the Rnd function to generate a random integer value from 1 to 6.

MyValue = Int((6 * Rnd) + 1)        ' Generate random value between 1 and 6.


RowHeight Property

Applies To

Form, Query, Table.

Description

You can use the RowHeight property to specify the height of all rows in Datasheet view.

Note The RowHeight property applies to all fields in Datasheet view and to form controls when the form is in Datasheet view.

Setting

You set the RowHeight property in Datasheet view by dragging the lower border of the record selector or by clicking the Row Height command on the Format menu. When you set the RowHeight property using the Row Height command, the value is expressed in points.

In Visual Basic, the RowHeight property setting is a Long value that represents the datasheet row height in twips. To specify the default height for the current font, you can set the RowHeight property to True (-1).

See Also

ColumnHidden Property, ColumnOrder Property, ColumnWidth Property.

Example

See the ColumnWidth property example.


RowSourceType, RowSource Properties

Applies To

Chart Control, Combo Box Control, List Box Control, Unbound Object Frame Control.

Description

You can use the RowSourceType and RowSource properties together to tell Microsoft Access how to provide data to a list box, a combo box, or an unbound OLE object such as a chart. For example, to display rows of data in a list box from a query named CustomerList, set the list box’s RowSourceType property to Table/Query and its RowSource property to the query named CustomerList.

Setting

The RowSourceType property has the following settings.

Setting | Description
Table/Query | (Default) The data is from a table, query, or SQL statement specified by the RowSource setting.
Value List | The data is a list of items specified by the RowSource setting.
Field List | The data is a list of field names from a table, query, or SQL statement specified by the RowSource setting.

Note You can also set the RowSourceType property with a user-defined function. In this case the data is an array of values defined by the user. The function name is entered without a preceding equal sign (=) and without the trailing pair of parentheses. You must provide specific function code arguments to tell Microsoft Access how to fill the control.

The RowSource property setting depends on the RowSourceType property setting.

For this RowSourceType | this RowSource
Table/Query | Enter a table name, a query name, or an SQL statement.
Value List | Enter a list of items using semicolons (;) as separators.
Field List | Enter a table name, a query name, or an SQL statement.

Note If the RowSourceType property is set to a user-defined function, the RowSource property must be left blank.

You can set the RowSourceType and RowSource properties using the control’s property sheet, a macro, or Visual Basic.

For table fields, you can set these properties in table Design view for fields with the DisplayControl property set to combo box or list box.

Note Microsoft Access sets these properties automatically when you select Lookup Wizard as the data type for a field in table Design view.

In Visual Basic, set the RowSourceType property using a string expression with one of these values: "Table/Query", "Value List", or "Field List". You also use a string expression to set the value of the RowSource property. To set the RowSourceType property to a user-defined function, enter the name of the function.

Remarks

When you have a limited number of values that do not change, you can set the RowSourceType property to Value List and then enter the values that make up the list in the RowSource property.

When you create a user-defined function to insert items into a list box or combo box, Microsoft Access calls the function repeatedly to get the information it needs. User-defined RowSourceType functions must be written in a very specific function format.

See Also

BoundColumn Property, ColumnWidths Property, ControlSource Property, RecordSource Property, RowSourceType (User-Defined Function) — Code Argument Values.

Example Settings

The following examples show sample RowSource property settings for each RowSourceType property setting.

When RowSourceType is set to Value List

If the RowSourceType property is set to Value List, the following table shows valid settings for the RowSource and ColumnCount properties and an illustration of the resulting list.

RowSource setting | List
Mon;Tue;Wed (ColumnCount = 1) |
 | One-column list with three rows

RowSource setting | List
1;Monday;2;Tuesday;3;Wednesday;4;Thursday (ColumnCount = 2) |
 | Two-column list with four rows
Country;Capital;China;Beijing;Brazil;Brasilia (ColumnCount = 2, ColumnHeads = Yes) |
 | Two-column list with one row of column heads and two rows of data

When RowSourceType is set to Table/Query

If the RowSourceType property is set to Table/Query, you can set the RowSource property to a table or query name — for example, CategoryList.

The following is a valid SQL statement for a two-column list drawn from the Categories table.

SELECT [CategoryID], [CategoryName] FROM [Categories] BY [CategoryName];

If the CategoryList query and the SQL statement define the same set of records, the list for either property setting looks like the following illustration.

When RowSourceType is set to Field List

If the RowSourceType property is set to Field List and the RowSource property to CustomerList (the query described in the previous example), the resulting list looks like the following illustration.

When RowSourceType is set to User-Defined

If the RowSourceType property is set to the name of a user-defined function, then the RowSource property setting must be left blank. For example, a user-defined function named ListMDBs that fills a combo box with the names of all the databases in the current directory is entered in the property sheet like the following illustration.

Example

The following example sets the RowSourceType property for a combo box to Table/Query, and it sets the RowSource property to a query named EmployeeList.

Forms![frmEmployees]![cmboNames].RowSourceType = "Table/Query"![frmEmployees]![cmboNames].RowSource = "EmployeeList"


RowSourceType (User-Defined Function) -- Code Argument Values

Description

The Visual Basic function you create must accept five arguments. The first argument must be declared as a control and the remaining arguments as Variants. The function itself must return a Variant.

Syntax

Function functionname(fld As Control, id As Variant, row As Variant, col As, code As Variant) As Variant

The following are the five required arguments.

Argument | Description
fld | A control variable that refers to the list box or combo box being filled.
id | A unique value that identifies the control being filled; this is useful when you want to use the same user-defined function for more than one list box or combo box and must distinguish between them. (The example sets this variable to the value of the Timer function.)
row | The row being filled (zero-based).

Argument | Description
col | The column being filled (zero-based).
code | A value that specifies the kind of information being requested.

Note Because Microsoft Access calls a list function several times to insert items into a list, often you must preserve information from call to call. The best way to do this is to use Static variables.

Microsoft Access calls the user-defined function repeatedly using different values in the code argument to specify the information it needs. The code argument can have the following values.

Code | Meaning | Function returns
0 | Initialize | Nonzero if the function can fill the list; False or Null otherwise.
1 | Open | Nonzero ID value if the function can fill the list; False or Null otherwise.
2 | (Not used) |
3 | Number of rows | Number of rows in the list (can be zero); -1 if unknown.
4 | Number of columns | Number of columns in the list (can’t be zero); must match the property sheet value.
5 | Column width | Width (in twips) of the column specified by the col argument; or -1 to use the default width.
6 | List entry | List entry to be displayed in the row and column specified by the row and col arguments.
7 | Format string | Format string to be used to format the list entry displayed in the row and column specified by the row and col arguments; or Null to use the default format.
8 | (Not used) |
9 | End (the last call to a list function always uses this value) | Nothing.

Microsoft Access calls your list function once for codes 0, 1, 3, and 4. It initializes the list function, opens the query, and determines the number of rows and columns.

Microsoft Access calls your list function twice for code 5 — once to determine the total width of the list box or combo box and a second time to set the column width.

The number of times your list function is called for codes 6 and 7 to get list entries and to format strings varies depending on the number of entries, the user’s scrolling, and other factors.

Microsoft Access calls the list function for code 9 when the form is closed or each time the list box or combo box is queried.

Whenever a particular value (such as the number of columns) is required, returning Null or any invalid value causes Microsoft Access to stop calling the list function with that code.

Tip You can use the Select Case code structure from the example as a template for your own RowSourceType user-defined functions.

Your user-defined function can use the numeric codes or the corresponding constants. Intrinsic constants have several advantages. They don’t have to be loaded or declared, and they’re more descriptive than the numeric codes. The following table lists the numeric codes and their corresponding intrinsic constants.

Code | Intrinsic Constant
0 | acLBInitialize
1 | acLBOpen
3 | acLBGetRowCount
4 | acLBGetColumnCount
5 | acLBGetColumnWidth
6 | acLBGetValue
7 | acLBGetFormat
8 | acLBClose
9 | acLBEnd

Note You can’t create your own constants with the same names as Microsoft Access intrinsic constants.

Example

The following user-defined function returns a list of the next four Mondays following today’s date. To call this function from a list box control, enter ListMondays as the RowSourceType property setting and leave the RowSource property setting blank.

Function ListMondays(fld As Control,id As Variant,row As Variant, _
        col As Variant,code As Variant) As Variant
    Dim intOffset As Integer
    Select Case code
        Case 0                        ' Initialize.
            ListMondays = True
        Case 1                        ' Open.
            ListMondays = Timer        ' Generate unique ID for control.
        Case 3                        ' Get number of rows.
            ListMondays = 4
        Case 4                        ' Get number of columns.
            ListMondays = 1
        Case 5                        ' Get column width.
            ListMondays = -1            ' -1 forces use of default width.
        Case 6                        ' Get the data.
            intOffset = Abs((9 - Weekday(Now))Mod 7)
            ListMondays = Format(Now() + intOffset + 7 * row,"mmmm d")
    End SelectFunction

The following example uses a static array to store the names of the databases in the current directory. To call this function, enter ListMDBs as the RowSourceType property setting and leave the RowSource property setting blank.

Function ListMDBs (fld As Control, id As Variant, row As Variant, _
        col As Variant, code As Variant) As Variant
    Static dbs(127), Entries
    Dim ReturnVal
    ReturnVal = Null
    Select Case code
        Case LB_INITIALIZE            ' Initialize.
            Entries = 0
            dbs(Entries ) = Dir("*.MDB")
            Do Until dbs(Entries) = "" Or Entries >= 127
                Entries = Entries+1
                dbs(Entries) = Dir
            Loop
            ReturnVal = Entries
        Case LB_OPEN                    ' Open.
            ReturnVal = Timer        ' Generate unique ID for control.
        Case LB_GETROWCOUNT            ' Get number of rows.
            ReturnVal = Entries
        Case LB_GETCOLUMNCOUNT        ' Get number of columns.
            ReturnVal = 1
        Case LB_GETCOLUMNWIDTH        ' Column width.
            ReturnVal = -1            ' -1 forces use of default width.
        Case LB_GETVALUE                ' Get data.
            ReturnVal = dbs(row)
        Case LB_END                    ' End.
            For Entries = 0 to 127
                dbs(Entries) = ""
            Next
    End Select
    ListMDBs = ReturnValFunction


RSet Statement

Description

Right aligns a string within a string variable.

Syntax

RSet stringvar = string

The RSet statement syntax has these parts:

Part | Description
stringvar | Name of string variable.
string | String expression to be right-aligned within stringvar.

Remarks

RSet replaces any leftover characters in stringvar with spaces, back to its beginning.

RSet can’t be used with user-defined types.

See Also

LSet Statement.

Example

This example uses the RSet statement to right align a string within a string variable.

MyString = "0123456789"            ' Initialize string.MyString = "Right->"        ' MyString contains "   Right->".


RTrim Function

See LTrim, RTrim, and Trim Functions.


Run Method

Description

You can use the Run method to carry out a specified Microsoft Access or user-defined Function or Sub procedure. This method is useful when you are controlling Microsoft Access from another application through OLE Automation. For example, you can use the Run method from an OLE Automation controller to carry out a Sub procedure that is defined within a Microsoft Access database.

Syntax

application.Run procedure[, arg1, arg2, ..., arg30]

The Run method uses the following arguments.

Argument | Description
application | The Application object.
procedure | The name of the Function or Sub procedure to be run.
arg1, arg2, ... | Optional. The arguments for the specified Function or Sub procedure. You can supply a maximum of thirty arguments.

Remarks

You can set a reference to the Microsoft Access type library from any other OLE Automation controller and use the objects, methods, and properties defined in that library in your code. However, you can’t set a reference to an individual Microsoft Access database from any application other than Microsoft Access. The Run method provides a way to call a procedure you have defined in a Microsoft Access database from another application.

For example, suppose you have defined a procedure NewForm in a database named WizCode.mdb. The NewForm procedure takes a string argument. You can call NewForm in the following manner from Visual Basic 4.0.

Dim appAccess As New Access.Application.OpenCurrentDatabase ("C:\My Documents\WizCode.mdb").Run "WizCode.NewForm", "Some String"

If another procedure with the same name may reside in a different database, qualify procedure with the name of the database in which the desired procedure resides.

You can also use the Run method to call a procedure in a referenced Microsoft Access database from another database. Although you can call a procedure in a referenced database as though it were in the current database, doing so loads the potential call tree of the module in the referenced database. For performance and resource reasons, you may want to use the Run method, which loads only the module in which the procedure resides.

Microsoft Access ignores any value returned by a procedure called by the Run method.

Example

The following example runs a user-defined Sub procedure in a module in a Microsoft Access database from another application that acts as an OLE Automation controller.

To try this example, create a new database called WizCode.mdb and open a new module in that database. Enter the following code, save the module, and close the database.

Sub Greeting(strName As String)
    MsgBox("Hello, " & strName)Sub

Once you have completed this step, run the following code from Microsoft Excel or Microsoft Visual Basic. Make sure that you have added a reference to the Microsoft Access type library by clicking References on the Tools menu and selecting Microsoft Access For Windows 95 in the References dialog box.

' Include in Declarations section of module.
' From Microsoft Excel, use "Dim appAccess As Object".appAccess As Access.Application
RunAccessSub()
    ' Create instance of Microsoft Access Application object.
    Set appAccess = CreateObject("Access.Application.7")
    ' Open WizCode database in Microsoft Access window.
    appAccess.OpenCurrentDatabase ("C:\My Documents\WizCode.mdb")
    ' Run Sub procedure.
    appAccess.Run "Greeting", "Joe"Sub


RunApp Action

Description

You can use the RunApp action to run a Microsoft Windows-based or MS-DOS–based application, such as Microsoft Excel, Microsoft Word for Windows, or Microsoft PowerPoint®, from within Microsoft Access. For example, you may want to paste or link Microsoft Excel spreadsheet data into your Microsoft Access database.

Setting

The RunApp action uses the following argument.

Action argument | Description
Command Line | The command line used to start the application (including the path name and any other necessary parameters, such as switches that run the application in a particular mode). This is a required argument.

Remarks

The application selected with this action loads and runs in the foreground. The macro containing this action continues to run.

You can transfer data between the other application and Microsoft Access by using the Windows dynamic data exchange (DDE) facility or the Clipboard. You can use the SendKeys action to send keystrokes to the other application (although DDE is a more efficient method for transferring data). You can also share data among applications using OLE Automation.

MS-DOS–based applications run in an MS-DOS window within the Windows environment.

This action has the same effect as double-clicking a program icon in a Windows program group or running a program from the Run dialog box in the Windows Program Manager. In Windows 95, there are a number of ways to start an application, including starting the program from the Windows Explorer, using the Run command on the Start menu, and double-clicking a program icon on the Windows Desktop.

You can’t run the RunApp action in Visual Basic. Use the Visual Basic Shell function instead.


RunCode Action

Description

You can use the RunCode action to run a Visual Basic Function procedure.

Setting

The RunCode action uses the following argument.

Action argument | Description
Function Name | The name of the Visual Basic Function procedure to execute. Put any function arguments in parentheses. This is a required argument.

Note To use the Expression Builder to select a function for this argument, click the Build button to the right of the Function Name box. Click a function in the list in the Expression Builder.

Remarks

The user-defined Function procedures are stored in Microsoft Access modules.

You must include parentheses, even if the Function procedure doesn’t have any arguments, as in the following example.

TestFunction()

Unlike user-defined function names used for event property settings, the function name in the Function Name argument does not begin with an equal sign (=).

Microsoft Access ignores the return value of the function.

Tip To run a Sub procedure or event procedure written in Visual Basic, create a Function procedure that calls the Sub procedure or event procedure. Then use the RunCode action to run the Function procedure.

If you use the RunCode action to call a function, Microsoft Access looks for the function with the name specified by the Function Name argument in the standard modules for the database. However, when this action runs in response to choosing a menu command on a form or report or in response to an event on a form or report, Microsoft Access looks for the function first in the form or report module and then in the standard modules.

This action isn’t available in Visual Basic. Run the desired Function procedure directly in Visual Basic.

See Also

Eval Function, OpenModule Action.


RunMacro Action

Description

You can use the RunMacro action to run a macro. The macro can be in a macro group.

You can use this action to:

  • Run a macro from within another macro.
  • Run a macro based on a certain condition.
  • Attach a macro to a custom menu command.

Setting

The RunMacro action uses the following arguments.

Action argument | Description
Macro Name | The name of the macro to run. The Macro Name box in the Action Arguments section of the Macro window shows all macros (and macro groups) in the current database. If the macro is in a macro group, it is listed under the macro group name in the list as macrogroupname.macroname. This is a required argument.
 | If you run a macro containing the RunMacro action in a library database, Microsoft Access looks for the macro with this name in the library database and doesn’t look for it in the current database.
Repeat Count | The maximum number of times the macro will run. If you leave this argument blank (and the Repeat Expression argument is also blank), the macro runs once.
Repeat Expression | An expression that evaluates to True (-1) or False (0). The macro stops running if the expression evaluates to False. The expression is evaluated each time the macro runs.

Remarks

If you enter a macro group name for the Macro Name argument, Microsoft Access runs the first macro in the macro group.

This action is similar to clicking Macro on the Tools menu, which runs a specified macro. However, the command runs the macro only once, whereas the RunMacro action can run a macro as many times as you want.

Tip You can use the Repeat Count and Repeat Expression arguments to determine how many times the macro runs:

  • If you leave both arguments blank, the macro runs once.
  • If you enter a number for Repeat Count but leave Repeat Expression blank, the macro runs the specified number of times.
  • If you leave Repeat Count blank but enter an expression for Repeat Expression, the macro runs until the expression evaluates to False.
  • If you enter values for both arguments, the macro runs the number of times specified in Repeat Count or until Repeat Expression evaluates to False, whichever occurs first.

When you run the original macro, and it reaches the RunMacro action, Microsoft Access runs the called macro. When the called macro has finished, Microsoft Access returns to the original macro and performs the next action.

Note Notes

  • You can call a macro in the same macro group or in another macro group.
  • You can nest macros. That is, you can run macro A, which in turn calls macro B, and so on. In each case, when the called macro has finished, Microsoft Access returns to the macro that called it and runs the next action in that macro.

To run the RunMacro action in Visual Basic, use the RunMacro method of the DoCmd object.

See Also

RunMacro Method.


RunMacro Method

Applies To

DoCmd Object.

Description

The RunMacro method carries out the RunMacro action in Visual Basic. For more information on how the action and its arguments work, see the action topic.

Syntax

DoCmd.RunMacro macroname[, repeatcount][, repeatexpression]

The RunMacro method uses the following arguments.

Argument | Description
macroname | A string expression that is the valid name of a macro in the current database. If you execute Visual Basic code containing the RunMacro method in a library database, Microsoft Access looks for the macro with this name in the library database and doesn’t look for it in the current database.
repeatcount | A numeric expression that evaluates to an integer, which is the number of times the macro will run.
repeatexpression | A numeric expression that is evaluated each time the macro runs. When it evaluates to False (0), the macro stops running.

Remarks

You can use “macrogroupname.macroname” for the macroname argument to run a particular macro in a macro group.

If you specify the repeatexpression argument and leave the repeatcount argument blank, you must include the repeatcount argument’s comma. If you leave a trailing argument blank, don’t use a comma following the last argument you specify.

See Also

DoCmd Object.

Example

This example runs the macro Print Sales.

DoCmd.RunMacro "Print Sales"


RunningSum Property

Applies To

Report.

Description

You can use the RunningSum property to calculate record-by-record or group-by-group totals in a report. The RunningSum property specifies whether a text box on a report displays a running total and lets you set the range over which values are accumulated. For example, if you group data by month and show the sum of each month’s sales in the group footer. You can show the running sum of accumulated sales over the entire report (sales for January in the January footer, sales for January plus February in the February footer, and so on) by adding a text box to the footer that shows the sum of sales and setting its RunningSum property to Over All.

Note The RunningSum property applies only to a text box on a report.

Setting

The RunningSum property has the following settings.

Setting | Description | Visual Basic
No | (Default) The text box displays the data from the underlying field for the current record. | 0
Over Group | The text box displays a running sum of values in the same group level. The value accumulates until another group level section is encountered. | 1
Over All | The text box displays a running sum of values in the same group level. The value accumulates until the end of the report. | 2

You can set the RunningSum property using the text box’s property sheet, a macro, or Visual Basic. You can set the RunningSum property only in Design view.

Remarks

Place the text box in the detail section to calculate a record-by-record total. For example, to number the records appearing in a detail section of a report, set the ControlSource property for the text box to 1, and set the RunningSum property to Over Group.

Place the text box in a group header or group footer to calculate a group-by-group total.

You can have up to 10 nested group levels in a report.

Example

The following example shows a sales report with two group levels — Month and Type of Food. Each text box in the Type of Food group footer (January Chocolates, January Meat, and so on) contains the following expression:

= Sum([Sales])

The RunningSum property of each text box is set to one of the three different values: No, Over Group, and Over All.

Example

The following example sets the RunningSum property for a text box named SalesTotal to 2 (Over All).

Reports![rptSales]![SalesTotal].RunningSum = 2

Group levels | No | Over Group | Over All
Month: January
Type of Food: Chocolates
02-Jan | 25 |  |
22-Jan | 75 |  |
January Chocolates | 100 | Jan Food 100 | YTD Sales 100
Type of Food: Meat
03-Jan | 90 |  |
20-Jan | 60 |  |
January Meat | 150 | Jan Food 250 | YTD Sales 250
Month: February
Type of Food: Chocolates
05-Feb | 70 |  |
19-Feb | 80 |  |
February Chocolates | 150 | Feb Food 150 | YTD Sales 400
Type of Food: Meat
12-Feb | 150 |  |
22-Feb | 100 |  |
February Meat | 250 | Feb Food 400 | YTD Sales 650


RunPermissions Property

Applies To

Query.

Description

You can use the RunPermissions property in a multiuser environment with a secure workgroup to override the existing user permissions. This allows you to view a query or run an append, delete, make-table, or update query that you otherwise would not have permission to run. For example, as a user, you may have read-only permission for queries, while the owner of the queries has read/write permission. If the owner set the RunPermissions property to specify the owner’s permissions, you can run an append query to add records to a table.

Note The RunPermissions property applies only to append, crosstab, delete, make-table, select, and update queries.

Setting

The RunPermissions property uses the following settings.

Setting | Description
Owner’s | All users are allowed the owner’s permissions to view or run the query.
User’s | (Default) Users have only their own permissions to view or run the query.

You can set this property using the query property sheet.

You can also set the RunPermissions property in SQL view of the Query window by using the WITH OWNERACCESS OPTION declaration in the SQL statement.

Example

The following example is a select query based on the Categories table that enables all users to have the owner’s permissions for the query.

SELECT DISTINCTROW Categories.[CategoryID], _
    Categories.[CategoryName], Categories.DescriptionCategories OWNERACCESS OPTION;


RunSQL Action

Description

You can use the RunSQL action to run a Microsoft Access action query using the corresponding SQL statement. You can also run a data-definition query.

Setting

The RunSQL action uses the following argument.

Action argument | Description
SQL Statement | The SQL statement for the action query or data-definition query you want to run. The maximum length of this statement is 256 characters. This is a required argument.

Remarks

You can use action queries to append, delete, and update records and to save a query’s result set as a new table. You can use data-definition queries to create, alter, and delete tables, and to create and delete indexes. With the RunSQL action, you can perform these operations directly from a macro without having to use stored queries.

If you need to type an SQL statement longer than 256 characters, use the RunSQL method of the DoCmd object in Visual Basic instead. You can type SQL statements of up to 32,768 characters in Visual Basic.

Microsoft Access queries are actually SQL statements that are created when you design a query using the design grid in the Query window. The following table shows the Microsoft Access action queries and data-definition queries and their corresponding SQL statements.

Query type | SQL statement
Action |
Append | INSERT INTO
Delete | DELETE
Make-table | SELECT...INTO
Update | UPDATE
Data-definition (SQL-specific) |
Create a table | CREATE TABLE
Alter a table | ALTER TABLE
Delete a table | DROP TABLE
Create an index | CREATE INDEX
Delete an index | DROP INDEX

You can also use an IN clause with these statements to modify data in another database.

Note To run a select query or crosstab query from a macro, use the View argument of the OpenQuery action to open an existing select query or crosstab query in Datasheet view. You can also run existing action queries and SQL-specific queries in the same way.

Tip To see the SQL equivalent of a Microsoft Access query, click SQL on the View menu in the Query window. Use the listed SQL statements as models to create queries to run with the RunSQL action. Duplicating an SQL statement in the SQL Statement argument for the RunSQL action has the same effect as running this Microsoft Access query in the Query window.

See Also

OpenQuery Action, RunSQL Method.


RunSQL Method

Applies To

DoCmd Object.

Description

The RunSQL method carries out the RunSQL action in Visual Basic. For more information on how the action and its arguments work, see the action topic.

Syntax

DoCmd.RunSQL sqlstatement

The RunSQL method uses the following arguments.

Argument | Description
sqlstatement | A string expression that is a valid SQL statement for an action query or a data-definition query. It uses an INSERT INTO, DELETE, SELECT...INTO, UPDATE, CREATE TABLE, ALTER TABLE, DROP TABLE, CREATE INDEX, or DROP INDEX statement. Include an IN clause if you want to access another database.

Remarks

The maximum length of the sqlstatement argument is 32,768 characters (unlike the SQL Statement action argument in the Macro window, whose maximum length is 256 characters).

See Also

DoCmd Object, OpenQuery Method, RunSQL Action.

Example

This example updates the Employees table, changing each sales manager’s title to Regional Sales Manager.

DoCmd.RunSQL "UPDATE Employees " & _
    "SET Employees.Title = 'Regional Sales Manager' " & _
    "WHERE Employees.Title = 'Sales Manager';"


Save Action

Description

You can use the Save action to save either a specified Microsoft Access object or the active object if none is specified. You can also save the active object with a new name (this functions the same as the Save As command).

Setting

The Save action uses the following arguments.

Action argument | Description
Object Type | The type of object you want to save. Click Table, Query, Form, Report, Macro, or Module in this argument’s drop-down list in the Action Arguments section of the Macro window. To select the active object, leave this argument blank. If you select an object type in this argument, you must select an existing object’s name in the Object Name argument.
Object Name | The name of the object to be saved. The Object Name box shows all objects in the database of the type selected in the Object Type argument. If you leave the Object Type argument blank, you can leave this argument blank to save the active object, or enter a new name in this argument to save the active object with this name. If you enter a new name, the name must follow the standard naming conventions for Microsoft Access objects.

Remarks

The Save action works on all database objects that the user can explicitly open and save. The specified object must be open for the Save action to have any effect on the object. This action has the same effect as selecting an object and then saving it by clicking Save on the File menu, or clicking the Save button on the toolbar. Leaving the Object Type argument blank and entering a new name in the Object Name argument has the same effect as clicking Save As/Export on the File menu, and entering a new name for the active object. Using the Save action enables you to specify an object to save and to perform a Save As command from a macro.

The Save action, whether it is carried out in a macro run in the current database or in a library database, always saves the specified object or the active object in the database in which the object was created.

If you save the active object with a new name, but the name is the same as the name of an existing object of this type, a dialog box asks if you want to overwrite the existing object. If you’ve set the Warnings On argument of the SetWarnings action to No, the dialog box isn’t displayed and the old object is automatically overwritten.

To run the Save action in Visual Basic, use the Save method of the DoCmd object.

See Also

Close Action, CopyObject Action, Quit Action, Rename Action, Save Method, TransferDatabase Action.


Save Method

Applies To

DoCmd Object.

Description

The Save method carries out the Save action in Visual Basic. For more information on how the action and its arguments work, see the action topic.

Syntax

DoCmd.Save [objecttype, objectname]

The Save method uses the following arguments.

Argument | Description
objecttype | One of the following intrinsic constants:
 | acTable
objectname | A string expression that is the valid name of an object of the type selected with the objecttype argument

Remarks

If you leave the objecttype and objectname arguments blank, Microsoft Access saves the active object. If you leave the objecttype argument blank, but enter a name in the objectname argument, Microsoft Access saves the active object with the specified name. If you enter an object type in the objecttype argument, you must enter an existing object’s name in the objectname argument.

If you leave the objecttype argument blank, but enter a name in the objectname argument, you must include the objecttype argument’s comma.

The Save method, whether it is executed in the current database or in a library database, always saves the specified object or the active object in the database in which the object was created.

See Also

Close Method, CopyObject Method, DoCmd Object, Quit Method, Quit Method (DoCmd Object), Rename Method, Save Action, TransferDatabase Method.

Example

This example uses the Save method to save the active object (a form) with the new name “New Employees Form”.

DoCmd.Save , "New Employees Form"


SaveSetting Statement

Description

Saves or creates an application entry in the Windows registry entry.

Syntax

SaveSetting(appname, section, key, setting)

The SaveSetting statement syntax has these named arguments:

Part | Description
appname | String expression containing the name of the application or project to which the setting applies.
section | String expression containing the name of the section where the key setting is being saved.
key | String expression containing the name of the key setting being saved.
setting | Expression containing the value that key is being set to.

Remarks

An error occurs if the key setting could not be saved for any reason.

See Also

DeleteSetting Statement, GetAllSettings Function, GetSetting Function.

Example

The following example first uses the SaveSetting statement to make entries in the Windows registry (or .ini file on 16-bit Windows platforms) for the MyApp application, then uses the DeleteSetting statement to remove them.

' Place some settings in the registry.(appname := "MyApp", section := "Startup", _
    key := "Top", setting := 75)("MyApp","Startup", "Left", 50)("MyApp","Startup", "Password", "Swordfish")
' Remove app entry and all settings from registry.("MyApp", "Startup")


Scale Method

Applies To

Report Object.

Description

The Scale method defines the coordinate system for a Report object.

Syntax

object.Scale[(x1, y1) - (x2, y2)]

You can use this method only in an event procedure or a macro specified by the event properties OnPrint or OnFormat for a report section, or OnPage for a report.

The Scale method uses the following arguments.

Argument | Description
object | The Report object to which the coordinate system is applied
x1, y1 | Single values for the horizontal and vertical coordinates that define the position of the upper-left corner of the object
x2, y2 | Single values for the horizontal and vertical coordinates that define the position of the lower-right corner of the object

Remarks

You can use the Scale method to reset the coordinate system to any scale you choose. Using the Scale method with no arguments resets the coordinate system to twips. The Scale method affects the coordinate system for the Print method and the report graphics methods, which include the Circle, Line, and PSet methods.

See Also

Circle Method; Event Properties; Line Method; PrintOut Method; PSet Method; ScaleHeight, ScaleWidth Properties; ScaleLeft, ScaleTop Properties; ScaleMode Property.


ScaleHeight, ScaleWidth Properties

Applies To

Report.

Description

You can use the ScaleHeight and ScaleWidth properties to specify the number of units for the vertical or horizontal measurement of the page when the Circle, Line, PSet, or Print method is used while a report is printed or previewed.

Setting

  • ScaleHeight — A Single data type value used in a numeric expression to set the number of units for the vertical measurement of the page.
  • ScaleWidth — A Single data type value used in a numeric expression to set the number of units for the horizontal measurement of the page.

The default settings are the internal height and width of a report page in twips.

You can set the ScaleHeight and ScaleWidth properties only in a macro or a Visual Basic event procedure specified by a section’s OnPrint property setting.

Remarks

You can use the ScaleHeight and ScaleWidth properties to create a custom coordinate scale for drawing or printing. For example, the statement ScaleHeight = 100 defines the internal height of the section as 100 units, or one vertical unit as 1/100 of the height.

Use the ScaleMode property to define a scale based on a standard unit of measurement, such as points, pixels, characters, inches, millimeters, or centimeters.

Setting the ScaleHeight and ScaleWidth properties to positive values makes coordinates increase in value from top to bottom and left to right. Setting them to negative values makes coordinates increase in value from bottom to top and right to left.

Using these properties and the related ScaleLeft and ScaleTop properties, you can set up a full coordinate system with both positive and negative coordinates. All four of these scale properties interact with the ScaleMode property in the following ways:

  • Setting any other Scale property to any value automatically sets the ScaleMode property to 0.
  • Setting the ScaleMode property to a number greater than 0 changes ScaleHeight and ScaleWidth to the new unit of measurement and sets ScaleLeft and ScaleTop to 0. Also, the CurrentX and CurrentY property settings change to reflect the new coordinates of the current point.

You can also use the Scale method to set the ScaleHeight, ScaleWidth, ScaleLeft, and ScaleTop properties in one statement.

Note The ScaleHeight and ScaleWidth properties aren’t the same as the Height and Width properties.

See Also

Circle Method; CurrentX, CurrentY Properties; Line Method; Print Method; PSet Method; ScaleLeft, ScaleTop Properties; ScaleMode Property.


ScaleLeft, ScaleTop Properties

Applies To

Report.

Description

You can use the ScaleLeft and ScaleTop properties in Visual Basic to specify the horizontal or vertical coordinates that describe the location of the left and top edges of a page when the Circle, Line, PSet, or Print method is used while a report is previewed, printed, or its output is saved to a file.

Setting

  • ScaleLeft—A Single data type value used in a numeric expression to set the number of units for the horizontal coordinate of the left edge of a page. The default setting is 0.
  • ScaleTop—A Single data type value used in a numeric expression to set the number of units for the vertical coordinate of the top edge of a page. The default setting is 0.

You can set the ScaleLeft and ScaleTop properties only in a macro or a Visual Basic event procedure specified by a section’s OnPrint property setting.

Remarks

Using these properties and the related ScaleHeight and ScaleWidth properties, you can set up a full coordinate system with both positive and negative coordinates. These four scale properties interact with the ScaleMode property in the following ways:

  • Setting any other Scale property to any value automatically sets the ScaleMode property to 0.
  • Setting the ScaleMode property to a number greater than 0 changes ScaleHeight and ScaleWidth to the new unit of measurement and sets ScaleLeft and ScaleTop to 0. Also, the CurrentX and CurrentY property settings change to reflect the new coordinates of the current point.

You can also use the Scale method to set the ScaleHeight, ScaleWidth, ScaleLeft, and ScaleTop properties in one statement.

Note The ScaleLeft and ScaleTop properties aren’t the same as the Left and Top properties.

See Also

Circle Method; Event Properties; Line Method; PrintOut Method; PSet Method; Scale Method; ScaleHeight, ScaleWidth Properties; ScaleMode Property.


ScaleMode Property

Applies To

Report.

Description

You can use the ScaleMode property in Visual Basic to specify the unit of measurement for coordinates on a page when the Circle, Line, PSet, or Print method is used while a report is previewed or printed.

Setting

The ScaleMode property uses the following settings.

Setting | Description
0 | Indicates that one or more of the ScaleHeight, ScaleWidth, ScaleLeft, and ScaleTop properties are set to custom values
1 | (Default) Twip
2 | Point
3 | Pixel
4 | Character (horizontal = 120 twips per unit; vertical = 240 twips per unit)
5 | Inch
6 | Millimeter
7 | Centimeter

The property setting has an Integer data type value.

You can set the ScaleMode property only in a macro or a Visual Basic event procedure specified by a section’s OnPrint property setting.

Remarks

Using the related ScaleHeight, ScaleWidth, ScaleLeft, and ScaleTop properties, you can create a custom coordinate system with both positive and negative coordinates. These four Scale properties interact with the ScaleMode property in the following ways:

  • Setting any other Scale property to any value automatically sets the ScaleMode property to 0.
  • Setting the ScaleMode property to a number greater than 0 changes ScaleHeight and ScaleWidth to the new unit of measurement and sets ScaleLeft and ScaleTop to 0. The CurrentX and CurrentY property settings change to reflect the new coordinates of the current point.

See Also

Circle Method; CurrentX, CurrentY Properties; Event Properties; Line Method; PrintOut Method; PSet Method; Scale Method; ScaleHeight, ScaleWidth Properties; ScaleLeft, ScaleTop Properties.


ScaleTop Property

See ScaleLeft, ScaleTop Properties.


ScaleWidth Property

See ScaleHeight, ScaleWidth Properties.


Screen Object

Description

The Screen object refers to the particular form, report, or control that currently has the focus.

Remarks

You can use the Screen object together with its properties to refer to a particular form, report, or control that has the focus. For example, you can use the Screen object with the ActiveForm property to refer to the form in the active window without knowing the form’s name. The following example displays the name of the form in the active window.

MsgBox Screen.ActiveForm.Name

Referring to the Screen object doesn’t make a form, report, or control active. To make a form, report, or control active, you must use the SelectObject method of the DoCmd object.

If you refer to the Screen object when there is no active form, report, or control, Microsoft Access returns a run-time error. For example, if a standard module is in the active window, the code in the example above would return an error.

Properties
ActiveControl Property, ActiveForm Property, ActiveReport Property, PreviousControl Property.

See Also
Control Object, Form Object, Report Object, SelectObject Action.

Example
The following example uses the Screen object to print the name of the form in the active window and of the active control on that form.

Sub ActiveObjects()
    Dim frm As Form, ctl As Control

    ' Return Form object pointing to active form.
    Set frm = Screen.ActiveForm
    MsgBox frm.Name & " is the active form."
    ' Return Control object pointing to active control.
    Set ctl = Screen.ActiveControl
    MsgBox ctl.Name & " is the active control on this form."Sub


ScrollBars Property

Applies To

Form, Text Box Control.

Description

You can use the ScrollBars property to specify whether scroll bars appear on a form or in a text box control.

Setting

The ScrollBars property uses the following settings.

Setting | Description | Visual Basic
Neither | (Default for text boxes) No scroll bars appear on the form or text box. | 0
Horizontal Only | Horizontal scroll bar appears on the form. Not applicable to text boxes. | 1
Vertical Only | Vertical scroll bar appears on the form or text box. | 2
Both | (Default for forms) Vertical and horizontal scroll bars appear on the form. Not applicable to text boxes. | 3

You can set this property in the form or control’s property sheet or using a macro or Visual Basic.

For a text box, you can set this property using the default control style.

Remarks

If the your form is larger than the available display window, you can use the ScrollBars property to allow the user to view the entire form.

You can use the NavigationButtons property to control record navigation.

See Also

Modal Property, NavigationButtons Property, PopUp Property, RecordSelectors Property.


Second Function

Description

Returns a whole number between 0 and 59, inclusive, representing the second of the minute.

Syntax

Second(time)

The time argument is any numeric or string expression, or any combination, that can represent a time. If time contains Null, Null is returned.

See Also

Day Function, Hour Function, Minute Function, Now Function, Time Function, Time Statement.

Example

This example uses the Second function to obtain the second of the minute from a specified time. In the development environment, the time (date literal) is displayed in short time format using the locale settings of your code.

MyTime = #4:35:17 PM#                    ' Assign a time.= Second(MyTime)                ' MySecond contains 17.


Section Property

Applies To

Bound Object Frame Control, Chart Control, Check Box Control, Combo Box Control, Command Button Control, Form, Label Control, Line Control, List Box Control, Option Button Control, Option Group Control, Page Break Control, Rectangle Control, Report, Subform/Subreport Control, Text Box Control, Toggle Button Control, Unbound Object Frame Control.

Description

You can use the Section property to identify a section of a form or report and provide access to the properties of that section. You can also identify controls by the section of a form or report where the control appears.

Setting

The Section property is an Integer data type value corresponding to a particular section.

Setting | Description
0 | Form detail section or report detail section
1 | Form or report header section
2 | Form or report footer section
3 | Form or report page header section
4 | Form or report page footer section

Setting | Description
5 | Group-level 1 header section (reports only)
6 | Group-level 1 footer section (reports only)
7 | Group-level 2 header section (reports only)
8 | Group-level 2 footer section (reports only)

If a report has additional group-level sections, the header/footer pairs are numbered consecutively beginning with 9.

The Section property is read-only in all views.

For forms and reports, the Section property is an array of all existing sections in the form or report specified by the section number. For example, Section(0) refers to a form’s detail section and Section(3) refers to a form’s header section.

You can also refer to a section by name. The following statements refer to the Detail0 section for the Customers form and are equivalent.

Forms![Customers].Section(0).Visible![Customers].Detail0.Visible

Remarks

For forms and reports, you must combine the Section property with other properties that apply to form or report sections. The following example shows how to refer to the Visible property of the page header section of the Customers form.

Forms![Customers].Section(3).Visible

For controls, you can use the Section property to determine which section of a form or report a control is on. The following example uses the Section property to determine which section contains the CustomerID control.

Dim intSectionNumber As Integer= Forms![Customers]![CustomerID].Section

See Also

CanGrow, CanShrink Properties; Event Properties; FillColor Property; ForceNewPage Property; Height, Width Properties; KeepTogether Property—Sections; NewRowOrCol Property; SpecialEffect Property; Visible Property (Microsoft Access).


Seek Function

Description

Returns the current read/write position within a file opened using the Open statement.

Syntax

Seek(filenumber)

The filenumber argument is any valid file number.

Remarks

Seek returns a value between 1 and 2,147,483,647 (equivalent to 231 - 1), inclusive. For files open in Random mode, Seek returns the number of the next record read or written. For files opened in Binary, Output, Append, or Input mode, Seek returns the byte position at which the next operation is to take place. The first byte in a file is at position 1, the second byte is at position 2, and so on.

See Also

Get Statement, Open Statement, Put Statement, Seek Statement.

Example

This example uses the Seek function to return the current file position. The example assumes TESTFILE is a file containing records of the user-defined type Record.

Type Record    ' Define user-defined type.
    ID As Integer
    Name As String * 20Type

For files opened in random-file mode, Seek returns number of next record.

Dim MyRecord As Record    ' Declare variable."TESTFILE" For Random As #1 Len = Len(MyRecord)While Not EOF(1)    ' Loop until end of file.
    Get #1, , MyRecord    ' Read next record.
    Debug.Print Seek(1)    ' Print record number to Debug
                ' window.#1            ' Close file.

For files opened in modes other than Random mode, Seek returns the byte position at which the next operation takes place. Assume TESTFILE is a file containing a few lines of text.

Open "TESTFILE" For Input As #1        ' Open file for reading.While Not EOF(1)                    ' Loop until end of file.
    MyChar = Input(1, #1)            ' Read next character of data.
    Debug.Print Seek(1)                ' Print byte position to Debug
                                    ' window.#1                                ' Close file.


Seek Statement

Description

Sets the position for the next read or write within a file opened using the Open statement.

Syntax

Seek [#]filenumber, position

The Seek statement syntax has these parts:

Part | Description
filenumber | Any valid file number.
position | Number in the range 1 to 2,147,483,647, inclusive, that indicates where the next read or write should occur.

Remarks

Record numbers specified in Get and Put statements override file positioning performed by Seek.

Performing a file write after doing a Seek operation beyond the end of a file extends the file. If you attempt a Seek operation to a negative or zero position, an error occurs.

See Also

Get Statement, Open Statement, Put Statement, Seek Function.

Example

This example uses the Seek statement to set the position for the next read or write within a file. This example assumes TESTFILE is a file containing records of the user-defined type Record.

Type Record    ' Define user-defined type.
    ID As Integer
    Name As String * 20Type

For files opened in random-file mode, Seek sets the next record.

Dim MyRecord As Record    ' Declare variable.
' Open file in random-file mode."TESTFILE" For Random As #1 Len = Len(MyRecord)= LOF(1) \ Len(MyRecord)    ' Get number of records in file.
' The loop reads all records starting from the last.RecordNumber = MaxSize To 1 Step - 1
    Seek #1, RecordNumber    ' Set position.
    Get #1, , MyRecord    ' Read record.RecordNumber#1    ' Close file.

For files opened in modes other than Random mode, Seek sets the byte position at which the next operation will take place. Assume TESTFILE is a file containing a few lines of text.

Open "TESTFILE" For Input As #1            ' Open file for input.= LOF(1)                            ' Get size of file in bytes.
' The loop reads all characters starting from the last.NextChar = MaxSize To 1 Step -1
    Seek #1, NextChar                    ' Set position.
    MyChar = Input(1, #1)                ' Read character.NextChar#1                                    ' Close file.


Select Case Statement

Description

Executes one of several groups of statements, depending on the value of an expression.

Syntax

Select Case testexpression
[Case expressionlist-n
 [statements-n]] . . .
[Case Else
 [elsestatements]]
End Select

The Select Case statement syntax has these parts:

Part | Description
testexpression | Any numeric or string expression.
expressionlist-n | Delimited list of one or more of the following forms: expression, expression To expression, Is comparisonoperator expression. The To keyword specifies a range of values. If you use the To keyword, the smaller value must appear before To. Use the Is keyword with comparison operators (except Is and Like) to specify a range of values. If not supplied, the Is keyword is automatically inserted.
statements-n | One or more statements executed if testexpression matches any part of expressionlist-n.
elsestatements | One or more statements executed if testexpression doesn’t match any of the Case clause.

Remarks

If testexpression matches any expressionlist expression associated with a Case clause, the statements following that Case clause are executed up to the next Case clause, or, for the last clause, up to the End Select. Control then passes to the statement following End Select. If testexpression matches an expressionlist expression in more than one Case clause, only the statements following the first match are executed.

The Case Else clause is used to indicate the statements to be executed if no match is found between the testexpression and an expressionlist in any of the other Case selections. When there is no Case Else statement and no expression listed in the Case clauses matches testexpression, execution continues at the statement following End Select.

Although not required, it is a good idea to have a Case Else statement in your Select Case block to handle unforeseen testexpression values.

You can use multiple expressions or ranges in each Case clause. For example, the following line is valid:

Case 1 To 4, 7 To 9, 11, 13, Is > MaxNumber

Note The Is comparison operator is not the same as the Is keyword used in the Select Case statement.

You also can specify ranges and multiple expressions for character strings. In the following example, Case matches strings that are exactly equal to everything, strings that fall between nuts and soup in alphabetical order, and the current value of TestItem:

Case "everything", "nuts" To "soup", TestItem

Select Case statements can be nested. Each Select Case statement must have a matching End Select statement.

See Also

If...Then...Else Statement; On...GoSub, On...GoTo Statements.

Example

This example uses the Select Case statement to evaluate the value of a variable. The second Case clause contains the value of the variable being evaluated, and therefore only the statement associated with it is executed.

Number = 8                    ' Initialize variable.Case Number            ' Evaluate Number.1 To 5                    ' Number between 1 and 5.
    Debug.Print "Between 1 and 5"
' The following is the only Case clause that evaluates to True.6, 7, 8                    ' Number between 6 and 8.
    Debug.Print "Between 6 and 8"Is > 8 And Number < 11    ' Number is 9 or 10..Print "Greater than 8"Else                    ' Other values.
    Debug.Print "Not between 1 and 10"Select


Selected Property

Applies To

List Box Control.

Description

You can use the Selected property in Visual Basic to determine if an item in a list box is selected.

Setting

The Selected property is a zero based array of all the items in a list box that contains the selected state of each item in the list.

Setting | Description
True (-1) | The list box item is selected.
False (0) | The list box item isn’t selected.

You can get or set the Selected property using Visual Basic.

This property is available only at run time.

Remarks

When a list box control’s MultiSelect property is set to None, only one item can have its Selected property set to True. When a list box control’s MultiSelect Property is set to Simple or Extended, any or all of the items can have their Selected property set to True.

You can use the Selected property to select items in a list box using Visual Basic. For example, the following expression selects the fifth item in the list.

Me!Listbox.Selected(4) = True

See Also

Column Property, ItemsSelected Collection, ListIndex Property, MultiSelect Property.

Example

The following example uses the Selected property to move selected items in the lstSource list box to the lstDestination list box. The lstDestination list box’s RowSourceType property is set to Value List and the control’s RowSource property is constructed from all the selected items in the lstSource control. The lstSource list box’s MultiSelect property is set to Extended. The CopySelected( ) function is called from the cmdCopyItems command button.

Sub cmdCopyItem_Click()
    CopySelected MeSub
CopySelected(frm As Form) As Integer
    Dim ctlSource As Control
    Dim ctlDest As Control
    Dim strItems As String
    Dim intCurrentRow As Integer
    Set ctlSource = frm!lstSource
    Set ctlDest = frm!lstDestination
    For intCurrentRow = 0 To ctlSource.Listcount - 1
        If ctlSource.Selected(intCurrentRow) = True Then
            strItems = strItems & ctlSource.Column(0, intCurrentRow) _
                & ";"
        End If
    Next intCurrentRow
    ' Reset destination control's RowSource.
    ctlDest.RowSource = ""
    ctlDest.RowSource = strItemsFunction


SelectObject Action

Description

You can use the SelectObject action to select a specified database object.

Setting

The SelectObject action uses the following arguments.

Action argument | Description
Object Type | The type of database object to select. Click Table, Query, Form, Report, Macro, or Module from the Object Type box in the Action Arguments section of the Macro window. This is a required argument.
Object Name | The name of the object to select. The Object Name box shows all objects in the database of the type selected by the Object Type box. This is a required argument.
In Database Window | Determines whether Microsoft Access selects the object in the Database window. Click Yes to select the object or No not to select the object in the Database window. The default is No.

Remarks

The SelectObject action works with any Microsoft Access object that can receive the focus. This action gives the specified object the focus and shows the object if it is hidden. If the object is a form, the SelectObject action sets the form’s Visible property to Yes and returns the form to the mode set by its form properties (for example, as a modal or pop-up form).

If the object isn’t open in one of the other Microsoft Access windows, you can select it in the Database window by setting the In Database Window argument to Yes. If you set the In Database Window argument to No, an error message appears when you try to select an object that isn’t open.

Often, you might use this action to select an object on which you want to perform additional actions. For example, you may want to restore an object that has been minimized (using the Restore action) or maximize a window that contains an object you want to work with (using the Maximize action).

If you select a form, you can use the GoToControl, GoToRecord, and GoToPage actions to move to specific areas on the form. The GoToRecord action also works for datasheets.

To run the SelectObject action in Visual Basic, use the SelectObject method of the DoCmd object.

See Also

Restore Action, SelectObject Method, SetValue Action.


SelectObject Method

Description

The SelectObject method carries out the SelectObject action in Visual Basic. For more information on how the action and its arguments work, see the action topic.

Syntax

DoCmd.SelectObject objecttype, objectname [, indatabasewindow]

The SelectObject method uses the following arguments.

Argument | Description
objecttype | One of the following intrinsic constants: acTable acQuery acForm acReport acMacro acModule

Argument | Description
objectname | A string expression that is the valid name of an object of the type selected with the objecttype argument.
indatabasewindow | Use True (-1) to select the object in the Database window. Use False (0) to select an object that is already open. If you leave this argument blank, the default (False) is assumed.

Remarks

If you leave the indatabasewindow argument blank, don’t use a comma following the objectname argument.

Example

This example selects the form Customers in the Database window.

DoCmd.SelectObject acForm, "Customers", True


SelHeight, SelWidth Properties

Applies To

Query, Table.

Description

You can use the SelHeight property to specify or determine the number of selected rows (records) in the current selection rectangle. You can use the SelWidth property to specify or determine the number of selected columns (fields) in the current selection rectangle. For example, if you have selected a group of rows and columns within Datasheet view of the Customers table, you can use the SelHeight and SelWidth properties to determine the number of rows and columns in the selection rectangle.

Setting

  • SelHeight — a Long Integer value between 0 and the number of selected rows in the selection rectangle.
  • SelWidth — a Long Integer value between 0 and the number of selected columns in the selection rectangle.

These properties are not available in Design view. These properties are only available in Visual Basic.

Remarks

If there is no selection, the value returned by these properties will be zero.

You can use these properties with the SelTop and SelLeft properties to specify or determine the actual position of the selection rectangle on the datasheet. If there is no selection, then these properties return the row number and column number of the cell with the focus.

The SelHeight and SelWidth properties contain the position of the lower-right corner of the selection rectangle. The SelTop and SelLeft property values determine the upper-left corner of the selection rectangle. If there is no selection, then the SelHeight and SelWidth properties are set to zero.

See Also

SelTop, SelLeft Properties.

Example

The following example shows how to use the SelHeight, SelWidth, SelTop, and SelLeft properties to determine the position and size of a selection rectangle in datasheet view. The SetHeightWidth procedure assigns the height and width of the current selection rectangle to the variables lngHeight, lngWidth, lngTop, and lngLeft and displays those values in a message box.

Sub SetHeightWidth(frm As Form)
    Dim lngNumRows As Long, lngNumColumns As Long
    Dim lngTopRow As Long, lngLeftColumn As Long
    Dim strMsg As String
    If frm.CurrentView = 2 Then            ' Form is in Datasheet view.
        lngNumRows = frm.SelHeight        ' Number of rows selected.
        lngNumColumns = frm.SelWidth        ' Number of columns selected.
        lngTopRow = frm.SelTop    ' Topmost row selected.
        lngLeftColumn = frm.SelLeft        ' Leftmost column selected.
        strMsg = "Number of rows: " & lngNumRows & vbCrLf
        strMsg = strMsg & "Number of columns: " & lngNumColumns & vbCrLf
        strMsg = strMsg & "Top row: " & lngTopRow & vbCrLf
        strMsg = strMsg & "Left column: " & lngLeftColumn
        MsgBox strMsg
    End IfSub


SelLeft Property

See SelTop, SelLeft Properties.


SelLength, SelStart, SelText Properties

Applies To

Combo Box Control, Text Box Control.

Description

You can use these properties for tasks such as positioning the insertion point, establishing an insertion range, selecting parts of strings in a control, and deleting text.

  • SelLength — You can use this property to specify or determine the number of characters selected in a text box control or the text box portion of a combo box.
  • SelStart — You can use this property to specify or determine the starting point of the selected text or the position of the insertion point if no text is selected.
  • SelText — You can use this property to specify or determine the string containing the selected text or a zero-length string ("") if no characters are selected.

Setting

  • SelLength, SelStart — An integer in the range 0 to the total number of characters in the control or text box portion of the combo box.
  • SelText — A string expression that equal to the text selected in the control.

You can set the SelLength and SelStart properties using only a macro or Visual Basic. The SelText property is read-only.

Remarks

To set or return these properties for a control, the control must have the focus (to move the focus to a control, you can use the SetFocus method).

Setting the SelLength property to a number less than 0 produces a run-time error.

Setting the SelStart property to a number greater than the number of characters in the control sets the property to the existing text length.

Changing the SelStart property cancels the selection, places an insertion point in the text, and sets the SelLength property to 0.

See Also

SetFocus Method, Text Property.

Example

The following example uses two event procedures to search for text specified by a user. The text to search through is set in the form’s Load event procedure. The Click event procedure for the Find button (which the user chooses to start the search) prompts the user for the text to search for and selects the text in the text box if the search is successful.

Sub Form_Load()
    Dim ctlTextToSearch As Control
        Set ctlTextToSearch = Forms![Form1]![TextBox1]
        ctlTextToSearch.SetFocus          ' Move focus to text box.
        ctlTextToSearch.Text = _
            "This company places large orders twice a year for"
        ctlTextToSearch.Text = ctlTextToSearch.Text _
            & " garlic, oregano, chilies and cumin."Sub
Find_Click()
    Dim strSearch As String, intWhere As Integer
    Dim ctlTextToSearch As Control
    ' Get search string from user.
    Set ctlTextToSearch = Forms![Form1]![TextBox1]
        ' Move focus to text box.
        ctlTextToSearch.SetFocus
        strSearch = InputBox ("Enter text to be found:")
        ' Find string in text.
        intWhere = InStr (ctlTextToSearch.Text, strSearch)
        If intWhere Then                                   ' If found.
            ctlTextToSearch.SelStart = intWhere - 1       ' Set SelStart.
            ctlTextToSearch.SelLength = Len(strSearch)  ' Set SelLength.
        Else
            MsgBox "String not found."                   ' Notify user.
        End IfSub


SelTop, SelLeft Properties

Applies To

Query, Table.

Description

You can use the SelTop property to specify or determine which row (record) is topmost in the current selection rectangle. You can use the SelLeft property to specify or determine which column (field) is leftmost in the current selection rectangle. For example, if you have selected a group of rows and columns within Datasheet view of the Customer table, you can use the SelTop and SelLeft properties to determine the first row and first column selected in the selection rectangle.

Setting

  • SelTop — a Long Integer value between 0 and the number of the topmost row in the current selection rectangle.
  • SelLeft — a Long Integer value between 0 and the number of the leftmost column in the current selection rectangle.

These properties are not available in Design view. These properties are available only in Visual Basic.

Remarks

If there is no selection, the value returned by these properties is the row and column of the cell with the focus.

You can use these properties with the SelHeight and SelWidth properties to specify or determine the actual size of the selection rectangle. The SelTop and SelLeft properties determine the position of the upper-left corner of the selection rectangle. The SelHeight and SelWidth properties determine the lower-right corner of the selection rectangle.

See Also

SelHeight, SelWidth Properties.

Example

See the SelHeight, SelWidth properties example.


SelWidth Property

See SelHeight, SelWidth Properties.


SendKeys Action

Description

You can use the SendKeys action to send keystrokes directly to Microsoft Access or to an active Microsoft Windows-based application.

Setting

The SendKeys action uses the following arguments.

Action argument | Description
Keystrokes | The keystrokes you want Microsoft Access or the application to process. You can type up to 256 characters. This is a required argument.
Wait | Specifies whether the macro should pause until the keystrokes have been processed. Click Yes to pause or No not to pause. The default is No.

Remarks

Microsoft Access processes the keystrokes it receives through the SendKeys action exactly as if you had typed them directly in a Microsoft Access window.

To specify the keystrokes, use the same syntax as the SendKeys statement.

You can use this action to enter information in a dialog box, particularly if you don’t want to interrupt the macro to respond manually to the dialog box. Some Microsoft Access actions, such as Print and FindRecord, automatically select the options in certain frequently used dialog boxes. You can use the SendKeys action to select the options in less commonly used dialog boxes.

Notes

  • Because the dialog box suspends the macro, you must put the SendKeys action before the action that causes the dialog box to open and set the Wait argument to No to avoid breaks in the processing.
  • The timing of the keystrokes reaching Microsoft Access or another application can be tricky. As a result, it’s recommended that if there is some other method (such as the FindRecord action) you can use to achieve a desired task, use that method rather than using the SendKeys action to fill in the options in a dialog box.

If you want to send more than 256 characters to Microsoft Access or another Windows-based application, you can use several SendKeys actions in succession in a macro.

Using the SendKeys action to send keystrokes triggers the appropriate KeyDown, KeyUp, and KeyPress events. Sending non-ANSI keystrokes (such as a function key) doesn’t trigger the KeyPress event.

This action isn’t available from Visual Basic. Use the SendKeys statement instead.

See Also

GoToControl Action; KeyDown, KeyUp Events; KeyPress Event; SelectObject Action; SendKeys Statement; SetValue Action.


SendKeys Statement

Description

Sends one or more keystrokes to the active window as if typed at the keyboard.

Syntax

SendKeys string[, wait]

The SendKeys statement syntax has these named arguments :

Part | Description
string | String expression specifying the keystroke(s) to send.
wait | Boolean value specifying the wait mode. If False (default), control is returned to the procedure immediately after the keys are sent. If True, keystrokes must be processed before control is returned to the procedure.

Remarks

Each key is represented by one or more characters. To specify a single keyboard character, use the character itself. For example, to represent the letter A, use "A" for string. If you want to represent more than one character, append each additional character to the one preceding it. To represent the letters A, B, and C, use "ABC" for string.

The plus sign (+), caret (^), percent sign (%), tilde (~), and parentheses ( ) have special meanings to SendKeys. To specify one of these characters, enclose it within braces. For example, to specify the plus sign, use {+}. Brackets ([ ]) have no special meaning to SendKeys, but you must enclose them in braces as well, because in other applications, brackets do have a special meaning that may be significant when dynamic data exchange (DDE) occurs. To send brace characters, use {{} and {}}.

To specify characters that aren’t displayed when you press a key (such as ENTER or TAB) and keys that represent actions rather than characters, use the codes shown below:

Key | Code
BACKSPACE | {BACKSPACE}, {BS}, or {BKSP}
BREAK | {BREAK}
CAPS LOCK | {CAPSLOCK}
DEL | {DELETE} or {DEL}
DOWN ARROW | {DOWN}
END | {END}
ENTER | {ENTER}
ENTER | {~}
ESC | {ESC}
HELP | {HELP}
HOME | {HOME}
INS | {INSERT}
LEFT ARROW | {LEFT}
NUM LOCK | {NUMLOCK}
PAGE DOWN | {PGDN}
PAGE UP | {PGUP}
PRINT SCREEN | {PRTSC}
RIGHT ARROW | {RIGHT}
SCROLL LOCK | {SCROLLLOCK}
TAB | {TAB}
UP ARROW | {UP}

Key | Code
F1 | {F1}
F2 | {F2}
F3 | {F3}
F4 | {F4}
F5 | {F5}
F6 | {F6}
F7 | {F7}
F8 | {F8}
F9 | {F9}
F10 | {F10}
F11 | {F11}
F12 | {F12}
F13 | {F13}
F14 | {F14}
F15 | {F15}
F16 | {F16}

To specify keys combined with any combination of the SHIFT, CTRL, and ALT keys, precede the regular key code with one or more of the following codes:

Key | Code
SHIFT | +
CTRL (CONTROL) | ^
ALT | %

To specify that any combination of SHIFT, CTRL, and ALT should be held down while several other keys are pressed, enclose the code for those keys in parentheses. For example, to specify to hold down SHIFT while E and C are pressed, use “+(EC)”. To specify to hold down SHIFT while E is pressed, followed by C without SHIFT, use “+EC”.

To specify repeating keys, use the form {key number}. You must put a space between key and number. For example, {LEFT 42} means press the LEFT ARROW key 42 times; {h 10} means press h 10 times.

Note SendKeys can’t send keystrokes to an application that is not designed to run in Microsoft Windows. SendKeys also can’t send the PRINT SCREEN (PRTSC) key to any application.

See Also

AppActivate Statement, DoEvents Function.

Example

This example uses the Shell function to run the Calculator application included with Microsoft Windows; it then uses the SendKeys statement to send keystrokes to add some numbers and then quit the Calculator. The SendKeys statement is not available on the Macintosh. (To see the example, paste it into a procedure, then run the procedure. Because AppActivate changes the focus to the Calculator application, you can’t single step through the code.)

ReturnValue = Shell("CALC.EXE", 1)    ' Run Calculator.ReturnValue                 ' Activate the Calculator.I = 1 To 100                        ' Set up counting loop.
    SendKeys I & "{+}", True            ' Send keystrokes to CalculatorI                                ' to add each value of I."=", True                    ' Get grand total."%{F4}", True                ' Send ALT+F4 to close Calculator.


SendObject Action

Description

You can use the SendObject action to include the specified Microsoft Access datasheet, form, report, or module in an electronic mail message, where it can be viewed and forwarded. You can include objects in Microsoft Excel (.xls) version 7.0, rich-text (.rtf), or MS-DOS Text (.txt) format in messages for Microsoft Mail, Microsoft Windows for Workgroups mail, or another electronic mail application that uses the Microsoft Mail Applications Programming Interface (MAPI). If you have an electronic mail application that uses the Vendor Independent Mail (VIM) protocol and have installed and set up the dynamic-link library (Mapivim.dll) that converts MAPI mail messages to the VIM protocol, you can send Microsoft Access objects to the VIM mail application.

Setting

The SendObject action uses the following arguments.

Action argument | Description
Object Type | The type of object to include in the mail message. Click Table (for a table datasheet), Query (for a query datasheet), Form (for a form or form datasheet), Report, or Module in the Object Type box in the Action Arguments section of the Macro window. You can’t send a macro. If you want to include the active object, select its type by this argument, but leave the Object Name box blank. The default is Table.

Object Name | The name of the object to include in the mail message. The Object Name box shows all objects in the database of the type selected by the Object Type argument. If you leave both the Object Type and Object Name boxes blank, Microsoft Access sends a message to the mail application without any database object.
 | If you run a macro containing the SendObject action in a library database, Microsoft Access looks for the object with this name first in the library database, then in the current database.
OutputFormat | The type of format you want used for the included object. You can click Microsoft Excel (*.xls), Rich Text Format (*.rtf), or MS-DOS Text (*.txt) in the Output Format box. Modules can be sent only in MS-DOS Text format. If you leave this box blank, Microsoft Access prompts you for the output format.
To | The recipients of the message whose names you want to put on the To line in the mail message. If you leave this argument blank, Microsoft Access prompts you for the recipients’ names. Separate the recipients’ names you specify in this argument and in the Cc and Bcc arguments with a semicolon (;) or with the list separator set in the Number tab of the Regional Settings properties sheet in the Windows Control Panel. If Microsoft Access can’t identify the recipients’ names, it doesn’t send the message.
Cc | The recipients of the message whose names you want to put on the Cc (“carbon copy”) line in the mail message. If you leave this box blank, the Cc line in the mail message is blank.
Bcc | The recipients of the message whose names you want to put on the Bcc (“blind carbon copy”) line in the mail message. If you leave this box blank, the Bcc line in the mail message is blank.
Subject | The subject of the message. This text appears on the Subject line in the mail message. If you leave this box blank, the Subject line in the mail message is blank.

Message Text | Any text you want to include in the message in addition to the database object. This text appears in the main body of the mail message, after the object. If you leave this box blank, no additional text is included in the mail message. If you leave the Object Type and Object Name boxes blank, you can use this argument to send a mail message without a database object.
Edit Message | The indicator whether the message can be edited before it’s sent. If you select Yes, the electronic mail application starts automatically, and the message can be edited. If you select No, the message is sent without providing a chance to edit the message. The default is No.

Remarks

The SendObject action is available only if you have a MAPI-compliant electronic mail application installed on your computer, or if you have a VIM-compliant electronic mail application and have installed and set up Mapivim.dll. For information on how to install and set up Microsoft Access support for VIM mail applications, see the Microsoft Office Resource Kit.

The object in the mail message is in the selected output format. When you double-click the object, the appropriate application starts with the object opened. The application for each type of output format is Microsoft Excel (for .xls files), Microsoft Word for Windows (for .rtf files), and Microsoft Windows Notepad (for .txt files).

The following rules apply when you use the SendObject action to include a database object in a mail message:

  • You can send table, query, and form datasheets. In the included object, all fields in the datasheet look as they do in Microsoft Access, except fields containing OLE objects. The columns for these fields are included in the object, but the fields are blank.
  • For a control bound to a Yes/No field (a toggle button, option button, or check box), the output file displays the value -1 (Yes) or 0 (No).
  • If you send a form in Form view, the included object always contains the form’s Datasheet view.
  • If you send a report, the only controls that are included in the object are text boxes (for .xls files), or text boxes and labels (for .rtf and .txt files). All other controls are ignored. Header and footer information is also not included. The only exception to this is that when you send a report in Microsoft Excel format, a text box in a group footer containing an expression using the Sum function is included in the object. No other control in a header or footer (and no aggregate function other than Sum) is included in the object.
  • Subreports are included in the object (for any of the output formats), but subforms aren’t.

If you send the data in a report and the columns and rows of data in the included object do not align as in the report, the following tips may help:

  • You can point to Size on the Format menu, then click To Fit to size the controls.
  • You can avoid overlapping controls or placing controls too close together.
  • You can point to Align on the Format menu, then click the appropriate command to align the controls on the report. Controls that are not aligned in the same row may be placed in separate rows, causing additional spacing.

The SendObject action has the same effect as clicking Send on the File menu, and the action arguments correspond to the settings in the Send dialog boxes.

Note The Send command applies only to the active object. If you use the SendObject action, you can specify the object you want to send.

To run the SendObject action in Visual Basic, use the SendObject method of the DoCmd object.

See Also

OutputTo Action, SendObject Method.


SendObject Method

Applies To

DoCmd Object.

Description

The SendObject method carries out the SendObject action in Visual Basic. For more information on how the action and its arguments work, see the action topic.

Syntax

DoCmd.SendObject [objecttype] [, objectname] [, outputformat] [, to] [, cc] [,bcc] [, subject] [, messagetext] [, editmessage]

The SendObject method uses the following arguments.

Argument | Description
objecttype | One of the following intrinsic constants: acQuery acForm acReport acModule
objectname | A string expression that is the valid name of an object of the type selected with the objecttype argument. If you want to include the active object in the mail message, specify the object’s type with the objecttype argument and leave this argument blank. If you leave both the objecttype and objectname arguments blank, Microsoft Access sends a message to the electronic mail application without a database object. If you execute Visual Basic code containing the SendObject method in a library database, Microsoft Access looks for the object with this name first in the library database, then in the current database.
outputformat | One of the following intrinsic constants: acFormatXLS acFormatRTF acFormatTXT If you leave this argument blank, Microsoft Access prompts you for the output format.
to | A string expression that lists the recipients whose names you want to put on the To line in the mail message. Separate the recipient names you specify in this argument and in the cc and bcc arguments with a semicolon (;) or with the list separator set in the Number tab of the Regional Settings properties sheet in the Windows Control Panel. If Microsoft Access can’t identify the recipient names, it doesn’t send the message. If you leave this argument blank, Microsoft Access prompts you for the recipients.
cc | A string expression that lists the recipients whose names you want to put on the Cc line in the mail message. If you leave this argument blank, the Cc line in the mail message is blank.
bcc | A string expression that lists the recipients whose names you want to put on the Bcc line in the mail message. If you leave this argument blank, the Bcc line in the mail message is blank.
subject | A string expression containing the text you want to put on the Subject line in the mail message. If you leave this argument blank, the Subject line in the mail message is blank.

messagetext | A string expression containing the text you want to include in the body of the mail message, after the object. If you leave this argument blank, the object is all that is included in the body of the mail message.
editmessage | Use True (-1) to open the electronic mail application immediately with the message loaded, so the message can be edited. Use False (0) to send the message without editing it. If you leave this argument blank, the default (True) is assumed.

Remarks

Modules can be sent only in MS-DOS Text format, so if you specify acModule for the objecttype argument, you must specify acFormatTXT for the outputformat argument.

You can leave an optional argument blank in the middle of the syntax, but you must include the argument’s comma. If you leave a trailing argument blank, don’t use a comma following the last argument you specify.

See Also

DoCmd Object, OutputTo Method.

Example

This example includes the Employees table in a mail message in Microsoft Excel format and specifies To, Cc, and Subject lines in the mail message. The mail message is sent immediately, without editing.

DoCmd.SendObject acTable, "Employees", acFormatXLS, _
    "Nancy Davolio; Andrew Fuller", "Joan Weber", , _
    "Current Spreadsheet of Employees", , False


Set Statement

Description

Assigns an object reference to a variable or property.

Syntax

Set objectvar = {[New] objectexpression | Nothing}

The Set statement syntax has these parts:

Part | Description
objectvar | Name of the variable or property; follows standard variable naming conventions.
New | Keyword used to create a new instance of a Visual Basic object or an externally creatable OLE Automation object. The New keyword can’t be used to create new instances of any intrinsic data type and can’t be used to create dependent OLE Automation objects.
objectexpression | Expression consisting of the name of an object, another declared variable of the same object type, or a function or method that returns an object of the same object type.
Nothing | Discontinues association of objectvar with any specific object. Assigning objectvar to Nothing releases all the system and memory resources associated with the previously referenced object when no other variable refers to it.

Remarks

To be valid, objectvar must be an object type consistent with the object being assigned to it.

The Dim, Private, Public, ReDim, and Static statements only declare a variable that refers to an object. No actual object is referred to until you use the Set statement to assign a specific object.

The following example illustrates how Dim is used to formally declare the variable MyDatabase as Database. No instance of Database actually exists. Set then assigns a reference to a new instance of Database to the MyDatabase variable.

Dim MyDatabase As DatabaseMyDatabase = New Database

Generally, when you use Set to assign an object reference to a variable, no copy of the object is created for that variable. Instead, a reference to the object is created. More than one object variable can refer to the same object. Because these variables are references to (rather than copies of) the object, any change in the object is reflected in all variables that refer to it.

However, when you use the New keyword in the Set statement, you are actually creating an instance of the object. The new instance is not loaded until the first reference is made to it or one of the object’s members.

See Also

Dim Statement, Let Statement, Private Statement, Public Statement, ReDim Statement, Static Statement.

Example

This example uses the Set statement to assign object references to variables. YourObject is assumed to be a valid object with a Text property.

Set MyObject = YourObject            ' Assign object reference.
' MyObject and YourObject refer to the same object..Text = "Hello World"        ' Initialize property.= MyObject.Text                ' Returns "Hello World".
' Discontinue association. MyObject no longer refers to YourObject.MyObject = Nothing                ' Release the object.


SetAttr Statement

Description

Sets attribute information for a file.

Syntax

SetAttr pathname, attributes

The SetAttr statement syntax has these named arguments:

Part | Description
pathname | String expression that specifies a filename — may include directory or folder, and drive.
attributes | Constant or numeric expression, the sum of which specifies file attributes.

Settings

The attributes argument settings are:

Constant | Value | Description
vbNormal | 0 | Normal (default).
vbReadOnly | 1 | Read-only.
vbHidden | 2 | Hidden.
vbSystem | 4 | System file.
vbArchive | 32 | File has changed since last backup.

Note These constants are specified by Visual Basic for applications. As a result, the names can be used anywhere in your code in place of the actual values.

Remarks

A run-time error occurs if you try to set the attributes of an open file.

See Also

FileAttr Function, GetAttr Function.

Example

This example uses the SetAttr statement to set attributes for a file.

SetAttr "TESTFILE", vbHidden                    ' Set hidden attribute."TESTFILE", vbHidden + vbReadOnly    ' Set hidden and read-only
                                            ' attributes.


SetFocus Method

Applies To

Bound Object Frame Control, Chart Control, Check Box Control, Combo Box Control, Command Button Control, Form, Label Control, List Box Control, Option Button Control, Option Group Control, Subform/Subreport Control, Text Box Control, Toggle Button Control, Unbound Object Frame Control.

Description

The SetFocus method moves the focus to the specified form, the specified control on the active form, or the specified field on the active datasheet.

Syntax

object.SetFocus

The SetFocus method uses the following argument.

Argument | Description
object | A Form object that represents a form, or a Control object that represents a control on the active form or datasheet

Remarks

Use the SetFocus method when you want a particular field or control to have the focus so that all user input is directed to this object.

In order to read some of the properties of a control, you need to ensure that that control has the focus. For example, a text box must have the focus before you can read its Text property.

Other properties can be set only when a control doesn’t have the focus. For example, you can’t set a control’s Visible or Locked properties to False when that control has the focus.

You can also use the SetFocus method to navigate in a form according to certain conditions. For example, if the user selects Not Applicable for the first of a set of questions on a form that is a questionnaire, your Visual Basic code might then automatically skip the questions in that set and move the focus to the first control in the next set of questions.

You can move the focus only to a visible control or form. A form and controls on a form aren’t visible until the form’s Load event has finished. Therefore, if you use the SetFocus method in a form’s Load event to move the focus to that form, you must use the Repaint method before the SetFocus method.

You can’t move the focus to a control if its Enabled property is set to False. You must set a control’s Enabled property to True before you can move the focus to that control. You can, however, move the focus to a control if its Locked property is set to True.

If a form contains controls for which the Enabled property is set to True, you can’t move the focus to the form itself. You can only move the focus to controls on the form. In this case, if you try to use SetFocus to move the focus to a form, the focus is set to the control on the form that last received the focus.

Tip You can use the SetFocus method to move the focus to a subform, which is a type of control. You can also move the focus to a control on a subform by using the SetFocus method twice, moving the focus first to the subform and then to the control on the subform.

See Also

Control Object; Form Object; GotFocus, LostFocus Events; GoToControl Action; SelectObject Action.

Example

The following example uses the SetFocus method to move the focus to an EmployeeID text box on an Employees form.

Dim ctlText As ControlctlText = Forms!Employees!EmployeeID.SetFocus


SetMenuItem Action

Description

You can use the SetMenuItem action to set the state of menu items (enabled or disabled, checked or unchecked) on the custom menu bar or global menu bar for the active window.

Setting

The SetMenuItem action uses the following arguments.

Action argument | Description
Menu Index | The index of the menu that contains the command for which you want to set the state. Enter an Integer value, starting from 0, for the index of the desired menu in the custom menu bar or global menu bar for the active window. The index is relative to the menu’s position in the menu bar macro for the custom menu bar or global menu bar (the position of this menu’s AddMenu action in the menu bar macro, counting from 0). The menu bar’s display may be somewhat different, since you can use conditional expressions in the menu bar macro to hide or display custom menu items. This is a required argument. If you select a menu with this argument and leave the Command Index and Subcommand Index arguments blank, you can enable or disable the menu name itself. You can’t, however, check or uncheck a menu name (Microsoft Access ignores the Check and Uncheck settings for the Flag argument for menu names).
Command Index | The index of the command for which you want to set the state. Enter an Integer value, starting from 0, for the index of the desired command in the menu selected with the Menu Index argument. The index is relative to the command’s position in the macro group that defines the selected menu for the custom menu bar or global menu bar (the position of this command’s macro in the macro group, counting from 0). The menu’s display may be somewhat different, since you can use conditional expressions in the menu’s macro group to hide or display custom menu commands.
Subcommand Index | The index of the subcommand for which you want to set the state. This applies only if the desired command has a submenu. Enter an Integer value, starting from 0, for the index of the desired subcommand in the submenu selected with the Command Index argument. The index is relative to the subcommand’s position in the macro group that defines the selected submenu for the custom menu bar or global menu bar (the position of this subcommand’s macro in the macro group, counting from 0).
Flag | The state you want to set the command or subcommand to. You can select Gray to disable the command (so it appears dimmed), Ungray to enable it, Check to place a check by the command (typically indicating it has been selected or toggled), or Uncheck to remove the check. The default is Ungray.

Remarks

The SetMenuItem action works only on a custom menu bar or global menu bar for the active window. It does not work on the built-in Microsoft Access menu bars, and if the active window does not have a custom menu bar or global menu bar, running a macro containing the SetMenuItem action causes a run-time error. Note that a global menu bar, if you have defined one, replaces the built-in menu bar for all Microsoft Access windows, except where you have added a custom menu bar for a form or report.

You can use this action to set the state of menu commands and subcommands, but not subcommands of subcommands.

You can use the SetMenuItem action to temporarily set the state of a Microsoft Access menu command (put into the custom menu using the DoMenuItem action). However, as soon as Microsoft Access refreshes the menu, the command returns to its normal state. For example, if you use the SetMenuItem action to disable a custom menu command that maps to the Cut command on the Edit menu, the command is automatically enabled again when you select a piece of text.

To run the SetMenuItem action in Visual Basic, use the SetMenuItem method of the DoCmd object.

See Also

AddMenu Action, DoMenuItem Action, MenuBar Property, SetMenuItem Method.


SetMenuItem Method

Applies To

DoCmd Object.

Description

The SetMenuItem method carries out the SetMenuItem action in Visual Basic. For more information on how the action and its arguments work, see the action topic.

Syntax

DoCmd.SetMenuItem menuindex [, commandindex] [, subcommandindex] [,flag]

The SetMenuItem method uses the following arguments.

Argument | Description
menuindex | An integer, counting from 0, that is the valid index of a menu on the custom menu bar or global menu bar for the active window, as defined in the menu bar macro for the custom menu bar or global menu bar. If you select a menu with this argument and leave the commandindex and subcommandindex arguments blank (or set them to -1), you can enable or disable the menu name itself. You can’t, however, check or uncheck a menu name (Microsoft Access ignores the acMenuCheck and acMenuUncheck settings for the flag argument for menu names).
commandindex | An integer, counting from 0, that is the valid index of a command on the menu selected with the menuindex argument, as defined in the macro group that defines the selected menu for the custom menu bar or global menu bar for the active window.
subcommandindex | An integer, counting from 0, that is the valid index of a subcommand in the submenu selected with the commandindex argument, as defined in the macro group that defines the selected submenu for the custom menu bar or global menu bar for the active window.
flag | One of the following intrinsic constants: acMenuUngray acMenuGray acMenuUncheck acMenuCheck If you leave this argument blank, the default (acMenuUngray) is assumed.

Remarks

You can leave an optional argument blank in the middle of the syntax, but you must include the argument’s comma. If you leave a trailing argument blank, don’t use a comma following the last argument you specify.

See Also

AddMenu Action, DoCmd Object, DoMenuItem Method, MenuBar Property, SetMenuItem Action.

Example

This example uses the SetMenuItem method to disable the second command in the first menu on the custom menu bar for the active window.

DoCmd.SetMenuItem 0, 1, , acMenuGray


SetOption Method

See GetOption, SetOption Methods.


SetValue Action

Description

You can use the SetValue action to set the value of a Microsoft Access field, control, or property on a form, a form datasheet, or a report.

Setting

The SetValue action uses the following arguments.

Action argument | Description
Item | The name of the field, control, or property whose value you want to set. You must use the full syntax to refer to this item, such as controlname (for a control on the form or report from which the macro was called) or Forms!formname!controlname. This is a required argument.
Expression | The expression Microsoft Access uses to set the value for this item. You must always use the full syntax to refer to any objects in the expression. For example, to increase the value in a Salary control on an Employees form by 10 percent, use Forms!Employees!Salary*1.1. This is a required argument.
 | Note You shouldn’t use an equal sign (=) before the expression in this argument. If you do, Microsoft Access evaluates the expression and then uses this value as the expression in this argument. This can produce unexpected results if the expression is a string. For example, if you type ="String1" for this argument, Microsoft Access first evaluates the expression as String1. Then it uses String1 as the expression in this argument, expecting to find a control or property named String1 on the form or report that called the macro.

Note To use the Expression Builder to create an expression for either of these action arguments, click the Build button to the right of the Expression box.

Remarks

You can use this action to set a value for a field or control on a form, a form datasheet, or a report. You can also set the value for almost all control, form, and report properties in any view. To find out whether a particular property can be set using a macro and which views it can be set in, see the topic for that property.

You can also set the value for a field in a form’s underlying table even if the form doesn’t contain a control bound to the field. Use the syntax Forms!formname!fieldname in the Item box to set the value for such a field. You can also refer to a field in a report’s underlying table using the syntax Reports!reportname!fieldname, but there must be a control on the report bound to this field, or the field must be referred to in a calculated control on the report.

If you set the value of a control on a form, the SetValue action doesn’t trigger the control’s form-level validation rules, but it does trigger the underlying field’s table-level validation rules if the control is a bound control. The SetValue action also triggers recalculation, but the recalculation may not happen immediately. To trigger immediate repainting and force the recalculation to completion, use the RepaintObject action. The value you set in a control using the SetValue action is also not affected by an input mask set in the control’s or underlying field’s InputMask property.

To change the value of a control, you can use the SetValue action in a macro specified by the control’s AfterUpdate event property. However, you can’t use the SetValue action in a macro specified by a control’s BeforeUpdate event property to change the value of the control (although you can use SetValue to change the value of other controls). You can also use SetValue in a macro specified by the BeforeUpdate or AfterUpdate property of a form to change the value of any controls in the current record.

Note

Note You can’t use the SetValue action to set the value of the following controls:

  • Bound controls and calculated controls on reports.
  • Calculated controls on forms.

Tip You can use the SetValue action to hide or show a form in Form view. Enter Forms!formname.Visible in the Item box and No or Yes in the Expression box. Setting a modal form’s Visible property to No hides the form and makes it modeless. Setting the property to Yes displays the form and makes it modal again.

Changing the value of or adding new data in a control using the SetValue action in a macro does not trigger events such as BeforeUpdate, BeforeInsert, or Change that occur when you change or enter data in these controls in the user interface. These events also don’t occur if you set the value of the control using Visual Basic.

This action isn’t available in Visual Basic. Set the value directly in Visual Basic.

See Also

RepaintObject Action, SendKeys Action.


SetWarnings Action

Description

You can use the SetWarnings action to turn system messages on or off.

Setting

The SetWarnings action uses the following argument.

Action argument | Description
Warnings On | Specifies whether system messages are displayed. Click Yes to turn on system messages or No not to turn on system messages. The default is No.

Remarks

You can use this action to prevent modal warnings and message boxes from stopping the macro. However, error messages are always displayed. Also, Microsoft Access displays any dialog boxes that require input other than just choosing a button (such as OK, Cancel, Yes, or No) — for example, any dialog box that requires you to enter text or select one of several options.

This action has the same effect as pressing ENTER whenever a warning or message box is displayed. Typically, an OK or Yes is chosen in response to the warning or message.

When the macro finishes, Microsoft Access automatically turns the display of the system messages back on.

Often, you’ll use this action with the Echo action, which hides the results of a macro until it is finished. You can use the SetWarnings action to hide the warnings and message boxes as well.

Caution Although the SetWarnings action can simplify interactions with macros, you must be careful about turning system messages off. In some situations, you won’t want to continue a macro if a certain warning message is displayed. Unless you’re confident of the outcome of all macro actions, you should avoid using this action.

To run the SetWarnings action in Visual Basic, use the SetWarnings method of the DoCmd object.

See Also

Echo Action, SetWarnings Method.


SetWarnings Method

Applies To

DoCmd Object.

Description

The SetWarnings method carries out the SetWarnings action in Visual Basic. For more information on how the action and its argument work, see the action topic.

Syntax

DoCmd.SetWarnings warningson

The SetWarnings method uses the following arguments.

Argument | Description
warningson | Use True (-1) to turn on the display of system messages and False (0) to turn it off.

Remarks

If you turn the display of system messages off in Visual Basic, you must turn it back on, or it will remain off, even if the user presses CTRL+BREAK or Visual Basic encounters a breakpoint. You may want to create a macro that turns the display of system messages on and then assign that macro to a key combination or a custom menu command. You could then use the key combination or menu command to turn the display of system messages on if it has been turned off in Visual Basic.

See Also

DoCmd Object, Echo Method, Echo Method (DoCmd Object).

Example

This example turns the display of system messages off.

DoCmd.SetWarnings False


Sgn Function

Description

Returns an integer indicating the sign of a number.

Syntax

Sgn(number)

The number argument can be any valid numeric expression.

Return Values

If number is | Sgn returns
Greater than zero | 1
Equal to zero | 0
Less than zero | -1

Remarks

The sign of the number argument determines the return value of the Sgn function.

See Also

Abs Function.

Example

This example uses the Sgn function to determine the sign of a number.

MyVar1 = 12: MyVar2 = -2.4: MyVar3 = 0= Sgn(MyVar1)            ' Returns 1.= Sgn(MyVar2)            ' Returns -1.= Sgn(MyVar3)            ' Returns 0.


Shell Function

Description

Runs an executable program.

Syntax

Shell(pathname[, windowstyle])

The Shell function syntax has these named arguments:

Part | Description
pathname | Name of the program to execute and any required arguments or command line switches; may include directory or folder and drive. May also be the name of a document that has been associated with an executable program.
windowstyle | Number corresponding to the style of the window in which the program is to be run. If windowstyle is omitted, the program is started minimized with focus.

The windowstyle named argument has these values:

Constant | Value | Description
vbHide | 0 | Window is hidden and focus is passed to the hidden window.
vbNormalFocus | 1 | Window has focus and is restored to its original size and position.
vbMinimizedFocus | 2 | Window is displayed as an icon with focus.
vbMaximizedFocus | 3 | Window is maximized with focus.
vbNormalNoFocus | 4 | Window is restored to its most recent size and position. The currently active window remains active.
vbMinimizedNoFocus | 6 | Window is displayed as an icon. The currently active window remains active.

Remarks

If the Shell function successfully executes the named file, it returns the task identification (ID) of the started program. The task ID is a unique number that identifies the running program. If the Shell function can’t start the named program, an error occurs.

Note The Shell function runs other programs asynchronously. This means you can’t depend on a program started with Shell to be finished executing before the statements following the Shell function in your application are executed.

See Also

AppActivate Statement.

Example

This example uses the Shell function to run an application specified by the user.

' Specifying 1 as the second argument opens the application in
' normal size and gives it the focus.= Shell("C:\WINDOWS\CALC.EXE", 1)        ' Run Calculator.
' Launch Microsoft Excel.= Shell("Microsoft Excel")            ' Specify filename.


ShortcutMenu Property

Applies To

Form.

Description

You can use the ShortcutMenu property to specify whether a shortcut menu is displayed when you click the right mouse button while the pointer is over an object on a form. You might want to disable a shortcut menu to prevent the user from changing the form’s underlying record source.

Setting

The ShortcutMenu property uses the following settings.

Setting | Description | Visual Basic
Yes | (Default) Shortcut menus are displayed. | True (-1)
No | Shortcut menus aren’t displayed. | False (0)

You can set this property using the form’s property sheet, a macro, or Visual Basic.

Remarks

If you’re developing a wizard, you might want to hide shortcut menus on your wizard forms to prevent the user from viewing or using them. This is especially true for forms that display choices. For example, the ShortcutMenu property for the Startup form in the Northwind sample database is set to No. This prevents users from displaying shortcut menus for the form or controls on the form.

See Also

AllowFilters Property, ShortcutMenuBar Property, StartupShortcutMenuBar Property.

Example

The following example disables the shortcut menu for the Invoice form.

Forms![Invoice].ShortcutMenu = False


ShortcutMenuBar Property

Applies To

Application Object, Bound Object Frame Control, Chart Control, Check Box Control, Combo Box Control, Command Button Control, Form, Image Control, Label Control, List Box Control, Option Button Control, Option Group Control, Report, Toggle Button Control, Unbound Object Frame Control.

Description

You can use the ShortcutMenuBar property to specify the menu bar macro to use to display a shortcut menu when you right click on a form or control.

Setting

You set the ShortcutMenuBar property using the name of a menu bar macro.

You can set the ShortcutMenuBar property in the form or control’s property sheet, a macro, or using Visual Basic.

For controls on forms, you can also set this property using the control’s default control style.

In Visual Basic, set this property using a string expression that is the name of the menu bar macro you want to run.

Tip To create a menu bar macro, you can use the Menu Builder by clicking the Build button in the ShortcutMenuBar property box of the form or control you want to attach the menu to. The Menu Builder creates and names the menu bar macro and the macro group containing the actions for the menu commands on the menus you create.

Remarks

The macro specified in the ShortcutMenuBar property must contain a single AddMenu action that specifies the name of another macro that defines the menu itself.

Shortcut menus are not available to any object if the AllowShortcutMenus property is set to False.

See Also

AddMenu Action, AllowShortcutMenus Property, MenuBar Property, ShortcutMenu Property.


ShowAllRecords Action

Description

You can use the ShowAllRecords action to remove any applied filter from the active table, query result set, or form, and display all records in the table or result set or all records in the form’s underlying table or query.

Setting

The ShowAllRecords action doesn’t use any arguments.

Remarks

Use this action to ensure that all records (including any changed or new records) are displayed for a table, query result set, or form. This action causes a requery of the records for a form or subform.

You can also use this action to remove any filter that was applied with the ApplyFilter action, the Apply Filter/Sort command on the Records menu, or the Filter Name or Where Condition argument of the OpenForm action.

This action has the same effect as clicking Remove Filter/Sort on the Records menu or clicking the Remove Filter button on the toolbar in Form view or Datasheet view.

To run the ShowAllRecords action in Visual Basic, use the ShowAllRecords method of the DoCmd object.

See Also

ApplyFilter Action, OpenForm Action, RepaintObject Action, Requery Action, ShowAllRecords Method.


ShowAllRecords Method

Applies To

DoCmd Object.

Description

The ShowAllRecords method carries out the ShowAllRecords action in Visual Basic. For more information on how the action works, see the action topic.

Syntax

DoCmd.ShowAllRecords

This method uses no arguments.

See Also

ApplyFilter Method, DoCmd Object, OpenForm Method, Recalc Method, Refresh Method, Repaint Method, RepaintObject Method, Requery Method, Requery Method (DoCmd Object), ShowAllRecords Action.


ShowGrid Property

Applies To

Form, Query, Table.

Description

You can use the ShowGrid property to specify whether gridlines are visible when the table, query, or form is displayed in Datasheet view.

Note The ShowGrid property is included in this version of Microsoft Access only for compatibility with previous versions. It is recommended that you use the DatasheetGridLinesBehavior property instead.

The ShowGrid property applies to all fields in Datasheet view.

Setting

The ShowGrid property uses the following settings.

Setting | Description | Visual Basic
True | The display grid lines are displayed in Datasheet view. | True (-1)
False | The grid lines aren’t displayed in Datasheet view. | False (0)

In previous versions of Microsoft Access, you could set the ShowGrid property in Datasheet view by clicking Gridlines on the Format menu.

See Also

DatasheetCellsEffect Property, DatasheetGridLinesBehavior Property.


ShowToolbar Action

Description

You can use the ShowToolbar action to display or hide a built-in toolbar or a custom toolbar. You can display a built-in toolbar in all Microsoft Access windows or just the view in which the toolbar is normally displayed (for example, the Form view toolbar in Form view).

Setting

The ShowToolbar action uses the following arguments.

Action argument | Description
Toolbar Name | The name of the toolbar you want to display or hide. The Toolbar Name box shows all the built-in toolbars in Microsoft Access, followed by any custom toolbars you’ve defined in the current database. This is a required argument.
 | If the Allow Built-In Toolbars check box in the Startup dialog box (which is displayed when you click Startup on the Tools menu) is cleared, the Toolbar Name box shows only the custom toolbars you’ve defined, and you can use this action only to display and hide custom toolbars.
 | If you run a macro containing the ShowToolbar action in a library database, Microsoft Access looks for the toolbar with this name first in the library database, then in the current database.
Show | The indicator whether to display or hide the toolbar and in which views to hide or display it. The default is No (hide the toolbar).
 | For built-in toolbars, you can select Yes to display the toolbar in all Microsoft Access windows that become active, Where Appropriate to display the toolbar only in the view it’s normally displayed in (as Microsoft Access does by default), or No to hide the toolbar in all Microsoft Access windows.
 | For custom toolbars, you can select Yes or Where Appropriate to display the custom toolbar in all Microsoft Access windows that become active or No to hide the toolbar in all Microsoft Access windows.

You can use this action in a macro with conditional expressions to display or hide one or more toolbars depending on certain conditions.

Remarks

If you want to show a particular toolbar on just one form or report, you can set the OnActivate property of the form or report to the name of a macro that contains a ShowToolbar action to show the toolbar. Then set the OnDeactivate property of the form or report to the name of a macro that contains a ShowToolbar action to hide the toolbar.

The ShowToolbar action has the same effect as clicking Toolbars on the View menu, and selecting or clearing a specific toolbar.

Note The ShowToolbar action enables you to specify whether a built-in toolbar is displayed in all Microsoft Access windows or just the view in which it’s normally displayed.

The built-in toolbars are also not available to display or hide using this action if you set the AllowBuiltInToolbars property to False (0) in Visual Basic, or if you set the Built-In Toolbars Available option to False in Visual Basic using the SetOption method.

To run the ShowToolbar action in Visual Basic, use the ShowToolbar method of the DoCmd object.

See Also

Event Properties; GetOption, SetOption Methods; ShowToolbar Method.


ShowToolbar Method

Applies To

DoCmd Object.

Description

The ShowToolbar method carries out the ShowToolbar action in Visual Basic. For more information on how the action and its arguments work, see the action topic.

Syntax

DoCmd.ShowToolbar toolbarname [, show]

The ShowToolbar method uses the following arguments.

Argument | Description
toolbarname | A string expression that is the valid name of a Microsoft Access built-in toolbar or a custom toolbar you’ve created. If you execute Visual Basic code containing the ShowToolbar method in a library database, Microsoft Access looks for the toolbar with this name first in the library database, then in the current database.
show | One of the following intrinsic constants: acToolbarYes acToolbarWhereApprop acToolbarNo If you leave this argument blank, the default (acToolbarYes) is assumed.

Remarks

If you leave the show argument blank, don’t use a comma following the toolbarname argument.

See Also

AllowBuiltInToolbars Property; DoCmd Object; GetOption, SetOption Methods; ShowToolbar Action.

Example

This example displays the custom toolbar named CustomToolbar in all Microsoft Access windows that become active.

DoCmd.ShowToolbar "CustomToolbar", acToolbarYes


Sin Function

Description

Returns the sine of an angle.

Syntax

Sin(number)

The number argument can be any valid numeric expression that expresses an angle in radians.

Remarks

The Sin function takes an angle and returns the ratio of two sides of a right triangle. The ratio is the length of the side opposite the angle divided by the length of the hypotenuse.

The result lies in the range -1 to 1.

To convert degrees to radians, multiply degrees by pi/180. To convert radians to degrees, multiply radians by 180/pi.

See Also

Atn Function, Cos Function, Derived Math Functions, Tan Function.

Example

This example uses the Sin function to return the sine of an angle.

MyAngle = 1.3                    ' Define angle in radians.= 1 / Sin(MyAngle)    ' Calculate cosecant.


Single Data Type

Description

Single (single-precision floating-point) variables are stored as IEEE 32-bit (4-byte) floating-point numbers, ranging in value from -3.402823E38 to -1.401298E-45 for negative values and from 1.401298E-45 to 3.402823E38 for positive values. The type-declaration character for Single is !.

See Also

CSng Function, Data Type Summary, Def type Statements, Double Data Type, Variant Data Type.


SizeMode Property

Applies To

Bound Object Frame Control, Chart Control, Image Control, Unbound Object Frame Control.

Description

You can use the SizeMode property to specify how to size a picture or other object in a bound object frame, an unbound object frame, or an image control.

Setting

The SizeMode property uses the following settings.

Setting | Description | Visual Basic
Clip | (Default) Displays the object at actual size. If the object is larger than the control, its image is clipped on the right and bottom by the control’s borders. | 0
Stretch | Sizes the object to fill the control. This setting may distort the proportions of the object. | 1
Zoom | Displays the entire object, resizing it as necessary without distorting the proportions of the object. This setting may leave extra space in the control if the control is resized. | 3

You can set the SizeMode property using the property sheet, a macro, or Visual Basic You can also set this property in a control’s default control style.

Tip Use the Clip setting for the fastest display. You can use the Stretch setting for bar graphs and line graphs without concern for size adjustments. The Stretch setting can distort circles and photos.

See Also

Action Property, Resize Event.

Example

See the Action property example.


SizeToFit Method

Applies To

Command Button Control, Image Control, Label Control, Option Button Control, Subform/Subreport Control, Unbound Object Frame Control.

Description

You can use the SizeToFit method to size a control so it fits the text or image that it contains. For example, you can apply the SizeToFit method to a command button that is too small to display all the text in its Caption property.

Syntax

control.SizeToFit

The SizeToFit method uses the following argument.

Argument | Description
control | A control that displays text or an image, including the label, toggle button, command button, image, unbound object frame, and subform/subreport controls.

Remarks

Using the SizeToFit method is equivalent to selecting a control on a form or report, pointing to Size on the Format menu, and clicking To Fit. You can apply the SizeToFit method to controls only in form Design view or report Design view.

The SizeToFit method will make a control larger or smaller, depending on the size of the text or image it contains.

Use the SizeToFit method in conjunction with the CreateControl function to size new controls that you have created in code.

Note Not all controls that contain text or an image can be sized by the SizeToFit method. Several controls are bound to data that can vary in size from one record to the next. These controls include the text box, list box, combo box, and bound object frame controls.

See Also

Caption Property; CreateControl, CreateReportControl Functions; CreateForm, CreateReport Functions.

Example

The following example creates a new form and creates a new command button on the form. The procedure then sets the control’s Caption property and sizes the control to fit the caption.

Sub SizeNewControl()
    Dim frm As Form, ctl As Control

    ' Create new form.
    Set frm = CreateForm
    ' Create new command button.
    Set ctl = CreateControl(frm.Name, acCommandButton, , , , 500, 500)
    ' Restore form.
    DoCmd.Restore
    ' Set control's Caption property.
    ctl.Caption = "Extremely Long Control Caption"
    ' Size control to fit caption.
    ctl.SizeToFitSub


SLN Function

Description

Returns the straight-line depreciation of an asset for a single period.

Syntax

SLN(cost, salvage, life)

The SLN function has these named arguments:

Part | Description
cost | Initial cost of the asset.
salvage | Value of the asset at the end of its useful life.
life | Length of the useful life of the asset.

Remarks

The period for which the depreciation is returned is expressed in the same unit of time as the useful life of the asset. All arguments must be positive numbers.

Example

This example uses the SLN function to return the straight-line depreciation of an asset for a single period given the asset’s initial cost (InitCost), the salvage value at the end of the asset’s useful life (SalvageVal), and the total life of the asset in years (LifeTime).

Const YEARMONTHS = 12                ' Number of months in a year.= "###,##0.00"                    ' Define money format.= InputBox("What's the initial cost of the asset?")= _
    InputBox("What's the asset's value at the end of its useful life?")= InputBox("What's the asset's useful life in months?")While MonthLife < YEARMONTHS        ' Ensure period is >= 1 year.
    MsgBox "Asset life must be a year or more."
    MonthLife = InputBox("What's the asset's useful life in months?")= MonthLife / YEARMONTHS    ' Convert months to years.LifeTime <> Int(MonthLife / YEARMONTHS) Then
    LifeTime = Int(LifeTime + 1)        ' Round up to nearest year.If= SLN(InitCost, SalvageVal, LifeTime)"The depreciation is " & Format(PDepr, Fmt) & " per year."


SortOrder Property

Applies To

Report, Sorting and Grouping Box.

Description

You use the SortOrder property to specify the sort order for fields and expressions in a report. By specifying a sort order, you can organize your records in a particular order. For example, if you’re printing a list of suppliers, you can sort the records alphabetically by company name.

Setting

The SortOrder property uses the following settings.

Setting | Description | Visual Basic
Ascending | (Default) Sorts values in ascending (A to Z, 0 to 9) order | False (0)
Descending | Sorts values in descending (Z to A, 9 to 0) order | True (-1)

You can set the SortOrder property in the Sorting and Grouping box of a report, a macro, or Visual Basic.

In Visual Basic, you set the SortOrder property in report Design view or the Open event procedure of a report using the GroupLevel property.

See Also

CreateGroupLevel Function; GroupHeader, GroupFooter Properties; GroupInterval Property; GroupLevel Property; GroupOn Property; KeepTogether Property — Groups.

Example

See the GroupInterval property example.


Source Property (Microsoft Access)

Applies To

Query.

Description

You can use the Source property to specify the source connection string and source database for a query’s input table or query. This is necessary if you are accessing data in an external table without linking the table.

Note Using the Source property and the SourceConnectStr property to access ODBC tables is much slower than using linked tables.

Setting

You set the Source property using a string expression. The following examples show how you can use the Source property to connect to several different types of external databases.

Type of database | Specify this | Sample setting
Microsoft Access | The path and database name. Microsoft Access adds the filename extension automatically. | C:\Accts\Customers
dBASE® | The database type and path. For a list of specifiers, see the Connect property. | dBASE IV;DatabaseTable=C:\DBDATA
SQL Server (ODBC) | The name of the source database and any additional information required by the product, such as a logon identification (ID) and password. You can also use the ODBC Connection String Builder to create the connection string. | ODBC;DSN=salessrv;UID=jace;=password;DATABASE=sales;

You can set this property in a query’s field list property sheet.

You can also set it in SQL view of the Query window by using the FROM and IN clauses in the SQL statement.

Remarks

When all the input tables in a query come from the same external database, use the query’s SourceConnectStr and SourceDatabase properties instead of setting the Source property for each input table or query.

See Also

DestConnectStr, DestinationDB, DestinationTable Properties; SourceConnectStr, SourceDatabase Properties.

Example

You can’t set this property in code directly. It’s set when you create a new query using an SQL statement. The FROM clause in the SQL statement corresponds to the Source property setting.

The following example sets the ControlSource property for a text box to a field in a dBASE IV® table.

Dim strGetSQL AS String= "SELECT DISTINCTROW Customers.[Company Name], _
    FROM [dBASE IV; DATABASE = c:\dbdata].Customers;"!Customers.txtCompanyName.ControlSource = strGetSQL

In the next example, the source of data for the query is a dBASE IV table named Customers in the C:\Dbdata directory. You can enter this SQL statement in SQL view of a Query window.

SELECT DISTINCTROW Customers.[Company Name], Customers.Phone[dBASE IV; DATABASE = c:\dbdata].Customers;


Source Property (Visual Basic)

Applies To

Err Object.

Description

Returns or sets the name of the object or application that originally generated the error.

Syntax

object.Source [= stringexpression]

The Source property syntax has these parts:

Part | Description
object | Always the Err object.
stringexpression | A string expression representing the application that generated the error.

Remarks

The Source property specifies a string expression representing the object that originally generated the error; the expression is usually the object’s class name or programmatic ID. Use Source to provide your users with information when your code is unable to handle an error generated in an accessed object. For example, if you access Microsoft Excel and it generates a Division by zero error, Microsoft Excel sets Err.Number to its error code for that error and sets Source to Excel.Application. Note that if the error is generated in another object called by Microsoft Excel, Microsoft Excel intercepts the error and sets Err.Number to its own code for Division by zero. However, it leaves the other Err object properties (including Source) as set by the object that generated the error. Source always contains the name of the object that originally generated the error — your code can try to handle the error according to the error documentation of the object you accessed. If your error handler fails, you can use the Err object information to describe the error to your user, using Source and the other Err properties to inform the user which object originally caused the error, its description of the error, and so forth.

When generating an error from code, Source is your application’s programmatic ID. For OLE Automation class modules, Source should contain a name having the form project.class. Not all Visual Basic host applications can create OLE Automation objects. See your host application’s documentation to determine whether it can create classes and OLE Automation objects.

Note The On Error Resume Next construct may be preferable to On Error GoTo when dealing with errors generated during access to other objects. Checking Err after each interaction with an object removes ambiguity about which object your code was accessing when the error occurred. Thus, you can be sure which object placed the error code in Err.Number, as well as which object originally generated the error (the one specified in Err.Source).

See Also

Description Property, Err Object, GetObject Function, HelpContext Property, HelpFile Property, LastDLLError Property, Number Property, On Error Statement.

Example

This example assigns the Programmatic ID of an OLE Automation object created in Visual Basic to the variable MyObjectID, then assigns that to the Source property of the Err object when it generates an error with the Raise method. When handling errors, you should not use the Source property (or any Err properties other than Number) programatically. The only valid use of properties other than Number is for displaying rich information to an end user in cases where you cannot handle an error.

' An object of type MyClass generates an error and fills all Err object
' properties, including Source, which receives MyObjectID, which is a
' combination of the Title property of the App object and the Name
' property of the MyClass object.= App.Title & "." & MyClass.Name.Raise Number := vbObjectError + 894, Source := MyObjectID, _
    Description := "Was not able to complete your task", _
    HelpFile := MyHelpFile, HelpContext := MyHelpContext


SourceConnectStr, SourceDatabase Properties

Applies To

Query.

Description

You can use these properties to access external data when you can’t link the external tables to your database.

  • SourceConnectStr — You can use this property to specify the name of the application used to create an external database.
  • SourceDatabase — You can use this property to specify the external database in which the input tables or queries for a query reside.

Note The SourceConnectStr and SourceDatabase properties apply to all queries except data-definition, pass-through, and union queries.

Setting

You use a string expression to set the value of the SourceConnectStr and SourceDatabase properties.

You can set these properties in the query property sheet or in SQL view of the Query window. In the SQL statement, the properties correspond to the IN clause.

Note If you are accessing multiple database sources, use the Source property

Remarks

You must use the SourceConnectStr and SourceDatabase properties to access tables from external databases created in applications that don’t use linked tables.

The following are examples of these property settings if an application that doesn’t use linked tables accesses the data from databases created by Microsoft Access and other database products:

  • For a Microsoft Access database, the SourceDatabase property setting is the path and database name (for example, C:\Accounts\Customers). Microsoft Access adds the filename extension automatically. The SourceConnectStr property doesn’t have a value for a Microsoft Access database.
  • For a database created by a product such as Paradox, the SourceDatabase property setting is the path (for example, C:\Paradoxdata). The SourceConnectStr property setting is the specifier for the database type (for example, Paradox 3.5;). For a list of specifiers, see the Connect property.
  • The following example uses dBASE IV tables in the C:\Dbdata directory as the source of data for the query.

        SELECT DISTINCTROW Customers.[Company Name], Orders.[Order ID], _
        Orders.[Order Date] FROM Customers INNER JOIN Orders ON _
        Customers.[Customer ID] = Orders.[Customer ID] _
        IN 'C:\Dbdata'[dBASE IV;];
  • For an Open Database Connectivity (ODBC) database, the SourceConnectStr property setting is the name of the source database and any additional information required by the product, such as a logon identification (ID) and password. For example, for a Microsoft SQL Server database, the setting might be:

        ODBC;DSN=salessrv;UID=jace;PWD=password;DATABASE=sales;

The SourceDatabase property doesn’t have a value for an ODBC database.

See Also

DestConnectStr, DestinationDB, DestinationTable Properties; Source Property (Microsoft Access).


SourceDoc Properties

Applies To

Bound Object Frame Control, Chart Control, Unbound Object Frame Control.

Description

You can use the SourceDoc property to specify the file to be linked or embedded when you create a linked object or embedded object using the Action property in Visual Basic.

Setting

For an embedded object, enter the filename for the file you want to use as a template and set the Action property to acOLECreateEmbed.

For a linked object, enter the full path and filename for the file to be linked and set the Action property to acOLECreateLink.

You can set this property using the property sheet, a macro, or Visual Basic.

Note While this property appears in the property sheet, it takes effect only when used with the Action property in Visual Basic.

Remarks

You can use the SourceDoc property to specify the file to be linked and the control’s SourceItem property to specify the data within that file. If you want to link the entire object, leave the SourceItem property blank.

When a linked unbound object is created, the control’s SourceItem property setting is concatenated with its SourceDoc property setting. In Form view, Datasheet view, and Print Preview, the control’s SourceItem property setting is a zero-length string (" "), and its SourceDoc property setting is the full path to the linked file, followed by an exclamation point (!) or a backslash (\) and the SourceItem property setting as in the following example.

"C:\Work\Qtr1\Revenue.xls!R1C1:R30C15"

See Also

Action Property, Class Property, OLEType Property, OLETypeAllowed Property, SourceItem Property.

Example

See the Action property example.


SourceItem Property

Applies To

Bound Object Frame Control, Unbound Object Frame Control.

Description

You can use the SourceItem property to specify the data within a file to be linked when you create a linked OLE object.

Setting

You can set the SourceItem property by specifying data in units recognized by the application supplying the object. For example, when you link to Microsoft Excel, you specify the SourceItem property setting using a cell or cell-range reference such as R1C1 or R3C4:R9C22 or a named range such as Revenues.

Note To determine the syntax to describe a unit of data for a particular object, see the documentation for the application that created the object.

You can set this property using the property sheet, a macro, or Visual Basic.

In Visual Basic, you set this property using a string expression.

Remarks

The control’s OLETypeAllowed property must be set to Linked or Either when you use this property. Use the control’s SourceDoc property to specify the file to link.

See Also

Action Property, Class Property, OLEType Property, OLETypeAllowed Property, SourceDoc Property.

Example

See the Action property example.


SourceObject Property

Applies To

Subform/Subreport Control, Unbound Object Frame Control.

Description

You can use the SourceObject property to identify the form or report that is the source of the subform or subreport on a form or report. You can also use this property for linked unbound object frames to determine the complete path and filename of the file that contains the data linked to the object frame.

Setting

Enter the name of the form or report that is the source of the subform or subreport in the control’s property sheet. If you add a subform or subreport to the form or report by dragging it from the Database window, the SourceObject property is set automatically in the property sheet.

For unbound object frames, the SourceObject property is set automatically when you use the Object command on the Insert menu to insert a linked OLE object.

For a subform or subreport, you can set this property using the control’s property sheet, a macro, or Visual Basic.

In Visual Basic, you set this property using a string expression that is a name of a form or report.

For linked unbound object frames, the SourceObject property can’t be set in any view.

Note You can’t set or change the SourceObject property in the Open or Format events of a report.

Remarks

If you delete the SourceObject property setting in the property sheet for a subform or subreport, the control remains on the form but is no longer bound to the source form or report.

See Also

LinkChildFields, LinkMasterFields Properties; Parent Property.

Example

The following example displays the name of the form that is the source of the Product List subform control in the Debug window.

Debug.Print Forms![Categories]![Product List].SourceObject


Space Function

Description

Returns a string consisting of the specified number of spaces.

Syntax

Space(number)

The number argument is the number of spaces you want in the string.

Remarks

The Space function is useful for formatting output and clearing data in fixed-length strings.

See Also

Spc Function, String Function.

Example

This example uses the Space function to return a string consisting of a specified number of spaces.

' Returns a string with 10 spaces.= Space ( 10 )
' Insert 10 spaces between two strings.= "Hello" & Space ( 10 )  & "World"


Spc Function

Description

Used with the Print # statement or the Print method to position output.

Syntax

Spc(n)

The n argument is the number of spaces to insert before displaying or printing the next expression in a list.

Remarks

If n is less than the output-line width, the next print position immediately follows the number of spaces printed. If n is greater than the output-line width, Spc calculates the next print position using the formula:

currentprintposition + (n Mod width)

For example, if the current print position is 24, and the output-line width is 80 and you specify Spc(90), the next print will start at position 34 (current print position + the remainder of 90/80). If the difference between the current print position and the output-line width is less than n (or n Mod width), the Spc function skips to the beginning of the next line and generates a number of spaces equal to n - (width - currentprintposition).

Note Make sure your tabular columns are wide enough to accommodate wide letters.

When you use the Print method with a proportionally spaced font, the width of space characters printed using the Spc function is always an average of the width of all characters in the point size for the chosen font. However, there is no correlation between the number of characters printed and the number of fixed-width columns those characters occupy. For example, the uppercase letter W occupies more than one fixed-width column and the lowercase letter I occupies less.

See Also

Mod Operator, Print # Statement, Print Method, Space Function, Tab Function, Width # Statement.

Example

This example uses the Spc function to position output in a file and in the Debug window.

' The Spc function can be used with the Print # statement."TESTFILE" For Output As #1    ' Open file for output.#1, "10 spaces between here"; Spc(10); "and here."#1    ' Close file.

The following statement causes the text to be printed in the Debug window (using the Print method), preceded by 30 spaces.

Debug.Print Spc(30); "Thirty spaces later..."


SpecialEffect Property

Applies To

Bound Object Frame Control, Chart Control, Check Box Control, Combo Box Control, Form Section, Image Control, Label Control, List Box Control, Option Button Control, Option Group Control, Rectangle Control, Report Section, Text Box Control, Unbound Object Frame Control.

Description

You can use the SpecialEffect property to specify whether special formatting will apply to a section or control.

Setting

The SpecialEffect property uses the following settings.

Setting | Example | Description | Visual Basic
Flat |  | The object appears flat and has the system’s default colors or custom colors that were set in Design view. | 0
Raised |  | The object has a highlight on the top and left and a shadow on the bottom and right. | 1
Sunken |  | The object has a shadow on the top and left and a highlight on the bottom and right. | 2
Etched |  | The object has a sunken line surrounding the control. | 3
Shadow |  | The object has a shadow below and to the right of the control. | 4
Chiseled |  | The object has a sunken line below the control. | 5

You can set this property using the Formatting toolbar, the object’s property sheet, a macro, or Visual Basic.

For controls, you can set the default for this property using the default control style of the Label button on the Control bar.

Remarks

The SpecialEffect property setting affects related property settings for the BorderStyle, BorderColor, and BorderWidth properties. For example, if the SpecialEffect property is set to Raised the settings for the BorderStyle, BorderColor, and BorderWidth properties are ignored. In addition, changing or setting the BorderStyle, BorderColor, and BorderWidth properties may cause Microsoft Access to change the SpecialEffect property setting.

See Also

BackStyle Property, BorderColor Property, BorderStyle Property, BorderWidth Property.


Sqr Function

Description

Returns the square root of a number.

Syntax

Sqr(number)

The number argument can be any valid numeric expression greater than or equal to 0.

Example

This example uses the Sqr function to calculate the square root of a number.

MySqr = Sqr(4)            ' Returns 2.= Sqr(23)            ' Returns 4.79583152331272.= Sqr(0)            ' Returns 0.= Sqr(-4)            ' Generates a run-time error.


StartupForm Property

Description

You can use the StartupForm property to specify the name of the form that opens when your database first opens. For example, you can use this property to display a specified form that contains a menu of all available forms, queries, and reports within a Microsoft Access application when the database opens.

Setting

The StartupForm property is a string expression that is the name of a form in the current database.

You can set this property by using a macro or Visual Basic. You can also set this property using the Display Form option in the Startup dialog box, available by clicking Startup on the Tools menu. This is the easiest way to set this property.

Remarks

The StartupForm property is preferred over the OpenForm action in the AutoExec macro. Because Microsoft Access runs the AutoExec macro after it parses the startup properties, your application should not use an OpenForm action in its AutoExec macro if the StartupForm property is set.

If this property is blank, the Microsoft Access default database setting is used (the Database Window opens).

This property’s setting does not take effect until the next time the application database opens.

See Also

AllowBreakIntoCode Property, StartupMenuBar Property, StartupShortcutMenuBar Property, StartupShowDBWindow Property, StartupShowStatusBar Property.

Example

This example shows procedure named SetStartupProperties that passes the name of the property to be set, its data type, and its desired setting. The general purpose procedure ChangeProperty attempts to set the startup property and, if the property is not found, uses the CreateProperty method to append it to the database properties collection. This is necessary because these properties do not appear in the properties collection until they have been set or changed at least once.

Sub SetStartupProperties()
    ChangeProperty "StartupForm", dbText, "Customers"
    ChangeProperty "StartupShowDBWindow", dbInteger, False
    ChangeProperty "StartupShowStatusBar", dbInteger, False
    ChangeProperty "AllowBuiltinToolbars", dbInteger, False
    ChangeProperty "AllowFullMenus", dbInteger, True
    ChangeProperty "AllowBreakIntoCode", dbInteger, False
    ChangeProperty "AllowSpecialKeys", dbInteger, True
    ChangeProperty "AllowBypassKey", dbInteger, TrueSub
ChangeProperty(strPropName As String, varPropType As _
        Variant, varPropValue As Variant) As Integer
    Dim dbs As Database, prp As Property
    Const conPropNotFountError = 3270
    Set dbs = CurrentDb
    On Error GoTo Change_Err
    dbs.Properties(strPropName) = varPropValue
    ChangeProperty = True_Bye:
    Exit Function_Err:
    If Err = conPropNotFoundError Then  'prop not found
        Set prp = dbs.CreateProperty(strPropName, _
            varPropType, varPropValue)
        dbs.Properties.Append prp
        Resume Next
    Else
        ' Unknown error.
        ChangeProperty = False
        Resume Change_Bye
    End IfFunction


StartupMenuBar Property

Description

You can use the StartupMenuBar property to specify the menu bar macro that creates the global menu bar for your application. For example, you can use the StartupMenuBar property to display a custom menu bar that does not contain the Security menu. This prevents a user from accessing any of the Security menu commands from the menu bar.

Setting

The StartupMenuBar property is a string expression that is the name of a menu bar macro in the current database.

You can set this property by using a macro or Visual Basic. You can also set this property using the Menu Bar option in the Startup dialog box, available by clicking Startup on the Tools menu. This is the easiest way to set this property.

Remarks

If you are setting the StartupMenuBar property, you should not use a SetValue action in the AutoExec macro to set the MenuBar property for the Application object. Since Microsoft Access runs the AutoExec macro after it parses the startup properties, the global menu bar set in the AutoExec macro would replace the menu set by the StartupMenuBar property.

You can also create custom menu bars using the MenuBar property for forms and reports. These custom menu bars are displayed when a specific form or report opens and replace the global menu bar in those cases.

If the StartupMenuBar property is blank, Microsoft Access displays the built-in menu bar. If this property is not blank (default) then the setting of the AllowFullMenus property has no effect.

This property’s setting does not take effect until the next time the application database opens.

Setting this property has the same effect as setting the MenuBar property of Application object (except the MenuBar property setting takes effect immediately).

See Also

AllowBreakIntoCode Property, MenuBar Property, StartupForm Property, StartupShortcutMenuBar Property, StartupShowDBWindow Property, StartupShowStatusBar Property.


StartupShortcutMenuBar Property

Description

You can use the StartupShortcutMenuBar property to specify the shortcut menu bar macro that is the global menu for your application.

Setting

The StartupShortcutMenuBar property is a string expression that is the name of a menu bar macro that displays a custom shortcut menu bar.

You can set this property by using a macro or Visual Basic code. You can also set this property using the Shortcut option in the Startup dialog box, available by clicking Startup on the Tools menu. This is the easiest way to set this property.

Remarks

If you are setting the StartupShortcutMenuBar property, you should not use a SetValue action in the AutoExec macro to set the ShortcutMenuBar property for the Application object. Since Microsoft Access runs the AutoExec macro after it parses the startup properties, the global shortcut menu set in the AutoExec macro would replace the shortcut menu set in the StartupShortcutMenuBar property.

You can also create custom shortcut menu bars using the ShortcutMenuBar property for forms, reports, and controls. These custom shortcut menu bars are displayed when you use the right mouse button to click in a specific form, report, or control.

If this property is blank, Microsoft Access displays the built-in shortcut menu bar.

This property’s setting does not take effect until the next time the application database opens.

Setting this property has the same effect as setting the ShortcutMenuBar property of Application object (except the ShortcutMenuBar property setting takes effect immediately).

See Also

AllowBreakIntoCode Property, AllowFullMenus Property, AllowShortcutMenus Property.


StartupShowDBWindow Property

Description

You can use the StartupShowDBWindow property to specify whether or not the Database window is displayed when your application database opens. For example, you can open a main form when your application database opens and hide the Database window.

Setting

The StartupShowDBWindow property has the following settings.

Setting | Description
True (-1) | Display the Database window at startup.
False (0) | Don’t display the Database window at startup.

You can set this property by using a macro or Visual Basic. You can also set this property using the Display Database Window option in the Startup dialog box, available by clicking Startup on the Tools menu. This is the easiest way to set this property.

Remarks

You can set the StartupShowDBWindow property to False to hide the Database window so the user cannot see the tables, queries, macros, and modules within your database.

This property’s setting does not take effect until the next time the database opens.

See Also

AllowBreakIntoCode Property, StartupForm Property, StartupMenuBar Property, StartupShortcutMenuBar Property, StartupShowStatusBar Property.

Example

See the StartupForm property example.


StartupShowStatusBar Property

Description

You can use the StartupShowStatusBar property to specify whether or not the status bar should appear when the application database opens. For example, you can use the StartupShowStatusBar property to prevent display of the status bar if you do not want to display any status messages in your application.

Setting

The StartupShowStatusBar property has the following settings.

Setting | Description
True (-1) | Display the status bar at startup.
False (0) | Don’t display the status bar at startup.

You can set this property by using a macro or Visual Basic. You can also set this property using the Display Status Bar option in the Startup dialog box, available by clicking Startup on the Tools menu. This is the easiest way to set this property.

Remarks

This property’s setting does not take effect until the next time the application database opens.

See Also

AllowBreakIntoCode Property, StartupForm Property, StartupMenuBar Property, StartupShortcutMenuBar Property, StartupShowDBWindow Property, StatusBarText Property.

Example

See the StartupForm property example.


Static Statement

Description

Used at procedure level to declare variables and allocate storage space. Variables declared with the Static statement retain their value as long as the code is running.

Syntax

Static varname[([subscripts])][As [New] type][, varname[([subscripts])][As[New] type]] . . .

The Static statement syntax has these parts:

Part | Description
varname | Name of the variable; follows standard variable naming conventions.
subscripts | Dimensions of an array variable; up to 60 multiple dimensions may be declared. The subscripts argument uses the following syntax:
 | [lower To] upper [,[lower To] upper] . . . When not explicitly stated in lower, the lower bound of an array is controlled by the Option Base statement. The lower bound is zero if no Option Base statement is present.
New | Keyword used to indicate that a declared object variable is a new instance of a Visual Basic object or an externally creatable OLE Automation object. The New keyword can’t be used to create variables of any intrinsic data type and can’t be used to create dependent OLE Automation objects.
type | Data type of the variable; may be Byte, Boolean, Integer, Long, Currency, Single, Double, Date, String (for variable-length strings), String * length (for fixed-length strings), Object, Variant, a user-defined type, or an object type. Use a separate As type clause for each variable being defined.

Remarks

Once module code is running, variables declared with the Static statement retain their value until the module is reset or restarted. Use the Static statement in nonstatic procedures to explicitly declare Static variables.

Use a Static statement within a procedure to declare the data type of a Static variable. For example, the following statement declares a fixed-size array of integers:

Static EmployeeNumber(200) As Integer

Also use the Static statement to declare the object type of a variable. The following declares a variable for a new instance of a worksheet:

Static X As New Worksheet

If the New keyword is not used when declaring an object variable, no instance of the object actually exists. A variable that refers to an object must be assigned an existing object using the Set statement before it can be used. Until it is assigned an object, the declared object variable has the special value Nothing, which indicates that it does not refer to any particular instance of an object.

If you do not specify a data type or object type, and there is no Def type statement in the module, the variable is Variant by default.

Note The Static statement and the Static keyword affect the lifetime of variables differently. If you declare a procedure using the Static keyword (as in Static Sub CountSales ()), the storage space for all local variables within the procedure is allocated once and the value of the variables is preserved for the entire time the program is running. For nonstatic procedures, storage space for variables is allocated each time the procedure is called and released when the procedure is exited. The Static statement is used to declare variables within nonstatic procedures to preserve their value for as long as the program is running.

When variables are initialized, a numeric variable is initialized to 0, a variable-length string is initialized to a zero-length string, and a fixed-length string is filled with zeros. Variant variables are initialized to Empty. Each element of a user-defined type variable is initialized as if it were a separate variable.

Tip When you use the Static statement in a procedure, it is a generally accepted programming practice to put the Static statement at the beginning of the procedure with any Dim statements.

See Also

Array Function, Dim Statement, Function Statement, Option Base Statement, Private Statement, Public Statement, ReDim Statement, Sub Statement.

Example

This example uses the Static statement to retain the value of a variable for as long as module code is running.

' Function definition.KeepTotal(Number)
    ' Only the variable Accumulate preserves its value between calls.
    Static Accumulate
    Accumulate = Accumulate + Number
    KeepTotal = AccumulateFunction
' Static function definition.Function MyFunction(Arg1, Arg2, Arg3)
    ' All local variables preserve value between function calls.
    Accumulate = Arg1 + Arg2 + Arg3
    Half = Accumulate / 2
    MyFunction = HalfFunction


StatusBarText Property

Applies To

Bound Object Frame Control, Check Box Control, Combo Box Control, Command Button Control, Form, List Box Control, Option Button Control, Option Group Control, Subform/Subreport Control, Text Box Control, Toggle Button Control, Unbound Object Frame Control.

Description

You can use the StatusBarText property to specify the text that is displayed in the status bar when a control is selected.

Note The StatusBarText property applies only to controls on a form.

Setting

You set the StatusBarText property using a string expression up to 255 characters long.

You can set this property in the or control’s property sheet or using a macro or Visual Basic.

You can also set this property using the control’s default control style.

Note The length of the text you can display in the status bar depends on your computer hardware and video display.

Remarks

You can use the StatusBarText property to provide specific information about a control. For example, when a text box has the focus, a brief instruction can tell the user what kind of data to enter.

If you create a control by dragging a field from the field list, the value in a field’s Description property is copied to the StatusBarText property.

See Also

Caption Property, Description Property.


Stop Statement

Description

Suspends execution.

Syntax

Stop

Remarks

You can place Stop statements anywhere in procedures to suspend execution. Using the Stop statement is similar to setting a breakpoint in the code.

The Stop statement suspends execution, but unlike End, it doesn’t close any files or clear variables, unless it is in a compiled executable (.exe) file.

See Also

End Statement.

Example

This example uses the Stop statement to suspend execution for each iteration through the For...Next loop.

For I = 1 To 10            ' Start For...Next loop.
    Debug.Print I        ' Print I to Debug window.
    Stop                    ' Stop during each iteration.I


StopAllMacros Action

Description

You can use the StopAllMacros action to stop all nested macros that are currently running.

Setting

The StopAllMacros action doesn’t use any arguments.

Remarks

You typically use this action when an error condition makes it necessary to stop all macros. You can use a conditional expression in the macro’s action row that contains this action. When the expression evaluates to True (-1), Microsoft Access stops all macros.

For example, you might have a macro that displays a message box as one of a number of complex actions, including running other macros. If the user chooses Cancel in this message box, the StopAllMacros action can stop all the macros that are running.

If a macro has used the Echo or SetWarnings actions to turn echo or the display of system messages off, the StopAllMacros action automatically turns them back on.

This action is not available in Visual Basic.

See Also

Echo Action, SetWarnings Action, StopMacro Action.


StopMacro Action

Description

You can use the StopMacro action to stop the currently running macro.

Setting

The StopMacro action doesn’t use any arguments.

Remarks

You typically use this action when a condition makes it necessary to stop the macro. You can use a conditional expression in the macro’s action row that contains this action. When the expression evaluates to True (-1), Microsoft Access stops the macro.

For example, you might create a macro that opens a form showing the daily order totals for the date entered in a custom dialog box. You could use a conditional expression to be sure that the Order Date control on the dialog box contains a valid date. If it doesn’t, the MsgBox action can display an error message and the StopMacro action can stop the macro.

If the macro has used the Echo or SetWarnings actions to turn echo or the display of system messages off, the StopMacro action automatically turns them back on.

This action is not available from Visual Basic.

See Also

Echo Action, SetWarnings Action, StopAllMacros Action.


Str Function

Description

Returns a string representation of a number.

Syntax

Str(number)

The number argument is any valid numeric expression.

Remarks

When numbers are converted to strings, a leading space is always reserved for the sign of number. If number is positive, the returned string contains a leading space and the plus sign is implied.

Use the Format function to convert numeric values you want formatted as dates, times, or currency or in other user-defined formats. Unlike Str, the Format function doesn’t include a leading space for the sign of number.

Note The Str function recognizes only the period (.) as a valid decimal separator. When a possibility exists that different decimal separators may be used (for example, in international applications), you should use CStr to convert a number to a string.

See Also

CStr Function, Format Function, Val Function.

Example

This example uses the Str function to return a string representation of a number. When a number is converted to a string, a leading space is always reserved for its sign.

MyString = Str(459)            ' Returns " 459".= Str(-459.65)        ' Returns "-459.65".= Str(459.001)        ' Returns " 459.001".


StrComp Function

Description

Returns a value indicating the result of a string comparison.

Syntax

StrComp(string1, string2[, compare])

The StrComp function syntax has these named arguments:

Part | Description
string1 | Any valid string expression.
string2 | Any valid string expression.

Part | Description
compare | Specifies the type of string comparison. The compare argument can be omitted, it can be 0 or 1, or it can be the value of the CollatingOrder property of a Field object. Specify 0 (default) to perform a binary comparison. Specify 1 to perform a textual comparison. Specify the return value of the CollatingOrder property if you want to sort or compare values from a database in the same way the database itself would. If compare is Null, an error occurs. If compare is omitted, the Option Compare setting determines the type of comparison.

Remarks

If | StrComp returns
string1 is less than string2 | -1
string1 is equal to string2 | 0
string1 is greater than string2 | 1
string1 or string2 is Null | Null

See Also

Option Compare Statement.

Example

This example uses the StrComp function to return the results of a string comparison. If the third argument is 1, a textual comparison is performed; if the third argument is 0 or omitted, a binary comparison is performed.

MyStr1 = "ABCD": MyStr2 = "abcd"                    ' Define variables.= StrComp(MyStr1, MyStr2, 1)                ' Returns 0.= StrComp(MyStr1, MyStr2, 0)                ' Returns -1.= StrComp(MyStr2, MyStr1)                    ' Returns 1.


StrConv Function

Description

Returns a converted string.

Syntax

StrConv(string, conversion)

The StrConv function syntax has these named arguments:

Part | Description
string | The string expression to be converted.
conversion | The sum of values specifying the type of conversion to perform.

Settings

The conversion argument settings are:

Constant | Value | Description
vbUpperCase | 1 | Converts the string to uppercase characters.
vbLowerCase | 2 | Converts the string to lowercase characters.
vbProperCase | 3 | Converts the first letter of every word in string to uppercase.
vbWide* | 4* | Converts narrow (single-byte) characters in string to wide (double-byte) characters.
vbNarrow* | 8* | Converts wide (double-byte) characters in string to narrow (single-byte) characters.
vbKatakana** | 16** | Converts Hiragana characters in string to Katakana characters.
vbHiragana** | 32** | Converts Katakana characters in string to Hiragana characters.
vbUnicode*** | 64*** | Converts the string to Unicode™ using the default code page of the system.
vbFromUnicode*** | 128*** | Converts the string from Unicode to the default code page of the system.

* Applies to Far East locales.

** Applies to Japan only.

*** Specifying this bit on the Macintosh or Windows 16-bit systems causes a run-time error.

Note These constants are specified by Visual Basic for applications. As a result, they may be used anywhere in your code in place of the actual values. Most can be combined (for example vbUpperCase + vbWide) except when they are mutually exclusive (for example vbUnicode + vbFromUnicode). The constants vbWide, vbNarrow, vbKatakana, and vbHiragana cause run-time errors when used in locales where they do not apply.

For proper casing the following are valid word separators: Null (Chr$(0)), horizontal tab (Chr$(9)), linefeed (Chr$(10)), vertical tab (Chr$(11)), form feed (Chr$(12)), carriage return (Chr$(13)), space (SBCS) (Chr$(32)). The actual value for a space varies by country for DBCS.

See Also

Chr Function, String Data Type.


String Data Type

Description

There are two kinds of strings:

  • Variable-length strings, which can contain up to approximately 2 billion (231) characters (approximately 64K (216) characters for Microsoft Windows version 3.1 and earlier).
  • Fixed-length strings, which can contain 1 to approximately 64K (216) characters.

Note Public fixed-length strings can’t be used in class modules.

The type-declaration character for String is $. The codes for String characters range from 0 to 255. The first 128 characters (0 – 127) of the character set correspond to the letters and symbols on a standard U.S. keyboard. These first 128 characters are the same as those defined by the ASCII character set. The second 128 characters (128 – 255) represent special characters, such as letters in international alphabets, accents, currency symbols, and fractions.

See Also

CStr Function, Data Type Summary, Def type Statements, String Function, Variant Data Type.


String Function

Description

Returns a repeating character string of the length specified.

Syntax

String(number, character)

The String function syntax has these named arguments:

Part | Description
number | Length of the returned string. If number contains Null, Null is returned.
character | Character code specifying the character or string expression whose first character is used to build the return string. If character contains Null, Null is returned.

Remarks

If you specify a number for character greater than 255, String converts the number to a valid character code using the formula:

character Mod 256

See Also

Mod Operator, Space Function, String Data Type.

Example

This example uses the String function to return repeating character strings of the length specified.

MyString = String(5, "*")        ' Returns "*****".= String(5, 42)            ' Returns "*****".= String(10, "ABC")        ' Returns "AAAAAAAAAA".


Sub Statement

Description

Declares the name, arguments, and code that form the body of a Sub procedure.

Syntax

[Private | Public] [Static] Sub name [(arglist)]
[statements]
[Exit Sub]
[statements]End Sub

The Sub statement syntax has these parts:

Part | Description
Public | Indicates that the Sub procedure is accessible to all other procedures in all modules. If used in a private module (one that contains an Option Private statement) the procedure is not available outside the project.
Private | Indicates that the Sub procedure is accessible only to other procedures in the module where it is declared.
Static | Indicates that the Sub procedure’s local variables are preserved between calls. The Static attribute doesn’t affect variables that are declared outside the Sub, even if they are used in the procedure.
name | Name of the Sub; follows standard variable naming conventions.
arglist | List of variables representing arguments that are passed to the Sub procedure when it is called. Multiple variables are separated by commas.
statements | Any group of statements to be executed within the body of the Sub procedure.

The arglist argument has the following syntax and parts:

[Optional][ByVal | ByRef][ParamArray] varname[( )] [As type]

Part | Description
Optional | Indicates that an argument is not required. If used, all subsequent arguments in arglist must also be optional and declared using the Optional keyword. All Optional arguments must be Variant. Optional can’t be used for any argument if ParamArray is used.
ByVal | Indicates that the argument is passed by value.
ByRef | Indicates that the argument is passed by reference.
ParamArray | Used only as the last argument in arglist to indicate that the final argument is an Optional array of Variant elements. The ParamArray keyword allows you to provide an arbitrary number of arguments. It may not be used with ByVal, ByRef, or Optional.
varname | Name of the variable representing the argument; follows standard variable naming conventions.
type | Data type of the argument passed to the procedure; may be Byte, Boolean, Integer, Long, Currency, Single, Double, Date, String (variable length only), Object, Variant, a user-defined type, or an object type.

Remarks

If not explicitly specified using either Public or Private, Sub procedures are public by default. If Static is not used, the value of local variables is not preserved between calls.

All executable code must be in procedures. You can’t define a Sub procedure inside another Sub, Function, or Property procedure.

The Exit Sub keywords cause an immediate exit from a Sub procedure. Program execution continues with the statement following the statement that called the Sub procedure. Any number of Exit Sub statements can appear anywhere in a Sub procedure.

Like a Function procedure, a Sub procedure is a separate procedure that can take arguments, perform a series of statements, and change the value of its arguments. However, unlike a Function procedure, which returns a value, a Sub procedure can’t be used in an expression.

You call a Sub procedure using the procedure name followed by the argument list. See the Call statement for specific information on how to call Sub procedures.

Caution Sub procedures can be recursive; that is, they can call themselves to perform a given task. However, recursion can lead to stack overflow. The Static keyword usually is not used with recursive Sub procedures.

Variables used in Sub procedures fall into two categories: those that are explicitly declared within the procedure and those that are not. Variables that are explicitly declared in a procedure (using Dim or the equivalent) are always local to the procedure. Variables that are used but not explicitly declared in a procedure are also local unless they are explicitly declared at some higher level outside the procedure.

Caution A procedure can use a variable that is not explicitly declared in the procedure, but a naming conflict can occur if anything you have defined at the module level has the same name. If your procedure refers to an undeclared variable that has the same name as another procedure, constant or variable, it is assumed that your procedure is referring to that module-level name. Explicitly declare variables to avoid this kind of conflict. You can use an Option Explicit statement to force explicit declaration of variables.

Note You can’t use GoSub, GoTo, or Return to enter or exit a Sub procedure.

See Also

Call Statement, Dim Statement, Function Statement, Option Explicit Statement, Property Get Statement, Property Let Statement, Property Set Statement.

Specifics (Microsoft Access)

In Microsoft Access, a public Sub procedure in a standard module is available to all other procedures in the database and in all other Microsoft Access databases. However, it is not available to any other applications.

If a Sub procedure is declared as public within a private module, then the procedure is available to all other procedures in that database, but is not available to other Microsoft Access databases. Form modules and report modules are always private, as are standard modules that contain an Option Private Module statement.

If you declare a Sub procedure as private in any module, that procedure is available only to other procedures within the same module.

Note If a Sub procedure is available to other Microsoft Access databases, it will be visible from those databases in the Object Browser.

When you create an event procedure for a form or report, Microsoft Access automatically inserts a code stub for a Sub procedure and precedes it with the Private keyword. For example, draw a command button on a new form, set its OnClick property to [Event Procedure], and click on the Build button to view the form’s module. Microsoft Access inserts the following code for you in the module.

Private Sub Command0_Click
Sub

You can then enter the code that you want to execute when that button’s Click event occurs.

Example

This example uses the Sub statement to define the name, arguments, and code that form the body of a Sub procedure.

' Sub procedure definition.SubComputeArea(Length, TheWidth)        ' Sub procedure with two
                                        ' arguments.
    Dim Area As Double                    ' Declare local variable.
    If Length = 0 Or TheWidth = 0 Then    ' If either argument = 0.
        Exit Sub                            ' Exit Sub immediately.
    End If
    Area = Length * TheWidth                ' Calculate area of rectangle.
    Debug.Print Area                        ' Print Area to Debug window.Sub


Switch Function

Description

Evaluates a list of expressions and returns a value or an expression associated with the first expression in the list that is True.

Syntax

Switch(expr-1, value-1[, expr-2, value-2 . . . [, expr-n, value-n]])

The Switch function syntax has these parts:

Part | Description
expr | Variant expression you want to evaluate.
value | Value or expression that is returned if the corresponding expression is True.

Remarks

The Switch function argument list consists of pairs of expressions and values. The expressions are evaluated as they appear in the list from left to right and the value associated with the first expression to evaluate True is returned. If the parts aren’t properly paired, a run-time error occurs. For example, if expr-1 is True, Switch returns value-1. If expr-1 is False, but expr-2 is True, Switch returns value-2, and so on.

Switch returns a Null value if:

  • None of the expressions is True.
  • The first True expression has a corresponding value that is Null.

Switch evaluates all of the expressions, even though it returns only one of them. For this reason, you should watch for undesirable side effects. For example, if the evaluation of any expression results in a division by zero error, an error occurs.

See Also

Choose Function, IIf Function, Select Case Statement.

Specifics (Microsoft Access)

The Switch function is most useful in a calculated control on a form or report. For example, you can use the Switch function to set the value of a control based on the value of another field. Set the ControlSource property of the control to an expression containing the Switch function.

In the following example, the Switch function returns a string that is the name of a shipper based on the value of the Freight field. If the value of the Freight field is less than $25, the Switch function returns “Speedy”; if it is greater than or equal to $25 but less than or equal to $50, the Switch function returns “United”; if it is greater than $50, the Switch function returns “Federal”.

= Switch([Freight] < 25, "Speedy", ([Freight] >= 25 and [Freight] <= _
    50), "United", [Freight] > 50, "Federal")

Note In a Visual Basic module, you may want to use the more full-featured Select Case statement to return a value from a set of several choices.

Example

This example uses the Switch function to return the name of a language that matches the name of a city.

Function MatchUp (CityName As String)
    Matchup = Switch(CityName = "London", "English", CityName _
        = "Rome", "Italian", CityName = "Paris", "French")Function

The following example uses the Switch function to determine the appropriate language for a specified city by evaluating the ShipCountry and ShipCity fields against a table named Language that contains country names and languages. You can enter the following expression in a calculated control on a form or report. The expression is shown on multiple lines for clarity; you can also enter it on a single line.

= Switch([ShipCity] = "Madrid", "Spanish", _
    [ShipCity] = "Berlin", "German", _
    [ShipCity] = "Torino", "Italian", _
    [ShipCountry] = "France", "French", _
    True, "English")

If the city is Madrid, the Switch function returns “Spanish”; if it is Berlin, it returns “German”; and so on. If the city is not one of those listed, but the country is France, it returns “French”. Otherwise, the Switch function returns “English”.


SYD Function

Description

Returns the sum-of-years’ digits depreciation of an asset for a specified period.

Syntax

SYD(cost, salvage, life, per)

The SYD function has these named arguments:

Part | Description
cost | Initial cost of the asset.
salvage | Value of the asset at the end of its useful life.
life | Length of the useful life of the asset.
per | Period for which asset depreciation is calculated.

Remarks

The arguments life and per must be expressed in the same units. For example, if life is given in months, per must also be given in months. All arguments must be positive numbers.

Example

Using the sum-of-years’ digits method, this example illustrates the use of the SYD function to return the depreciation of an asset for a specified period given the asset’s initial cost (InitCost), the salvage value at the end of the asset’s useful life (SalvageVal), and the total life of the asset in years (LifeTime). The period for which the depreciation is calculated is PDepr, also in years.

Const YEARMONTHS = 12                ' Number of months in a year.= "###,##0.00"                    ' Define money format.= InputBox("What's the initial cost of the asset?")= _
    InputBox("What's the asset's value at the end of its life?")= InputBox("What's the asset's useful life in months?")While MonthLife < YEARMONTHS        ' Ensure period is >= 1 year.
    MsgBox "Asset life must be a year or more."
    MonthLife = InputBox("What's the asset's useful life in months?")= MonthLife / YEARMONTHS    ' Convert months to years.LifeTime <> Int(MonthLife / YEARMONTHS) Then
    LifeTime = Int(LifeTime + 1)        ' Round up to nearest year.If= CInt(InputBox("For which year do you want depreciation?"))While DepYear < 1 Or DepYear > LifeTime
    MsgBox "You must enter at least 1 but not more than " & LifeTime
    DepYear = CInt(InputBox("For what year do you want depreciation?"))= SYD(InitCost, SalvageVal, LifeTime, DepYear)"The depreciation for year " & DepYear & " is " _
    & Format(PDepr, Fmt) & "."


SysCmd Function

Description

You can use SysCmd to perform one of the following functions:

  • Display a progress meter or optional specified text in the status bar.
  • Return information about Microsoft Access and its associated files.
  • Return the state of a specified database object to indicate whether the object is open, is a new object, or has been changed but not saved.

For example, if you are building a custom wizard that creates a new form, you can use the SysCmd function to display a progress meter indicating the progress of your wizard as it constructs the form.

Syntax

ReturnValue = SysCmd(action[, text][, value])ObjectState = SysCmd(action[, objecttype][, objectname])

The SysCmd function syntax has the following arguments.

Argument | Description
action | One of the following intrinsic constants identifying the type of action to take.
 | This set of constants applies to a progress meter. SysCmd returns a Null if these actions are successful. Otherwise, Microsoft Access generates a run-time error.

acSysCmdInitMeter | Initializes the progress meter. You must specify the text and value arguments when you use this action.
acSysCmdUpdateMeter | Updates the progress meter with the specified value. You must specify the text argument when you use this action.
.acSysCmdRemoveMeter | Removes the progress meter.
acSysCmdSetStatus | Sets the status bar text to text.
acSysCmdClearStatus | Resets the status bar text.

Argument | Description
action | This set of constants provides information about Microsoft Access:

acSysCmdRuntime | Returns True if a run-time version of Microsoft Access is running.
acSysCmdAccessVer | Returns the version number of Microsoft Access.
acSysCmdIniFile | Returns the name of the .ini file associated with Microsoft Access.
acSysCmdAccessDir | Returns the name of the directory where Msaccess.exe is located.
acSysCmdProfile | Returns the /profile setting specified by the user when starting Microsoft Access from the command line.
acSysCmdGetWorkgroupFile | Returns the path to the workgroup file (System.mdw).

This constant provides information on the state of a database object:

acSysCmdGetObjectState

Returns the state of the specified database object. You must specify the objecttype and objectname parts when you use this action value.

text | A string expression identifying the text to be displayed left-aligned in the status bar. Required when action is acSysCmdInitMeter or acSysCmdSetStatus; not valid for other action values.
value | A numeric expression that controls the display of the progress meter. Required when action is acSysCmdInitMeter or acSysCmdUpdateMeter; not valid for other action values.
objecttype | One of the following intrinsic constants: acTable acQuery acForm acReport acMacro acModule Required when action is acSysCmdGetObjectState; not valid for other action values.
objectname | A string expression that is the valid name of a database object of the type specified by the objecttype argument. Required when action is acSysCmdGetObjectState; not valid for other action values.

Remarks

By calling the SysCmd function with the various progress meter actions, you can display a progress meter in the status bar for an operation that has a known duration or number of steps, and update it to indicate the progress of the operation.

To display a progress meter in the status bar, you must first call the SysCmd function with the acSysCmdInitMeter action and the text and value arguments. When the action argument is acSysCmdInitMeter, value is the maximum value of the meter, or 100 percent.

To update the meter to show the progress of the operation, call SysCmd with the acSysCmdUpdateMeter action and the value argument. When action is acSysCmdUpdateMeter, SysCmd uses the value argument to calculate the percentage displayed by the meter. For example, if you set the maximum value to 200 and then update the meter with a value of 100, the progress meter will be half-filled.

You can also change the text that is displayed in the status bar by calling SysCmd with the acSysCmdSetStatus action and the text argument. For example, during a sort you might change the text to “Sorting...”. When the sort is complete, you would reset the status bar by removing the text. The text argument can contain approximately 80 characters. Because the status bar text is displayed using a proportional font, the actual number of characters you can display is determined by the total width of all the characters specified by text.

As you increase the width of the status bar text, you decrease the length of the meter. If the text is longer than the status bar and action is acSysCmdInitMeter, SysCmd ignores the text and doesn’t display anything in the status bar. If the text is longer than the status bar and action is acSysCmdSetStatus, SysCmd truncates the text to fit the status bar.

You can’t set the status bar text to a zero-length string (" "). If you want to remove the existing text from the status bar, set the text argument to a single space. The following examples illustrate ways to remove the text from the status bar:

varReturn = SysCmd(acSysCmdInitMeter, " ", 100)

varReturn = SysCmd(acSysCmdSetStatus, " ")

If the progress meter is already displayed when you set the text by calling SysCmd with the acSysCmdSetStatus action, the SysCmd function automatically removes the meter.

Call SysCmd with other actions to determine system information about Microsoft Access, including which version number of Microsoft Access is running, whether it is a run-time version, the location of the Microsoft Access executable file, the setting for the /Profile argument specified in the command line, and the name of an .ini file associated with Microsoft Access.

Note   Both general and customized settings for Microsoft Access are now stored in the Windows Registry, so you most likely won’t need an .ini file with your Microsoft Access application. The acSysCmdIniFile action exists for compatibility with earlier versions of Microsoft Access.

Call SysCmd with the acSysCmdGetObjectState action and the objecttype and objectname arguments to return the state of a specified database object. An object can be in one of four possible states: not open or nonexistent, open, new, or changed but not saved.

For example, if you are designing a wizard that inserts a new field in a table, you need to determine whether the structure of the table has been changed but not yet saved, so that you can save it before modifying its structure. You can check the value returned by SysCmd to determine the state of the table.

The SysCmd function with the acSysCmdGetObjectState action can return any combination of the following constants.

Constant | State of database object
acObjStateOpen | Open
acObjStateNew | New
acObjStateDirty | Changed but not saved

Note   If the object referred to by objectname is either not open or does not exist, SysCmd returns a value of zero.

Examples
The following example creates a snapshot-type Recordset object, reads each record, and displays a progress meter showing the current relative position in the snapshot.

Function ReadRecords (strTableName As String) As Integer

    Const conBadArgs = -1

    Dim dbs As Database, rst As RecordSet
    Dim lngCount As Long, strMsg As String

    Dim varReturn As Variant, lngX As Long

    ReadRecords = 0

    If strTableName <> "" Then
        DoCmd.Hourglass True
        Set dbs = CurrentDb
        On Error Resume Next
        Set rst = dbs.OpenRecordSet(strTableName)

        ' Get record count.
        rst.MoveLast
        rst.MoveFirst
        If Err Then
            ReadRecords = conBadArgs
        End If

        lngCount = rst.RecordCount
        On Error GoTo 0

        If lngCount Then
            strMsg = "Reading " & UCase$(strTableName) & "..."
            ReturnValue = SysCmd(acSysCmdInitMeter , strMsg, lngCount)
            ' Display message in status bar.
            For lngX = 1 To lngCount
                varReturn = SysCmd(acSysCmdUpdateMeter, lngX)

            ' Update meter.
                .                    ' Do something with record.
                .
                .

                rst.MoveNext            ' Go to next record.
            Next lngX

            GoSub CloseObjects
            ReadRecords = lngCount    ' Return number of records.
            Exit Function
        End If
    End If

    ' Not found or contains no records.

    strMsg = "Table '" & strTableName _
        & "'not found or contains no records.'"
    MsgBox strMsg, vbInformation, "ReadRecords"
    GoSub CloseObjects
    Exit Function

CloseObjects:
    On Error Resume Next
    rst.Close
    dbs.Close
    On Error GoTo 0
    DoCmd.Hourglass False
    Return

End Function

The next example illustrates how you can use the SysCmd function with the acSysCmdGetObjectState action to determine the state of the active database object.

Dim intObjType As Integer, strObjName As String, intObjState As Integer

intObjType = Application.CurrentObjectType= Application.CurrentObjectName

intObjState = SysCmd(acSysCmdGetObjectState, intObjType, strObjName)

If intObjState <> 0 Then
.

.
.If


Tab Function

Description

Used with the Print # statement or the Print method to position output.

Syntax

Tab[(n)]

The n argument is the column number to tab to before displaying or printing the next expression in a list. If omitted, Tab moves the cursor to the beginning of the next print zone. This allows Tab to be used instead of a comma in locales where the comma is used as a decimal separator.

Remarks

If the current print position on the current line is greater than n, Tab skips to the nth column on the next output line. If n is less than 1, Tab moves the print position to column 1. If n is greater than the output-line width, Tab calculates the next print position using the formula:

n Mod width

For example, if width is 80 and you specify Tab(90), the next print will start at column 10 (the remainder of 90/80). If n is less than the current print position, printing begins on the next line at the calculated print position. If the calculated print position is greater than the current print position, printing begins at the calculated print position on the same line.

The leftmost print position on an output line is always 1. When you use the Print # statement to print to files, the rightmost print position is the current width of the output file, which you can set using the Width # statement.

Note Make sure your tabular columns are wide enough to accommodate wide letters.

When you use the Tab function with the Print method, the print surface is divided into uniform, fixed-width columns. The width of each column is an average of the width of all characters in the point size for the chosen font. However, there is no correlation between the number of characters printed and the number of fixed-width columns those characters occupy. For example, the uppercase letter W occupies more than one fixed-width column and the lowercase letter I occupies less.

See Also

Mod Operator, Print # Statement, Print Method, Space Function, Spc Function, Width # Statement.

Example

This example uses the Tab function to position output in a file and in the Debug window.

' The Tab function can be used with the Print # statement."TESTFILE" For Output As #1    ' Open file for output.
' The second word prints at column 20.#1, "Hello"; Tab(20); "World."
' If the argument is omitted, cursor is moved to the next print zone.#1, "Hello"; Tab; "World"#1    ' Close file.

The Tab function can also be used with the Print method. The following statement prints text starting at column 10.

Debug.Print Tab(10); "10 columns from start."


TabIndex Property

Applies To

Bound Object Frame Control, Check Box Control, Combo Box Control, Command Button Control, List Box Control, Option Button Control, Option Group Control, Subform/Subreport Control, Text Box Control, Toggle Button Control, Unbound Object Frame Control.

Description

You can use the TabIndex property to specify a control’s place in the tab order on a form.

Note The TabIndex property applies only to controls on a form.

Setting

You can set the TabIndex property to an integer representing the position of the control within the tab order of the form. Valid settings are 0 for the first tab position, up to the total number of controls minus 1 for the last tab position. For example, if a form has three controls that each have a TabIndex property, valid TabIndex property settings are 0, 1, and 2.

Setting the TabIndex property to an integer less than 0 produces an error.

You can set this property using the control’s property sheet, a macro, or Visual Basic.

Remarks

By default, Microsoft Access assigns a tab order to controls in the order that you create them on a form. Each new control is placed last in the tab order. If you change the setting of a control’s TabIndex property to adjust the tab order, Microsoft Access automatically renumbers the TabIndex property setting of other controls to reflect insertions and deletions.

In Form view, invisible or disabled controls remain in the tab order but are skipped when you press the TAB key.

Changing the tab order of other controls on the form doesn’t affect what happens when you press a control’s access key. For example, if you’ve created an access key for the label of a text box, the focus will move to the text box whenever you press the label’s access key — even if you change the TabIndex property setting for the text box.

If you press an access key for a control that doesn’t have a TabIndex property, the focus moves to the next control in the tab order that can receive the focus.

See Also

AutoTab Property, TabStop Property.

Example

The following example reverses the tab order of a command button and a text box. Because Textbox1 was created first, it has a TabIndex property setting of 0 and Command1 has a setting of 1.

Sub Form_Click()
    Me![Command1].TabIndex = 0
    Me![TextBox1].TabIndex = 1Sub


TabStop Property

Applies To

Bound Object Frame Control, Chart Control, Check Box Control, Combo Box Control, Command Button Control, List Box Control, Option Button Control, Option Group Control, Subform/Subreport Control, Text Box Control, Toggle Button Control, Unbound Object Frame Control.

Description

You can use the TabStop property to specify whether a control can receive the focus in Form view.

Note The TabStop property applies only to controls on a form.

This property doesn’t apply to check box, option button, or toggle button controls when they appear in an option group. It does apply only to the option group itself.

Setting

The TabStop property uses the following settings.

Setting | Description | Visual Basic
Yes | (Default) You can move the focus to the control by pressing the TAB key. | True (-1)
No | You can’t move the focus to the control by pressing the TAB key. | False (0)

You can set this property using the control’s property sheet, a macro, or Visual Basic.

Remarks

When you create a control on a form, Microsoft Access automatically assigns the control a position in the form’s tab order. Each new control is placed last in the tab order. If you want to prevent a control from being available when you tab through the controls in a form, set the control’s TabStop property to No.

In Form view, hidden or disabled controls remain in the tab order but are skipped when you tab through the controls, even if their TabStop properties are set to Yes.

As long as a control’s Enabled property is set to Yes, you can click it or use an access key to select it, regardless of its TabStop property setting. For example, you can set the TabStop property of a command button to No to prevent users from selecting the button by pressing the TAB key. However, they can still click the command button to choose it.

See Also

AutoTab Property; Enabled, Locked Properties; TabIndex Property.


Tag Property

Applies To

Bound Object Frame Control, Chart Control, Check Box Control, Combo Box Control, Command Button Control, Form, Form Section, Image Control, Label Control, Line Control, List Box Control, Option Button Control, Option Group Control, Page Break Control, Rectangle Control, Report, Report Section, Text Box Control, Toggle Button Control, Unbound Object Frame Control.

Description

You can use the Tag property to store any extra information about a form, report, section, or control needed by your application.

Setting

You can enter a string expression up to 2048 characters long. The default setting is a zero-length string (" ").

You can set this property using the object’s property sheet, a macro, or Visual Basic.

Remarks

Unlike other properties, the Tag property setting doesn’t affect any of an object’s attributes.

You can use this property to assign an identification string to an object without affecting any of its other property settings or causing other side effects. The Tag property is useful when you need to check the identity of a form, report, section, or control that is passed as a variable to a procedure.

See Also

Name Property.

Example

The following example uses the Tag property to display custom messages about controls on a form. When a control has the focus, descriptive text is displayed in a label control called lblMessage. You specify the text for the message by setting the Tag property for each control to a short text string. When a control receives the focus, its Tag property is assigned to the label control’s Caption property.

Sub Form_Load()
    Dim frmMessageForm As Form
    Set frmMessageForm = Forms!Form1
    frmMessageForm!lblMessage.Caption = ""            ' Clear text.
    frmMessageForm!txtDescription.Tag = "Help text for the text box."
    frmMessageForm!cmdButton.Tag = "Help text for the command button."Sub
txtDescription_GotFocus()
    Me!lblMessage.Caption = Me!txtDescription.Tag    ' Tag property as
                                                    ' caption.Sub
txtDescription_LostFocus()
    Me!lblMessage.Caption = ""Sub
cmdButton_GotFocus()
    Me!lblMessage.Caption = Me!cmdButton.Tag            ' Tag property as
                                                    ' caption.Sub
cmdButton_LostFocus()
    Me.lblMessage.Caption = " "Sub


Tan Function

Description

Returns the tangent of an angle.

Syntax

Tan(number)

The number argument can be any valid numeric expression that expresses an angle in radians.

Remarks

Tan takes an angle and returns the ratio of two sides of a right triangle. The ratio is the length of the side opposite the angle divided by the length of the side adjacent to the angle.

To convert degrees to radians, multiply degrees by pi/180. To convert radians to degrees, multiply radians by 180/pi.

See Also

Atn Function, Cos Function, Sin Function.

Example

This example uses the Tan function to return the tangent of an angle.

MyAngle = 1.3                    ' Define angle in radians.= 1 / Tan(MyAngle)    ' Calculate cotangent.


Text Property

Applies To

Combo Box Control, Text Box Control.

Description

You can use the Text property to set or return the text contained in a text box or the text box portion of a combo box.

Setting

The Text property holds the text you want to display in the control.

You can set this property using only a macro or Visual Basic.

Remarks

To set or return a control’s Text property, the control must have the focus (to move the focus to a control, you can use the SetFocus method or GoToControl action).

See Also

Caption Property, Name Property, Value Property.

Example

This example uses the Text property to retrieve the text box portion of a combo box and then takes an action depending on the user’s selection. The Text property setting for the combo box is assigned to the global variable GetText after a user makes a selection in the combo box.

Dim GetText As Variant    ' Goes in Declarations section of         ' code module.Combo1_AfterUpdate()
    GetText = Me!Combo1.TextSub

The Click event procedure for the DoThis command button contains the code that determines the selection and takes appropriate action.

Sub DoThis_Click()
    Select Case GetText
        Case "ComboItem1"    ' Execute if first combo item is selected.
        .
        .
        .
        Case "ComboItem2"    ' Execute if second combo item is selected.
        .
        .
        .
        Case "ComboItem3"    ' Execute if third combo item is selected.
        .
        .
        .
    End Select


TextAlign Property

See LabelAlign, TextAlign Properties.


TextHeight Method

Applies To

Report Object.

Description

The TextHeight method returns the height of a text string as it would be printed in the current font of a Report object.

Syntax

object.TextHeight(strexpr)

The TextHeight method uses these arguments.

Argument | Description
object | The Report object that determines the font and point size
strexpr | The text string for which the text height will be determined

Remarks

You can use the TextHeight method to determine the amount of vertical space a text string will require in the current font when the report is formatted and printed. For example, a text string formatted in nine-point Arial will require a different amount of space than one formatted in twelve-point Courier. To determine the current font and point size for text in a report, check the settings for the report’s FontName and FontSize properties.

The value returned by the TextHeight method is expressed in terms of the coordinate system in effect for the report, as defined by the Scale method. You can use the ScaleMode property to determine the coordinate system currently in effect for the report.

If strexpr contains embedded carriage returns, the TextHeight method returns the cumulative height of the lines, including the leading space above and below each line. You can use the value returned by the TextHeight method to calculate the necessary space and positioning for multiple lines of text within a report.

See Also

FontName, FontSize Properties; Scale Method; TextWidth Method.

Example

The following example uses the TextHeight and TextWidth methods to determine the amount of vertical and horizontal space required to print a text string in the report’s current font.

To try this example in Microsoft Access, create a new report by clicking the New button on the Reports tab of the Database window. Set the OnPrint property of the Detail section to [Event Procedure]. Enter the following code in the report’s module, then switch to Print Preview.

Private Sub Detail_Print(Cancel As Integer, PrintCount As Integer)
    ' Set unit of measure to twips (default scale).
    Me.Scalemode = 1
    ' Print name and point size of report font.
    Debug.Print "Report Font: "; Me.FontName
    Debug.Print "Report Font Size: "; Me.FontSize
    ' Print height and width required for text string.
    Debug.Print "Text Height (Twips): "; Me.TextHeight("Product Report")
    Debug.Print "Text Width (Twips): "; Me.TextWidth("Product Report")Sub


TextWidth Method

Applies To

Report Object.

Description

The TextWidth method returns the width of a text string as it would be printed in the current font of a Report object.

Syntax

object.TextWidth(strexpr)

The TextWidth method uses the following arguments.

Argument | Description
object | The Report object that determines the font and point size
strexpr | The text string for which the text width will be determined

Remarks

You can use the TextWidth method to determine the amount of horizontal space a text string will require in the current font when the report is formatted and printed. For example, a text string formatted in nine-point Arial will require a different amount of space than one formatted in 12-point Courier. To determine the current font and point size for text in a report, check the settings for the report’s FontName and FontSize properties.

The value returned by the TextWidth method is expressed in terms of the coordinate system in effect for the report, as defined by the Scale method. You can use the ScaleMode property to determine the coordinate system currently in effect for the report.

If strexpr contains embedded carriage returns, the TextWidth method returns the width of the longest line, from the beginning of the line to the carriage return. You can use the value returned by the TextWidth method to calculate the necessary space and positioning for multiple lines of text within a report.

See Also

FontName, FontSize Properties; Scale Method; TextHeight Method.

Example

The following example uses the TextHeight and TextWidth methods to determine the amount of vertical and horizontal space required to print a text string in the report’s current font.

To try this example in Microsoft Access, create a new report by clicking the New button on the Reports tab of the Database window. Set the OnPrint property of the Detail section to [Event Procedure]. Enter the following code in the report’s module, then switch to Print Preview.

Private Sub Detail_Print(Cancel As Integer, PrintCount As Integer)
    ' Set unit of measure to twips (default scale).
    Me.Scalemode = 1
    ' Print name and point size of report font.
    Debug.Print "Report Font: "; Me.FontName
    Debug.Print "Report Font Size: "; Me.FontSize
    ' Print height and width required for text string.
    Debug.Print "Text Height (Twips): "; Me.TextHeight("Product Report")
    Debug.Print "Text Width (Twips): "; Me.TextWidth("Product Report")Sub


Time Function

Description

Returns a Date indicating the current system time.

Syntax

Time

Remarks

To set the system time, use the Time statement.

See Also

Date Function, Date Statement, Time Statement, Timer Function.

Specifics (Microsoft Access)

You can insert the current time on a form or report by clicking Date And Time on the Insert menu. This command creates a text box on a form or report and sets the ControlSource property of the text box to the expression =Time(). It is available only in form Design view and report Design view.

You can also use the Time function in a query expression or in a macro. However, you must include the parentheses after the function when you use it anywhere other than in a Visual Basic module, as in the expression Time().

Example

This example uses the Time function to return the current system time.

MyTime = Time    ' Return current system time.

You can use the Time function in a calculated control to return the current system time. For example, you can create a text box and set its ControlSource property to the following expression.

= Time()


Time Statement

Description

Sets the system time.

Syntax

Time = time

The time argument is any numeric or string expression, or any combination, that can represent a time.

Remarks

If time is a string, Time attempts to convert it to a time using the time separators you specified for your system. If it can’t be converted to a valid time, an error occurs.

Note If you use the Time statement to set the time on computers using versions of MS-DOS earlier than version 3.3, the change remains in effect only until you change it again or turn off your computer. Many computers have a battery-powered CMOS RAM that retains date and time information when the computer is turned off. However, to permanently change the time on computers running earlier versions of MS-DOS, you may have to use your Setup disk or perform some equivalent action. Refer to the documentation for your particular system.

See Also

Date Function, Date Statement, Time Function.

Example

This example uses the Time statement to set the computer system time to a user-defined time.

MyTime = #4:35:17 PM#        ' Assign a time.= MyTime                ' Set system time to MyTime.


Timer Event

Applies To

Form.

Description

The Timer event occurs for a form at regular intervals as specified by the form’s TimerInterval property.

Remarks

By running a macro or executing an event procedure when a Timer event occurs, you can control what Microsoft Access does at every timer interval. For example, you might want to requery underlying records or repaint the screen at specified intervals.

The TimerInterval property setting of the form specifies the interval, in milliseconds, between Timer events. The interval can be between 0 and 65,535 milliseconds. Setting the TimerInterval property to 0 prevents the Timer event from occurring.

See Also

Timer Function, TimerInterval Property.


Timer Event -- Event Procedures

Description

To create an event procedure that is executed when the Timer event occurs, set the OnTimer property to [Event Procedure], and click the Build button.

Syntax

Private Sub Form_Timer( )

Remarks

You can’t cancel the Timer event.

See Also

Timer Event — Macros.

Example

The following example demonstrates a digital clock you can display on a form. A label control displays the current time according to your computer’s system clock.

To try this example, add the following code to the Declarations section of a module for a form that contains a label named Clock. Set the form’s TimerInterval property to 1000 milliseconds to update the clock every second.

Private Sub Form_Timer()
    Clock.Caption = Time            ' Update time display.Sub


Timer Event -- Macros

Description

To run a macro when the Timer event occurs, set the OnTimer event property to the name of the macro.

Remarks

You can’t use the CancelEvent action in a Timer macro. However, setting the TimerInterval property of the form to 0 prevents the Timer event from occurring.

See Also

Timer Event — Event Procedures.


Timer Function

Description

Returns the number of seconds elapsed since midnight.

Syntax

Timer

See Also

Time Function.

Example

This example uses the Timer function to pause the application. The example also uses DoEvents to yield to other processes during the pause.

If (MsgBox("Press Yes to pause for 5 seconds", 4)) = vbYes Then
    PauseTime = 5    ' Set duration.
    Start = Timer    ' Set start time.
    Do While Timer < Start + PauseTime
        DoEvents                        ' Yield to other processes.
    Loop
    Finish = Timer    ' Set end time.
    TotalTime = Finish - Start    ' Calculate total time.
    MsgBox "Paused for " & TotalTime & " seconds"
    EndIf

You can use the Timer function to time operations and events in your Microsoft Access application by placing the Timer function immediately before and after the operation in your code that you wish to time. The following example uses the name of a query as its argument, then calculates how long it takes the query to run.

Sub QueryTimer (strQueryName As String)
    Dim sngStart As Single, sngEnd As Single
    Dim sngElapsed As Single

    sngStart = Timer                                    ' Get start time.
    DoCmd.OpenQuery strQueryName, acNormal            ' Run query.
    sngEnd = Timer                                    ' Get end time.
    sngElapsed = Format(sngEnd - sngStart, "Fixed")    ' Elapsed time.
    MsgBox ("The query " & strQueryName & " took " & sngElapsed _
        & " seconds to run.")Sub


TimerInterval Property

Applies To

Form.

Description

You can use the TimerInterval property in to specify the interval, in milliseconds, between Timer events on a form.

Setting

The TimerInterval property setting is a Long Integer between 0 and 2,147,483,647 representing the interval, in milliseconds, between Timer events on a form.

You can set this property using the form’s property sheet, a macro, or Visual Basic.

When using Visual Basic, you set the TimerInterval property in the form’s Load event.

Remarks

Put Visual Basic code you want run at intervals specified by the TimerInterval property in the Timer event procedure for a form. For example, to requery records every 30 seconds, you can put code in the Timer event procedure for a form to requery the records, and then set the TimerInterval property to 30000.

See Also

Timer Event.

Example

The following example shows how to create a flashing button on a form by displaying and hiding an icon on the button. The form’s Load event procedure sets the form’s TimerInterval property to 1000 so the icon display is toggled once every second.

Sub Form_Load()
    Me.TimerInterval = 1000SubForm_Timer()
    Static intShowPicture As Integer
    If intShowPicture Then
        Me!btnPicture.Picture = "C:\Icons\Flash.ico"
    Else
        Me!btnPicture.Picture = Null        ' Don't show icon.
    End If
    intShowPicture = Not intShowPictureSub


TimeSerial Function

Description

Returns a Date containing the time for a specific hour, minute, and second.

Syntax

TimeSerial(hour, minute, second)

The TimeSerial function syntax has these named arguments:

Part | Description
hour | Number between 0 (12:00 A.M.) and 23 (11:00 P.M.), inclusive, or a numeric expression.
minute | Any numeric expression.
second | Any numeric expression.

Remarks

To specify a time, such as 11:59:59, the range of numbers for each TimeSerial argument should be in the normally accepted range for the unit; that is, 0 – 23 for hours and 0 – 59 for minutes and seconds. However, you can also specify relative times for each argument using any numeric expression that represents some number of hours, minutes, or seconds before or after a certain time. The following example uses expressions instead of absolute time numbers. The TimeSerial function returns a time for 15 minutes before (-15) six hours before noon (12 - 6), or 5:45:00 A.M.

TimeSerial(12 - 6, -15, 0)

When any argument exceeds the normally accepted range for that argument, it increments to the next larger unit as appropriate. For example, if you specify 75 minutes, it is evaluated as one hour and 15 minutes. However, if any single argument is outside the range -32,768 to 32,767, or if the time specified by the three arguments, either directly or by expression, causes the date to fall outside the acceptable range of dates, an error occurs.

See Also

DateSerial Function, DateValue Function, Hour Function, Minute Function, Now Function, Second Function, TimeValue Function.

Example

This example uses the TimeSerial function to return a time for the specified hour, minute, and second.

MyTime = TimeSerial(16, 35, 17)        ' MyTime contains serial
                                    ' representation of 4:35:17 PM.


TimeValue Function

Description

Returns a Date containing the time.

Syntax

TimeValue(time)

The time argument is normally a string expression representing a time from 0:00:00 (12:00:00 A.M.) to 23:59:59 (11:59:59 P.M.), inclusive. However, time can also be any expression that represents a time in that range. If time contains Null, Null is returned.

Remarks

You can enter valid times using a 12- or 24-hour clock. For example, "2:24PM" and "14:24" are both valid time arguments.

If the time argument contains date information, TimeValue doesn’t return it. However, if time includes invalid date information, an error occurs.

See Also

DateSerial Function, DateValue Function, Hour Function, Minute Function, Now Function, Second Function, TimeSerial Function.

Example

This example uses the TimeValue function to convert a string to a time. You can also use date literals to directly assign a time to a Variant or Date variable (for example, MyTime = #4:35:17 PM#).

MyTime = TimeValue("4:35:17 PM")            ' Return a time.


Top Property

See Left, Top Properties.


TopValues Property

Applies To

Query.

Description

You can use the TopValues property to return a specified number of records or percentage of records that meet the criteria you specify. For example, you might want to return the bottom 10 values or the top 25 percent of values in a field.

Note The TopValues property applies only to append, make-table, and select queries.

Setting

The TopValues property setting is an Integer value representing the exact number of values to return or a number followed by a percent sign (%) representing the percentage of records to return. For example, to return the top 10 values, set the TopValues property to 10; to return the top 10 percent of values, set the TopValues property to 10 %.

You can set the TopValues property in the query property sheet.

You set this property in SQL view of the Query window by using a TOP n or TOP n PERCENT clause in the SQL statement.

You can also set the TopValues property using the Top Values combo box on the Query Design toolbar.

Note The TopValues property in the query property sheet and on the Query Design toolbar is a combo box that contains a list of values and percentage values. You can select one of these values or you may enter any valid setting into the text box portion of this control.

Remarks

Typically, you use the TopValues property setting together with sorted fields. The field you want to display top values for should be the leftmost field that has the Sort box clicked in the query design grid. An Ascending sort returns the bottommost records, and a Descending sort returns the topmost records. If you specify that a specific number of records be returned, all records with values that match the value in the last record are also returned.

For example, suppose a set of employees have the following sales totals.

If you set the TopValues property to 3 with a Descending sort on the Sales field, Microsoft Access returns the following four records.

Note To return the topmost or bottommost values without displaying duplicate values, set the UniqueValues property to Yes.

Example

You can’t set this property in code directly. It’s set when you create a new query using an SQL statement. The TOP n or TOP n PERCENT clause in the SQL statement corresponds to the TopValues property setting.

This example assigns an SQL string that returns the top 10 most expensive products to the RecordSource property for a form.

Dim strGetSQL As String= "SELECT DISTINCTROW TOP 10 Products.[ProductName], "= strGetSQL & "AS TenMostExpensiveProducts, "= strGetSQL & "Products.UnitPrice FROM Products "= strGetSQL & "ORDER BY Products.[UnitPrice] DESC;".RecordSource = strGetSQL


TransferDatabase Action

Description

You can use the TransferDatabase action to import or export data between the current Microsoft Access database and another database. You can also link a table to the current Microsoft Access database from another database. With a linked table, you have access to the table’s data while the table itself remains in the other database.

Setting

The TransferDatabase action uses the following arguments.

Remarks

You can import and export tables between Microsoft Access and other types of databases. You can also export Microsoft Access select queries to other types of databases, as long as these select queries don’t contain parameters. Microsoft Access exports the result set of the query in the form of a table. You can import and export any Microsoft Access database object if both databases are Microsoft Access databases.

If the database you’re accessing requires a password, a dialog box is displayed when you run the macro. Type the password in this dialog box.

The TransferDatabase action is similar to clicking the Import or Link Tables subcommand of the Get External Data command or the Save As/Export command on the File menu of the Database window. You can use these commands to select a source of data, such as Microsoft Access or a type of database, spreadsheet, or text file. If you select a database, one or more dialog boxes are displayed in which you select the type of object to import or export (for Microsoft Access databases), the name of the object, and other options, depending on the database you are importing from or exporting or linking to. The arguments for the TransferDatabase action reflect the options in these dialog boxes.

If you want to supply index information for a linked FoxPro or dBASE table, first link the FoxPro or dBASE table by clicking the Link Tables subcommand of the Get External Data command on the File menu and specify the indexes in the dialog boxes for this command. Microsoft Access stores the index information in a special information (.inf) file, located in the Access folder. You can then delete the link to the linked table. The next time you use the TransferDatabase action to link this FoxPro or dBASE table, Microsoft Access uses the index information that you’ve specified.

To run the TransferDatabase action in Visual Basic, use the TransferDatabase method of the DoCmd object.

See Also

Connect Property, CopyObject Action, OutputTo Action, Save Action, SendObject Action, TransferDatabase Method, TransferSpreadsheet Action, TransferText Action.


TransferDatabase Method

Applies To

DoCmd Object.

Description

The TransferDatabase method carries out the TransferDatabase action in Visual Basic. For more information on how the action and its arguments work, see the action topic.

Syntax

DoCmd.TransferDatabase [transfertype], databasetype, databasename [,objecttype], source, destination [, structureonly] [, saveloginid]

The TransferDatabase method uses the following arguments.

Remarks

You can leave an optional argument blank in the middle of the syntax, but you must include the argument’s comma. If you leave a trailing argument blank, don’t use a comma following the last argument you specify.

The administrator of an ODBC database can disable the feature provided by the saveloginid argument, requiring all users to enter the login ID and password each time they connect to the ODBC database.

See Also

CopyObject Method, DoCmd Object, Save Method, TransferDatabase Action, TransferSpreadsheet Method, TransferText Method.

Example

This example imports the NW Sales for April report from the Microsoft Access database NWSales.mdb into the Corporate Sales for April report in the current database.

DoCmd.TransferDatabase acImport, "Microsoft Access", _
    "C:\DBS\NWSales.mdb", acReport, "NW Sales for April", _
    "Corporate Sales for April"

This example links the ODBC database table Authors to the current database.

DoCmd.TransferDatabase acLink, "ODBC Database", _
    "ODBC;DSN=DataSource1;UID=User2;PWD=www;LANGUAGE=us_english;" _
    & "DATABASE=pubs", acTable, "Authors", "dboAuthors"

Argument | Description
transfertype | One of the following intrinsic constants: acImport acExport acLink If you leave this argument blank, the default (acImport) is assumed.
databasetype | A string expression that is the name of one of the types of databases you can use to import, export, or link data. In the Macro window, you can view the database types in the list for the Database Type action argument of the TransferDatabase action.

databasename | A string expression that is the full name, including the path, of the database you want to use to import, export, or link data.
objecttype | One of the following intrinsic constants: acTable acQuery acForm acReport acMacro acModule This is the type of object whose data you want to import, export, or link. You can specify an object other than acTable only if you are importing or exporting data between two Microsoft Access databases. If you are exporting the results of a Microsoft Access select query to another type of database, specify acTable for this argument. If you leave this argument blank, the default (acTable) is assumed.
source | A string expression that is the name of the object whose data you want to import, export, or link.
destination | A string expression that is the name of the imported, exported, or linked object in the destination database.
structureonly | Use True (-1) to import or export only the structure of a database table. Use False (0) to import or export the structure of the table and its data. If you leave this argument blank, the default (False) is assumed.
saveloginid | Use True to store the login identification (ID) and password for an ODBC database in the connection string for a linked table from the database. If you do this, you don’t have to log in each time you open the table. Use False if you don’t want to store the login ID and password. If you leave this argument blank, the default (False) is assumed. This argument is available only in Visual Basic.


TransferSpreadsheet Action

Description

You can use the TransferSpreadsheet action to import or export data between the current Microsoft Access database and a spreadsheet file. You can also link the data in a Microsoft Excel spreadsheet to the current Microsoft Access database. With a linked spreadsheet, you can view and edit the spreadsheet data with Microsoft Access while still allowing complete access to the data from your Microsoft Excel spreadsheet program.

Setting

The TransferSpreadsheet action uses the following arguments.

Action argument | Description
Transfer Type | The type of transfer you want to make. Select Import, Export, or Link in the Transfer Type argument in the Action Arguments section of the Macro window. The default is Import.
Spreadsheet Type | The type of spreadsheet to import from, export to, or link to. You can select one of a number of spreadsheet types in the box. The default is Microsoft Excel version 3.0.
 | Note You can import, export, and link spreadsheet data from Microsoft Excel spreadsheets, but you can only import and export data from Lotus® spreadsheets. Microsoft Access also no longer supports importing, exporting, or linking data from Lotus (WKS) or Microsoft Excel version 2.0 spreadsheets.
Table Name | The name of the Microsoft Access table to import spreadsheet data to, export spreadsheet data from, or link spreadsheet data to. You can also type the name of the Microsoft Access select query you want to export data from. This is a required argument. If you select Import in the Transfer Type argument, Microsoft Access appends the spreadsheet data to this table if the table already exists. Otherwise, Microsoft Access creates a new table containing the spreadsheet data.
Filename | The name of the spreadsheet file to import from, export to, or link to. Include the full path. This is a required argument. Microsoft Access creates a new spreadsheet when you export data from Microsoft Access. If the filename is the same as the name of an existing spreadsheet, Microsoft Access replaces the existing spreadsheet, unless you’re exporting to a Microsoft Excel version 5.0 or 7.0 workbook. In that case, Microsoft Access copies the exported data to the next available worksheet in the workbook.
Has Field Names | Specifies whether the first row of the spreadsheet contains the names of the fields. If you click Yes, Microsoft Access uses the names in this row as field names in the Microsoft Access table when you import or link the spreadsheet data. If you click No, Microsoft Access treats the first row as a normal row of data. The default is No. When you export Microsoft Access table or select query data to a spreadsheet, the field names are inserted into the first row of the spreadsheet if you have selected Yes for this argument. If you want to import or link the Database named range from a Microsoft Excel spreadsheet, you must click Yes in this box.

Action argument | Description
Range | The range of cells to import or link. Leave this argument blank to import or link the entire spreadsheet. You can type the name of a range in the spreadsheet or specify the range of cells to import or link, such as A1:E25 or A1..E25. If you are importing from or linking to a Microsoft Excel version 5.0 or 7.0 worksheet, you can prefix the range with the name of the worksheet and an exclamation point; for example, Budget!A1:C7. Microsoft Access ignores this argument when you export. If you are importing from or linking to a Microsoft Excel spreadsheet, you can specify the Database named range by typing DATABASE in the Range box. This name is reserved by Microsoft Access for this special named range in Microsoft Excel. For a description of specifying a range of cells as the Database named range in Microsoft Excel, see your Microsoft Excel documentation.

Remarks

You can export the data in Microsoft Access select queries to spreadsheets, as long as these select queries don’t contain parameters. Microsoft Access exports the result set of the query, treating it just like a table.

Spreadsheet data that you append to an existing Microsoft Access table must be compatible with the table’s structure. Each field in the spreadsheet must be of the same data type as the corresponding field in the table, and the fields must be in the same order (unless you set the Has Field Names argument to Yes, in which case the field names in the spreadsheet must match the field names in the table).

This action is similar to clicking the Import or Link Tables subcommand of the Get External Data command or the Save As/Export command on the File menu of the Database window. You can use these commands to select a source of data, such as Microsoft Access or a type of database, spreadsheet, or text file. If you select a spreadsheet, a series of dialog boxes appear, or a Microsoft Access wizard runs, in which you select the name of the spreadsheet and other options. The arguments of the TransferSpreadsheet action reflect the options in these dialog boxes or in the wizards.

To run the TransferSpreadsheet action in Visual Basic, use the TransferSpreadsheet method of the DoCmd object.

See Also

OutputTo Action, SendObject Action, TransferDatabase Action, TransferSpreadsheet Method, TransferText Action.


TransferSpreadsheet Method

Applies To

DoCmd Object.

Description

The TransferSpreadsheet method carries out the TransferSpreadsheet action in Visual Basic. For more information on how the action and its arguments work, see the action topic.

Syntax

DoCmd.TransferSpreadsheet [transfertype] [, spreadsheettype], tablename,filename [, hasfieldnames] [, range]

The TransferSpreadsheet method uses the following arguments.

Argument | Description
transfertype | One of the following intrinsic constants: acImport If you leave this argument blank, the default (acImport) is assumed
spreadsheettype | One of the following numeric settings: 0 Microsoft Excel version 3.0 Lotus (WK1) Lotus (WK3) Lotus (WJ2) — Japanese version only Microsoft Excel version 5.0 and version 7.0 Microsoft Excel version 4.0 Lotus (WK4) Note You can import, export, and link spreadsheet data from Microsoft Excel spreadsheets, but you can only import and export data from Lotus spreadsheets. Microsoft Access also no longer supports importing, exporting, or linking data from Lotus (WKS) or Microsoft Excel version 2.0 spreadsheets. If you leave this argument blank, the default (Microsoft Excel 3) is assumed.

tablename | A string expression that is the name of the Microsoft Access table you want to import spreadsheet data into, export spreadsheet data from, or link spreadsheet data to, or the Microsoft Access select query whose results you want to export to a spreadsheet.
filename | A string expression that is the file name and path of the spreadsheet you want to import from, export to, or link to.
hasfieldnames | Use True (-1) to use the first row of the spreadsheet as field names when importing, exporting, or linking. Use False (0) to treat the first row of the spreadsheet as normal data. If you leave this argument blank, the default (False) is assumed.
range | A string expression that is a valid range of cells or the name of a range in the spreadsheet. This argument applies only to importing. Leave this argument blank to import the entire spreadsheet.

Remarks

You can leave an optional argument blank in the middle of the syntax, but you must include the argument’s comma. If you leave a trailing argument blank, don’t use a comma following the last argument you specify.

See Also

DoCmd Object, OutputTo Method, SendObject Method, TransferDatabase Method, TransferSpreadsheet Action, TransferText Method.

Example

This example imports the data from the specified range of the Lotus spreadsheet Newemps.wk3 into the Microsoft Access Employees table. It uses the first row of the spreadsheet as field names.

DoCmd.TransferSpreadsheet acImport, 3, _
    "Employees",C:\Lotus\Newemps.wk3", True, "A1:G12"


TransferText Action

Description

You can use the TransferText action to import or export text between the current Microsoft Access database and a text file. You can also link the data in a text file to the current Microsoft Access database. With a linked text file, you can view and edit the text data with Microsoft Access while still allowing complete access to the data from your word processing program.

Setting

The TransferText action uses the following arguments.

Action argument | Description
Transfer Type | The type of transfer you want to make. You can import data from, export data to, or link to data in delimited or fixed-width text files. You can also export data to a Microsoft Word for Windows mail merge data file, which you can then use with the Word for Windows mail merge feature to create merged documents such as form letters and mailing labels.
 | Select Import Delimited, Import Fixed Width, Export Delimited, Export Fixed Width, Link Delimited, Link Fixed Width, or Export Word for Windows Merge in the Transfer Type argument in the Action Arguments section of the Macro window. The default is Import Delimited.
Specification Name | The specification name for the set of options that determines how a text file is imported, exported, or linked. This is a required argument for fixed-width text files.
 | You can use the Import or Link Tables subcommand of the Get External Data command or the Save As/Export command on the File menu to create a specification for a particular type of text file, such as a delimited text file that uses tabs to separate fields and has an MDY format for dates. When you click one of these commands and select a type of text file to import, export, or link, the Text Import Wizard, Text Export Wizard, or Link Text Wizard runs. You can click the Advanced button in the wizard and define and save a specification in the dialog box that is displayed. You can then type the specification name in this argument whenever you want to import or export the same type of text file.
 | You can import, export, or link delimited text files without typing a specification name for this argument. In this case, Microsoft Access uses the defaults from the wizard dialog box. Microsoft Access uses a predetermined format for mail merge data files, so you don’t ever need to type a specification name for this argument when you export these types of files.
Table Name | The name of the Microsoft Access table to import text data to, export text data from, or link text data to. You can also type the name of the Microsoft Access select query you want to export data from. This is a required argument.
 | If you click Import Delimited or Import Fixed Width in the Transfer Type box, Microsoft Access appends the text data to this table if the table already exists. Otherwise, Microsoft Access creates a new table containing the text data.
File Name | The name of the text file to import from, export to, or link to. Include the full path. This is a required argument.
 | Microsoft Access creates a new text file when you export data from Microsoft Access. If the filename is the same as the name of an existing text file, Microsoft Access replaces the existing text file.
Has Field Names | Specifies whether the first row of the text file contains the names of the fields. If you click Yes, Microsoft Access uses the names in this row as field names in the Microsoft Access table when you import or link the text data. If you click No, Microsoft Access treats the first row as a normal row of data. The default is No.
 | Microsoft Access ignores this argument for Word for Windows mail merge data files because the first row must contain the field names.
 | When you export Microsoft Access table or select query data to a delimited or fixed-width text file, Microsoft Access inserts the field names of your table or select query into the first row of the text file if you have selected Yes for this argument.
 | If you are importing or linking a fixed-width text file and click Yes in this box, the first row containing the field names must use the field delimiter set in the import/export specification to separate the field names. If you are exporting to a fixed-width text file and click Yes for this argument, Microsoft Access inserts the field names into the first row of the text file using this delimiter.

Remarks

You can export the data in Microsoft Access select queries to text files, as long as these select queries don’t contain parameters. Microsoft Access exports the result set of the query, treating it just like a table.

Text data that you append to an existing Microsoft Access table must be compatible with the table’s structure. Each field in the text must be of the same data type as the corresponding field in the table, and the fields must be in the same order (unless you set the Has Field Names argument to Yes, in which case the field names in the text must match the field names in the table).

Note This action is similar to clicking the Import or Link Tables subcommand of the Get External Data command or the Save As/Export command on the File menu of the Database window. You can use these commands to select a source of data, such as Microsoft Access or a type of database, spreadsheet, or text file. If you select a delimited or fixed-width text file, a wizard prompts you to select the name of the text file and other options. The arguments of the TransferText action reflect the options in these wizards.

An import/export specification stores the information Microsoft Access needs to import, export, or link a text file. You can use stored specifications to import, export, or link text data from or to similar text files. For example, you might receive weekly sales figures in a text file from a mainframe computer. You can create and save a specification for this type of data and then use the specification whenever you add this data to your Microsoft Access database.

To run the TransferText action in Visual Basic, use the TransferText method of the DoCmd object.

See Also

OutputTo Action, SendObject Action, TransferDatabase Action, TransferSpreadsheet Action, TransferText Method.


TransferText Method

Applies To

DoCmd Object.

Description

The TransferText method carries out the TransferText action in Visual Basic. For more information on how the action and its arguments work, see the action topic.

Syntax

DoCmd.TransferText [transfertype] [, specificationname], tablename, filename[, hasfieldnames]

The TransferText method uses the following arguments.

Argument | Description
transfertype | One of the following intrinsic constants: acImportDelim acImportFixed acExportDelim acExportFixed acExportMerge acLinkDelim acLinkFixed If you leave this argument blank, the default (acImportDelim) is assumed.
specificationname | A string expression that is the name of an import or export specification you have created and saved in the current database. This argument is required for fixed-width text files. For delimited text files and Microsoft Word for Windows mail merge data files, you can leave this argument blank to select the default import/export specifications.
tablename | A string expression that is the name of the Microsoft Access table you want to import text data to, export text data from, or link text data to, or the Microsoft Access select query whose results you want to export to a text file.
filename | A string expression that is the full name, including the path, of the text file you want to import from, export to, or link to.
hasfieldnames | Use True (-1) to use the first row of the text file as field names when importing, exporting, or linking. Use False (0) to treat the first row of the text file as normal data. If you leave this argument blank, the default (False) is assumed. This argument is ignored for Word for Windows mail merge data files, which must always contain the field names in the first row.

Remarks

You can leave an optional argument blank in the middle of the syntax, but you must include the argument’s comma. If you leave a trailing argument blank, don’t use a comma following the last argument you specify.

See Also

DoCmd Object, OutputTo Method, SendObject Method, TransferDatabase Method, TransferSpreadsheet Method, TransferText Action.

Example

This example exports the data from the Microsoft Access table External Report to the delimited text file April.doc using the specification Standard Output.

DoCmd.TransferText acExportDelim, "Standard Output", _
    "External Report", "C:\Txtfiles\April.doc"


Transparent Property

Applies To

Command Button Control.

Description

You can use the Transparent property to specify whether a command button is visible or transparent.

Tip Use the BackStyle property to make other controls visible or transparent.

Setting

The Transparent property uses the following settings.

Setting | Description | Visual Basic
Yes | The button is transparent. | True (-1)
No | (Default) The button is visible. | False (0)

You can set this property in the command button’s property sheet, a macro, or Visual Basic.

Remarks

You can use this property to place a transparent command button over another control. For example, you could place several transparent buttons over a picture displayed in an image frame and run various macros or Visual Basic event procedures depending which part of the picture the user clicks.

Note To hide and disable a button, use the Visible property. To disable a button without hiding it, use the Enabled property. To hide a button only when a form or report is printed, use the DisplayWhen property.

See Also

BackColor Property; BackStyle Property; BackStyle Property; DisplayWhen Property; Enabled, Locked Properties; Visible Property (Microsoft Access).


Trim Function

See LTrim, RTrim, and Trim Functions.


TripleState Property

Applies To

Check Box Control, Option Button Control, Toggle Button Control.

Description

You can use the TripleState property to specify how a check box, toggle button, or option button will display Null values.

Note The TripleState property does not apply to the specified controls when they are used inside of an option group control.

Setting

The TripleState property uses the following settings.

Setting

Description

Visual Basic

Yes | The control will cycle through states for Yes, No, and Null values. | True (-1)
No | (Default) The control will cycle through states for Yes and No values. Null values display like No values. | False (0)

You can set the TripleState property in a control’s property sheet, a macro, or using Visual Basic. You can also set this property in the control’s default control style.

This property can be set in any view.

Remarks

When the TripleState property of a control is set to Yes, the control appears dimmed when its Value property is set to Null.


Type Statement

Description

Used at module level to define a user-defined data type containing one or more elements.

Syntax

[Private | Public] Type varname
elementname [([subscripts])] As type
[elementname [([subscripts])] As type]
. . .End Type

The Type statement syntax has these parts:

Part | Description
Public | Used to declare user-defined types that are available to all procedures in all modules in all projects.
Private | Used to declare user-defined types that are available only within the module where the declaration is made.
varname | Name of the user-defined type; follows standard variable naming conventions.
elementname | Name of an element of the user-defined type. Element names also follow standard variable naming conventions, except that keywords can be used.
subscripts | Dimensions of an array element. Use only parentheses when declaring an array whose size can change. The subscripts argument uses the following syntax:
 | [lower To] upper [,[lower To] upper] . . .
 | When not explicitly stated in lower, the lower bound of an array is controlled by the Option Base statement. The lower bound is zero if no Option Base statement is present.
type | Data type of the element; may be Byte, Boolean, Integer, Long, Currency, Single, Double, Date, String, String * length (for fixed-length strings), Object, Variant, another user-defined type, or an object type.

Remarks

The Type statement can be used only at module level. Once you have declared a user-defined type using the Type statement, you can declare a variable of that type anywhere within the scope of the declaration. Use Dim, Private, Public, ReDim, or Static to declare a variable of a user-defined type.

In standard modules, user-defined types are public by default. This visibility can be changed using the Private keyword. In class modules, however, user-defined types can only be private and the visibility cannot be changed using the Public keyword.

Line numbers and line labels aren’t allowed in Type...End Type blocks.

User-defined types are often used with data records, which frequently consist of a number of related elements of different data types.

The following example shows the use of fixed-size arrays in a user-defined type:

Type StateData(1 To 100) As Integer            ' Declare a static array.As String * 30TypeWashington(1 To 100) As StateData

In the preceding example, StateData includes the CityCode static array, and the record Washington has the same structure as StateData.

When you declare a fixed-size array within a user-defined type, its dimensions must be declared with numeric literals or constants rather than variables.

The setting of the Option Base statement determines the lower bound for arrays within user-defined types.

See Also

Data Type Summary, Dim Statement, Option Base Statement, Private Statement, Public Statement, ReDim Statement, Static Statement.

Specifics (Microsoft Access)

In Microsoft Access, user-defined types in a standard module are public by default. To make a user-defined type in a standard module private, precede the Type statement with the Private keyword.

In a form module or report module, user-defined types are private and cannot be made public.

Example

This example uses the Type statement to define a user-defined data type. The Type statement is used at the module level only. If it appears in a Class Module, a Type statement must be preceded by the keyword Private.

Type EmployeeRecord                ' Create user-defined type.
    ID As Integer                ' Define elements of data type.As String * 20As String * 30As LongAs DateTypeMyRecord As EmployeeRecord    ' Declare variable.
' Assignment to EmployeeRecord variable must occur in a procedure..ID = 12003                ' Assign a value to an element.


TypeName Function

Description

Returns a string that provides information about a variable.

Syntax

TypeName(varname)

The varname argument can be any variable except a variable of a user-defined type.

Remarks

The string returned by TypeName can be any one of the following:

String Returned | Variable contains
objecttype | An OLE Automation object whose type is objecttype.
Byte | A byte
Integer | An integer.
Long | A long integer.
Single | A single-precision floating-point number.
Double | A double-precision floating-point number.
Currency | A currency value.
Date | A date.
String | A string.
Boolean | A Boolean value.
Error | An error value.
Empty | Uninitialized.
Null | No valid data.
Object | An object that supports OLE Automation.
Unknown | An OLE Automation object whose type is unknown.
Nothing | An object variable that doesn’t refer to an object.

If varname is an array, the returned string can be any one of the possible returned strings (or Variant) with empty parentheses appended. For example, if varname is an array of integers, TypeName returns “Integer()”.

See Also

Data Type Summary, IsArray Function, IsDate Function, IsEmpty Function, IsError Function, IsMissing Function, IsNull Function, IsNumeric Function, IsObject Function, Variant Data Type, VarType Function.

Example

This example uses the TypeName function to return information about a variable.

' Declare variables.StrVar As String, IntVar As Integer, CurVar As CurrencyArrayVar (1 To 5) As Integer= Null                            ' Assign Null value.= TypeName(StrVar)                ' Returns "String".= TypeName(IntVar)                ' Returns "Integer".= TypeName(CurVar)                ' Returns "Currency".= TypeName(NullVar)                ' Returns "Null".= TypeName(ArrayVar)                ' Returns "Integer()".

The following example creates several object variables and passes them to the TypeName function.

Sub ObjectTypes()dbs As Database, tdf As TableDeffld As Field

' Get current database.dbs = CurrentDb
' Return TableDef object pointing to Orders table.tdf = dbs.TableDefs("Orders")
' Return Field object pointing to OrderDate field.fld = tdf.Fields("OrderDate")
' Print value returned by TypeName for each object..Print TypeName(dbs).Print TypeName(tdf).Print TypeName(fld)Sub


UBound Function

Description

Returns the largest available subscript for the indicated dimension of an array.

Syntax

UBound(arrayname[, dimension])

The UBound function syntax has these parts:

Part | Description
arrayname | Name of the array variable; follows standard variable naming conventions.
dimension | Whole number indicating which dimension’s upper bound is returned. Use 1 for the first dimension, 2 for the second, and so on. If dimension is omitted, 1 is assumed.

Remarks

The UBound function is used with the LBound function to determine the size of an array. Use the LBound function to find the lower limit of an array dimension.

UBound returns the values listed in the table below for an array with these dimensions:

Dim A(1 To 100, 0 To 3, -3 To 4)

Statement | Return Value
UBound(A, 1) | 100
UBound(A, 2) | 3
UBound(A, 3) | 4

See Also

Dim Statement, LBound Function, Option Base Statement, Public Statement, ReDim Statement.

Example

This example uses the UBound function to determine the largest available subscript for the indicated dimension of an array.

Dim MyArray(1 To 10, 5 To 15, 10 To 20)    ' Declare array variables.AnyArray(10)= UBound(MyArray, 1)                ' Returns 10.= UBound(MyArray, 3)                ' Returns 20.= UBound(AnyArray)                    ' Returns 10.


UCase Function

Description

Returns a string that has been converted to uppercase.

Syntax

UCase(string)

The string argument is any valid string expression. If string contains Null, Null is returned.

Remarks

Only lowercase letters are converted to uppercase; all uppercase letters and nonletter characters remain unchanged.

See Also

LCase Function.

Example

This example uses the UCase function to return an uppercase version of a string.

LowerCase = "Hello World 1234"            ' String to convert.= UCase(LowerCase)                ' Returns "HELLO WORLD 1234".


Undo Method

Applies To

Form, Control.

Description

You can use the Undo method to reset a control or form when its value has been changed. For example, you can use the Undo method to clear a change to a record that contains an invalid entry.

Syntax

object.Undo

The Undo method uses the following argument.

Argument | Description
object | A Form object or a Control object.

Remarks

If the Undo method is applied to a form, all changes to the current record are lost. If the Undo method is applied to a control, only the control itself is affected.

This method must be applied before the form or control is updated. You may want to include this method in a form’s BeforeUpdate event or a control’s Change event.

The Undo method offers an alternative to using the SendKeys statement to send the value of the ESC key in an event procedure.

Example

The following example shows how you can use the Undo method within the Change event procedure to force a field named LastName to reset to the original value, if changed.

Private Sub LastName_Change()!LastName.UndoSub

The next example uses the Undo method to reset all changes to a form before the form is updated.

Private Sub Form_BeforeUpdate(Cancel As Integer).UndoSub


Unique Property

Applies To

Index.

Description

You can use the Unique property to specify that an index enforces uniqueness of the data in the table’s key index.

Setting

The Unique property uses the following settings.

Setting | Description | Visual Basic
Yes | The index is a key (unique) index. | True (-1)
No | The index is a non-key index. | False (0)

You can set this property in the Indexes window of table Design or in Visual Basic.

Note To access the Unique property of an index using Visual Basic, use the Data Access Object’s Unique property.

Remarks

A key index helps to optimize finding records. It consists of one or more fields that uniquely arrange all records in a table in a predefined order. If the index consists of one field, values in that field must be unique. If the index consists of more than one field, duplicate values can occur in each field, but each combination of values from all the indexed fields must be unique. A non-key index has fields with values that are not necessarily unique.

An index is the primary index for a table if its Primary property is set to Yes. Each table can have only one primary index.

See Also

IgnoreNulls Property, Primary Property, Unique Property (Microsoft Office 95 Data Access Reference).


UniqueRecords Property

Applies To

Query.

Description

You can use the UniqueRecords property to specify whether to return only unique records based on all fields in the underlying data source, not just those fields present in the query itself.

Note The UniqueRecords property applies only to crosstab, data-definition, pass-through, and union queries.

Setting

The UniqueRecords property uses the following settings.

Setting | Description
Yes | (Default) Doesn’t return duplicate records.
No | Returns duplicate records.

You can set the UniqueRecords property in the query property sheet or SQL view of the Query window.

Note You set this property when you create a new query using an SQL statement. The DISTINCTROW predicate corresponds to the UniqueRecords property setting. The DISTINCT predicate corresponds to the UniqueValues property setting.

Remarks

You can use the UniqueRecords property when you want to omit data based on entire duplicate records, not just duplicate fields. Microsoft Access considers a record to be unique as long as the value in one field in the record differs from the value in the same field in another record.

The UniqueRecords property has an effect only when you use more than one table in the query and select fields from the tables used in the query. The UniqueRecords property is ignored if the query includes only one table.

The UniqueRecords and UniqueValues properties are related in that only one of them can be set to Yes at a time. When you set UniqueRecords to Yes, for example, Microsoft Access automatically sets UniqueValues to No. You can, however, set both of them to No. When both properties are set to No, all records are returned.

See Also

ALL, DISTINCT, DISTINCTROW, TOP Predicates (SQL) (Microsoft Office 95 Data Access Reference), UniqueValues Property.

Example

The query in this example returns a list of customers from the Customers table who have at least one order in the Orders table.

Customers Table

Customer name | Customer ID
Bon app’ | 1
Simons bistro | 2
Reggiani Caseifici | 3
Queen Cozinha | 4

Orders Table

Customer ID | Order ID
1 | 10
2 | 11
2 | 12
4 | 13
4 | 14

This SQL statement returns the customer names in the following table.

SELECT DISTINCTROW Customers.[CompanyName] Customers INNER JOIN Orders ON .[CustomerID] = Orders.[CustomerID];

Customers returned | Customer ID
Bon app’ | 1
Simons bistro | 2
Queen Cozinha | 4


UniqueValues Property

Applies To

Query.

Description

You can use the UniqueValues property when you want to omit records that contain duplicate data in the fields displayed in Datasheet view. For example, if a query’s output includes more than one field, the combination of values from all fields must be unique for a given record to be included in the results.

Note The UniqueValues property applies only to all queries except append, make-table, and select queries.

Setting

The UniqueValues property uses the following settings.

Setting | Description
Yes | Displays only the records in which the values of all fields displayed in Datasheet view are unique.
No | (Default) Displays all records.

You can set the UniqueValues property in the query property sheet or SQL view of the Query window.

Note You can set this property when you create a new query using an SQL statement. The DISTINCT predicate corresponds to the UniqueValues property setting. The DISTINCTROW predicate corresponds to the UniqueRecords property setting.

Remarks

When you set the UniqueValues property to Yes, the results of the query aren’t updatable and won’t reflect subsequent changes made by other users.

The UniqueValues and UniqueRecords properties are related in that only one of them can be set to Yes at a time. When you set the UniqueValues property to Yes, for example, Microsoft Access automatically sets the UniqueRecords property to No. You can, however, set both of them to No. When both properties are set to No, all records are returned.

Tip If you want to count the number of instances of a value in a field, create a totals query.

See Also

ALL, DISTINCT, DISTINCTROW, TOP Predicates (SQL) (Microsoft Office 95 Data Access Reference); UniqueRecords Property.

Example

The SELECT statement in this example returns a list of the countries in which there are customers. Because there may be many customers in each country, many records could have the same country in the Customers table. However, each country is represented only once in the query results.

This example uses the Customers table, which contains the following data.

Country | Company name
Brazil | Familia Arquibaldo
Brazil | Gourmet Lanchonetes
Brazil | Hanari Carnes
France | Du monde entier
France | Folies gourmandes
Ireland | Hungry Owl All-Night Grocers
Germany | Frankenversand

This SQL statement returns the countries in the following table.

SELECT DISTINCT Customers.[Country]Customers;

Countries returned

Brazil

France

Ireland

Germany


Unload Event

See Load, Unload Events.


Unlock Statement

See Lock, Unlock Statements.


Updated Event

Applies To

Bound Object Frame Control, Unbound Object Frame Control.

Description

The Updated event occurs when an OLE object’s data has been modified.

Note The Updated event applies only to controls on a form, not controls on a report.

Remarks

You can use this event to determine if an object’s data has been changed since it was last saved.

The Updated event occurs when the data in an OLE object has been modified. This update can come from the application in which the object was created or from one of the linked copies of this object. As a result, this event is asynchronous with other Microsoft Access control events.

Note The Updated event and the BeforeUpdate and AfterUpdate events for bound and unbound object frames are not related. The Updated event occurs when an OLE object’s data is changed, and the BeforeUpdate and AfterUpdate events occur when data is updated. Although not related, all three events usually occur when an OLE object’s data is changed. The Updated event generally occurs before the BeforeUpdate and AfterUpdate events; however, this may not happen every time.

See Also

Action Property; BeforeUpdate, AfterUpdate Events; Class Property; OLEType Property; OLETypeAllowed Property; UpdateOptions Property.


Updated Event -- Event Procedures

Description

To create an event procedure that is run when the Updated event occurs, set the OnUpdated property to [Event Procedure], and click the Build button.

To see if an object’s data has been changed since it was last saved, set a global variable in the Updated event procedure indicating that the object needs to be saved. When you save the OLE object, reset the variable.

Syntax

Private Sub controlname_Updated (Code As Integer)

The Updated event procedure uses the following argument.

Argument | Description
controlname | A string that is the name of the control affected by the Updated event procedure.
Code | An intrinsic constant that indicates how the OLE object was updated. The Code argument can have the following constants:

Argument

acOLEChanged

Description

Indicates that the object’s data has changed.

acOLESaved | Indicates that the object’s data has been saved by the application that created the object. This usually occurs when the user chooses the application’s Update command or whatever command is used for updating.
acOLEClosed | Indicates that the file containing the object’s data has been closed by the application that created the object.
acOLERenamed | Indicates that the file containing the object’s data has been renamed by the application that created the object.

See Also

Updated Event — Macros.


Updated Event -- Macros

Description

To run a macro when the Updated event occurs, set the OnUpdated property to the name of the macro.

Remarks

You can use an Updated macro to display a message whenever an OLE object’s data has been updated. However, macros can’t return the code that determines how the OLE object was updated, so you typically use event procedures with this event.

You can’t use the CancelEvent action in an Updated macro.

See Also

Updated Event — Event Procedures.


UpdateOptions Property

Applies To

Bound Object Frame Control, Unbound Object Frame Control.

Description

You can use the UpdateOptions property to specify how a linked OLE object is updated.

Setting

The UpdateOptions property uses the following settings.

Setting | Description | Visual Basic
Automatic | (Default) Updates the object each time the linked data changes. | 0
Manual | Updates the object only when the control’s Action property is set to acOLEUpdate or the link is updated with the OLE/DDE Links command on the Edit menu. | 2

You can set the UpdateOptions property using the property sheet, a macro, or Visual Basic. You can also set this property in a control’s default control style.

The UpdateOptions property setting is also available through the OLE/DDE Links command on the Edit menu.

Remarks

Normally, the object is updated automatically whenever the linked data changes, but you can tell Microsoft Access to update the data only when it receives a specific instruction to do so. For example, if other users or applications can access or change linked spreadsheet data on a form, you can use this property to specify that the linked data only be updated when the database is opened in single-user mode.

When the UpdateOptions property is set to Manual, updates do not occur based on the Refresh Interval setting specified in the Advanced tab of the Options dialog box, available by clicking Options on the Tools menu.

Note When an object’s data is changed, the Updated event occurs.

See Also

Action Property, Class Property, OLEType Property, OLETypeAllowed Property, Updated Event.

Example

The following example sets the UpdateOptions property for an unbound object frame named OLE1 to update manually, and then uses the Action property to force an update of the OLE object in the control.

OLE1.UpdateOptions = 2.Action = acOLEUpdate


UserControl Property

Applies To

Application Object.

Description

You can use the UserControl property in Visual Basic to determine whether the current Microsoft Access application was started by the user or by another application using OLE Automation.

Setting

The UserControl property uses the following settings.

Setting | Description
True (-1) | The current application was started by the user.
False (0) | The current application was started by another application using OLE Automation.

You can determine the UserControl property setting only using Visual Basic.

This property is read-only in all views.

Remarks

When an application is launched by the user, the Visible and UserControl properties of the Application object are both set to True. When the UserControl property is set to True, it is not possible to set the Visible property of the Application object to False.

When an Application object is created using OLE Automation, the Visible and UserControl properties of the Application object are both set to False.

See Also

Application Object, Visible Property (Application Object).


V1xNullBehavior Property

Applies To

Database Object.

Description

You can use the V1xNullBehavior property to specify whether zero-length strings ("") used in code to fill Text or Memo fields are converted to Null.

Note This property applies only to Microsoft Access version 1.x databases that have been converted to Microsoft Access version 2.0 databases and that contain such code. Microsoft Access automatically creates this property when it converts a version 1.x database to a version 2.0 database.

Setting

The V1xNullBehavior property uses the following settings.

Setting | Description
True (-1) | Zero-length strings are converted to Null.
False (0) | Zero-length strings aren’t converted to Null.

You can set this property only using Visual Basic.

Note If you change the setting for this property, you must close and then reopen the database for your change to take effect.

Remarks

For fastest performance, modify code that sets any Text or Memo fields to zero-length strings so the fields are set to Null, and remove the property from the Properties collection.

See Also

AllowZeroLength Property, V1xNullBehavior Property (Microsoft Office 95 Data Access Reference).


Val Function

Description

Returns the numbers contained in a string.

Syntax

Val(string)

The string argument is any valid string expression.

Remarks

The Val function stops reading the string at the first character it can’t recognize as part of a number. Symbols and characters that are often considered parts of numeric values, such as dollar signs and commas, are not recognized. However, the function recognizes radix prefixes &O (for octal) and &H (for hexadecimal). Blanks, tabs, and linefeeds are stripped from the argument.

The following returns the value 1615198:

Val("    1615 198th Street N.E.")

In the code below, Val returns the decimal value -1 for the hexadecimal value shown:

Val("&HFFFF")

Note The Val function recognizes only the period (.) as a valid decimal separator. When a possibility exists that different decimal separators may be used (for example, in international applications), you should use CDbl instead to convert a string to a number.

See Also

CDbl Function, Str Function.

Example

This example uses the Val function to return the numbers contained in a string.

MyValue = Val("2457")                    ' Returns 2457.= Val(" 2 45 7")                    ' Returns 2457.= Val("24 and 57")                ' Returns 24.


ValidationRule, ValidationText Properties

Applies To

Check Box Control, Combo Box Control, List Box Control, Option Button Control, Option Group Control, Table Fields, Text Box Control, Toggle Button Control.

Description

You can use the ValidationRule property to specify requirements for data entered into a field or control. When data is entered that violates the ValidationRule setting, you can specify the message to be displayed to the user by setting the ValidationText property.

Note The ValidationRule and ValidationText properties do not apply to check box, option button, or toggle button controls when they are in an option group. They apply only to the option group itself.

Setting

Enter an expression for the ValidationRule property setting and text for the ValidationText property setting. The maximum length for each property setting is 255 characters.

For controls, you can set the property to any valid expression. For field and record validation rules, the expression can’t contain user-defined functions, domain or aggregate functions, the CurrentUser or Eval function, or references to forms, queries, or tables. In addition, field validation rules can’t contain references to other fields. For records, expressions can include references to fields in that table.

You can set the ValidationRule and ValidationText properties in:

  • The lower portion of table Design view (for a field validation rule).
  • The property sheet for a table (for a record validation rule).
  • The property sheet for a control on a form.
  • A macro or Visual Basic. In Visual Basic, use a string expression to set these properties.

Note For table fields and records, you can also set these properties in Visual Basic by using the Data Access Objects ValidationRule property.

Remarks

Microsoft Access automatically validates values based on a field’s data type; for example Microsoft Access doesn’t allow text in a numeric field. You can set more specific rules using the ValidationRule property.

If you set the ValidationRule property but not the ValidationText property, Microsoft Access displays a standard error message when the validation rule is violated. If you set the ValidationText property, the text you enter is displayed as the error message.

For example, when a record is added for a new employee, you can enter a ValidationRule property requiring that the employee Start Date field fall between the company’s founding date and the current date. If the date entered isn’t in this range, you can display the ValidationText property message: “Start date is incorrect.”

If you create a control by dragging a field from the field list, the field’s validation rule remains in effect, although it isn’t displayed in the control’s ValidationRule property box in the property sheet. This is because a field’s validation rule is inherited by a control bound to that field.

Control, field, and record validation rules are applied as follows:

  • Validation rules you set for fields and controls are applied when you edit the data and the focus leaves the field or control.
  • Validation rules for records are applied when you move to another record.
  • If you create validation rules for both a field and a control bound to the field, both validation rules are applied when you edit data and the focus leaves the control.

The following table contains expression examples for the ValidationRule and ValidationText properties.

ValidationRule property | ValidationText property
<> 0 | Entry must be a non-zero value.
> 1000 Or Is Null | Entry must be blank or greater than 1000.
Like "A???? " | Entry must be 5 characters and begin with the letter A.
>= #1/1/95# And <#1/1/96# | Entry must be a date in 1995.
DLookup("[CustomerID] ", "Customers", " [CustomerID] = Forms![Customers]![CustomerID] ") Is Null | Entry must be unique CustomerID (form-level validation only).

If you create a validation rule for a field, Microsoft Access doesn’t normally allow a Null value to be stored in the field. If you want to allow a Null value, add Is Null to the validation rule, as in “<> 8 Or Is Null”.

You can’t set field or record validation rules for tables created outside Microsoft Access (for example, dBASE, Paradox, and SQL Server). For these kinds of tables, you can create validation rules for controls only.

See Also

AllowZeroLength Property; Required Property; ValidationRule, ValidationText Properties (Microsoft Office 95 Data Access Reference).

Example

The following example creates a validation rule for a Field that allows only values over 65 to be entered. If a number less than 65 is entered, a message is displayed. The properties are set using the SetFieldValidation function.

Dim strTblName As String, strFldName As StringstrValidRule As String, strValidText As String, intX As Integer= "Customers"= "Age"= ">= 65"= "Enter a number greater than or equal to 65."= SetFieldValidation(strTblName, strFldName, _
    strValidRule, strValidText)
SetFieldValidation(strTblName As String, _
        strFldName As String, strValidRule As String, _
        strValidText As String) As Integer
    Dim db As Database, td As TableDef, fld As Field
    Set db = CurrentDb
    Set td = db.TableDefs(strTblName)
    Set fld = td.Fields(strFldName)
    fld.ValidationRule = strValidRule
    fld.ValidationText = strValidTextFunction

The next example uses the SetTableValidation function to set record level validation to ensure that the value in the EndDate field comes after the value in the StartDate field.

Dim strTblName As String, strValidRule As StringstrValidText As StringintX As Integer= "Employees"= "EndDate > StartDate"= "Enter an EndDate that is later than the StartDate."= SetTableValidation(strTblName, strValidRule, strValidText)
SetTableValidation(strTblName As String, _
        strValidRule As String, strValidText As String) As Integer
    Dim db As Database, td As TableDef
    Set db = CurrentDb
    Set td = db.TableDefs(strTblName)
    td.ValidationRule = strValidRule
    td.ValidationText = strValidTextFunction


Value Property

Applies To

Check Box Control, Combo Box Control, List Box Control, Option Button Control, Option Group Control, Text Box Control, Toggle Button Control.

Description

You can use the Value property to determine or specify if a control is selected, the selected value or option within the control, or the text contained in a text box control.

  • Check box, option button, and toggle button controls — You can use this property to determine or specify whether or not the control is selected.
  • Combo box, list box, and option group controls — You can use this property to determine or specify which value or option in the control is selected.
  • Text box controls — You can use this property to determine or specify the text in the text box.

Setting

The Value property uses the following setting depending on the specified control.

Control | Setting | Description | Visual Basic
Check box | True False | The check box is selected (Default) The check box is cleared. | True (-1) False (0)
Combo box | The text in the text box portion of the control. | This may or may not be the same as the setting for the Text property of the control. The current setting for the Text property is what is displayed in the text box portion of the combo box; the Value property is set to the Text property setting only after this text is saved. |
List box | List box item value | The value in the bound column for the item selected in the list. |
Option button | True False | The option button is selected (Default) The option button isn’t selected. | True (-1) False (0)
Option group | OptionValue property setting | The OptionValue property setting for the selected control in the group. |
Text box | The value of the control’s Text property | The Text property returns the formatted string. The Text property may be different than the Value property for a text box control. The Text property is the current contents of the control. The Value property is the saved value of the text box control. The Text property is always be current while the control has the focus. |
Toggle button | True | The toggle button is selected (pressed in). | True (-1)
 | False | The toggle button isn’t selected (not pressed in). | False (0)

You can set this property using only a macro or Visual Basic.

Remarks

The Value property returns or sets a control’s default property, which is the property that is assumed when you don’t explicitly specify a property name. For example, because the default value of a text box is the value of the Text property, you can refer to its Text property setting without explicitly specifying the name of the property with the following code.

Forms!frmCustomers!txtLastName = "Smith"

This means that the following two statements are equivalent text.

Forms!frmCustomers!optCreditApproved.Value = True!Form1!optCreditApproved = True

Note The Value property is not the same as the DefaultValue property, which specifies the value that a property is assigned when a new record is created.

See Also

DefaultValue Property, OldValue Property, OptionValue Property, Text Property, Value Property (Microsoft Office 95 Data Access Reference).

Example

The following example shows how you can call one of two procedures, depending whether the Credit check box on the Customers form is selected or cleared.

Sub PaymentType()Forms!Customers!Credit.Value = False ThenForms!Customers!Credit.Value = True ThenIfSub


Variant Data Type

Description

The Variant data type is the data type that all variables become if not explicitly declared as some other type (using statements such as Dim, Private, Public, or Static). The Variant data type has no type-declaration character.

The Variant is a special data type that can contain any kind of data except fixed-length String data and user-defined types. A Variant can also contain the special values Empty, Error, Nothing, and Null. You can determine how the data in a Variant is treated using the VarType or TypeName function.

Numeric data can be any integer or real number value ranging from
.797693134862315E308 to -4.94066E-324 for negative values and from 4.94066E-324 to 1.797693134862315E308 for positive values. Generally, numeric Variant data is maintained in its original data type within the Variant. For example, if you assign an Integer to a Variant, subsequent operations treat the Variant as if it were an Integer. However, if an arithmetic operation is performed on a Variant containing a Byte, an Integer, a Long, or a Single, and the result exceeds the normal range for the original data type, the result is promoted within the Variant to the next larger data type. A Byte is promoted to an Integer, an Integer is promoted to a Long, and a Long and a Single are promoted to a Double. An error occurs when Variant variables containing Currency and Double values exceed their respective ranges.

You can use the Variant data type in place of any data type to work with data in a more flexible way. If the contents of a Variant variable are digits, they may be either the string representation of the digits or their actual value, depending on the context. For example:

Dim MyVar As Variant= 98052

In the example shown above, MyVar contains a numeric representation — the actual value 98052. Arithmetic operators work as expected on Variant variables that contain numeric values or string data that can be interpreted as numbers. If you use the + operator to add MyVar to another Variant containing a number or to a variable of a numeric data type, the result is an arithmetic sum. See the information about addition and concatenation operators for complete information on how to use them with Variant data.

The value Empty denotes a Variant variable that hasn’t been initialized (assigned an initial value). A Variant containing Empty is 0 if it is used in a numeric context and a zero-length string (" ") if it is used in a string context.

Don’t confuse Empty with Null. Null indicates that the Variant variable intentionally contains no valid data.

In a Variant, Error is a special value used to indicate that an error condition has occurred in a procedure. However, unlike for other kinds of errors, normal application-level error handling does not occur. This allows you, or the application itself, to take some alternative based on the error value. Error values are created by converting real numbers to error values using the CVErr function.

See Also

CVar Function, CVErr Function, Data Type Summary, Def type Statements, Dim Statement, Nothing, Private Statement, Public Statement, Static Statement, TypeName Function.


VarType Function

Description

Returns a value indicating the subtype of a variable.

Syntax

VarType(varname)

The varname argument can be any variable except a variable of a user-defined type.

Return Values

Constant | Value | Variable type description
vbEmpty | 0 | Empty (uninitialized)
vbNull | 1 | Null (no valid data)
vbInteger | 2 | Integer
vbLong | 3 | Long integer
vbSingle | 4 | Single-precision floating-point number
vbDouble | 5 | Double-precision floating-point number
vbCurrency | 6 | Currency
vbDate | 7 | Date
vbString | 8 | String
vbObject | 9 | OLE Automation object
vbError | 10 | Error
vbBoolean | 11 | Boolean
vbVariant | 12 | Variant (used only with arrays of Variants)
vbDataObject | 13 | Non-OLE Automation object
vbByte | 17 | Byte
vbArray | 8192 | Array

Note These constants are specified by Visual Basic for applications. As a result, the names can be used anywhere in your code in place of the actual values.

Remarks

The VarType function never returns the value for vbArray by itself. It is always added to some other value to indicate an array of a particular type. The constant vbVariant is only returned in conjunction with vbArray to indicate that the argument to the VarType function is an array of type Variant. For example, the value returned for an array of integers is calculated as vbInteger + vbArray, or 8194. If an object has a default property, VarType (object) returns the type of its default property.

See Also

Data Type Summary, IsArray Function, IsDate Function, IsEmpty Function, IsError Function, IsMissing Function, IsNull Function, IsNumeric Function, IsObject Function, TypeName Function, Variant Data Type.

Example

This example uses the VarType function to determine the subtype of a variable.

' Initialize variables.= 459: StrVar = "Hello World": DateVar = #2/12/69# = VarType(IntVar)                ' Returns 2.= VarType(DateVar)                ' Returns 7.= VarType(StrVar)                ' Returns 8.


Verb Property

Applies To

Bound Object Frame Control, Chart Control, Unbound Object Frame Control.

Description

You can use the Verb property to specify the operation to perform when an OLE object is activated, which is permitted when the control’s Action property is set to acOLEActivate.

Setting

You can set the Verb property by specifying an Integer data type value indicating the position of a verb in the list of verbs returned by the ObjectVerbs property. A verb, such as edit or play, specifies an operation a user can perform on an OLE object. you can set the Verb property to 1 to specify the first verb in the list, you can set it to 2 to specify the second verb in the list, and so on.

You can set the Verb property using the property sheet, a macro, or Visual Basic. You can also set this property using the default control style.

If you don’t set the ObjectVerbs property, you can set the Verb property to one of the following values to indicate the operation to perform. These values specify the standard verbs supported by all objects.

Constant | Value | Description
acOLEVerbPrimary | 0 | Performs the default operation for the object.
acOLEVerbShow | -1 | Activates the object for editing.
acOLEVerbOpen | -2 | Opens the object in a separate application window.
acOLEVerbHide | -3 | For embedded objects, hides the application that created the object.

With some application’s objects, you can use these additional values.

Constant | Value | Description
acOLEVerbInPlaceUIActivate | -4 | Activates the object for editing within the control. The menus and toolbars of the object application become available in the container application.
acOLEVerbInPlaceActivate | -5 | Activates the object within the control. The menus and toolbars of the object application aren’t available in the container application.

Remarks

Each object supports its own set of verbs. For example, many objects support the verbs edit and play. You can use the ObjectVerbs and ObjectVerbsCount properties to find out which verbs are supported by an object.

Microsoft Access automatically uses an object’s default verb if the user double-clicks an object for which the AutoActivate property is set to Double-Click.

See Also

Action Property, AutoActivate Property, ObjectVerbs Property, ObjectVerbsCount Property, OLEType Property, OLETypeAllowed Property.


ViewsAllowed Property

See DefaultView, ViewsAllowed Properties.


Visible Property

Applies To

Bound Object Frame Control, Chart Control, Check Box Control, Combo Box Control, Command Button Control, Form, Form Section, Image Control, Label Control, Line Control, List Box Control, Option Button Control, Option Group Control, Page Break Control, Rectangle Control, Report, Report Section, Subform/Subreport Control, Text Box Control, Toggle Button Control, Unbound Object Frame Control.

Description

You can use the Visible property to show or hide a form, report, form or report section, or control. This may be useful if you want to maintain access to information on a form without it being visible. For example, you could use the value of a control on a hidden form as the criteria for a query.

Setting

The Visible property uses the following settings.

Setting | Description | Visual Basic
Yes | (Default) The object is visible. | True (-1)
No | The object is not visible. | False (0)

You can set this property using the object’s property sheet (for sections and all controls except page breaks), a macro, or Visual Basic.

For forms and reports you must set this property using a macro or Visual Basic.

For controls, you can set this property using the default control style.

Remarks

The Visible property has no effect on a column in Datasheet view. To specify whether a column is visible in Datasheet view, you use the ColumnHidden property.

To hide an object when printing, you use the DisplayWhen property.

You can use the Visible property to hide a control on a form by including the property in a macro that runs when the Current event occurs. For example, you can show or hide a congratulatory message next to a salesperson’s monthly sales total in a sales report, depending on the sales total.

Note There is also a Visible property of the Application object that can be set to cause the application to be invisible. This property can only be set using Visual Basic.

See Also

Current Event, Format Event, Transparent Property, Visible Property (Application Object).


Visible Property (Application Object)

Applies To

Application Object.

Description

You can use the Visible property of the Application object to specify or determine whether a Microsoft Access application is visible.

Setting

The Visible property uses the following settings.

Setting | Description
True (-1) | The application is visible.
False (0) | The application isn’t visible.

You can set the Visible property of the Application object only using Visual Basic.

Remarks

When an application is launched by the user, the Visible and UserControl properties of the Application object are both set to True. When the UserControl property is set to True, it is not possible to set the Visible property of the Application object to False.

When an Application object is created using OLE Automation, the Visible and UserControl properties of the Application object are both set to False.

Note When the Visible property of the Application object is set to False, the application is minimized but is not hidden from the user.

See Also

Application Object, UserControl Property, Visible Property.


Weekday Function

Description

Returns a whole number representing the day of the week.

Syntax

Weekday(date, [firstdayofweek])

The Weekday function syntax has these named arguments:

Part | Description
date | Numeric or string expression, in any combination, that can represent a date. If date contains Null, Null is returned.
firstdayofweek | A constant that specifies the first day of the week, as described in Settings. If omitted, vbSunday is assumed.

Settings

The firstdayofweek argument has these settings:

Constant | Value | Description
vbUseSystem | 0 | Use NLS API setting.
vbSunday | 1 | Sunday
vbMonday | 2 | Monday
vbTuesday | 3 | Tuesday
vbWednesday | 4 | Wednesday
vbThursday | 5 | Thursday
vbFriday | 6 | Friday
vbSaturday | 7 | Saturday

Return Values

The Weekday function can return any of these values:

Constant | Value | Description
vbSunday | 1 | Sunday
vbMonday | 2 | Monday
vbTuesday | 3 | Tuesday
vbWednesday | 4 | Wednesday
vbThursday | 5 | Thursday
vbFriday | 6 | Friday
vbSaturday | 7 | Saturday

See Also

Date Function, Date Statement, Day Function, Month Function, Now Function, Year Function.

Example

This example uses the Weekday function to obtain the day of the week from a specified date.

MyDate = #February 12, 1969#            ' Assign a date.= Weekday(MyDate)            ' MyWeekDay contains 4 because
                                    ' MyDate represents a Wednesday.


WhatsThisButton Property

Applies To

Form.

Description

You can use the WhatsThisButton property to specify whether a Whats This button is added to a form’s title bar.

Note You can’t display the Whats This button on the title bar of a form unless the MinMaxButtons property is set to None.

Setting

The WhatsThisButton property uses the following settings.

Setting | Description | Visual Basic
Yes | A Whats This help button appears on the title bar. | True (-1)
No | (Default) A Whats This help button doesn’t appear on the title bar. | False (0)

You can set the WhatsThisButton property in the form’s property sheet, a macro, or using Visual Basic.

This property can be set only in form Design view.

Remarks

Choosing the Whats This button from the title bar of a form causes the Help Select mouse pointer to appear. With the Help Select mouse pointer, you can click any control to access its custom Help topic specified by the control’s HelpContextID property. If the control doesn’t have a custom Help topic, the form’s custom Help topic is displayed. If neither the form or the control has a custom Help topic, Microsoft Access Help is displayed.

See Also

ControlTipText Property; HelpButton Property; HelpContextID, HelpFile Properties (Microsoft Access); MinMaxButtons Property.


While...Wend Statement

Description

Executes a series of statements as long as a given condition is True.

Syntax

While condition
[statements]Wend

The While...Wend statement syntax has these parts:

Part | Description
condition | Numeric or string expression that evaluates to True or False. If condition is Null, condition is treated as False.
statements | One or more statements executed while condition is True.

Remarks

If condition is True, all statements in statements are executed until the Wend statement is encountered. Control then returns to the While statement and condition is again checked. If condition is still True, the process is repeated. If it is not True, execution resumes with the statement following the Wend statement.

While...Wend loops can be nested to any level. Each Wend matches the most recent While.

Tip The Do...Loop statement provides a more structured and flexible way to perform looping.

See Also

Do...Loop Statement, With Statement.

Example

This example uses the While...Wend statement to increment a counter variable. The statements in the loop are executed as long as the condition evaluates to True.

Counter = 0                            ' Initialize variable.Counter < 20                    ' Test value of Counter.
    Counter = Counter + 1            ' Increment Counter.                                ' End While loop when Counter > 19..Print Counter                    ' Prints 20 in Debug window.


Width Property

See Height, Width Properties.


Width # Statement

Description

Assigns an output-line width to a file opened using the Open statement.

Syntax

Width #filenumber, width

The Width statement syntax has these parts:

Part | Description
filenumber | Any valid file number.
width | Numeric expression in the range 0 to 255, inclusive, that indicates how many characters appear on a line before a new line is started. If width equals 0, there is no limit to the length of a line. The default value for width is 0.

See Also

Open Statement, Print # Statement.

Example

This example uses the Width # statement to set the output-line width for a file.

Open "TESTFILE" For Output As #1        ' Open file for output.#1, 5                            ' Set output-line width to 5.I = 0 To 9                        ' Loop 10 times.
    Print #1, Chr(48 + I);            ' Prints five characters per line.I#1                                ' Close file.


WillContinue Property

Applies To

Report.

Description

You can use the WillContinue property to determine if the current section will continue on the following page.

Setting

The WillContinue property is set by Microsoft Access and is read-only in all views.

Value | Description
True (-1) | The current section continues on the following page.
False (0) | The current section doesn’t continue on the following page.

You can get the value of the WillContinue property using a macro or Visual Basic.

Remarks

You can use the WillContinue property to determine whether to show or hide certain controls, depending on the value of the property. For example, you may have a hidden label in a page header containing the text “Continued on next page”. If the value of the WillContinue property is True, you can make the hidden label visible.

See Also

HasContinued Property.


WindowHeight, WindowWidth Properties

Applies To

Form.

Description

You can use these properties to return the height and width of a form in twips.

Setting

WindowHeight property settings are Integer values.

WindowWidth property settings are Integer values.

These property settings are read-only and are available only in a macro or Visual Basic.

Remarks

The WindowHeight property is measured from the upper-left corner of the form to its lower-left corner. The WindowWidth property is measured from the upper left corner of the form to its upper-right corner.

See Also

InsideHeight, InsideWidth Properties; Left, Top Properties.


With Statement

Description

Executes a series of statements on a single object or a user-defined type.

Syntax

With object
[statements]End With

The With statement syntax has these parts:

Part | Description
object | Name of an object or a user-defined type.
statements | One or more statements to be executed on object.

Remarks

The With statement allows you to perform a series of statements on a specified object without requalifying the name of the object. For example, if you have a number of different properties to change on a single object, it is more convenient to place the property assignment statements within the With control structure, referring to the object once instead of referring to it with each property assignment. The following example illustrates use of the With statement to assign values to several properties of the same object.

With MyLabel
.Height = 2000
.Width = 2000
.Caption = "This is MyLabel"With

Note Once a With block is entered, object can’t be changed. As a result, you can’t use a single With statement to affect a number of different objects.

You can nest With statements by placing one With block within another. However, because members of outer With blocks are masked within the inner With blocks, you must provide a fully qualified object reference in an inner With block to any member of an object in an outer With block.

Important Do not jump into or out of With blocks. You may get errors or unpredictable behavior if statements in a With block are executed, but either the With or End With statement is not executed.

See Also

Do...Loop Statement.

Example

This example uses the With statement to execute a series of statements on a single object. The object MyObject and its properties are generic names used for illustration purposes only.

With MyObject
    .Height = 100            ' Same as MyObject.Height = 100.
    .Caption = "Hello"        ' Same as MyObject.Caption = "Hello".
    With .Font
        .Color = Red            ' Same as MyObject.Font.Color = Red.
        .Bold = True            ' Same as MyObject.Font.Bold = True.
    End WithWith


Write # Statement

Description

Writes raw data to a sequential file.

Syntax

Write #filenumber, [outputlist]

The Write statement syntax has these parts:

Part | Description
filenumber | Any valid file number.
outputlist | One or more comma-delimited numeric or string expressions to write to a file.

Remarks

If you omit outputlist and include a comma after filenumber, a blank line is printed to the file. Multiple expressions can be separated with a space, a semicolon, or a comma. A space has the same effect as a semicolon.

When Write # is used to write data to a file, several universal assumptions are followed so the data can always be read and correctly interpreted using Input #, regardless of locale:

  • Numeric data is always written using the period (.) as the decimal separator.
  • For Boolean data, either #TRUE# or #FALSE# is printed. The True and False keywords are not translated, regardless of locale.
  • Date data is written to the file using the universal date format. When either the date or the time component is missing or zero, only the part provided gets written to the file.
  • Nothing is written to the file if outputlist data is Empty. However, for Null data, #NULL# is written.
  • For Error data, the output appears as #ERROR errorcode#. The Error keyword is not translated, regardless of locale.

Unlike the Print # statement, the Write # statement inserts commas between items and quotation marks around strings as they are written to the file. You don’t have to put explicit delimiters in the list. Write # inserts a newline character, that is, a carriage return (Chr(13)) or carriage return-linefeed (Chr(13) + Chr (10)), after it has written the final character in outputlist to the file.

See Also

Input # Statement, Open Statement, Print # Statement.

Example

This example uses the Write # statement to write raw data to a sequential file.

Open "TESTFILE" For Output As #1        ' Open file for output.#1, "Hello World", 234            ' Write comma delimited data.#1,                            ' Write blank line.

' Assign Boolean, Date, Null, and Error values.= False : MyDate = #February 12, 1969# : MyNull = Null= CVErr(32767)
' Boolean data is written as #TRUE# or #FALSE#. Date literals are
' written in universal date format, for example, #1994-07-13#
' represents July 13, 1994. Null data is written as #NULL#.
' Error data is written as #ERROR errorcode#.#1, MyBool ; " is a Boolean value"#1, MyDate ; " is a date"#1, MyNull ; " is a null value"#1, MyError ; " is an error value"#1                                ' Close file.


Xor Operator

Description

Used to perform a logical exclusion on two expressions.

Syntax

result = expression1 Xor expression2

The Xor operator syntax has these parts:

Part | Description
result | Any numeric variable.
expression1 | Any expression.
expression2 | Any expression.

Remarks

If one, and only one, of the expressions evaluates to True, result is True. However, if either expression is Null, result is also Null. When neither expression is Null, result is determined according to the following table:

If expression1 is | And expression2 is | The result is
True | True | False
True | False | True
False | True | True
False | False | False

The Xor operator also performs a bit-wise comparison of identically positioned bits in two numeric expressions and sets the corresponding bit in result according to the following truth table:

If bit in expression1 is | And bit in expression2 is | The result is
0 | 0 | 0
0 | 1 | 1
1 | 0 | 1
1 | 1 | 0

See Also

Operator Precedence.

Example

This example uses the Xor operator to perform logical exclusion on two expressions.

A = 10: B = 8: C = 6: D = Null        ' Initialize variables.= A > B Xor B > C            ' Returns False.= B > A Xor B > C            ' Returns True.= B > A Xor C > B            ' Returns False.= B > D Xor A > B            ' Returns Null.= A Xor B                    ' Returns 2 (bit-wise comparison).


Year Function

Description

Returns a whole number representing the year.

Syntax

Year(date)

The date argument is any numeric or string expression, or any combination, that can represent a date. If date contains Null, Null is returned.

See Also

Date Function, Date Statement, Day Function, Month Function, Now Function, Weekday Function.

Example

This example uses the Year function to obtain the year from a specified date. In the development environment, the date literal is displayed in short date format using the locale settings of your code.

MyDate = #February 12, 1969#				' Assign a date.
MyYear = Year(MyDate)					' MyYea


Appendix A Microsoft Access Object Hierarchy

The following illustration shows the hierarchy of Microsoft Access objects. All objects and collections are objects and collections of the Application object.


Appendix B ANSI Character Set

The following table shows the ANSI character set. The ASCII character set is the same as the first 128 characters of the ANSI character set.


In the event you cannot install the Microsoft® Access Developer’s Toolkit, please refer to the telephone support offerings below. Microsoft’s support offerings range from no-cost and low-cost electronic information services (available 24 hours a day, 7 days a week) to annual support plans and CD-ROM subscription programs. Please check the Technical Support section in online Help for detailed information.

Microsoft support services are subject to Microsoft’s then-current prices, terms, and conditions, which are subject to change without notice.

Standard Support

No-charge support from Microsoft support engineers is available via a toll call between 6:00 A.M and 6:00 P.M. Pacific time, Monday through Friday, excluding holidays. In Canada, call between 8:00 A.M and 8:00 P.M. Eastern time, Monday through Friday, excluding holidays. This support is available for 30 days after you make your first call.

  • In the United States, for technical support for the Microsoft Access Developer’s Toolkit, call (206) 635-7050.
  • In Canada, for technical support for the Microsoft Access Developer’s Toolkit, call (905) 568-3503.

When you call, you should be at your computer and have the appropriate product documentation at hand. Be prepared to give the following information:

  • The version number of the Microsoft product that you are using
  • The type of hardware that you are using, including network hardware, if applicable
  • The exact wording of any messages that appeared on your screen
  • A description of what happened and what you were doing at the time
  • A description of how you tried to solve the problem


Priority Support

The Microsoft Support Network offers priority telephone access to Microsoft support engineers 24 hours a day, 7 days a week, excluding holidays, in the U.S. In Canada, the hours are from 6:00 A.M to midnight, 7 days a week, excluding holidays.

  • In the United States, call (900) 555-2300; $2.95 (U.S.) per minute, $95 maximum. Charges appear on your telephone bill. Not available in Canada.
  • In the United States, call (800) 936-5800, at $95 (U.S.) per incident, billed to your VISA, MasterCard, or American Express card.
  • In Canada, call (800) 668-7975 for more information.


Text Telephone

Microsoft text telephone (TT/TDD) services are available for the deaf or hard-of-hearing. In the United States, using a TT/TDD modem, dial (206) 635-4948. In Canada, using a TT/TDD modem, dial (905) 568-9641.


Product Support Worldwide

The following list contains Microsoft subsidiary offices and the countries/regions they serve. If there is no Microsoft office in your country/region, please contact the establishment from which you purchased your Microsoft product. This list provides only basic technical support phone and fax numbers; other services such as BBS and sales numbers may be available. For additional subsidiary information, check the Product Support Services Worldwide section in online Help.

When you call, you should be at your computer and have the appropriate product documentation at hand. Please follow the guidelines listed above under “Standard Support.”

Area | Telephone Numbers | Fax Numbers | Area | Telephone Numbers | Fax Numbers
Argentina | (54) (1) 815-1521 | (54) (1) 814-0372 | Korea | (82) (2) 531-4800 | (82) (2) 563-5194
Australia | (61) (02) 870-2131 | (61) (02)805-0519 | Luxembourg | (32) 2-5133274 (Dutch speaking)(32) 2-5023432 (English speaking)(32) 2-5132268 (French speaking) |
Austria | 0660-6761 | 0222-68 16 2710 | Mexico | (52) (5) 325-0912 |
Belgium | 02-5133274 (Dutch speaking)02-5023432 (English speaking) 02-5132268 (French speaking) |  | Netherlands | 02503-77877 (Dutch speaking)02503-77853 (English speaking) |
Bolivia | See Argentina |  | New Zealand | 64 (9) 357-5575 | 64 (9) 358-0092
Brazil | (55) (11) 871-0090 | (55) (11) 241-1157 | Northern Ireland | See United Kingdom |
Caribbean | (214) 714-9100 | (809) 273-3636 | Norway | (47) (22) 02 25 50 | (47) (22) 02 25 70
Chile | 56 2 232 4467 | 56 2 233 5917 | Papua New Guinea | See Australia |
Colombia | (571) 618 2255 | (571) 618 2269 | Paraguay | See Argentina |
Czech Republic | (+42) (2) 245 10554 | (+42) (2) 266020 | Poland | (+48) (2) 6216793 or (+48) (71) 441357 | (+48) (2) 6615434
Denmark | (45) (44) 89 01 | (45) (44) 89 01 44 | Portugal | (351) 1 4412205 | (351) 1 4412101
Dubai | (971) 4 513 888 | (971) 4 527 444 | Taiwan | (886) (2) 508-9501 | (886) (2) 504-3121
Ecuador | (593) (2) 463-094 |  | Republic of Ireland | See United Kingdom |
England | See United Kingdom |  | Scotland | See United Kingdom |
Finland | Contact your local dealer | (46) (0)8 752 29 00 | Singapore | (65) 220-7202 | (65) 227-6811
France | (33) (1) 69-86-10-20 | (33) (1) 69-28-00-28 | Slovak Republic | (+42) (7) 312083 | (+42) (2) 266020
French Polynesia | See France |  | Slovenia | (+386) (61) 1232354 |
Germany | 089/3176-1180 | 089-3176-1000 | South Africa | (Toll Free): 0 802 11 11 04(Toll): (2) 11 445 0100 | (27) 11 445 0045 or (27) 11 445 0046
Greece | (30) (1) 6893-631through (30) (1) 6893-635 | (30) (1) 6893 636 | Spain | (34) (1) 803-9960 | (34) (1) 803-8310
Hong Kong SAR, China | (852) 804-4222 | 2535-9293 | Sweden | (46) (8) 752 09 29 | (46) (0)8 752 29 00
Hungary | (+36) 2MSINFO (267-4636) | (+36) (1) 268-1558 | Switzerland | Microsoft Access for Windows 95: 01/342-4121Technical support (French speaking): 022-738 96 88 | 01-831 08 69
India | (01) (91) 646 0694 |  | Turkey | (90) 212 2585998 | (90) 212 2585954
Ireland | See United Kingdom |  | United Kingdom | (01734) 271000 | (01734) 270080
Israel | 972-3-613-0833 | 972-3-613-0834 | Uruguay | See Argentina |
Italy | (39) (2) 7039-8351 | (39) (2) 7039-2020 | Venezuela | 58.2.910046 or 58.2.910510 | 58.2.923835
Japan | (81) (424) 41-8700 | (81) (3) 5454-8100 | Wales | See United Kingdom |


Excel Object Model Chart


Microsoft Excel File Format

Microsoft Office Technical Documentation Group

Created: November, 1995

Click to open or copy the BIFFVIEW project files

Click to open or copy the DUMPBIFF project files

The binary interchange file format (BIFF) is the file format in which Microsoft Excel workbooks are saved on disk. Microsoft Excel versions 5.0 and later use compound files; this is the OLE 2 implementation of the Structured Storage Model standard. For more information on this technology, see the OLE 2 Programmer's Reference, Volume One, and Inside OLE 2, both published by Microsoft Press® and available from your local bookstore.

File Format Versions: BIFF5 and BIFF7

The BIFF7 file format of Microsoft Excel version 7.0 is nearly identical to the BIFF5 file format of Microsoft Excel version 5.0. There are some new records in BIFF7 and some records that have changed from BIFF5. This article documents both the BIFF5 and BIFF7 file formats.

The following tables describe the new records and changed records in BIFF7. For more information on the new and changed records, see the appropriate record description, later in this article.

New Records in BIFF7

Number | Record
1A5h | FILESHARING2
13Dh | TABID
EAh | TABIDCONF

Changed Records in BIFF7

Number | Record | Changes
9Eh | AUTOFILTER | The BIFF7 record includes several new fields to support the Top 10 AutoFilter feature.
5Bh | FILESHARING | The BIFF7 and BIFF5 records are identical, but the behavior of the record changes in BIFF7 when the workbook contains a shared list.

There are also several new streams in the BIFF7 file. The User Names and Revision Log streams support the new shared list feature in Microsoft Excel 7.0. The binary format of these streams is not documented.

The DocumentSummaryInformation (new to BIFF7) and SummaryInformation streams support the document properties available in Microsoft Excel 7.0, which are standardized across the Office 95 family of applications.

The Workbook Compound File

An OLE 2 compound file is essentially "a file system within a file." The compound file contains a hierarchical system of storages and streams. A storage is analogous to a directory, and a stream is analogous to a file in a directory. Each Microsoft Excel workbook is stored in a compound file, an example of which is shown in the following illustration. This file is a workbook that contains three sheets: a worksheet with a PivotTable, a Visual Basic module, and a chart.

If a workbook contains embedded objects, then the file will also contain storages written by the applications that created the objects. The PivotTable data cache storage and VBA PROJECT storage are not documented. The CompObj stream contains OLE 2 component object data, and the Summary Info stream contains the standardized file summary information such as title, subject, author, and so on.

The Book stream begins with a BOF record, and then contains workbook global records up to the first EOF. The workbook global section contains one BOUNDSHEET record for each sheet in the workbook. You can use the dt field (document type), the lbPlyPos field (stream position of the BOF record for the sheet), and the cch/rgch fields (sheet name as a byte-counted string) to quickly read selected sheets in the workbook.

Each sheet in the workbook is stored after the workbook global section, beginning with BOF and ending with EOF. If you read the file in a continuous stream (instead of using the BOUNDSHEET records), you can test the dt field of each BOF record to determine the sheet type.

Simple Save (New for BIFF7)

Microsoft Excel 7.0, uses a new simple save method from OLE 2, which was developed to increase performance. If a workbook contains no Visual Basic modules, no PivotTables, and no embedded objects on worksheets, then Microsoft Excel uses the simple save method.

When Microsoft Excel 7.0 saves a workbook using simple save, the streams in the file must be at least 4kbytes long. The OLE 2 code adds padding bytes to the streams to ensure that they are at least 4kbytes long. If you use a low-level binary viewer to examine the resulting file, you will see the padding bytes appearing as "garbage" at the end of the streams.

To find the actual end of the Book stream, you can increment a counter every time you read a BOF record and then decrement it every time you read an EOF record. When the counter reaches zero, then you have read the last EOF in the Book stream and you can ignore the rest of the bytes in that stream.

Other Microsoft Excel File Formats

Although chart records are written as part of the Book stream, they are documented in another article. Microsoft Excel creates several other files, some of which are documented. The workspace file is documented in a separate article. The toolbar file (.XLB extension in Microsoft Windows) is not documented.

This article contains BIFF documentation for Microsoft Excel versions 5.0 and 7.0 only. Earlier versions of BIFF documentation are available on the Development Library (published by the Microsoft Developer Network). The Library is a CD-based reference source for Windows-based developers. For more information about this service, contact Microsoft Developer Network via email (devnetwk@microsoft.com), via Compuserve (>INTERNET:devnetwk@microsoft.com), or call (800) 759-5474.

BIFF Record Information

Although different BIFF record types contain different information, every record has the same basic format. All BIFF records consist of the following three sections:

Record Number

This 16-bit word identifies the record. The hexadecimal value of the record number is included in parentheses in the heading of the record description. For example, the EOF record's heading appears in this article as "EOF: End of File (0Ah)."

Record Data Length

This 16-bit word equals the length of the following record data, in bytes. The record length depends on the type of data in the record. For example, the EOF record is always the same length, while a FORMULA record varies in length depending on the length of the formula itself.

Record Data

This is the portion of the record containing the actual data that describes the formula, window, object, and so on.

The format for all BIFF records is described in the following table.

Offset | Length (bytes) | Contents
0 | 2 | Record number
2 | 2 | Record data length
4 | Variable | Record data

A BIFF record has a length limit of 2084 bytes, including the record type and record length fields. Therefore, the record data field must be no longer than 2080 bytes. A large data object has a parent record and then one or more CONTINUE records to store the data. For example, embedded bitmap graphic objects often use a parent IMDATA record and several CONTINUE records.

If a field (or a bit in a field) is marked "Reserved," then your application should treat the field or bit as a "don't-care" when you read or write the BIFF file. If a field (or bit in a field) is marked "Reserved; must be zero," then you must write zeros to the field or bit when you write a BIFF file.

Byte Swapping

Microsoft Excel BIFF files are transportable across the MS-DOS/Windows (Intel® 80x86), and Apple Macintosh (Motorola® 680x0) operating systems, among others. To support transportability, Microsoft Excel writes BIFF files in the 80x86 format, where the low-order byte of the word appears first in the file, followed by the high-order byte. For example, the BOF record consists of six 16-bit words:

0809 0008 0500 0005 096C 07C9

and it appears in a BIFF file as:

09 08 08 00 00 05 05 00 6C 09 C9 07

Whenever Microsoft Excel for the Macintosh reads or writes a BIFF file, it calls a function that swaps the high- and low-order bytes of every 16-bit word in every record in the file. For 32-bit longs, the bytes in each 16-bit word are swapped first, and then the two 16-bit words are swapped. Be sure to include a byte-swap function in any custom BIFF utility you write for the Macintosh.

BIFF Versions

You can determine the BIFF version (and infer the Microsoft Excel version that wrote the file) by testing the high-order byte of the record number of the BOF record. For example, the first BOF record in a BIFF5/BIFF7 workbook file is:

09 08 08 00 00 05 05 00 6C 09 C9 07 (08h in high-order byte)

while the BOF record in a BIFF4 chart file is:

09 04 06 00 00 00 20 00 00 00 (04h in high-order byte)

In BIFF4 and earlier, some records (other than the BOF record) contained version information in the high-order byte of their record numbers. This proved to be redundant, so for BIFF5 and later, Microsoft Excel determines the BIFF version by reading the high-order byte of the record number of the BOF record.

Beginning with this version of the Microsoft Excel Developer's Kit, record numbers are documented as full 16-bit numbers instead of 8-bit numbers with a high-order version number byte. For example, the DIMENSIONS record is now documented as record number 200h instead of 00h. This causes the records to appear in a different order in the following table, "BIFF Records: Record Number Order."

Indexing in BIFF Records

In BIFF files, rows and columns are always stored zero-based, rather than with an offset of one as they appear in a sheet. For example, cell A1 is stored as row 0 (rw = 00h), column 0 (col = 00h); cell B3 is row 2 (rw = 02h), column 1 (col = 01h), and so on.

In most cases, you can use the variable-naming conventions in this article to determine if a variable is zero-based. Variable names that begin with the letter i are usually indexes, which are zero-based. For example, the variable ixfe occurs in every cell record; it is a zero-based index into the table of XF records. Variable names that begin with the letter c are usually counts, which are one-based. For example, many records contain a cch, which is a count of characters in the following string.

Undefined Cells in the Sheet

To reduce file size, cells that don't contain values or formulas and aren't referenced by formulas in any other cell are considered to be undefined cells. Such undefined cells don't appear in the BIFF file.

For example, if a worksheet has a value in cell A3, and the formula =A3+A4 in cell B10, then the only defined cells on the worksheet are A3, A4, and B10. No other cells need to exist.

Using this technique, entire rows can be undefined if they have no defined cells in them. In the preceding example, only rows 3, 4, and 10 are defined, so the file contains only three ROW records.

Cell Records

The term "cell records" refers to the BIFF record types that actually contain cell data. Cell records that appear in BIFF5/BIFF7 files are shown in the following table.

Record | Contents
ARRAY | An array-entered formula
BLANK | An empty cell
BOOLERR | A Boolean or error value
FORMULA | A cell formula, stored as parse tokens
LABEL | A string constant
NUMBER | An IEEE floating-point number
MULBLANK | Multiple empty cells (new to BIFF5)
MULRK | Multiple RK numbers (new to BIFF5)
RK | An RK number
RSTRING | Cell with character formatting
SHRFMLA | A shared formula (new to BIFF5)
STRING | A string that represents the result of a formula

Microsoft Excel stores cell records in blocks that have at most 32 rows. Each row that contains cell records has a corresponding ROW record in the block, and each block contains a DBCELL record at the end of the block. For more information about row blocks and about optimizing your code when searching for cell records, see Finding Cell Records in BIFF Files.

BIFF Record Order

BIFF record order has changed as the file format has evolved. The simplest way to determine BIFF record order is to create a workbook in Microsoft Excel and then use the BiffView utility to examine the record order.

BIFF Utilities

There are two BIFF utilities in the Microsoft Solutions Development Kit. Use the BiffView utility (BIFFVIEW.EXE, a Windows program) to examine BIFF5/BIFF7 workbook files. Use DUMPBIFF.EXE (an MS-DOS program) to examine the BIFF5/BIFF7 workspace file.

BIFF Records: Alphabetical Order

Number | Record
22 | 1904: 1904 Date System
87 | ADDIN: Workbook Is an Add-in Macro
C2 | ADDMENU: Menu Addition
221 | ARRAY: Array-Entered Formula
9E | AUTOFILTER: AutoFilter Data
9D | AUTOFILTERINFO: Drop-Down Arrow Count
40 | BACKUP: Save Backup Version of the File
201 | BLANK: Cell Value, Blank Cell
809 | BOF: Beginning of File
DA | BOOKBOOL: Workbook Option Flag
205 | BOOLERR: Cell Value, Boolean or Error
29 | BOTTOMMARGIN: Bottom Margin Measurement
85 | BOUNDSHEET: Sheet Information
0C | CALCCOUNT: Iteration Count
0D | CALCMODE: Calculation Mode
42 | CODEPAGE: Default Code Page
7D | COLINFO: Column Formatting Information
3C | CONTINUE: Continues Long Records
A9 | COORDLIST: Polygon Object Vertex Coordinates
8C | COUNTRY: Default Country/Region and WIN.INI Country/Region
5A | CRN: Nonresident Operands
D7 | DBCELL: Stream Offsets
50 | DCON: Data Consolidation Information
52 | DCONNAME: Data Consolidation Named References
51 | DCONREF: Data Consolidation References
225 | DEFAULTROWHEIGHT: Default Row Height
55 | DEFCOLWIDTH: Default Width for Columns
C3 | DELMENU: Menu Deletion
10 | DELTA: Iteration Increment
200 | DIMENSIONS: Cell Table Size
B8 | DOCROUTE: Routing Slip Information
88 | EDG: Edition Globals
0A | EOF: End of File
16 | EXTERNCOUNT: Number of External References
223 | EXTERNNAME: Externally Referenced Name
17 | EXTERNSHEET: External Reference
2F | FILEPASS: File Is Password-Protected
5B | FILESHARING: File-Sharing Information
1A5h | FILESHARING2: File-Sharing Info for Shared Lists (BIFF7)
9B | FILTERMODE: Sheet Contains Filtered List
9C | FNGROUPCOUNT: Built-in Function Group Count
9A | FNGROUPNAME: Function Group Name
231 | FONT: Font Description
15 | FOOTER: Print Footer on Each Page
41E | FORMAT: Number Format
406 | FORMULA: Cell Formula
AB | GCW: Global Column Width Flags
82 | GRIDSET: State Change of Gridlines Option
80 | GUTS: Size of Row and Column Gutters
83 | HCENTER: Center Between Horizontal Margins
14 | HEADER: Print Header on Each Page
8D | HIDEOBJ: Object Display Options
1B | HORIZONTALPAGEBREAKS: Explicit Row Page Breaks
7F | IMDATA: Image Data
20B | INDEX: Index Record
E2 | INTERFACEEND: End of User Interface Records
E1 | INTERFACEHDR: Beginning of User Interface Records
11 | ITERATION: Iteration Mode
204 | LABEL: Cell Value, String Constant
26 | LEFTMARGIN: Left Margin Measurement
95 | LHNGRAPH: Named Graph Information
94 | LHRECORD: .WK? File Conversion Information
98 | LPR: Sheet Was Printed Using LINE.PRINT( )
C1 | MMS: ADDMENU/DELMENU Record Group Count
BE | MULBLANK: Multiple Blank Cells
BD | MULRK: Multiple RK Cells
218 | NAME: Defined Name
1C | NOTE: Note Associated with a Cell
203 | NUMBER: Cell Value, Floating-Point Number
5D | OBJ: Describes a Graphic Object
63 | OBJPROTECT: Objects Are Protected
D3 | OBPROJ: Visual Basic Project
DE | OLESIZE: Size of OLE Object
92 | PALETTE: Color Palette Definition
41 | PANE: Number of Panes and Their Position
13 | PASSWORD: Protection Password
4D | PLS: Environment-Specific Print Record
0E | PRECISION: Precision
2B | PRINTGRIDLINES: Print Gridlines Flag
2A | PRINTHEADERS: Print Row/Column Labels
12 | PROTECT: Protection Flag
89 | PUB: Publisher
B9 | RECIPNAME: Recipient Name
0F | REFMODE: Reference Mode
27 | RIGHTMARGIN: Right Margin Measurement
27E | RK: Cell Value, RK Number
208 | ROW: Describes a Row
D6 | RSTRING: Cell with Character Formatting
5F | SAVERECALC: Recalculate Before Save
AF | SCENARIO: Scenario Data
AE | SCENMAN: Scenario Output Data
DD | SCENPROTECT: Scenario Protection
A0 | SCL: Window Zoom Magnification
1D | SELECTION: Current Selection
A1 | SETUP: Page Setup
BC | SHRFMLA: Shared Formula
90 | SORT: Sorting Options
96 | SOUND: Sound Note
99 | STANDARDWIDTH: Standard Column Width
207 | STRING: String Value of a Formula
293 | STYLE: Style Information
91 | SUB: Subscriber
C5 | SXDI: Data Item
DC | SXEXT: External Source Information
D5 | SXIDSTM: Stream ID
B4 | SXIVD: Row/Column Field IDs
B5 | SXLI: Line Item Array
B6 | SXPI: Page Item
CD | SXSTRING: String
D0 | SXTBL: Multiple Consolidation Source Info
D2 | SXTBPG: Page Item Indexes
D1 | SXTBRGIITM: Page Item Name Count
B1 | SXVD: View Fields
B2 | SXVI: View Item
B0 | SXVIEW: View Definition
E3 | SXVS: View Source
13Dh | TABID: Sheet Tab Index Array (BIFF7)
EAh | TABIDCONF: Sheet Tab ID of Conflict History (BIFF7)
236 | TABLE: Data Table
60 | TEMPLATE: Workbook Is a Template
28 | TOPMARGIN: Top Margin Measurement
DF | UDDESC: Description String for Chart Autoformat
5E | UNCALCED: Recalculation Status
84 | VCENTER: Center Between Vertical Margins
1A | VERTICALPAGEBREAKS: Explicit Column Page Breaks
3D | WINDOW1: Window Information
23E | WINDOW2: Sheet Window Information
19 | WINDOWPROTECT: Windows Are Protected
5C | WRITEACCESS: Write Access User Name
86 | WRITEPROT: Workbook Is Write-Protected
81 | WSBOOL: Additional Workspace Information
59 | XCT: CRN Record Count
E0 | XF: Extended Format

BIFF Records: Record Number Order

Number | Record
0A | EOF: End of File
0C | CALCCOUNT: Iteration Count
0D | CALCMODE: Calculation Mode
0E | PRECISION: Precision
0F | REFMODE: Reference Mode
10 | DELTA: Iteration Increment
11 | ITERATION: Iteration Mode
12 | PROTECT: Protection Flag
13 | PASSWORD: Protection Password
13Dh | TABID: Sheet Tab Index Array (BIFF7)
14 | HEADER: Print Header on Each Page
15 | FOOTER: Print Footer on Each Page
16 | EXTERNCOUNT: Number of External References
17 | EXTERNSHEET: External Reference
19 | WINDOWPROTECT: Windows Are Protected
1A | VERTICALPAGEBREAKS: Explicit Column Page Breaks
1A5h | FILESHARING2: File-Sharing Info for Shared Lists (BIFF7)
1B | HORIZONTALPAGEBREAKS: Explicit Row Page Breaks
1C | NOTE: Note Associated with a Cell
1D | SELECTION: Current Selection
200 | DIMENSIONS: Cell Table Size
201 | BLANK: Cell Value, Blank Cell
203 | NUMBER: Cell Value, Floating-Point Number
204 | LABEL: Cell Value, String Constant
205 | BOOLERR: Cell Value, Boolean or Error
207 | STRING: String Value of a Formula
208 | ROW: Describes a Row
20B | INDEX: Index Record
218 | NAME: Defined Name
22 | 1904: 1904 Date System
221 | ARRAY: Array-Entered Formula
223 | EXTERNNAME: Externally Referenced Name
225 | DEFAULTROWHEIGHT: Default Row Height
231 | FONT: Font Description
236 | TABLE: Data Table
23E | WINDOW2: Sheet Window Information
26 | LEFTMARGIN: Left Margin Measurement
27 | RIGHTMARGIN: Right Margin Measurement
27E | RK: Cell Value, RK Number
28 | TOPMARGIN: Top Margin Measurement
29 | BOTTOMMARGIN: Bottom Margin Measurement
293 | STYLE: Style Information
2A | PRINTHEADERS: Print Row/Column Labels
2B | PRINTGRIDLINES: Print Gridlines Flag
2F | FILEPASS: File Is Password-Protected
3C | CONTINUE: Continues Long Records
3D | WINDOW1: Window Information
40 | BACKUP: Save Backup Version of the File
406 | FORMULA: Cell Formula
41 | PANE: Number of Panes and Their Position
41E | FORMAT: Number Format
42 | CODEPAGE: Default Code Page
4D | PLS: Environment-Specific Print Record
50 | DCON: Data Consolidation Information
51 | DCONREF: Data Consolidation References
52 | DCONNAME: Data Consolidation Named References
55 | DEFCOLWIDTH: Default Width for Columns
59 | XCT: CRN Record Count
5A | CRN: Nonresident Operands
5B | FILESHARING: File-Sharing Information
5C | WRITEACCESS: Write Access User Name
5D | OBJ: Describes a Graphic Object
5E | UNCALCED: Recalculation Status
5F | SAVERECALC: Recalculate Before Save
60 | TEMPLATE: Workbook Is a Template
63 | OBJPROTECT: Objects Are Protected
7D | COLINFO: Column Formatting Information
7F | IMDATA: Image Data
80 | GUTS: Size of Row and Column Gutters
809 | BOF: Beginning of File
81 | WSBOOL: Additional Workspace Information
82 | GRIDSET: State Change of Gridlines Option
83 | HCENTER: Center Between Horizontal Margins
84 | VCENTER: Center Between Vertical Margins
85 | BOUNDSHEET: Sheet Information
86 | WRITEPROT: Workbook Is Write-Protected
87 | ADDIN: Workbook Is an Add-in Macro
88 | EDG: Edition Globals
89 | PUB: Publisher
8C | COUNTRY: Default Country/Region and WIN.INI Country/Region
8D | HIDEOBJ: Object Display Options
90 | SORT: Sorting Options
91 | SUB: Subscriber
92 | PALETTE: Color Palette Definition
94 | LHRECORD: .WK? File Conversion Information
95 | LHNGRAPH: Named Graph Information
96 | SOUND: Sound Note
98 | LPR: Sheet Was Printed Using LINE.PRINT( )
99 | STANDARDWIDTH: Standard Column Width
9A | FNGROUPNAME: Function Group Name
9B | FILTERMODE: Sheet Contains Filtered List
9C | FNGROUPCOUNT: Built-in Function Group Count
9D | AUTOFILTERINFO: Drop-Down Arrow Count
9E | AUTOFILTER: AutoFilter Data
A0 | SCL: Window Zoom Magnification
A1 | SETUP: Page Setup
A9 | COORDLIST: Polygon Object Vertex Coordinates
AB | GCW: Global Column Width Flags
AE | SCENMAN: Scenario Output Data
AF | SCENARIO: Scenario Data
B0 | SXVIEW: View Definition
B1 | SXVD: View Fields
B2 | SXVI: View Item
B4 | SXIVD: Row/Column Field IDs
B5 | SXLI: Line Item Array
B6 | SXPI: Page Item
B8 | DOCROUTE: Routing Slip Information
B9 | RECIPNAME: Recipient Name
BC | SHRFMLA: Shared Formula
BD | MULRK: Multiple RK Cells
BE | MULBLANK: Multiple Blank Cells
C1 | MMS: ADDMENU/DELMENU Record Group Count
C2 | ADDMENU: Menu Addition
C3 | DELMENU: Menu Deletion
C5 | SXDI: Data Item
CD | SXSTRING: String
D0 | SXTBL: Multiple Consolidation Source Info
D1 | SXTBRGIITM: Page Item Name Count
D2 | SXTBPG: Page Item Indexes
D3 | OBPROJ: Visual Basic Project
D5 | SXIDSTM: Stream ID
D6 | RSTRING: Cell with Character Formatting
D7 | DBCELL: Stream Offsets
DA | BOOKBOOL: Workbook Option Flag
DC | SXEXT: External Source Information
DD | SCENPROTECT: Scenario Protection
DE | OLESIZE: Size of OLE Object
DF | UDDESC: Description String for Chart Autoformat
E0 | XF: Extended Format
E1 | INTERFACEHDR: Beginning of User Interface Records
E2 | INTERFACEEND: End of User Interface Records
E3 | SXVS: View Source
EAh | TABIDCONF: Sheet Tab ID of Conflict History (BIFF7)

Record Descriptions

The first two fields in every BIFF record are record number and record length. Because these fields have the same offset and size in every BIFF record, they're not documented in the following descriptions. For more information about the record number and record length fields, see BIFF Record Information.

1904: 1904 Date System (22h)

The 1904 record stores the date system used by Microsoft Excel.

Record Data

Offset | Name | Size | Contents
4 | f1904 | 2 | = 1 if the 1904 date system is used

ADDIN: Workbook Is an Add-in Macro (87h)

This record has no record data field. If the ADDIN record is present in the BIFF file, it signifies that the macro is an add-in macro. The ADDIN record, if present, must immediately follow the first BOF record in the Book stream.

ADDMENU: Menu Addition (C2h)

The ADDMENU record stores a menu addition. When you add a menu object (a menu bar, a menu, a menu item, or a submenu item) to the user interface, Microsoft Excel writes a group of ADDMENU records for each object. The first record stores the menu bar, the second stores the menu, the third stores the menu item, and the fourth stores the submenu item (note how this is identical to the menu hierarchy in the user interface). The number of records in the group depends on the level of the menu structure at which the addition occurs. For example, adding a menu to a menu bar causes two ADDMENU records to be written. Adding a submenu item to a menu item causes four records to be written.

If fInsert is true (equal to 01h), the menu object is added at this level of the hierarchy. For example, if fInsert is true in the second ADDMENU record of the group, Microsoft Excel adds a new menu to an existing menu bar. If fInsert is false (equal to 00h), the record is a placeholder, and one of the following ADDMENU records in the group will define the menu addition.

For menu items and submenu items, the icetab field stores the index to the added command, if the item is attached to a built-in command. The icetabBefore field stores the index to the command before which the new command is added. If either of these indexes equals FFFFh, the corresponding string from the rgch field is used instead of a built-in command.

The caitm field is equal to the number of following ADDMENU records that are to be inserted at this level of the menu hierarchy.

Record Data

Offset | Name | Size | Contents
4 | icetabItem | 2 | Icetab of the command
6 | icetabBefore | 2 | Icetab of the existing command before which the new command is inserted
8 | caitm | 1 | Number of ADDMENU records at the next level of the menu hierarchy
9 | fInsert | 1 | = 1, insert this menu object = 0, this is a placeholder record
10 | rgch | var | stItem, stBefore, stMacro, stStatus, stHelp strings (see text)

The rgch field stores five concatenated strings, as described in the following table. Null strings will appear in the rgch field as a single byte (00h).

String | Contents
stItem | Text of the menu object
stBefore | Text of the item before which this item is added
stMacro | Macro name, encoded using a technique similar to the encoded filenames in the EXTERNSHEET record (for more information, see EXTERNSHEET)
stStatus | Status bar text (for add-ins)
stHelp | Help filename and context ID (for add-ins)

ARRAY: Array-Entered Formula (221h)

An ARRAY record describes a formula that was array-entered into a range of cells. The range of cells in which the array is entered is defined by the rwFirst, rwLast, colFirst, and colLast fields.

The ARRAY record occurs directly after the FORMULA record for the cell in the upper-left corner of the array — that is, the cell defined by the rwFirst and colFirst fields.

The parsed expression is the array formula, stored in the Microsoft Excel internal format. For an explanation of the parsed format, see Microsoft Excel Formulas.

Record Data

Offset | Name | Size | Contents
4 | rwFirst | 2 | First row of the array
6 | rwLast | 2 | Last row of the array
8 | colFirst | 1 | First column of the array
9 | colLast | 1 | Last column of the array
10 | grbit | 2 | Option flags
12 | chn | 4 | (See text)
16 | cce | 2 | Length of the parsed expression
18 | rgce | var | Parsed expression

You should ignore the chn field when you read the BIFF file. If you write a BIFF file, the chn field must be 00000000h.

The grbit field contains the option flags listed in the following table.

Offset | Bits | Mask | Name | Contents
0 | 0 | 01h | fAlwaysCalc | Always calculate the formula.
 | 1 | 02h | fCalcOnLoad | Calculate the formula when the file is opened.
 | 7–2 | FCh | (unused) |
1 | 7–0 | FFh | (unused) |

AUTOFILTER: AutoFilter Data (9Eh) (Changed for BIFF7)

This record stores data for an active AutoFilter.

Record Data—BIFF5

Offset | Name | Size | Contents
4 | iEntry | 2 | Index of the active AutoFilter
6 | grbit | 2 | Option flags
8 | doper1 | 10 | DOPER structure for first filter condition (see text)
18 | doper2 | 10 | DOPER structure for the second filter condition (see text)
28 | rgch | var | String storage for vtString DOPER (see text)

The grbit field contains the option flags listed in the following table.

Offset | Bits | Mask | Name | Contents
0 | 1-0 | 03h | wJoin | = 1 if the custom filter conditions are ANDed = 0 if the custom filter conditions are ORed
 | 2 | 04h | fSimple1 | = 1 if the first condition is a simple equality (for optimization)
 | 3 | 08h | fSimple2 | = 1 if the second condition is a simple equality (for optimization)
 | 7-4 | F0h | (Reserved) |
1 | 7-0 | FFh | (Reserved) |

Record Data—BIFF7

Offset | Name | Size | Contents
4 | iEntry | 2 | Index of the active AutoFilter
6 | grbit | 2 | Option flags
8 | doper1 | 10 | DOPER structure for the first filter condition (see text)
18 | doper2 | 10 | DOPER structure for the second filter condition (see text)
28 | rgch | var | String storage for vtString DOPER (see text)

The grbit field contains the option flags listed in the following table.

Offset | Bits | Mask | Name | Contents
0 | 1-0 | 0003h | wJoin | = 1 if the custom filter conditions are ANDed = 0 if the custom filter conditions are ORed
 | 2 | 0004h | fSimple1 | = 1 if the first condition is a simple equality (for optimization)
 | 3 | 0008h | fSimple2 | = 1 if the second condition is a simple equality (for optimization)
 | 4 | 0010h | fTop10 | = 1 if the condition is a Top 10 AutoFilter
 | 5 | 0020h | fTop | = 1 if the Top 10 AutoFilter shows the top items; = 0 if it shows the bottom items
 | 6 | 0040h | fPercent | = 1 if the Top 10 AutoFilter shows percentage; = 0 if it shows items
 | 15-7 | FF80h | wTop10 | The number of items to show (from 1 to 500 decimal, expressed as a binary number)

DOPER Structures—BIFF5 and BIFF7

The database oper structures (DOPERs) are 10-byte parsed definitions of the filter conditions that appear in the Custom AutoFilter dialog box. The DOPER structures are defined in the following sections.

DOPER Structure for RK Numbers (vt = 02h)

Offset | Name | Size | Contents
0 | vt | 1 | Data type (see text)
1 | grbitSgn | 1 | Comparison code (see text)
2 | rk | 4 | RK number (see RK)
6 | (reserved) | 4 |

DOPER Structure for IEEE Floating-Point Numbers (vt = 04h)

Offset | Name | Size | Contents
0 | vt | 1 | Data type (see text)
1 | grbitSgn | 1 | Comparison code (see text)
2 | num | 8 | IEEE floating-point number

DOPER Structure for Strings (vt = 06h)

Offset | Name | Size | Contents
0 | vt | 1 | Data type (see text)
1 | grbitSgn | 1 | Comparison code (see text)
2 | (reserved) | 4 |
6 | cch | 1 | Length of the string (the string is stored in rgch field that follows the DOPER structures)
7 | (reserved) | 3 |

DOPER Structure for Boolean and Error Values (vt = 08h)

Offset | Name | Size | Contents
0 | vt | 1 | Data type (see text)
1 | grbitSgn | 1 | Comparison code (see text)
2 | fError | 1 | Boolean/error flag
3 | bBoolErr | 1 | Boolean value or error value
4 | (reserved) | 6 |

The bBoolErr field contains the Boolean or error value, as determined by the fError field. If the fError field contains a 0 (zero), the bBoolErr field contains a Boolean value; if the fError field contains a 1, the bBoolErr field contains an error value.

Boolean values are 1 for true and 0 for false.

Error values are listed in the following table.

Error value | Value (hex) | Value (dec.)
#NULL! | 00h | 0
#DIV/0! | 07h | 7
#VALUE! | 0Fh | 15
#REF! | 17h | 23
#NAME? | 1Dh | 29
#NUM! | 24h | 36
#N/A | 2Ah | 42

The vt field contains the data type of the DOPER, as shown in the following table. For the DOPER types 00h, 0Ch, and 0Eh, the remaining 9 bytes of the DOPER are ignored.

vt | DOPER type
00h | Filter condition not used
02h | RK number
04h | IEEE number
06h | String
08h | Boolean or error value
0Ch | Match all blanks
0Eh | Match all non-blanks

The grbitSgn field corresponds to comparison operators, as shown in the following table.

grbitSgn | Operator
01 | <
02 | =
03 | <=
04 | >
05 | <>
06 | >=

AUTOFILTERINFO: Drop-Down Arrow Count (9Dh)

This record stores the count of AutoFilter drop-down arrows. Each drop-down arrow has a corresponding OBJ record. If at least one AutoFilter is active (in other words, the range has been filtered at least once), there will be a corresponding FILTERMODE record in the file. There will also be one AUTOFILTER record for each active filter.

Record Data

Offset | Name | Size | Contents
4 | cEntries | 2 | Number of AutoFilter drop-down arrows on the sheet

BACKUP: Save Backup Version of the File (40h)

The BACKUP record specifies whether or not Microsoft Excel should save backup versions of a file.

Record Data

Offset | Name | Size | Contents
4 | fBackupFile | 2 | = 1 if Microsoft Excel should save a backup version of the file

BLANK: Cell Value, Blank Cell (201h)

A BLANK record describes an empty cell. The rw field contains the 0-based row number. The col field contains the 0-based column number.

Record Data

Offset | Name | Size | Contents
4 | rw | 2 | Row
6 | col | 2 | Column
8 | ixfe | 2 | Index to the XF record

BOF: Beginning of File (809h)

The BOF record marks the beginning of the Book stream in the BIFF file. It also marks the beginning of record groups (or "substreams" of the Book stream) for sheets in the workbook. You can determine the BIFF version from the high-order byte of the record number field, as shown in the following table.

BOF Record Number Field

Offset | Name | Size | Contents
0 | vers | 1 | ver: = 00 BIFF2 = 02 BIFF3 = 04 BIFF4 = 08 BIFF5/BIFF7
1 | bof | 1 | 09h

Record Data

Offset | Name | Size | Contents
4 | vers | 2 | Version number (0500 for BIFF5 and BIFF7)
6 | dt | 2 | Substream type: 0005h = Workbook globals 0006h = Visual Basic module 0010h = Worksheet or dialog sheet 0020h = Chart 0040h = Microsoft Excel 4.0 macro sheet 0100h = Workspace file
8 | rupBuild | 2 | Build identifier (internal use only)
10 | rupYear | 2 | Build year (internal use only)

The rupBuild and rupYear fields contain numbers that identify the version (build) of Microsoft Excel that wrote the file. If you write a BIFF file, you can use the BiffView utility to determine the current values of these fields by examining any BOF record in a workbook file.

BOOKBOOL: Workbook Option Flag (DAh)

This record saves a workbook option flag.

Record Data

Offset | Name | Size | Contents
4 | fNoSaveSupp | 2 | =1 if the Save External Link Values option is turned off (Options dialog box, Calculation tab)

BOOLERR: Cell Value, Boolean or Error (205h)

A BOOLERR record describes a cell that contains a constant Boolean or error value. The rw field contains the 0-based row number. The col field contains the 0-based column number.

Record Data

Offset | Name | Size | Contents
4 | rw | 2 | Row
6 | col | 2 | Column
8 | ixfe | 2 | Index to the XF record
10 | bBoolErr | 1 | Boolean value or error value
11 | fError | 1 | Boolean/error flag

The bBoolErr field contains the Boolean or error value, as determined by the fError field. If the fError field contains a 0 (zero), the bBoolErr field contains a Boolean value; if the fError field contains a 1, the bBoolErr field contains an error value.

Boolean values are 1 for true and 0 for false.

Error values are listed in the following table.

Error value | Value (hex) | Value (dec.)
#NULL! | 00h | 0
#DIV/0! | 07h | 7
#VALUE! | 0Fh | 15
#REF! | 17h | 23
#NAME? | 1Dh | 29
#NUM! | 24h | 36
#N/A | 2Ah | 42

BOTTOMMARGIN: Bottom Margin Measurement (29h)

The BOTTOM MARGIN record specifies the bottom margin in inches when a sheet is printed. The num field is in 8-byte IEEE floating-point format.

Record Data

Offset | Name | Size | Contents
4 | num | 8 | Bottom margin

BOUNDSHEET: Sheet Information (85h)

This record stores the sheet name, sheet type, and stream position.

Record Data

Offset | Name | Size | Contents
4 | lbPlyPos | 4 | Stream position of the start of the BOF record for the sheet
8 | grbit | 2 | Option flags
10 | cch | 1 | Length of the sheet name
11 | rgch | var | Sheet name

The grbit field contains the options listed in the following table.

Offset | Bits | Mask | Name | Contents
0 | 7-0 | 0Fh | dt | Sheet type: 00h = worksheet or dialog sheet 01h = Microsoft Excel 4.0 macro sheet 02h = chart 06h = Visual Basic module
1 | 1–0 | 03h | hsState | Hidden state: 00h = visible 01h = hidden 02h = very hidden (see text)
 | 7-2 | FCh | (Reserved) |

A Visual Basic procedure can set the Visible property of a sheet to create a very hidden sheet. A very hidden sheet can be made visible again by a Visual Basic procedure, but there is no way to make the sheet visible through the user interface of Microsoft Excel.

CALCCOUNT: Iteration Count (0Ch)

The CALCCOUNT record stores the Maximum Iterations option from the Options dialog box, Calculation tab.

Record Data

Offset | Name | Size | Contents
4 | cIter | 2 | Iteration count

CALCMODE: Calculation Mode (0Dh)

The CALCMODE record stores options from the Options dialog box, Calculation tab.

Record Data

Offset | Name | Size | Contents
4 | fAutoRecalc | 2 | Calculation mode: = 0 for manual = 1 for automatic = –1 for automatic, except tables

CODEPAGE: Default Code Page (42h)

The CODEPAGE record stores the default code page (character set) that was in use when the workbook was saved.

Record Data

Offset | Name | Size | Contents
4 | cv | 2 | Code page the file is saved in: 01B5h (437 dec.) = IBM PC (Multiplan) 8000h (32768 dec.) = Apple Macintosh 04E4h (1252 dec.) = ANSI (Microsoft Windows)

COLINFO: Column Formatting Information (7Dh)

The COLINFO record describes the column formatting for a range of columns.

Record Data

Offset | Name | Size | Contents
4 | colFirst | 2 | First formatted column (0-based)
6 | colLast | 2 | Last formatted column (0-based)
8 | coldx | 2 | Column width, in 1/256s of a character width
10 | ixfe | 2 | Index to XF record that contains the default format for the column (for more information about the XF records, see XF)
12 | grbit | 2 | Options
14 | (reserved) | 1 | Reserved; must be 0 (zero)

The grbit field contains the options listed in the following table.

Offset | Bits | Mask | Name | Contents
0 | 0 | 01h | fHidden | = 1 if the column range is hidden
 | 7–1 | FEh | (Unused) |
1 | 2–0 | 07h | iOutLevel | Outline level of column range
 | 3 | 08h | (Reserved) | Reserved; must be 0 (zero)
 | 4 | 10h | fCollapsed | = 1 if the column range is collapsed in outlining
 | 7–5 | E0h | (Reserved) | Reserved; must be 0 (zero)

CONTINUE: Continues Long Records (3Ch)

Records that are longer than 2084 bytes (this includes the 4 bytes for record number and record length) must be split into several records. The first section appears in the base record; subsequent sections appear in CONTINUE records.

Record Data

Offset | Name | Size | Contents
4 |  | var | Continuation of record data

COORDLIST: Polygon Object Vertex Coordinates (A9h)

This record stores the coordinates of the vertices in a polygon object.

Record Data

Offset | Name | Size | Contents
4 | rgVTX | var | Array of vertex coordinates

The VTX structure is defined as follows:

typedef struct _vtx
    {
    unsigned short int x;
    unsigned short int y;
    }
        VTX;

The upper-left corner of a polygon's bounding rectangle is (x = 0h, y = 0h), and the lower-right corner is (x = 4000h, y = 4000h), as shown in the following illustration.

After the polygon is drawn, Microsoft Excel normalizes the coordinates in rgVTX to the bounding rectangle. The actual size of the polygon can be derived from the size of the bounding rectangle in the common object fields section of the OBJ record.

COUNTRY: Default Country/Region and WIN.INI Country/Region (8Ch)

This record contains localization information.

Record Data

Offset | Name | Size | Contents
4 | iCountryDef | 2 | Default country/region index
6 | iCountryWinIni | 2 | Country/region index from the Win.ini file

The default country/region index, iCountryDef, is determined by the localized version of Microsoft Excel that created the BIFF file. For example, all BIFF files created by the U.S. version of Microsoft Excel have iCountryDef = 1. If Microsoft Excel for Windows created the BIFF file, iCountryWinIni is equal to the index that corresponds to the country/region setting in the Win.ini file. Country/region indexes are defined in the following table.

Index | Country/Region
1 | United States
2 | Canada
3 | Latin America, except Brazil
31 | Netherlands
32 | Belgium
33 | France
34 | Spain
39 | Italy
41 | Switzerland
43 | Austria
44 | United Kingdom
45 | Denmark
46 | Sweden
47 | Norway
49 | Germany
52 | Mexico
55 | Brazil
61 | Australia
64 | New Zealand
81 | Japan
82 | South Korea
351 | Portugal
354 | Iceland
358 | Finland
785 | Arabic
886 | Taiwan
972 | Israel

CRN: Nonresident Operands (5Ah)

The CRN record describes nonresident operands in a formula. For example, if you have a worksheet that contains the formula =EXT.XLS!A1*A3, where EXT.XLS is not the active workbook, the nonresident operand EXT.XLS!A1 generates a CRN record that describes cell A1. If the nonresident operand contains more than one row, there is one CRN record for each row. For example, if the formula =EXT.XLS!A1:A4*4 is array-entered on a worksheet, there will be four CRN records.

If a worksheet contains two different formulas and each formula has multiple nonresident operands, Microsoft Excel may create one CRN record or several CRN records, depending on how the nonresident cells are arranged. For example, suppose that a worksheet contains two formulas (in different cells), =EXT.XLS!A1*2 and =EXT.XLS!B1*2. Because the nonresident operands are in a row and are not separated by an empty cell, Microsoft Excel creates only one CRN record containing information about cells A1 and B1.

If, however, the formulas are =EXT.XLS!A1*2 and =EXT.XLS!C1*2, Microsoft Excel creates two CRN records because an empty cell (B1) separates the two operands, A1 and C1.

Record Data

Offset | Name | Size | Contents
4 | colLast | 1 | Last column of the nonresident operand
5 | colFirst | 1 | First column of the nonresident operand
6 | rw | 2 | Row of the nonresident operand
8 | OPER | var | OPER structure; see the following description

The OPER structure repeats for each cell in the nonresident operand. For example, the formula =SUM(EXT.XLS!A1:A3) produces one CRN record with three OPER structures.

OPER Structure If the Cell Contains a Number

Offset | Name | Size | Contents
0 | grbit | 1 | = 01h for a cell that contains a number
1 | num | 8 | IEEE floating-point number

OPER Structure If the Cell Contains a String

Offset | Name | Size | Contents
0 | grbit | 1 | = 02h for a cell that contains a string
1 | cch | 1 | Number of characters in the string
2 | rgch | var | String

OPER Structure If the Cell Contains a Boolean Value

Offset | Name | Size | Contents
0 | grbit | 1 | = 04h for a cell that contains a Boolean value
1 | f | 2 | = 1 if TRUE = 0 if FALSE
3 | (unused) | 6 |

OPER Structure If the Cell Contains an Error Value

Offset | Name | Size | Contents
0 | grbit | 1 | = 10h for a cell that contains an error value
1 | err | 2 | Error value
3 | (unused) | 6 |

DBCELL: Stream Offsets (D7h)

The DBCELL record stores stream offsets for the BIFF file. There is one DBCELL record for each block of ROW records and associated cell records. Each block can contain data for up to 32 rows. For more information about the DBCELL record, see Finding Cell Records in BIFF Files.

Record Data

Offset | Name | Size | Contents
4 | dbRtrw | 4 | Offset from the start of the DBCELL record to the start of the first ROW record in the block; this is an offset to an earlier position in the stream.
8 | rgdb | var | Array of stream offsets (2 bytes each). For more information, see Finding Cell Records in BIFF Files

DCON: Data Consolidation Information (50h)

The DCON record stores options from the Consolidate dialog box (Data menu).

Record Data

Offset | Name | Size | Contents
4 | iiftab | 2 | Index to the data consolidation function (see the following table)
6 | fLeftCat | 2 | = 1 if the Left Column option is turned on
8 | fTopCat | 2 | = 1 if the Top Row option is turned on
10 | fLinkConsol | 2 | = 1 if the Create Links To Source Data option is turned on

The iiftab field, described in the following table, corresponds to the Function option in the Consolidate dialog box (Data menu).

Function | Iiftab
Average | 0
Count Nums | 1
Count | 2
Max | 3
Min | 4
Product | 5
StdDev | 6
StdDevp | 7
Sum | 8
Var | 9
Varp | 10

DCONNAME: Data Consolidation Named References (52h)

The DCONREF record contains the complete description of a named range of cells for the Consolidate command (Data menu). The stFile field contains an encoded workbook name; for information about this field, see EXTERNSHEET.

Record Data

Offset | Name | Size | Contents
4 | cchName | 1 | Length of the named range of the source area
5 | stName | var | Named range of the source area for consolidation
var | cchFile | 1 | Length of the workbook name
var | stFile | var | Workbook name

DCONREF: Data Consolidation References (51h)

The DCONNAME record contains the complete description of a range of cells for the Consolidate command (Data menu). The rgch field contains an encoded workbook name; for information about this field, see EXTERNSHEET

Record Data

Offset | Name | Size | Contents
4 | rwFirst | 2 | First row of the source area for consolidation
6 | rwLast | 2 | Last row of the source area for consolidation
8 | colFirst | 1 | First column of the source area for consolidation
9 | colLast | 1 | Last column of the source area for consolidation
10 | cch | 1 | Length of the workbook name
11 | rgch | 1 | Workbook name

DEFAULTROWHEIGHT: Default Row Height (225h)

The DEFAULTROWHEIGHT record specifies the height of all undefined rows on the sheet. The miyRw field contains the row height in units of 1/20th of a point. This record does not affect the row height of any rows that are explicitly defined.

Record Data

Offset | Name | Size | Contents
4 | grbit | 2 | Option flags (see the following table)
6 | miyRw | 2 | Default row height

The grbit field contains the option flags listed in the following table.

Offset | Bits | Mask | Name | Contents
0 | 0 | 01h | fUnsynced | = 1 if all undefined rows have incompatible font height and row height
 | 1 | 02h | fDyZero | = 1 if all undefined rows have 0 (zero) height
 | 2 | 04h | fExAsc | = 1 if all undefined rows have an extra space above
 | 3 | 08h | fExDsc | = 1 if all undefined rows have an extra space below
 | 7–4 | F0h | (Unused) |
1 | 7–0 | FFh | (Unused) |

DEFCOLWIDTH: Default Width for Columns (55h)

The DEFCOLWIDTH record specifies the width, measured in characters, for columns not explicitly sized in the COLWIDTH record.

Record Data

Offset | Name | Size | Contents
4 | cchdefColWidth | 2 | Default width of the columns

DELMENU: Menu Deletion (C3h)

The DELMENU record stores a menu deletion and is very similar to the ADDMENU record. For more information about menu system modification, see ADDMENU.

If fDelete is true (equal to 01h), the menu object is deleted at this level of the hierarchy. For example, if fDelete is true in the second DELMENU record of the group, Microsoft Excel deletes the specified menu from a menu bar. If fDelete is false (equal to 00h), the record is a placeholder, and one of the following DELMENU records in the group will define the menu deletion.

For menu items and submenu items, the icetabItem field stores the index to the deleted command if the item is attached to a built-in command. If icetabItem equals FFFFh, the stItem string from the rgch field is used instead.

Record Data

Offset | Name | Size | Contents
4 | icetabItem | 2 | Icetab of the command
6 | cditm | 1 | Number of DELMENU records at the next level of the menu hierarchy
7 | fDelete | 1 | = 1, delete this menu object = 0, this is a placeholder record
8 | fMultiple | 1 | = 1 if this item has subitems
9 | rgch | var | stItem (see text)

The first byte of the stItem string is the byte count, and the last byte is reserved.

DELTA: Iteration Increment (10h)

The DELTA record stores the Maximum Change value from the Options dialog box, Calculation tab. The number is in 8-byte IEEE floating-point format.

Record Data

Offset | Name | Size | Contents
4 | numDelta | 8 | Maximum iteration change

DIMENSIONS: Cell Table Size (200h)

The DIMENSIONS record contains the minimum and maximum bounds of the sheet. It provides a concise indication of the sheet size.

Note that both the rwMac and colMac fields are greater by 1 than the actual last row and column. For example, a worksheet that exists between cells B3 and D6 would have the following dimensions in the dimensions record (note rows and columns are 0-based in BIFF files in which row 1 and column A are both coded as 0):

rwMic = 2 — indicates that 3 is the first row

colMic = 1 — indicates that B is the first column

rwMac = 6 — indicates that 6 is the last row

colMac = 4 — indicates that D is the last column

Record Data

Offset | Name | Size | Contents
4 | rwMic | 2 | First defined row on the sheet
6 | rwMac | 2 | Last defined row on the sheet, plus 1
8 | colMic | 2 | First defined column on the sheet
10 | colMac | 2 | Last defined column on the sheet, plus 1
12 | (Reserved) | 2 | Reserved; must be 0 (zero)

DOCROUTE: Routing Slip Information (B8h)

This record stores originator information for a routing slip and other information for document routing. The rgch field contains the concatenation of seven null-terminated strings: Subject, Message, Route ID, Custom Message Type, Book Title, Originator's Friendly Name, and Originator's System-Specific Address. The lengths of the strings are contained in the seven fields, cchSubject through ulEIDSize.

Record Data

Offset | Name | Size | Contents
4 | iStage | 2 | Routing stage
6 | cRecip | 2 | Number of recipients
8 | delOption | 2 | Delivery option: = 0, one at a time = 1, all at once
10 | wFlags | 2 | Option flags
12 | cchSubject | 2 | Length of the Subject string
14 | cchMessage | 2 | Length of the Message string
16 | cchRouteID | 2 | Length of the Route ID string
18 | cchCustType | 2 | Length of the Custom Message Type string
20 | cchBookTitle | 2 | Length of the Book Title string
22 | cchOrg | 2 | Length of the Originator's Friendly Name string
24 | ulEIDSize | 4 | Length of the Originator's System-Specific Address string
28 | rgch | var | (See text)

The wFlags field contains the option flags listed in the following table.

Offset | Bits | Mask | Name | Contents
0 | 0 | 01h | fRouted | = 1 if the document has been routed
 | 1 | 02h | fReturnOrig | = 1 if the document should be returned to its originator
 | 2 | 04h | fTrackStatus | = 1 if the status message should be sent
 | 3 | 08h | fCustomType | = 1 if the status message is a custom message type
 | 6-4 | 70h | (Reserved) |
 | 7 | 80h | fSaveRouteInfo | = 1 if the routing slip information should be saved
1 | 7-0 | FFh | (Reserved) |

EDG: Edition Globals (88h)

The EDG record contains information about the publisher/subscriber feature. This record can be created only by Microsoft Excel for the Macintosh. However, if any other platform version of Microsoft Excel encounters the EDG record in a BIFF file, it leaves the record in the file, unchanged, when the file is saved.

Record Data

Offset | Name | Size | Contents
4 | lcsec | 4 | Count of all section records that have ever been created in this document, plus 1 (includes published embedded charts)
8 | crtpub | 2 | Count of all PUB records in the file (includes published embedded charts)
10 | (Reserved) | 2 | Reserved; must be 0 (zero)

EOF: End of File (0Ah)

The EOF record marks the end of the workbook stream or the end of one of the substreams in the workbook stream. It has no record data field and is simply 0A000000h.

EXTERNCOUNT: Number of External References (16h)

The EXTERNCOUNT record specifies the number of externally referenced workbooks, DDE references, and OLE references contained in a Microsoft Excel workbook.

For example, a worksheet contains the following formulas in cells A1:A3:

=SALES.XLS!Profits

=Signal|System!Formats

=Signal|StockInfo!MSFT

This worksheet would have a value of 3 in the cxals field of the EXTERNCOUNT record, corresponding to the three external references SALES.XLS, Signal|System, and Signal|StockInfo.

Record Data

Offset | Name | Size | Contents
4 | cxals | 2 | Number of external references

EXTERNNAME: Externally Referenced Name (223h)

The EXTERNNAME record stores an externally referenced name, DDE link, or OLE link. All EXTERNNAME records associated with a supporting workbook must directly follow the EXTERNSHEET record for the workbook. The order of EXTERNNAME records in a BIFF file should not be changed.

External Name

When the EXTERNNAME record stores an external name, fOle and fOleLink are both equal to zero (FALSE), and the record has the form shown in the following table.

Offset | Name | Size | Contents
4 | grbit | 2 | Option flags
6 | (Reserved) | 4 | Reserved; must be 0 (zero)
10 | cch | 1 | Length of the external name
11 | rgch | var | External name
var | cce | 2 | Length of the name definition
var | rgce | var | Name definition, in parsed expression format; for more information, see Microsoft Excel Formulas.

The grbit field contains the option flags listed in the following table.

Bits | Mask | Name | Contents
0 | 0001h | fBuiltin | = 1 if the name is a built-in name
1 | 0002h | fWantAdvise | N/A for External Names (must be 0 (zero))
2 | 0004h | fWantPict | N/A for External Names (must be 0 (zero))
3 | 0008h | fOle | N/A for External Names (must be 0 (zero))
4 | 0010h | fOleLink | N/A for External Names (must be 0 (zero))
15-5 | FFE0h | (reserved) | Reserved; must be 0 (zero)

DDE Link

When the EXTERNNAME record stores a DDE link, the record has the form shown in the following table.

Offset | Name | Size | Contents
4 | grbit | 2 | Option flags
6 | (Reserved) | 4 | Reserved; must be 0 (zero)
10 | cch | 1 | Length of the external name
11 | rgch | var | External name
var | rgoper | var | Array of OPERs that stores the current value of the name

The grbit field contains the option flags listed in the following table.

Bits | Mask | Name | Contents
0 | 0001h | fBuiltin | N/A for DDE links (must be 0 (zero))
1 | 0002h | fWantAdvise | = 0 for manual DDE links = 1 for automatic DDE links
2 | 0004h | fWantPict | = 1 if Microsoft Excel wants a cfPict clipboard format representation of the data; OBJ and IMDATA records store the image
3 | 0008h | fOle | = 1 if this record stores the OLE StdDocumentName identifier (no rgoper follows rgch)
4 | 0010h | fOleLink | = 0 for DDE links
14-5 | 7FE0h | cf | The clipboard format for which the DDE Advise succeeded; this is used to reduce the time required for future Advise cycles
15 | 8000h | (Reserved) | Reserved; must be 0 (zero)

OLE Link

When the EXTERNNAME record stores an OLE link, fWantAdvise and fOleLink are equal to 1 (TRUE), and the record has the form shown in the following table.

Offset | Name | Size | Contents
4 | grbit | 2 | Option flags
6 | lStgName | 4 | OLE 2 storage identifier
10 | cch | 1 | Length of the link name
11 | rgch | var | Link name

The grbit field contains the option flags listed in the following table.

Bits | Mask | Name | Contents
0 | 0001h | fBuiltin | N/A for OLE links (must be 0 (zero))
1 | 0002h | fWantAdvise | = 0 for manual OLE links = 1 for automatic OLE links
2 | 0004h | fWantPict | = 1 if Microsoft Excel wants a cfPict clipboard format representation of the data; OBJ and IMDATA records store the image
3 | 0008h | fOle | N/A for OLE links (must be 0 (zero))
4 | 0010h | fOleLink | = 1 for OLE links
15-5 | FFE0h | (Reserved) | Reserved; must be 0 (zero)

EXTERNSHEET: External Reference (17h)

The EXTERNSHEET record specifies an externally referenced workbook. The cxals field of the EXTERNCOUNT record specifies the number of EXTERNSHEET records. You should not change the order of EXTERNSHEET records.

An externally referenced workbook is called a source workbook. The workbook that refers to it is called a dependent workbook.

Record Data

Offset | Name | Size | Contents
4 | cch | 1 | Length of the filename
5 | rgch | var | Filename

The cch field contains the length of the source workbook filename. The rgch field contains the source workbook filename.

Filename Encoding

Whenever possible, filenames are encoded to make BIFF files transportable across file systems. Encoded filenames are identified by the first character of the rgch field. The first character of the rgch field may be any one of the values listed in the following table.

Name | Value | Meaning
chEmpty | 00 | Reference to an empty workbook name (see text)
chEncode | 01 | Filename has been encoded (see the following table)
chSelf | 02 | Self-referential external reference (see text)

chEmpty indicates that the filename is an external reference to an empty workbook name, as in the formula =Sheet1!$A$1.

chSelf indicates that the filename is an external reference in which the dependent and source workbooks are the same. An example of this is the workbook SALES.XLS, which contains the formula =SALES.XLS!$A$1.

A chDDE key (03h) can occur in the rgch field; it is not necessarily the first character in the field, as are chEmpty, chEncode, and chSelf. This key indicates that the external reference is a DDE or OLE link. In a DDE link, the chDDE key replaces the | (pipe) character that separates the DDE application and topic. In an OLE link, chDDE separates the classname and filename.

A chEncode at the beginning of rgch indicates that the filename of the source workbook has been encoded to a less system-dependent filename. The special keys listed in the following table are recognized in the rgch field.

Name | Value | PC file systems | Macintosh file system
chVolume | 01 | Represents an MS-DOS drive letter. It is followed by the drive letter. For example, the formula ='D:\SALES.XLS'!A1 generates the chVolume key when the dependent workbook is not on the D drive. UNC filenames, such as \\server\share\myfile.xls, generate an @ character after the chVolume key; this replaces the initial double backslash (\\). | Represents a single-character volume name. Because single-character volume names are uncommon on the Macintosh, the chLongVolume key is used to represent volume names that are longer than a single character.
chSameVolume | 02 | Indicates that the source workbook is on the same drive as the dependent workbook (the drive letter is omitted). For example, the formula ='\SALES.XLS'!A1 generates the chSameVolume key when the dependent workbook is not in the root directory. | Indicates that the source workbook is in the same volume as the dependent workbook (the volume name is omitted).
ChDownDir | 03 | Indicates that the source workbook is in a subdirectory of the current directory. For example, the formula ='XL\SALES.XLS'!A1 generates the chDownDir key. The subdirectory name precedes the chDownDir key, and the filename follows it. | Indicates that the source workbook is in a folder in the current folder. For example, the formula =':XL:Sales1992'!A1 generates the chDownDir key. The folder name precedes the chDownDir key, and the filename follows it.
chUpDir | 04 | Indicates that the source workbook is in the parent directory of the current directory. For example, the formula ='..\SALES.XLS'!A1 generates the chUpDir key. | Indicates that the source workbook is in the parent folder of the current folder. For example, the formula ='::Sales1992'!A1 generates the chUpDir key.
chLongVolume | 05 | (Not used) | The chLongVolume key is followed by the length of the name (1 byte) and then by the volume name string.
chStartupDir | 06 | Indicates that the source workbook is in the startup directory (the Xlstart subdirectory of the directory that contains Excel.exe). | Indicates that the source workbook is in the Excel Startup Folder (5), which is in the System Folder.
chAltStartupDir | 07 | Indicates that the source workbook is in the alternate startup directory. | Indicates that the source workbook is in the alternate startup folder.
chLibDir | 08 | Indicates that the source workbook is in the Library directory. | Indicates that the source workbook is in the Macro Library folder.

FILEPASS: File Is Password-Protected (2Fh)

If you type a protection password (File menu, Save As command, Options dialog box), the FILEPASS record appears in the BIFF file. The wProtPass field contains the encrypted password. All records after FILEPASS are encrypted; you cannot read these encrypted records.

Note that this record specifies a file protection password, as opposed to the PASSWORD record (type 13h), which specifies a sheet-level or workbook-level protection password.

Record Data

Offset | Name | Size | Contents
4 | wProtPass | 4 | Encrypted password

FILESHARING: File-Sharing Information (5Bh)

This record stores file-sharing options selected in the Options dialog box, accessed by using the Save As command (File menu). The write reservation password that you type in the dialog box is encrypted to an integer, wResPass. This record also contains the user name of the file's creator, stUNWriteRes.

Changes for BIFF7

There are minor changes to the behavior of this record in BIFF7. For Microsoft Excel version 7.0 workbooks that do not contain shared lists, this record behaves as it does in BIFF5.

For Microsoft Excel version 7.0 workbooks that contain shared lists, there will be both FILESHARING and FILESHARING2 records in the Book stream. In this case, FILESHARING always contains a dummy password. FILESHARING2 contains either a dummy password if the workbook is not write protected, or a valid password if the workbook is write protected.

Record Data

Offset | Name | Size | Contents
4 | fReadOnlyRec | 2 | = 1 if the Read Only Recommended option is selected in the Options dialog box
6 | wResPass | 2 | Encrypted password (if this field is 0 (zero), there is no write reservation password)
8 | cch | 1 | Length of the user name
9 | stUNWriteRes | var | User name

FILESHARING2: File-Sharing Information for Shared Lists (1A5h) (New for BIFF7)

In Microsoft Excel version 7.0 workbooks that contain shared lists, FILESHARING2 contains either a dummy password if the workbook is not write protected, or a valid password if the workbook is write-protected. If the workbook does not contain shared lists, this record does not appear in the file.

This record does not appear in BIFF5 files.

Record Data

Offset | Name | Size | Contents
4 | fReadOnlyRec | 2 | = 1 if the Read Only Recommended option is selected in the Options dialog box
6 | wResPass | 2 | Encrypted password (if this field is 0 (zero), there is no write reservation password)
8 | cch | 1 | Length of the user name
9 | stUNWriteRes | var | User name

FILTERMODE: Sheet Contains Filtered List (9Bh)

If the sheet contains a filtered list, the file will contain a FILTERMODE record. This record has no record data field.

FNGROUPCOUNT: Built-in Function Group Count (9Ch)

This record stores the number of built-in function groups (Financial, Math & Trig, Date & Time, and so on) in the current version of Microsoft Excel.

Record Data

Offset | Name | Size | Contents
4 | cFnGroup | 2 | Number of built-in function groups

FNGROUPNAME: Function Group Name (9Ah)

This record stores the name of a custom function category.

Record Data

Offset | Name | Size | Contents
4 | cch | 1 | Size of the function category name
5 | rgch | var | Function category name

FONT: Font Description (231h)

The workbook font table contains at least five FONT records. FONT records are numbered as follows: ifnt = 00h (the first FONT record in the table), ifnt = 01h, ifnt = 02h, ifnt = 03h, ifnt = 05h (minimum table), and then ifnt = 06h, ifnt = 07h, and so on. Notice that ifnt = 04h never appears in a BIFF file. This is for backward-compatibility with previous versions of Microsoft Excel. If you read FONT records, remember to index the table correctly, skipping ifnt = 04h.

Record Data

Offset | Name | Size | Contents
4 | dyHeight | 2 | Height of the font (in units of 1/20th of a point).
6 | grbit | 2 | Font attributes (see the following table).
8 | icv | 2 | Index to the color palette.
10 | bls | 2 | Bold style; a number from 100dec to 1000dec (64h to 3E8h) that indicates the character weight ("boldness"). The default values are 190h for normal text and 2BCh for bold text.
12 | sss | 2 | Superscript/subscript: 00h = None 01h = Superscript 02h = Subscript
14 | uls | 1 | Underline style: 00h = None 01h = Single 02h = Double 21h = Single Accounting 22h = Double Accounting
15 | bFamily | 1 | Font family, as defined by the Windows API LOGFONT structure.
16 | bCharSet | 1 | Character set, as defined by the Windows API LOGFONT structure.
17 | (Reserved) | 1 | Reserved; must be 0 (zero).
18 | cch | 1 | Length of the font name.
19 | rgch | var | Font name.

The grbit field contains the font attributes listed in the following table.

Offset | Bits | Mask | Name | Contents
0 | 0 | 01h | (Reserved) | Reserved; must be 0 (zero)
 | 1 | 02h | fItalic | = 1 if the font is italic
 | 2 | 04h | (Reserved) | Reserved; must be 0 (zero)
0 | 3 | 08h | fStrikeout | = 1 if the font is struck out
 | 4 | 10h | fOutline | = 1 if the font is outline style (Macintosh only)
 | 5 | 20h | fShadow | = 1 if the font is shadow style (Macintosh only)
 | 7-6 | C0h | (Reserved) | Reserved; must be 0 (zero)
1 | 7–0 | FFh | (Unused) |

FOOTER: Print Footer on Each Page (15h)

The FOOTER record stores a print footer string for a sheet. This string appears at the bottom of every page when the sheet is printed.

Record Data

Offset | Name | Size | Contents
4 | cch | 1 | Length of the footer string (bytes)
5 | rgch | var | Footer string

FORMAT: Number Format (41Eh)

The FORMAT record describes a number format in the workbook.

All the FORMAT records should appear together in a BIFF file. The order of FORMAT records in an existing BIFF file should not be changed. You can write custom number formats in a file, but they should be added at the end of the existing FORMAT records.

Record Data

Offset | Name | Size | Contents
4 | ifmt | 2 | Format index code (for internal use only)
6 | cch | 1 | Length of the format string
7 | rgch | var | Number format string

Microsoft Excel uses the ifmt field to identify built-in formats when it reads a file that was created by a different localized version.

FORMULA: Cell Formula (406h)

A FORMULA record describes a cell that contains a formula.

Record Data

Offset | Name | Size | Contents
4 | rw | 2 | Row
6 | col | 2 | Column
8 | ixfe | 2 | Index to XF record
10 | num | 8 | Current value of the formula (see text)
18 | grbit | 2 | Option flags
20 | chn | 4 | (See text)
24 | cce | 2 | Length of the parsed expression
26 | rgce | var | Parsed expression

The chn field should be ignored when you read the BIFF file. If you write a BIFF file, the chn field must be 00000000h.

The grbit field contains the option flags listed in the following table.

Offset | Bits | Mask | Name | Contents
0 | 0 | 01h | fAlwaysCalc | Always calculate the formula.
 | 1 | 02h | fCalcOnLoad | Calculate the formula when the file is opened.
 | 2 | 04h | (Reserved) |
 | 3 | 08h | fShrFmla | = 1 if the formula is part of shared formula group.
 | 7–4 | F0h | (Unused) |
1 | 7–0 | FFh | (Unused) |

For more information about shared formulas, see SHRFMLA.

The rw field contains the 0-based row number. The col field contains the 0-based column number.

If the formula evaluates to a number, the num field contains the current calculated value of the formula in 8-byte IEEE format. If the formula evaluates to a string, a Boolean value, or an error value, the most-significant 2 bytes of the num field are FFFFh.

A Boolean value is stored in the num field, as shown in the following table. For more information about Boolean values, see BOOLERR.

Offset | Name | Size | Contents
0 | otBool | 1 | = 1 always
1 | (Reserved) | 1 | Reserved; must be 0 (zero)
2 | f | 1 | Boolean value
3 | (Reserved) | 3 | Reserved; must be 0 (zero)
6 | fExprO | 2 | = FFFFh

An error value is stored in the num field, as shown in the following table. For more information about error values, see BOOLERR.

Offset | Name | Size | Contents
0 | otErr | 1 | = 2 always
1 | (Reserved) | 1 | Reserved; must be 0 (zero)
2 | err | 1 | Error value
3 | (Reserved) | 3 | Reserved; must be 0 (zero)
6 | fExprO | 2 | = FFFFh

If the formula evaluates to a string, the num field has the structure shown in the following table.

Offset | Name | Size | Contents
0 | otString | 1 | = 0 always
1 | (Reserved) | 5 | Reserved; must be 0 (zero)
6 | fExprO | 2 | = FFFFh

The string value is not stored in the num field; instead, it is stored in a STRING record that immediately follows the FORMULA record.

The cce field contains the length of the formula. The rgce field contains the formula in its parsed format. For more information, see Microsoft Excel Formulas.

GCW: Global Column-Width Flags (ABh)

This record contains an array of 256 flag bits, where each bit represents a column on the sheet. If a bit is true, it means that the corresponding column has the Use Standard Width option turned on. If a bit is false, it means that the column has the Use Standard Width option turned off. If the Standard Width measurement has been changed (that is, if it is no longer the default), Microsoft Excel writes a STANDARDWIDTH record.

Record Data

Offset | Name | Size | Contents
4 | cb | 2 | Number of bytes in the global column-width flags
6 | grbitGCW | 2 | Global column-width flags for columns A through P
8 | grbitGCW | 2 | Global column-width flags for columns Q through AF
... | ... | ... | ...
4+cb | grbitGCW | 2 | Global column-width flags for columns IG through IV

The grbitGCW field contains the option flags listed in the following table.

Bits | Mask | Name | Contents
0 (LSB) | 0001h | fGCWcol1 | Flag for column 1 (for example, column A)
1 | 0002h | fGCWcol2 | Flag for column 2 (for example, column B)
2 | 0004h | fGCWcol3 | Flag for column 3 (for example, column C)
... | ... | ... | ...
15 | 8000h | fGCWcol16 | Flag for column 16 (for example, column P)

GRIDSET: State Change of Gridlines Option (82h)

This record indicates that the user changed the state of the Gridlines option in the Page Setup dialog box, Sheet tab.

Record Data

Offset | Name | Size | Contents
4 | fGridSet | 2 | = 1 if the user has ever changed the setting of the Gridlines option

GUTS: Size of Row and Column Gutters (80h)

This record contains the size of the row and column gutters, measured in screen units. The row and column gutters are the spaces that contain outline symbols. They are located above column headings and to the left of row headings.

Record Data

Offset | Name | Size | Contents
4 | dxRwGut | 2 | Size of the row gutter that appears to the left of the rows
6 | dyColGut | 2 | Size of the column gutter that appears above the columns
8 | iLevelRwMac | 2 | Maximum outline level (for the row gutter)
10 | iLevelColMac | 2 | Maximum outline level (for the column gutter)

HCENTER: Center Between Horizontal Margins (83h)

If the Horizontally option is selected on the Margins tab in the Page Setup dialog box, fHCenter = 1.

Record Data

Offset | Name | Size | Contents
4 | fHCenter | 2 | = 1 if the sheet is to be centered between horizontal margins when printed

HEADER: Print Header on Each Page (14h)

The HEADER record specifies a print header string for a sheet. This string appears at the top of every page when the sheet is printed.

Record Data

Offset | Name | Size | Contents
4 | cch | 1 | Length of the header string (bytes)
5 | rgch | var | Header string

HIDEOBJ: Object Display Options (8Dh)

The HIDEOBJ record stores options selected in the Options dialog box, View tab.

Record Data

Offset | Name | Size | Contents
4 | fHideObj | 2 | = 2 if the Hide All option is turned on = 1 if the Show Placeholders option is turned on = 0 if the Show All option is turned on

HORIZONTALPAGEBREAKS: Explicit Row Page Breaks (1Bh)

The HORIZONTALPAGEBREAKS record contains a list of explicit row page breaks. The cbrk field contains the number of page breaks. The rgrw field is an array of 2-byte integers that specifies rows. Microsoft Excel sets a page break before each row contained in the list of rows in the rgrw field. The rows must be sorted in ascending order.

Record Data

Offset | Name | Size | Contents
4 | cbrk | 2 | Number of page breaks
6 | rgrw | var | Array of rows

IMDATA: Image Data (7Fh)

The IMDATA record contains the complete description of a bitmapped graphic object, such as a drawing created by a graphics tool.

Record Data

Offset | Name | Size | Contents
4 | cf | 2 | Image format: = 02h, Windows metafile or Macintosh PICT format = 09h, Windows bitmap format = 0Eh, Native format (see text)
6 | env | 2 | Environment from which the file was written: = 1, Microsoft Windows = 2, Apple Macintosh
8 | lcb | 4 | Length of the image data
12 | data | var | Image data

For more information about the Microsoft Windows metafile file format, see the documentation for the Microsoft Windows Software Development Kit.

For more information about the Apple Macintosh PICT file format, see The Programmer's Apple Mac Sourcebook (published by Microsoft Press,
ISBN 1-55615-168-3), section 2.087, "PICT File Format"; or see Inside Macintosh Volume V (published by Addison-Wesley Publishing Company, Inc., ISBN 0-201-17719-6).

If the image is in Microsoft Windows bitmap format (cf = 09h), the data field consists of a BITMAPCOREINFO data structure followed by the actual bitmap. The BITMAPCOREINFO data structure consists of a BITMAPCOREHEADER structure, followed by an array of RGBTRIPLE structures that define the color table. For more information about these structures, see the documentation for the Microsoft Windows Software Development Kit.

Native format (cf = 0Eh) stores an embedded object from another application. The image data is in the foreign application's format and cannot be directly processed by Microsoft Excel.

INDEX: Index Record (20Bh)

Microsoft Excel writes an INDEX record immediately after the BOF record for each worksheet substream in a BIFF file. For more information about the INDEX record, see Finding Cell Records in BIFF Files.

Record Data

Offset | Name | Size | Contents
4 | (Reserved) | 4 | Reserved; must be 0 (zero)
8 | rwMic | 2 | First row that exists on the sheet
10 | rwMac | 2 | Last row that exists on the sheet, plus 1
12 | (Reserved) | 4 | Reserved; must be 0 (zero)
16 | rgibRw | var | Array of file offsets to the DBCELL records for each block of ROW records. A block contains ROW records for up to 32 rows. For more information, see Finding Cell Records in BIFF Files.

The rwMic field contains the number of the first row in the sheet that contains a value or a formula that is referenced by a cell in some other row. Because rows (and columns) are always stored 0-based rather than 1-based (as they appear on the screen), cell A1 is stored as row 0; cell A2 is row 1, and so on. The rwMac field contains the 0-based number of the last row in the sheet, plus 1.

INTERFACEEND: End of User Interface Records (E2h)

This records marks the end of the user interface section of the Book stream. It has no record data field.

INTERFACEHDR: Beginning of User Interface Records (E1h)

This records marks the beginning of the user interface section of the Book stream. It has no record data field.

ITERATION: Iteration Mode (11h)

The ITERATION record stores the Iteration option from the Options dialog box, Calculation tab.

Record Data

Offset | Name | Size | Contents
4 | fIter | 2 | = 1 if the Iteration option is on

LABEL: Cell Value, String Constant (204h)

A LABEL record describes a cell that contains a string constant. The rw field contains the 0-based row number. The col field contains the 0-based column number. The string length is contained in the cch field and must be in the range of 0000h–00FFh (0–255). The string itself is contained in the rgch field.

Record Data

Offset | Name | Size | Contents
4 | rw | 2 | Row
6 | col | 2 | Column
8 | ixfe | 2 | Index to the XF record
10 | cch | 2 | Length of the string
12 | rgch | var | The string

LEFTMARGIN: Left Margin Measurement (26h)

The LEFTMARGIN record specifies the width of the left margin, in inches. The num field is in 8-byte IEEE floating-point format.

Record Data

Offset | Name | Size | Contents
4 | num | 8 | Left margin

LHNGRAPH: Named Graph Information (95h)

Record Data

This record is similar to the .WKS NGRAPH record, except that the first 13 references are not written. Instead, there are 13 integers that indicate whether the references X, A–F, and Data Label A–F are defined.

LHRECORD: .WK? File Conversion Information (94h)

This record contains information that Microsoft Excel uses when it converts an .XLS file to a .WKS, .WK1, or .WK3 file, or vice versa.

Record Data

LHRECORD contains subrecords that resemble BIFF records. Each subrecord consists of the three fields described in the following table.

Offset (within subrecord) | Length (bytes) | Contents
0 | 2 | Subrecord type (rtlh)
2 | 2 | Length of the subrecord data
4 | var | Subrecord data

The following table describes the subrecords.

rtlh | Subrecord name | Contents
01h | (Reserved) | Reserved for future use.
02h | lhrtHpstGrHeader | Header string for the /Graph Save Print help command.
03h | lhrtHpstGrFooter | Footer string for the /Graph Save Print help command.
04h | lhrtNumGrLftMgn | Left margin for the /Graph Save Print help command (IEEE number).
05h | lhrtNumGrRgtMgn | Right margin for the /Graph Save Print help command (IEEE number).
06h | lhrtNumGrTopMgn | Top margin for the /Graph Save Print help command (IEEE number).
07h | lhrtNumGrBotMgn | Bottom margin for the /Graph Save Print help command (IEEE number).
08h | lhrtGrlh | Current /Graph View data. Structure similar to the .WKS GRAPH record except that the first 13 references are not written. Instead, there are 13 integers that indicate whether the references X, A–F, and Data Label A–F are defined.
09h | lhrtcchGlColWidth | Current global column width (integer).
0Ah | (Reserved) | Reserved for future use.
0Bh | lhrttblType | Current table type: = 0, none (default) = 1, table1 = 2, table2
0Ch | (Reserved) | Reserved for future use.

LPR: Sheet Was Printed Using LINE.PRINT() (98h)

If this record appears in a file, it indicates that the sheet was printed using the LINE.PRINT() macro function. The LPR record stores options associated with this function.

Record Data

Offset | Name | Size | Contents
4 | grbit | 2 | Option flags
6 | cchMargLeft | 2 | Left margin, expressed as a count of characters
8 | cchMargRight | 2 | Right margin, expressed as a count of characters
10 | cliMargTop | 2 | Top margin, expressed as a count of lines
12 | cliMargBot | 2 | Bottom margin, expressed as a count of lines
14 | cliPg | 2 | Number of lines per page
16 | cch | 1 | Length of the printer setup string
17 | rgch | var | Printer setup string

The grbit field contains the option flags listed in the following table.

Offset | Bits | Mask | Name | Contents
0 | 0 | 01h | fWait | = 1, alert the user after each sheet is printed
 | 1 | 02h | fFormatted | = 1, print headers and footers
 | 2 | 04h | fAutoLF | = 1, write only the carriage return (CR) character (no line feed) at the end of the line
 | 7–3 | F8h | (Unused) |
1 | 7–0 | FFh | (Unused) |

MMS: ADDMENU/DELMENU Record Group Count (C1h)

This record stores the number of ADDMENU groups and DELMENU groups in the Book stream.

Record Data

Offset | Name | Size | Contents
4 | caitm | 1 | Number of ADDMENU record groups
5 | cditm | 1 | Number of DELMENU record groups

MULBLANK: Multiple Blank Cells (BEh)

The MULBLANK record stores up to the equivalent of 256 BLANK records; the MULBLANK record is a file size optimization. The number of ixfe fields can be determined from the ColLast field and is equal to (colLast - colFirst + 1). The maximum length of the MULBLANK record is (256 x 2 + 10) = 522 bytes, because Microsoft Excel has at most 256 columns. Note that storing 256 blank cells in the MULBLANK record takes 522 bytes as compared with 2560 bytes for 256 BLANK records.

Record Data

Offset | Name | Size | Contents
4 | rw | 2 | Row number (0-based)
6 | colFirst | 2 | Column number (0-based) of the first column of the multiple RK record
8 | rgixfe | var | Array of indexes to XF records
10 | colLast | 2 | Last column containing the BLANKREC structure

MULRK: Multiple RK Cells (BDh)

The MULRK record stores up to the equivalent of 256 RK records; the MULRK record is a file size optimization. The number of 6-byte RKREC structures can be determined from the ColLast field and is equal to (colLast - colFirst + 1). The maximum length of the MULRK record is (256 x 6 + 10) = 1546 bytes, because Microsoft Excel has at most 256 columns. Note that storing 256 RK numbers in the MULRK record takes 1546 bytes as compared with 3584 bytes for 256 RK records.

Record Data

Offset | Name | Size | Contents
4 | rw | 2 | Row number (0-based)
6 | colFirst | 2 | Column number (0-based) of the first column of the multiple RK record
8 | rgrkrec | var | Array of 6-byte RKREC structures
var | colLast | 2 | Last column containing the RKREC structure

The RKREC structure is defined as follows:

typedef struct rkrec
        {
        SHORT ixfe;        /* index to XF record */
        long RK;        /* RK number */
        }
    RKREC;

NAME: Defined Name (218h)

The NAME record describes a defined name in the workbook.

Record Data

Offset | Name | Size | Contents
4 | grbit | 2 | Option flags
6 | chKey | 1 | Keyboard shortcut
7 | cch | 1 | Length of the name text
8 | cce | 2 | Length of the name definition
10 | ixals | 2 | Index to the sheet that contains this name, if the name is a local name (see text)
12 | itab | 2 | This field is equal to ixals
14 | cchCustMenu | 1 | Length of the custom menu text
15 | cchDescription | 1 | Length of the description text
16 | cchHelptopic | 1 | Length of the help topic text
17 | cchStatustext | 1 | Length of the status bar text
18 | rgch | var | Name text
var | rgce | var | Name definition (see text)
var | rgchCustMenu | var | Custom menu text
var | rgchDescr | var | Description text
var | rgchHelptopic | var | Help topic text
var | rgchStatustext | var | Status bar text

The grbit field contains the option flags listed in the following table.

Bits | Mask | Name | Contents
0 | 0001h | fHidden | = 1 if the name is hidden
1 | 0002h | fFunc | = 1 if the name is a function
2 | 0004h | fOB | = 1 if the name is a Visual Basic procedure
3 | 0008h | fProc | = 1 if the name is a function or command name on a macro sheet
4 | 0010h | fCalcExp | = 1 if the name contains a complex function
5 | 0020h | fBuiltin | = 1 if the name is a built-in name
11–6 | 0FC0h | fgrp | Function group index
12 | 1000h | fBig | = 1 if the name refers to binary data (see text)
15–13 | C000h | (Reserved) |

If the fBig bit in the grbit field is equal to 1, the NAME record contains a name attached to binary data. These names can be created only by calling the xlDefineBinaryName function from the Microsoft Excel C API. The first byte is the length of the name, which is followed by the name string. Following the name string is the data to which the name refers. The data can be up to 232 bytes long and can span multiple CONTINUE records.

The fCalcExp bit is set if the name definition contains a function that returns an array (for example, TREND, MINVERSE), contains a ROW or COLUMN function, or contains a user-defined function.

The chKey byte is significant only when the fProc bit is set in the grbit field. chKey is the keyboard shortcut for a command macro name. If the name is not a command macro name or has no keyboard shortcut, chKey is meaningless.

The cch field contains the length of the name text, and the rgch field contains the text itself. The cce field contains the length of the name definition, and the rgce field contains the definition itself. The location of rgce within the record depends on the length of the name text (rgch) field.

The name definition (rgce) is stored in the Microsoft Excel parsed format. For more information, see Microsoft Excel Formulas.

The NAME record stores two types of names: global names and local names. A global name is defined for an entire workbook, and a local name is defined on a single sheet. For example, MyName is a global name, whereas Sheet1!MyName is a local name. The ixals field in the NAME record will be nonzero for local names and will index the list of EXTERNSHEET records for the sheets in the workbook. The following field, itab, is equal to ixals.

All NAME records should appear together in a BIFF file. The order of NAME records in an existing BIFF file should not be changed. You can add new names to a file, but you should add them at the end of the NAME list (block of NAME records). Microsoft Excel saves the names to the BIFF file in alphabetic order, but this is not a requirement; Microsoft Excel will sort the name list, if necessary, when it loads a BIFF file.

Built-in Names

Microsoft Excel contains several built-in names — such as Criteria, Database, Auto_Open, and so on — for which the NAME records do not contain the actual name. Instead, cch always equals 1, and a single byte is used to identify the name as shown in the following table.

Built-in name | rgch
Consolidate_Area | 00
Auto_Open | 01
Auto_Close | 02
Extract | 03
Database | 04
Criteria | 05
Print_Area | 06
Print_Titles | 07
Recorder | 08
Data_Form | 09
Auto_Activate | 0A
Auto_Deactivate | 0B
Sheet_Title | 0C

NOTE: Note Associated with a Cell (1Ch)

The NOTE record specifies a note associated with a particular cell.

Record Data

Offset | Name | Size | Contents
4 | rw | 2 | Row of the note
6 | col | 2 | Column of the note
8 | cch | 2 | Length of the note (bytes)
10 | rgch | var | Text of the note

The cell is denoted by the rw and col fields. The rw field contains the 0-based row number. The col field contains the 0-based column number.

The cch field contains the length of the note in bytes. The rgch field contains the text of the note in ASCII format.

Notes longer than 2048 characters (bytes) must be divided into several NOTE records, with each record containing no more than 2048 characters. In this case, the first NOTE record contains the fields listed in the following table.

Offset | Name | Size | Contents
4 | rw | 2 | Row of the note
6 | col | 2 | Column of the note
8 | cch | 2 | Total length of the note
10 | rgch | 2048 | First 2048 characters of the note

Each successive NOTE record contains the fields listed in the following table.

Offset | Name | Size | Contents
4 | rw | 2 | = –1 always (FFFFh)
6 | (Reserved) | 2 | Reserved; must be 0 (zero)
8 | cch | 2 | Length of this section of the note
10 | rgch | var | This section of the note

NUMBER: Cell Value, Floating-Point Number (203h)

A NUMBER record describes a cell containing a constant floating-point number. The rw field contains the 0-based row number. The col field contains the 0-based column number. The number is contained in the num field in 8-byte IEEE floating-point format.

Record Data

Offset | Name | Size | Contents
4 | rw | 2 | Row
6 | col | 2 | Column
8 | ixfe | 2 | Index to the XF record
10 | num | 8 | Floating-point number value

OBJ: Describes a Graphic Object (5Dh)

BIFF files may contain several different variations of the OBJ record. They correspond to the graphic objects and dialog box controls available in Microsoft Excel: line object, rectangle object, check box object, and so on.

Record Data

The first 36 bytes of every OBJ record are fields that are common to all object types. The remaining fields are object-specific and are described in separate sections following the common object fields.

Common Object Fields

Offset | Name | Size | Contents
4 | cObj | 4 | Count (1-based) of the objects in the file
8 | OT | 2 | Object type: Group object: OT = 00h Line object: OT = 01h Rectangle object: OT = 02h Oval object: OT = 03h Arc object: OT = 04h Chart object: OT = 05h Text object: OT = 06h Button object: OT = 07h Picture object: OT = 08h Polygon object: OT = 09h Check box object: OT = 0Bh Option button object: OT = 0Ch Edit box object: OT = 0Dh Label object: OT = 0Eh Dialog frame object: OT = 0Fh Spinner object: OT = 10h Scroll bar object: OT = 11h List box object: OT = 12h Group box object: OT = 13h Drop-down object: OT = 14h
10 | id | 2 | Object identification number
12 | grbit | 2 | Option flags (see the following table)
14 | colL | 2 | Column containing the upper-left corner of the object's bounding rectangle
16 | dxL | 2 | X (horizontal) position of the upper-left corner of the object's bounding rectangle, relative to the left side of the underlying cell, expressed as 1/1024th of the cell's width
18 | rwT | 2 | Row containing the upper-left corner of the object's bounding rectangle
20 | dyT | 2 | Y (vertical) position of the upper-left corner of the object's bounding rectangle, relative to the top of the underlying cell, expressed as 1/1024th of the cell's height
22 | colR | 2 | Column containing the lower-right corner of the object's bounding rectangle.
24 | dxR | 2 | X (horizontal) position of the lower-right corner of the object's bounding rectangle, relative to the left side of the underlying cell, expressed as 1/1024th of the cell's width.
26 | rwB | 2 | Row containing the lower-right corner of the object's bounding rectangle.
28 | dyB | 2 | Y (vertical) position of the lower-right corner of the object's bounding rectangle, relative to the top of the underlying cell, expressed as 1/1024th of the cell's height.
30 | cbMacro | 2 | Length of the FMLA structure that stores the definition of the attached macro; see FMLA Structure. Some objects may store the length of the FMLA structure in a cbFmla that immediately preceded the FMLA; in these objects, cbMacro is ignored.
32 | (Reserved) | 6 | Reserved; must be 0 (zero).

The grbit field at byte 12 contains the flag bits listed in the following table.

Offset | Bits | Mask | Name | Contents
0 | 0 | 01h | fSel | = 1 if the object is selected
 | 1 | 02h | fAutoSize | = 1 if the object moves and sizes with the cells
 | 2 | 04h | fMove | = 1 if the object moves with the cells (Format Object dialog box, Properties tab)
 | 3 | 08h | (Reserved) | Reserved; must be 0 (zero)
 | 4 | 10h | fLocked | = 1 if the object is locked when the sheet is protected
 | 5 | 20h | (Reserved) | Reserved; must be 0 (zero)
 | 6 | 40h | (Reserved) | Reserved; must be 0 (zero)
 | 7 | 80h | fGrouped | = 1 if the object is part of a group of objects
1 | 0 | 01h | fHidden | = 1 if the object is hidden (this can only be done from a macro)
 | 1 | 02h | fVisible | = 1 if the object is visible
 | 2 | 04h | fPrint | = 1 if the object is printable
 | 7-3 | F8h | (Reserved) | Reserved; must be 0 (zero)

Line Object Fields

Offset | Name | Size | Contents
38 | icv | 1 | Index to the color palette for line color.
39 | lns | 1 | Line style: Solid: lns = 0 Dash: lns = 1 Dot: lns = 2 Dash-dot: lns = 3 Dash-dot-dot: lns = 4 Null (unused): lns = 5 Dark gray: lns = 6 Medium gray: lns = 7 Light gray: lns = 8
40 | lnw | 1 | Line weight: Hairline: lnw = 0 Single: lnw = 1 Double: lnw = 2 Thick: lnw = 3
41 | fAuto | 1 | Bit 0 = 1 if Automatic Border option is turned on (Format Object dialog box, Patterns tab). All other bits in fAuto are don't-care.
42 | es | 2 | End style structure (see the following table).
44 | iqu | 1 | Quadrant index (direction of line): Starts upper left, ends lower right: iqu = 0 Starts upper right, ends lower left: iqu = 1 Starts lower right, ends upper left: iqu = 2 Starts lower left, ends upper right: iqu = 3
45 | (Reserved) | 1 | Reserved; must be 0 (zero).
46 | cchName | 1 | Length of the name (null if no name).
47 | stName | var | Name (null if no name; may contain a padding byte to force word-boundary alignment).
var | fmla | var | FMLA structure (see the following section).

The end style structure (es) describes the arrowheads on the end point of the line. The structure contains four 4-bit fields, as described in the following table.

Offset | Bits | Mask | Name | Contents
0 | 3–0 | 0Fh | sest | Arrowhead style: None: sest = 0 Open: sest = 1 Filled: sest = 2 Double-ended open: sest = 3 Double-ended filled: sest = 4
 | 7–4 | F0h | sesw | Arrowhead width: Narrow: sesw = 0 Medium: sesw = 1 Wide: sesw = 2
1 | 3–0 | 0Fh | sesl | Arrowhead length: Short: sesl = 0 Medium: sesl = 1 Long: sesl = 2
 | 7–4 | F0h | (Unused) |

FMLA Structure

The FMLA structure stores a parsed expression for the macro that is attached to the object. For more information about parsed expressions, see Microsoft Excel Formulas. The FMLA structure is null if the object does not have a macro attached.

In some object types, the FMLA structure length is given by cbMacro in the common object fields. In other object types, the FMLA structure length is given by a cbFmla that immediately precedes the FMLA. In these object types, ignore cbMacro. There may be an optional padding byte at the end of the FMLA to force it to end on a word boundary. The FMLA structure has the form shown in the following table.

Offset | Name | Size | Contents
0 | cce | 2 | Length of the parsed expression
2 | (Reserved) | 4 |
6 | rgce | var | Parsed expression (may contain a padding byte to force word-boundary alignment)

Rectangle Object Fields

Offset | Name | Size | Contents
38 | icvBack | 1 | Index to the color palette for background color
39 | icvFore | 1 | Index to the color palette for foreground color
40 | fls | 1 | Fill pattern
41 | fAuto | 1 | Bit 0 = 1 if the Automatic Fill option is turned on (Format Object dialog box, Patterns tab). All other bits in fAuto are don't-care.
42 | icv | 1 | Index to the color palette for line color.
43 | lns | 1 | Line style (see Line Object Fields).
44 | lnw | 1 | Line weight (see Line Object Fields).
45 | fAuto | 1 | Bit 0 = 1 if the Automatic border option is turned on (Format Object dialog box, Patterns tab). All other bits in fAuto are don't-care.
46 | frs | 2 | Frame style structure (see the following table).
48 | cchName | 1 | Length of the name (null if no name).
49 | stName | var | Name (null if no name; may contain a padding byte to force word-boundary alignment).
var | fmla | var | FMLA structure (see FMLA Structure).

The frame style structure (frs) contains 16 bits. Because dxyCorner overlaps the byte boundary, the structure is defined as a single 16-bit field instead of two 8-bit fields.

Offset | Bits | Mask | Name | Contents
0 | 0 | 0001h | frt | = 1 if the rectangle has rounded corners (Format Object dialog box, Patterns tab)
 | 1 | 0002h | fShadow | = 1 if the rectangle has a shadow border (Format Object dialog box, Patterns tab)
 | 9-2 | 03FCh | dxyCorner | Diameter of the oval (actually a circle) that defines the rounded corners (if frt = 1)
 | 15–10 | FC00h | (Unused) |

Oval Object Fields

Offset | Name | Size | Contents
38 | icvBack | 1 | Index to the color palette for background color.
39 | icvFore | 1 | Index to the color palette for foreground color.
40 | fls | 1 | Fill pattern.
41 | fAuto | 1 | Bit 0 = 1 if the Automatic Fill option is turned on (Format Object dialog box, Patterns tab). All other bits in fAuto are don't-care.
42 | icv | 1 | Index to the color palette for line color.
43 | lns | 1 | Line style (see Line Object Fields).
44 | lnw | 1 | Line weight (see Line Object Fields).
45 | fAuto | 1 | Bit 0 = 1 if the Automatic Border option is turned on (Format Object dialog box, Patterns tab). All other bits in fAuto are don't-care.
46 | frs | 2 | Frame style structure (see the following table).
48 | cchName | 1 | Length of the name (null if no name).
49 | stName | var | Name (null if no name; may contain a padding byte to force word-boundary alignment).
var | fmla | var | FMLA structure (see FMLA Structure).

The frame style structure (frs) contains 16 bits. dxyCorner is not used for oval objects.

Offset | Bits | Mask | Name | Contents
0 | 0 | 0001h | frt | (Not used for oval objects)
 | 1 | 0002h | fShadow | = 1 if the oval has a shadow border (Format Object dialog box, Patterns tab)
 | 2–9 | 03FCh | dxyCorner | (Not used for oval objects)
 | 10–15 | FC00h | (Unused) |

Arc Object Fields

Offset | Name | Size | Contents
38 | icvBack | 1 | Index to the color palette for background color.
39 | icvFore | 1 | Index to the color palette for foreground color.
40 | fls | 1 | Fill pattern.
41 | fAuto | 1 | Bit 0 = 1 if the Automatic Fill option is turned on (Format Object dialog box, Patterns tab). All other bits in fAuto are don't-care.
42 | icv | 1 | Index to the color palette for line color.
43 | lns | 1 | Line style (see Line Object Fields).
44 | lnw | 1 | Line weight (see Line Object Fields).
45 | fAuto | 1 | Bit 0 = 1 if the Automatic Border option is turned on (Format Object dialog box, Patterns tab). All other bits in fAuto are don't-care.
46 | iqu | 1 | Quadrant index (the section of an oval that describes the arc): Upper-right quadrant of the oval: iqu = 0 Upper-left quadrant of the oval: iqu = 1 Lower-left quadrant of the oval: iqu = 2 Lower-right quadrant of the oval: iqu = 3
47 | (Reserved) | 1 | Reserved; must be 0 (zero).
48 | cchName | 1 | Length of the name (null if no name).
49 | stName | var | Name (null if no name; may contain a padding byte to force word-boundary alignment).
var | fmla | var | FMLA structure (see FMLA Structure).

Chart Object Fields

Offset | Name | Size | Contents
38 | icvBack | 1 | Index to the color palette for background color.
39 | icvFore | 1 | Index to the color palette for foreground color.
40 | fls | 1 | Fill pattern.
41 | fAuto | 1 | Bit 0 = 1 if the Automatic Fill option is turned on (Format Object dialog box, Patterns tab). All other bits in fAuto are don't-care.
42 | icv | 1 | Index to the color palette for line color.
43 | lns | 1 | Line style (see Line Object Fields).
44 | lnw | 1 | Line weight (see Line Object Fields).
45 | fAuto | 1 | Bit 0 = 1 if the Automatic Border option is turned on (Format Object dialog box, Patterns tab). All other bits in fAuto are don't-care.
46 | frs | 2 | Frame style structure (see Rectangle Object Fields).
48 | grbit | 2 | Option flags (shown LSB to MSB): fLinked:1 = 1 if linked to a chart sheet Reserved:15 Reserved; must be 0 (zero)
50 | (Reserved) | 16 | Reserved; must be 0 (zero)
66 | cchName | 1 | Length of the name (null if no name)
67 | stName | var | Name (null if no name; may contain a padding byte to force word-boundary alignment)
var | fmla | var | FMLA structure (see FMLA Structure)

An embedded chart BIFF substream immediately follows the chart object record. This embedded chart file begins with a BOF record and ends with an EOF record. For more information, see Microsoft Excel Chart Records.

Text Object Fields

Offset | Name | Size | Contents
38 | icvBack | 1 | Index to the color palette for background color.
39 | icvFore | 1 | Index to the color palette for foreground color.
40 | fls | 1 | Fill pattern.
41 | fAuto | 1 | Bit 0 = 1 if the Automatic Fill option is turned on (Format Object dialog box, Patterns tab). All other bits in fAuto are don't-care.
42 | icv | 1 | Index to the color palette for line color.
43 | lns | 1 | Line style (see Line Object Fields).
44 | lnw | 1 | Line weight (see Line Object Fields).
45 | fAuto | 1 | Bit 0 = 1 if the Automatic Border option is turned on (Format Object dialog box, Patterns tab). All other bits in fAuto are don't-care.
46 | frs | 2 | Frame style structure (see the preceding section, "Rectangle Object Fields").
48 | cbText | 2 | Length of the object text.
50 | (Reserved) | 2 | Reserved; must be 0 (zero).
52 | cbRuns | 2 | Total length of all TXORUNS structures in the record.
54 | ifntEmpty | 2 | If cbRuns = 0, the text object is empty, and these 2 bytes contain the index to the FONT record for the object. If the object contains text, cbRuns > 0, and these 2 bytes are reserved.
56 | (Reserved) | 2 | Reserved; must be 0 (zero).
58 | grbit | 2 | Option flags (see the following table).
60 | rot | 2 | Orientation of text within the object boundary (Format Object dialog box, Alignment tab): = 0, no rotation (text appears left to right) = 1, text appears top to bottom; letters are upright = 2, text is rotated 90 degrees counterclockwise = 3, text is rotated 90 degrees clockwise
62 | (Reserved) | 12 | Reserved; must be 0 (zero)
74 | cchName | 1 | Length of the name (null if no name)
75 | stName | var | Name (null if no name; may contain a padding byte to force word-boundary alignment)
var | fmla | var | FMLA structure (see FMLA Structure)
var | rgch | var | Object text; may contain a single padding byte at the end of the text for word-boundary alignment (cbText does not count this padding byte)
var | TXORUNS | 8 | TXORUNS structure (see TXORUNS)
var | TXORUNS | 8 | TXORUNS structure (see TXORUNS)

The grbit field at byte 58 contains the option flags listed in the following table.

Offset | Bits | Mask | Name | Contents
0 | 0 | 01h | (Reserved) | Reserved; must be 0 (zero)
 | 3–1 | 0Eh | alcH | Horizontal text alignment: = 001 left-aligned = 010 centered = 011 right-aligned = 100 justified
 | 6–4 | 70h | lcV | Vertical text alignment: = 001 left-aligned = 010 centered = 011 right-aligned = 100 justified
 | 7 | 80h | fAutoTextSize | = 1 if the Automatic Size option is turned on (Format Object dialog box, Alignment tab)
1 | 0 | 01h | (Unused) |
 | 1 | 02h | fLockText | = 1 if the Lock Text option is turned on (Format Object dialog box, Protection tab)
 | 2 | 04h | fFuzzy | = 1 if the object is selected (the broken border is displayed)
 | 7-3 | F8h | (Reserved) | Reserved; must be 0 (zero)

TXORUNS

The TXORUNS structure contains formatting information about the object text string. A TXORUNS structure occurs every time the text formatting changes. The TXORUNS structure is described in the following table.

Offset | Name | Size | Contents
0 | ichFirst | 2 | Index to the first character to which the formatting applies
2 | ifnt | 2 | Index to the FONT record
4 | (Reserved) | 4 |

There are always at least two TXORUNS structures in the text object record, even if the entire text string is normal font (ifnt = 0). The last TXORUNS structure, which ends the formatting information for the string, always has ichFirst = cbText, and ifnt = 0.

Button Object Fields

Offset | Name | Size | Contents
38 | icvBack | 1 | Index to the color palette for background color (fixed for buttons).
39 | icvFore | 1 | Index to the color palette for foreground color (fixed for buttons).
40 | fls | 1 | Fill pattern (fixed for buttons).
41 | grbit | 1 | Option flags (fixed for buttons).
42 | icv | 1 | Index to the color palette for line color (fixed for buttons).
43 | lns | 1 | Line style (fixed for buttons).
44 | lnw | 1 | Line weight (fixed for buttons).
45 | fAuto | 1 | Bit 0 = 1 (fixed for buttons).
46 | frs | 2 | Frame style structure (ignored for buttons).
48 | cbText | 2 | Length of the object text.
50 | (Reserved) | 2 | Reserved; must be 0 (zero).
52 | cbRuns | 2 | Total length of all TXORUNS structures in record
54 | ifntEmpty | 2 | If cbRuns = 0, the button object is empty, and these 2 bytes contain the index to the FONT record for the object. If the object contains text, cbRuns > 0, and these 2 bytes are reserved.
56 | (Reserved) | 2 | Reserved; must be 0 (zero).
58 | grbit | 2 | Option flags (see the following table).
60 | rot | 2 | Orientation of text within the object boundary (Format Object dialog box, Alignment tab): = 0, no rotation (text appears left to right) = 1, text appears top to bottom; letters are upright = 2, text is rotated 90 degrees counterclockwise = 3, text is rotated 90 degrees clockwise
62 | (Reserved) | 6 | Reserved; must be 0 (zero)
68 | grbit | 2 | Option flags (shown LSB to MSB): fDefault:1 = 1 if this is the default button fHelp:1 = 1 if this is the Help button fCancel:1 = 1 if this is the cancel button fDismiss:1 = 1 if this is the dismiss button Reserved:12 Reserved; must be 0 (zero)
70 | accel | 2 | Accelerator key character
72 | accel2 | 2 | Accelerator key character (Far East versions only)
74 | cchName | 1 | Length of the name (null if no name)
75 | stName | var | Name (null if no name; may contain a padding byte to force word-boundary alignment)
var | fmla | var | FMLA structure (see FMLA Structure)
var | rgch | var | Object text; may contain a single padding byte at the end of the text for word-boundary alignment (cbText does not count this padding byte)
var | TXORUNS | 8 | TXORUNS structure (see TXORUNS)
var | TXORUNS | 8 | TXORUNS structure (see TXORUNS)

The grbit field at byte 58 contains the option flags listed in the following table.

Offset | Bits | Mask | Name | Contents
0 | 0 | 01h | (Reserved) | Reserved; must be 0 (zero)
 | 3–1 | 0Eh | alcH | Horizontal text alignment: = 001 left-aligned = 010 centered = 011 right-aligned = 100 justified
 | 6–4 | 70h | alcV | Vertical text alignment: = 001 left-aligned = 010 centered = 011 right-aligned = 100 justified
 | 7 | 80h | fAutoTextSize | = 1 if the Automatic Size option is turned on (Format Object dialog box, Alignment tab)
1 | 0 | 01h | (Unused) |
 | 1 | 02h | fLockText | = 1 if the Lock Text option is turned on (Format Object dialog box, Protection tab)
 | 2 | 04h | fFuzzy | = 1 if the object is selected (the broken border is displayed)
 | 7-3 | F8h | (Reserved) | Reserved; must be 0 (zero)

Picture Object Fields

Offset | Name | Size | Contents
38 | icvBack | 1 | Index to the color palette for background color.
39 | icvFore | 1 | Index to the color palette for foreground color.
40 | fls | 1 | Fill pattern.
41 | fAuto | 1 | Bit 0 = 1 if the Automatic Fill option is turned on (Format Object dialog box, Patterns tab). All other bits in fAuto are don't-care.
42 | icv | 1 | Index to the color palette for line color.
43 | lns | 1 | Line style (see Line Object Fields).
44 | lnw | 1 | Line weight (see Line Object Fields).
45 | fAuto | 1 | Bit 0 = 1 if the Automatic Border option is turned on (Format Object dialog box, Patterns tab). All other bits in fAuto are don't-care.
46 | frs | 2 | Frame style structure (see the preceding section, "Rectangle Object Fields").
48 | cf | 2 | Image format: = 00h Text format = 01h Null format (no image data) = 02h Windows metafile or Macintosh PICT format = 09h Windows bitmap format
50 | (Reserved) | 4 | Reserved; must be 0 (zero)
54 | cbPictFmla | 2 | Length of the picture FMLA structure (the FMLA that contains the link to the picture)
56 | (Reserved) | 2 | Reserved; must be 0 (zero)
58 | grbit | 2 | Option flags (see the following table)
60 | (Reserved) | 4 | Reserved; must be 0 (zero)
64 | cchName | 1 | Length of the name (null if no name)
65 | stName | var | Name (null if no name; may contain a padding byte to force word-boundary alignment)
var | fmla | var | Attached macro FMLA structure (see FMLA Structure)
var | PictFmla | var | Picture FMLA structure (see FMLA Structure)
var | (Reserved) | 4 | Reserved; must be 0 (zero)

The grbit field at byte 58 contains the option flags listed in the following table.

Offset | Bits | Mask | Name | Contents
0 | 0 | 01h | fAutoPict | = 0 if the user manually sizes picture by dragging a handle
 | 1 | 02h | fDde | = 1 if the reference in the FMLA structure is a DDE reference
 | 2 | 04h | fIcon | = 1 if the picture is from a DDE link, and the only available representation of the picture is an icon
 | 7–3 | F8h | (Unused) |
1 | 7–0 | FFh | (Unused) |

Sheet Background in Microsoft Excel for Windows 95

The sheet background bitmap for worksheets and charts is stored as a hidden picture object that has the name__BkgndObj (the stName field at byte 65). An IMDATA record will also appear in the file to store the image description.

Group Object Fields

Offset | Name | Size | Contents
34 | (Reserved) | 4 | Reserved; must be 0 (zero).
38 | idNext | 2 | Object ID number (id) of the object that follows the last object in this group. If there are no objects following the group, idNext = 0.
40 | (Reserved) | 16 | Reserved; must be 0 (zero).

A Group OBJ record precedes the OBJ records for the group members.

Polygon Object Fields

Offset | Name | Size | Contents
38 | icvBack | 1 | Index to the color palette for background color.
39 | icvFore | 1 | Index to the color palette for foreground color.
40 | fls | 1 | Fill pattern.
41 | fAuto | 1 | Bit 0 = 1 if the Automatic Fill option is turned on (Format Object dialog box, Patterns tab). All other bits in fAuto are don't-care.
42 | icv | 1 | Index to the color palette for line color.
43 | lns | 1 | Line style (see the preceding section, "Line Object Fields").
44 | lnw | 1 | Line weight (see preceding section, "Line Object Fields")
45 | fAuto | 1 | Bit 0 = 1 if the Automatic Border option is turned on (Format Object dialog box, Patterns tab). All other bits in fAuto are don't-care.
46 | frs | 2 | Frame style structure (see the preceding section, "Rectangle Object Fields").
48 | wstate | 2 | If bit 0 = 1, the polygon is closed. All other bits are don't-care.
50 | (Reserved) | 10 |
60 | iMacSav | 2 | Number of vertices in the polygon (1-based).
62 | (Reserved) | 8 |
70 | cchName | 1 | Length of the name (null if no name).
71 | stName | var | Name (null if no name; may contain a padding byte to force word-boundary alignment).
var | fmla | var | FMLA structure (see FMLA Structure).

For polygon objects, a COORDLIST record follows the OBJ record.

Check Box Object Fields

Offset | Name | Size | Contents
38 | icvBack | 1 | Index to the color palette for background color (fixed for check box objects)
39 | icvFore | 1 | Index to the color palette for foreground color (fixed for check box objects)
40 | fls | 1 | Fill pattern (ignored for check box objects)
41 | fAuto | 1 | (Ignored for check box objects)
42 | icv | 1 | Index to the color palette for line color (fixed for check box objects)
43 | lns | 1 | Line style (ignored for check box objects)
44 | lnw | 1 | Line weight (ignored for check box objects)
45 | fAuto | 1 | (Ignored for check box objects)
46 | frs | 2 | Frame style structure (ignored for check box objects)
48 | (Reserved) | 10 | Reserved; must be 0 (zero)
58 | grbit | 2 | Option flags (see the following table)
60 | (Reserved) | 20 | Reserved; must be 0 (zero)
80 | cchName | 1 | Length of the name (null if no name)
81 | stName | var | Name (null if no name; may contain a padding byte to force word-boundary alignment)
var | cbFmla1 | 2 | Length of the FMLA structure for the attached macro (never null)
var | fmla1 | var | FMLA structure for the attached macro (see FMLA Structure)
var | cbFmla2 | 2 | Length of the FMLA structure for the cell link (never null)
var | fmla2 | var | FMLA structure for the cell link (see FMLA Structure)
var | cbText | 2 | Length of the object text (never null)
var | rgch | var | Object text; may contain a single padding byte at the end of the text for word-boundary alignment (cbText does not count this padding byte)
var | fChecked | 2 | = 0 if the check box is not checked = 1 the if check box is checked = 2 if the check box is gray (mixed)
var | accel | 2 | Accelerator key character
var | accel2 | 2 | Accelerator key character (Far East versions only)
var | grbit | 2 | Option flags (shown LSB to MSB): fNo3d:1 = 1 if 3-D shading is turned off fBoxOnly:1 = 1 if only the box is drawn Reserved:14 Reserved; must be 0 (zero)

The grbit field at byte 58 contains the option flags listed in the following table.

Offset | Bits | Mask | Name | Contents
0 | 7-0 | FFh | (Reserved) | Reserved; must be 0 (zero)
1 | 0 | 01h | (Unused) |
 | 1 | 02h | fLockText | = 1 if the Lock Text option is turned on (Format Object dialog box, Protection tab)
 | 2 | 04h | fFuzzy | = 1 if the object is selected (the broken border is displayed)
 | 7-3 | F8h | (Reserved) | Reserved; must be 0 (zero)

Dialog Frame Object Fields

Offset | Name | Size | Contents
38 | icvBack | 1 | Index to the color palette for background color (fixed for dialog frame objects)
39 | icvFore | 1 | Index to the color palette for foreground color (fixed for dialog frame objects)
40 | fls | 1 | Fill pattern (ignored for dialog frame objects)
41 | grbit | 1 | Option flags (ignored for dialog frame objects)
42 | icv | 1 | Index to the color palette for line color (fixed for dialog frame objects)
43 | lns | 1 | Line style (ignored for dialog frame objects)
44 | lnw | 1 | Line weight (ignored for dialog frame objects)
45 | fAuto | 1 | Bit 0 = 1 for dialog frame objects
46 | frs | 2 | Frame style structure (ignored for dialog frame objects)
48 | cbText | 2 | Length of the object text
50 | (Reserved) | 8 | Reserved; must be 0 (zero)
58 | grbit | 2 | Option flags (see the following table)
60 | (Reserved) | 14 | Reserved; must be 0 (zero)
74 | cchName | 1 | Length of the name (null if no name)
75 | stName | var | Name (null if no name; may contain a padding byte to force word-boundary alignment)
var | fmla | var | FMLA structure (see FMLA Structure)
var | rgch | var | Object text; may contain a single padding byte at the end of the text for word-boundary alignment (cbText does not count this padding byte)
var | TXORUNS | 8 | TXORUNS structure (see text)
var | TXORUNS | 8 | TXORUNS structure (see text)

The grbit field at byte 58 contains the option flags listed in the following table.

Offset | Bits | Mask | Name | Contents
0 | 7-0 | FFh | (Reserved) | Reserved; must be 0 (zero)
1 | 0 | 01h | (Unused) |
 | 1 | 02h | fLockText | = 1 if the Lock Text option is turned on (Format Object dialog box, Protection tab)
 | 2 | 04h | fFuzzy | = 1 if an object is selected (the broken border is displayed)
 | 7-3 | F8h | (Reserved) | Reserved; must be 0 (zero)

The TXORUNS structure contains formatting information about the object text string, which is the dialog box caption. There are two TXORUNS structures in the dialog frame object record. The first has ichFirst = 00h, and it has ifnt pointing to the FONT record for the text. The second has ichFirst = cbText, and it contains no other useful information. The TXORUNS structure is shown in the following table.

Offset | Name | Size | Contents
0 | ichFirst | 2 | Index to the first character to which the formatting applies
2 | ifnt | 2 | Index to the FONT record
4 | (Reserved) | 4 |

Drop-Down Object Fields

Offset | Name | Size | Contents
38 | icvBack | 1 | Index to the color palette for background color (fixed for drop-down objects)
39 | icvFore | 1 | Index to the color palette for foreground color (fixed for drop-down objects)
40 | fls | 1 | Fill pattern (ignored for drop-down objects)
41 | grbit | 1 | Option flags (ignored for drop-down objects)
42 | icv | 1 | Index to the color palette for line color (fixed for drop-down objects)
43 | lns | 1 | Line style (ignored for drop-down objects)
44 | lnw | 1 | Line weight (ignored for drop-down objects)
45 | fAuto | 1 | Bit 0 = 1 for drop-down objects
46 | frs | 2 | Frame style structure (ignored for drop-down objects)
48 | (Reserved) | 4 | Reserved; must be 0 (zero)
52 | iVal | 2 | Scroll bar position
54 | iMin | 2 | Scroll bar minimum value
56 | iMax | 2 | Scroll bar maximum value
58 | dInc | 2 | Amount to scroll when an arrow is clicked
60 | dPage | 2 | Amount to scroll when the scroll bar is clicked
62 | fHoriz | 2 | = 1 if the scroll bar is horizontal
64 | dxScroll | 2 | Width of the scroll bar
66 | grbit | 2 | Option flags (shown LSB to MSB): (Reserved):3 Reserved; must be 0 (zero) fNo3d:1 = 1 if 3-D shading is turned off (Reserved):12 Reserved; must be 0 (zero)
68 | (Reserved) | 18 | Reserved; must be 0 (zero)
86 | ifnt | 2 | Index to the FONT record for list box
88 | (Reserved) | 14 | Reserved; must be 0 (zero)
102 | xLeft | 2 | X (horizontal) position of the upper-left corner of the drop-down object's bounding rectangle
104 | yTop | 2 | Y (vertical) position of the upper-left corner of the drop-down object's bounding rectangle
106 | xRight | 2 | X (horizontal) position of the lower-right corner of the drop-down object's bounding rectangle
108 | yBot | 2 | Y (vertical) position of the lower-right corner of the drop-down object's bounding rectangle
110 | (Reserved) | 4 | Reserved; must be 0 (zero)
114 | cchName | 1 | Length of the name (null if no name)
115 | stName | var | Name (null if no name; may contain a padding byte to force word-boundary alignment)
var | cbFmla1 | 2 | Length of the FMLA structure for the attached macro (never null)
var | fmla1 | var | FMLA structure for the attached macro (see FMLA Structure)
var | cbFmla2 | 2 | Length of the FMLA structure for the cell link (never null)
var | fmla2 | var | FMLA structure for the cell link (see FMLA Structure)
var | cbFmla3 | 2 | Length of the FMLA structure for the input range (never null)
var | fmla3 | var | FMLA structure for the input range (see FMLA Structure)
var | cLines | 2 | Number of elements in the list box (1-based)
var | iSel | 2 | Index of the selected item (1-based)
var | grbit | 2 | Option flags (shown LSB to MSB): f(reserved):2 Reserved; must be 0 (zero) fValidIds:1 = 1 if idEdit is valid fNo3d:1 = 1 if 3-D shading is turned off (Reserved):12 Reserved; must be 0 (zero)
var | (Reserved) | 2 | Reserved; must be 0 (zero)
var | grbit | 2 | Option flags (shown LSB to MSB): wStyle:2 Drop-down style: 0 = combo, 1 = combo edit, 2 = simple 3 = max (Reserved):14 Reserved; must be 0 (zero)
var | cLine | 2 | Maximum number of lines that the drop-down list box contains before a scroll bar is added
var | dxMin | 2 | Minimum allowable width of the drop-down list box
var | (Reserved) | 2 | Reserved; must be 0 (zero)

Edit Box Object Fields

Offset | Name | Size | Contents
38 | icvBack | 1 | Index to the color palette for background color (fixed for edit box objects)
39 | icvFore | 1 | Index to the color palette for foreground color (fixed for edit box objects)
40 | fls | 1 | Fill pattern (ignored for edit box objects)
41 | grbit | 1 | Option flags (ignored for edit box objects)
42 | icv | 1 | Index to the color palette for line color (fixed for edit box objects)
43 | lns | 1 | Line style (ignored for edit box objects)
44 | lnw | 1 | Line weight (ignored for edit box objects)
45 | fAuto | 1 | Bit 0 = 1 for edit box objects
46 | frs | 2 | Frame style structure (ignored for edit box objects)
48 | (Reserved) | 10 | Reserved; must be 0 (zero)
58 | grbit | 2 | Option flags (see the following table)
60 | (Reserved) | 14 | Reserved; must be 0 (zero)
74 | cchName | 1 | Length of the name (null if no name)
75 | stName | var | Name (null if no name; may contain a padding byte to force word-boundary alignment)
var | cbFmla | 2 | Length of the FMLA structure for the attached macro (never null)
var | fmla | var | FMLA structure for the attached macro (see FMLA Structure)
var | cbText | 2 | Length of the object text (never null)
var | rgch | var | Object text; may contain a single padding byte at the end of the text for word-boundary alignment (cbText does not count this padding byte)
var | ivtEdit | 2 | Edit validation: = 000, Text = 001, Integer = 010, Number = 011, Reference = 100, Formula
var | fMultiLine | 2 | = 1 if the edit is a multiline edit
var | fVScroll | 2 | = 1 if the edit box has a vertical scroll bar
var | idList | 2 | Object ID of the linked list box or linked drop-down, if the edit box is part of a combination list-edit box or combination drop-down edit box. If idList = 0, this is a simple edit box.

The grbit field at byte 58 contains the option flags listed in the following table.

Offset | Bits | Mask | Name | Contents
0 | 7-0 | FFh | (Reserved) | Reserved; must be 0 (zero)
1 | 0 | 01h | (Unused) |
 | 1 | 02h | fLockText | = 1 if the Lock Text option is turned on (Format Object dialog box, Protection tab)
 | 2 | 04h | fFuzzy | = 1 if the object is selected (the broken border is displayed)
 | 7-3 | F8h | (Reserved) | Reserved; must be 0 (zero)

Group Box Object Fields

Offset | Name | Size | Contents
38 | icvBack | 1 | Index to the color palette for background color (fixed for group box objects).
39 | icvFore | 1 | Index to the color palette for foreground color (fixed for group box objects).
40 | fls | 1 | Fill pattern (ignored for group box objects).
41 | grbit | 1 | Option flags (ignored for group box objects).
42 | icv | 1 | Index to the color palette for line color (fixed for group box objects).
43 | lns | 1 | Line style (ignored for group box objects).
44 | lnw | 1 | Line weight (ignored for group box objects).
45 | fAuto | 1 | Bit 0 = 1 for group box objects.
46 | frs | 2 | Frame style structure (ignored for group box objects).
48 | (reserved) | 10 | Reserved; must be 0 (zero).
58 | grbit | 2 | Option flags (see the following table).
60 | (reserved) | 26 | Reserved; must be 0 (zero).
86 | cchName | 1 | Length of the name (null if no name).
87 | stName | var | Name (null if no name; may contain a padding byte to force word-boundary alignment).
var | cbFmla | 2 | Length of the FMLA structure (never null).
var | fmla | var | FMLA structure (see FMLA Structure).
var | cbText | 2 | Length of object text (never null)
var | rgch | var | Object text; may contain a single padding byte at the end of the text for word-boundary alignment (cbText does not count this padding byte).
var | accel | 2 | Accelerator key character.
var | accel2 | 2 | Accelerator key character (Far East versions only).
var | grbit | 2 | Option flags (shown LSB to MSB): fNo3d:1 = 1 if 3-D shading is off (Reserved):15 Reserved; must be 0 (zero)

The grbit field at byte 58 contains the option flags listed in the following table.

Offset | Bits | Mask | Name | Contents
0 | 7-0 | FFh | (Reserved) | Reserved; must be 0 (zero)
1 | 0 | 01h | (Unused) |
 | 1 | 02h | fLockText | = 1 if the Lock Text option is on (Format Object dialog box, Protection tab)
 | 2 | 04h | fFuzzy | = 1 if the object is selected (the broken border is displayed)
 | 7-3 | F8h | (Reserved) | Reserved; must be 0 (zero)

Label Object Fields

Offset | Name | Size | Contents
38 | icvBack | 1 | Index to the color palette for background color (fixed for label objects).
39 | icvFore | 1 | Index to the color palette for foreground color (fixed for label objects).
40 | fls | 1 | Fill pattern (ignored for label objects).
41 | grbit | 1 | Option flags (ignored for label objects).
42 | icv | 1 | Index to the color palette for line color (fixed for label objects).
43 | lns | 1 | Line style (ignored for label objects).
44 | lnw | 1 | Line weight (ignored for label objects).
45 | fAuto | 1 | Bit 0 = 1 for label objects.
46 | frs | 2 | Frame style structure (ignored for label objects).
48 | cbText | 2 | Length of object text.
50 | (Reserved) | 8 | Reserved; must be 0 (zero).
58 | grbit | 2 | Option flags (see the following table).
60 | (Reserved) | 14 | Reserved; must be 0 (zero).
74 | cchName | 1 | Length of the name (null if no name).
75 | stName | var | Name (null if no name; may contain a padding byte to force word-boundary alignment).
var | fmla | var | FMLA structure (see FMLA Structure).
var | rgch | var | Object text; may contain a single padding byte at the end of the text for word-boundary alignment (cbText does not count this padding byte).
var | TXORUNS | 8 | TXORUNS structure (see text).
var | TXORUNS | 8 | TXORUNS structure (see text)

The grbit field at byte 58 contains the option flags listed in the following table.

Offset | Bits | Mask | Name | Contents
0 | 7-0 | FFh | (Reserved) | Reserved; must be 0 (zero)
1 | 0 | 01h | (Unused) |
 | 1 | 02h | fLockText | = 1 if the Lock Text option is on (Format Object dialog box, Protection tab)
 | 2 | 04h | fFuzzy | = 1 if object is selected (the broken border is displayed)
 | 7-3 | F8h | (Reserved) | Reserved; must be 0 (zero)

The TXORUNS structure contains formatting information about the object text string, which is the label string. There are two TXORUNS structures in the label object record. The first has ichFirst = 00h and has ifnt pointing to the FONT record for the label. The second has ichFirst = cbText and contains no other useful information. The TXORUNS structure is shown in the following table.

Offset | Name | Size | Contents
0 | ichFirst | 2 | Index to the first character to which the formatting applies
2 | ifnt | 2 | Index to the FONT record
4 | (Reserved) | 4 |

List Box Object Fields

Offset | Name | Size | Contents
38 | icvBack | 1 | Index to the color palette for background color (fixed for list box objects).
39 | icvFore | 1 | Index to the color palette for foreground color (fixed for list box objects).
40 | fls | 1 | Fill pattern (ignored for list box objects).
41 | grbit | 1 | Option flags (ignored for list box objects).
42 | icv | 1 | Index to the color palette for line color (fixed for list box objects).
43 | lns | 1 | Line style (ignored for list box objects).
44 | lnw | 1 | Line weight (ignored for list box objects).
45 | fAuto | 1 | Bit 0 = 1 for list box objects.
46 | frs | 2 | Frame style structure (ignored for list box objects).
48 | (Reserved) | 4 | Reserved; must be 0 (zero).
52 | iVal | 2 | Scroll bar position.
54 | iMin | 2 | Scroll bar minimum value.
56 | iMax | 2 | Scroll bar maximum value.
58 | dInc | 2 | Amount to scroll when the arrow is clicked.
60 | dPage | 2 | Amount to scroll when the scroll bar is clicked.
62 | fHoriz | 2 | = 1 if the scroll bar is horizontal.
64 | dxScroll | 2 | Width of the scroll bar.
66 | grbit | 2 | Option flags (shown LSB to MSB): (Reserved):3 Reserved; must be 0 (zero). fNo3d:1 = 1 if 3-D shading is off. (Reserved):12 Reserved; must be 0 (zero).
68 | (Reserved) | 18 | Reserved; must be 0 (zero).
86 | ifnt | 2 | Index to the FONT record for the list box.
88 | (Reserved) | 4 | Reserved; must be 0 (zero).
92 | cchName | 1 | Length of the name (null if no name).
93 | stName | var | Name (null if no name; may contain a padding byte to force word-boundary alignment).
var | cbFmla1 | 2 | Length of the FMLA structure for the attached macro (never null).
var | fmla1 | var | FMLA structure for the attached macro (see FMLA Structure).
var | cbFmla2 | 2 | Length of the FMLA structure for the cell link (never null).
var | fmla2 | var | FMLA structure for cell link (see FMLA Structure).
var | cbFmla3 | 2 | Length of the FMLA structure for input range (never null).
var | fmla3 | var | FMLA structure for input range (see FMLA Structure).
var | cLines | 2 | Number of elements in the list box (1-based).
var | iSel | 2 | Index of the selected item (1-based).
var | grbit | 2 | Option flags (shown LSB to MSB): f(reserved):2 Reserved; must be 0 (zero). fValidIds:1 = 1 if idEdit is valid. fNo3d:1 = 1 if 3-D shading is off. wListSelType:2 List box selection type: 0 = standard. 1 = multi-select. 2 = extended-select (Reserved):10 Reserved; must be 0 (zero).
var | idEdit | 2 | Object ID of the linked edit box, if the list box is part of a combination list-edit box. If idList = 0, this is a simple list box.
var | rgbSel | var | Array of bytes, indicating which items are selected in a multi-select or extended-select list box. The number of elements in the array is equal to cLines. If an item is selected in the list box, the corresponding element in the array = 1.

Option Button Object Fields

Offset | Name | Size | Contents
38 | icvBack | 1 | Index to the color palette for background color (fixed for option button objects).
39 | icvFore | 1 | Index to the color palette for foreground color (fixed for option button objects).
40 | fls | 1 | Fill pattern (ignored for option button objects).
41 | fAuto | 1 | (Ignored for option button objects).
42 | icv | 1 | Index to the color palette for line color (fixed for option button objects).
43 | lns | 1 | Line style (ignored for option button objects).
44 | lnw | 1 | Line weight (ignored for option button objects).
45 | fAuto | 1 | (Ignored for option button objects).
46 | frs | 2 | Frame style structure (ignored for option button objects).
48 | (Reserved) | 10 | Reserved; must be 0 (zero).
58 | grbit | 2 | Option flags (see the following table).
60 | (Reserved) | 32 | Reserved; must be 0 (zero).
92 | cchName | 1 | Length of the name (null if no name).
93 | stName | var | Name (null if no name; may contain a padding byte to force word-boundary alignment).
var | cbFmla1 | 2 | Length of the FMLA structure for the attached macro (never null).
var | fmla1 | var | FMLA structure for the attached macro (see FMLA Structure).
var | cbFmla2 | 2 | Length of FMLA structure for the cell link (never null).
var | fmla2 | var | FMLA structure for the cell link (see FMLA Structure).
var | cbText | 2 | Length of the object text (never null).
var | rgch | var | Object text; may contain a single padding byte at the end of the text for word-boundary alignment (cbText does not count this padding byte).
var | fChecked | 2 | = 0 if the option button is not checked. = 1 if the option button is checked.
var | accel | 2 | Accelerator key character.
var | accel2 | 2 | Accelerator key character (Far East versions only).
var | grbit | 2 | Option flags (shown LSB to MSB): fNo3d:1 = 1 if 3-D shading is off. fBoxOnly:1 = 1 if only the box is drawn. Reserved:14 Reserved; must be 0 (zero).
var | idRadNext | 2 | Object ID of the next option button in the group.
var | fFirstBtn | 2 | = 1 if this option button is the first in the group.

The grbit field at byte 58 contains the option flags listed in the following table.

Offset | Bits | Mask | Name | Contents
0 | 7-0 | FFh | (Reserved) | Reserved; must be 0 (zero)
1 | 0 | 01h | (Unused) |
 | 1 | 02h | fLockText | = 1 if the Lock Text option is on (Format Object dialog box, Protection tab).
 | 2 | 04h | fFuzzy | = 1 if the object is selected (the broken border is displayed).
 | 7-3 | F8h | (Reserved) | Reserved; must be 0 (zero).

Scroll Bar Object Fields

Offset | Name | Size | Contents
38 | icvBack | 1 | Index to the color palette for background color (fixed for scroll bar objects).
39 | icvFore | 1 | Index to the color palette for foreground color (fixed for scroll bar objects).
40 | fls | 1 | Fill pattern (ignored for scroll bar objects).
41 | grbit | 1 | Option flags (ignored for scroll bar objects).
42 | icv | 1 | Index to the color palette for line color (fixed for scroll bar objects).
43 | lns | 1 | Line style (ignored for scroll bar objects).
44 | lnw | 1 | Line weight (ignored for scroll bar objects).
45 | fAuto | 1 | Bit 0 = 1 for scroll bar objects.
46 | frs | 2 | Frame style structure (ignored for scroll bar objects).
48 | (Reserved) | 4 | Reserved; must be 0 (zero).
52 | iVal | 2 | Scroll bar position.
54 | iMin | 2 | Scroll bar minimum value.
56 | iMax | 2 | Scroll bar maximum value.
58 | dInc | 2 | Amount to scroll when the arrow is clicked.
60 | dPage | 2 | Amount to scroll when the scroll bar is clicked.
62 | fHoriz | 2 | = 1 if the scroll bar is horizontal.
64 | dxScroll | 2 | Width of the scroll bar.
66 | grbit | 2 | Option flags (shown LSB to MSB): (Reserved):3 Reserved; must be 0 (zero). fNo3d:1 = 1 if 3-D shading is off. (Reserved):12 Reserved; must be 0 (zero).
68 | cchName | 1 | Length of the name (null if no name).
69 | stName | var | Name (null if no name; may contain a padding byte to force word-boundary alignment).
var | cbFmla1 | 2 | Length of the FMLA structure for the attached macro (never null).
var | fmla1 | var | FMLA structure for the attached macro (see FMLA Structure).
var | cbFmla2 | 2 | Length of the FMLA structure for the cell link (never null).
var | fmla2 | var | FMLA structure for the cell link (see FMLA Structure).

Spinner Object Fields

Offset | Name | Size | Contents
38 | icvBack | 1 | Index to the color palette for background color (fixed for spinner objects).
39 | icvFore | 1 | Index to the color palette for foreground color (fixed for spinner objects).
40 | fls | 1 | Fill pattern (ignored for spinner objects).
41 | grbit | 1 | Option flags (ignored for spinner objects).
42 | icv | 1 | Index to the color palette for line color (fixed for spinner objects).
43 | lns | 1 | Line style (ignored for spinner objects).
44 | lnw | 1 | Line weight (ignored for spinner objects).
45 | fAuto | 1 | Bit 0 = 1 for spinner objects.
46 | frs | 2 | Frame style structure (ignored for spinner objects).
48 | (Reserved) | 4 | Reserved; must be 0 (zero).
52 | iVal | 2 | Spinner position.
54 | iMin | 2 | Spinner minimum value.
56 | iMax | 2 | Spinner maximum value.
58 | dInc | 2 | Amount to scroll when the spinner is clicked.
60 | (Reserved) | 2 | Reserved; must be 0 (zero).
62 | fHoriz | 2 | = 1 if the spinner is horizontal.
64 | dxScroll | 2 | Width of the spinner.
66 | grbit | 2 | Option flags (shown LSB to MSB): (Reserved):3 Reserved; must be 0 (zero). fNo3d:1 = 1 if 3-D shading is off. (Reserved):12 Reserved; must be 0 (zero).
68 | cchName | 1 | Length of the name (null if no name).
69 | stName | var | Name (null if no name; may contain a padding byte to force word-boundary alignment).
var | cbFmla1 | 2 | Length of the FMLA structure for the attached macro (never null).
var | fmla1 | var | FMLA structure for the attached macro (see FMLA Structure).
var | cbFmla2 | 2 | Length of the FMLA structure for the cell link (never null).
var | fmla2 | var | FMLA structure for the cell link (see FMLA Structure).

OBJPROTECT: Objects Are Protected (63h)

The OBJPROTECT record stores an option from the Protection command.

Record Data

Offset | Name | Size | Contents
4 | fLockObj | 2 | = 1 if objects are protected

OBPROJ: Visual Basic Project (D3h)

The contents of this record are reserved.

Record Data

Offset | Name | Size | Contents
4 | (Reserved) | var |

OLESIZE: Size of OLE Object (DEh)

This record stores the size of an embedded OLE object (when Microsoft Excel is a server).

Record Data

Offset | Name | Size | Contents
4 | (Reserved) | 2 |
6 | rwFirst | 2 | First row
8 | rwLast | 2 | Last row
10 | colFirst | 1 | First column
11 | colLast | 1 | Last column

PALETTE: Color Palette Definition (92h)

The PALETTE record describes the colors selected in the Options dialog box, Color tab. Each rgch field contains 4 bytes: rgbRed, rgbGreen, rgbBlue, and an unused byte. The 3 color bytes correspond to the Red, Green, and Blue values in the Color Picker dialog box, and the unused byte is don't-care. The Color Picker dialog box appears when you click the Modify button on the Color tab. If the worksheet uses the default palette, the BIFF file does not contain the PALETTE record.

Record Data

Offset | Name | Size | Contents
4 | ccv | 2 | Count of color values that follow
6 | rgch | 4 | Color value of the first color in the palette
10 | rgch | 4 | Color value of the second color in the palette
14 | rgch | 4 | Color value of the third color in the palette
... | ... | ... | ...
var | rgch | 4 | Color value of the last color (= ccv) in the palette

PANE: Number of Panes and Their Position (41h)

The PANE record describes the number and position of unfrozen panes in a window.

Record Data

Offset | Name | Size | Contents
4 | x | 2 | Horizontal position of the split; 0 (zero) if none
6 | y | 2 | Vertical position of the split; 0 (zero) if none
8 | rwTop | 2 | Top row visible in the bottom pane
10 | colLeft | 2 | Leftmost column visible in the right pane
12 | pnnAct | 2 | Pane number of the active pane

The x and y fields contain the position of the vertical and horizontal splits, respectively, in units of 1/20 of a point. Either of these fields can be 0 (zero), indicating that the window is not split in the corresponding direction.

For a window with a horizontal split, the rwTop field is the topmost row visible in the bottom pane or panes. For a window with a vertical split, the colLeft field contains the leftmost column visible in the right pane or panes.

The pnnAct field indicates which pane is the active pane. The pnnAct field contains one of the following values:

0 = lower-right
1 = upper-right
2 = lower-left
3 = upper-left

If the window has frozen panes, as specified in the WINDOW2 record, x and y have special meaning. If there is a vertical split, x contains the number of columns visible in the top pane. If there is a horizontal split, y contains the number of rows visible in the left pane. Both types of splits can be present in a window, as in unfrozen panes.

PASSWORD: Protection Password (13h)

The PASSWORD record contains the encrypted password for a protected sheet or workbook. Note that this record specifies a sheet-level or workbook-level protection password, as opposed to the FILEPASS record, which specifies a file password.

Record Data

Offset | Name | Size | Contents
4 | wPassword | 2 | Encrypted password

PLS: Environment-Specific Print Record (4Dh)

The PLS record saves printer settings and printer driver information.

Record Data, Macintosh

Offset | Name | Size | Contents
4 | wEnv | 2 | Operating environment: 0 = Microsoft Windows. 1 = Apple Macintosh.
6 | rgb | var | TPrint structure (for more information about this structure, see Inside Macintosh, Volume II, page 149).

Record Data, Windows

Offset | Name | Size | Contents
4 | wEnv | 2 | Operating environment: 0 = Microsoft Windows. 1 = Apple Macintosh.
6 | rgb | var | DEVMODE structure (for more information about this structure, see the documentation for the Microsoft Windows Software Development Kit).

PRECISION: Precision (0Eh)

The PRECISION record stores the Precision As Displayed option from the Options dialog box, Calculation tab.

Record Data

Offset | Name | Size | Contents
4 | fFullPrec | 2 | = 0 if Precision As Displayed option is selected

PRINTGRIDLINES: Print Gridlines Flag (2Bh)

This record stores the Gridlines option from the Page Setup dialog box, Sheet tab.

Record Data

Offset | Name | Size | Contents
4 | fPrintGrid | 2 | = 1 to print gridlines

PRINTHEADERS: Print Row/Column Labels (2Ah)

The PRINT HEADERS record stores the Row And Column Headings option from the Page Setup dialog box, Sheet tab.

Record Data

Offset | Name | Size | Contents
4 | fPrintRwCol | 2 | = 1 to print row and column headings

PROTECT: Protection Flag (12h)

The PROTECT record stores the protection state for a sheet or workbook.

Record Data

Offset | Name | Size | Contents
4 | fLock | 2 | = 1 if the sheet or workbook is protected

PUB: Publisher (89h)

The PUB record contains information about the publisher/subscriber feature. This record can be created only by Microsoft Excel for the Macintosh. However, if Microsoft Excel for any other operating environment encounters the PUB record in a BIFF file, it leaves the record in the file, unchanged, when the file is saved.

Record Data

Offset | Name | Size | Contents
4 | grbit | 2 | Option flags
6 | ref | 6 | Reference structure describing the published area on the worksheet
12 | sec | 36 | Section record associated with the published area
48 | rgbAlias | var | Contents of the alias pointed to by the section record

The grbit field contains the option flags listed in the following table.

Offset | Bits | Mask | Name | Contents
0 | 0 | 01h | fAprPrinted | = 1 if the published appearance is shown when printed
 | 1 | 02h | fSizPrinted | = 1 if the published size is shown when printed
 | 7–2 | FCh | (Unused) |
1 | 7–0 | FFh | (Unused) |

RECIPNAME: Recipient Name (B9h)

This record stores recipient information about a routing slip. The rgch field contains the concatenation of two null-terminated strings: Recipient's Friendly Name, and Recipient's System-Specific Address.

Record Data

Offset | Name | Size | Contents
4 | cchRecip | 2 | Length of the recipient's friendly name string
6 | ulEIDSize | 4 | Length of the recipient's system-specific address string
10 | rgchRecip | var | (See the text)

REFMODE: Reference Mode (0Fh)

The REFMODE record stores the Reference Style option from the Options dialog box, General tab.

Record Data

Offset | Name | Size | Contents
4 | fRefA1 | 2 | Reference mode: = 1 for A1 mode = 0 for R1C1 mode

RIGHTMARGIN: Right Margin Measurement (27h)

The RIGHT MARGIN record specifies the right margin in inches. The num field is in 8-byte IEEE floating-point format.

Record Data

Offset | Name | Size | Contents
4 | num | 8 | Right margin

RK: Cell Value, RK Number (7Eh)

Microsoft Excel uses an internal number type, called an RK number, to save memory and disk space.

Record Data

Offset | Name | Size | Contents
4 | rw | 2 | Row number
6 | col | 2 | Column number
8 | ixfe | 2 | Index to the XF record that contains the cell format
10 | rk | 4 | RK number (see the following description)

An RK number is either a 30-bit integer or the most significant 30 bits of an IEEE number. The two LSBs of the 32-bit rk field are always reserved for RK type encoding; this is why the RK numbers are 30 bits, not the full 32. See the following diagram.

There are four different RK number types, as described in the following table.

RK type | Encode priority | Number (decimal) | RK number (hex) | Description of 30-bit encoding
0 | 1 | 1 | 3F F0 00 00 | IEEE number
1 | 3 | 1.23 | 40 5E C0 01 | IEEE number x 100
2 | 2 | 12345678 | 02 F1 85 3A | Integer
3 | 4 | 123456.78 | 02 F1 85 3B | Integer x 100

Microsoft Excel always attempts to store a number as an RK number instead of an IEEE number. There is also a specific priority of RK number encoding that the program uses. The following flowchart is a simplified version of the encoding algorithm. The algorithm always begins with an IEEE (full 64-bit) number.

\doc\art\pg31.bmp

You can use the following C code to demonstrate how to decode RK numbers:

Microsoft QuickC™

double NumFromRk(long rk)
    {
    double num;
    if(rk & 0x02)
        {
        // int
        num = (double) (rk >> 2);
        }
    else
        {
        // hi words of IEEE num
        *((long *)&num+1) = rk & 0xfffffffc;
        *((long *)&num) = 0;
        }
    if(rk & 0x01)
        // divide by 100
        num /= 100;
    return num;
    }
main()
    {
    printf("%f\n", NumFromRk (0x02f1853b));
    }

THINK C

short double NumFromRk(long int rk)
    {
    short double num;
    if(rk & 0x02)
        {
        /* int */
        num = (short double) (rk >> 2);
        }
    else
        {
        /* hi words of IEEE num */
        *((long int *)&num + 1) = 0;
        *((long int *)&num) = rk & 0xfffffffc;
        }
    if(rk & 0x01)
        /* divide by 100 */
        num /= 100;
    return num;
    }
main()
    {
    printf("%f\n", NumFromRk (0x02f1853b));
    }

If you write a NUMBER record to a BIFF file, Microsoft Excel may convert the number to an RK number when it reads the file.

ROW: Describes a Row (208h)

A ROW record describes a single row on a Microsoft Excel sheet. ROW records and their associated cell records occur in blocks of up to 32 rows. Each block ends with a DBCELL record. For more information about row blocks and about optimizing your code when searching for cell records, see Finding Cell Records in BIFF Files.

Record Data

Offset | Name | Size | Contents
4 | rw | 2 | Row number.
6 | colMic | 2 | First defined column in the row.
8 | colMac | 2 | Last defined column in the row, plus 1.
10 | miyRw | 2 | Row height.
12 | irwMac | 2 | Used by Microsoft Excel to optimize loading the file; if you are creating a BIFF file, set irwMac to 0.
14 | (Reserved) | 2 |
16 | grbit | 2 | Option flags.
18 | ixfe | 2 | If fGhostDirty = 1 (see grbit field), this is the index to the XF record for the row. Otherwise, this field is undefined. Note: ixfe uses only the low-order 12 bits of the field (bits 11–0). Bit 12 is fExAsc, bit 13 is fExDsc, and bits 14 and 15 are reserved. fExAsc and fExDsc are set to true if the row has extra space above or below, respectively.

The grbit field contains the option flags listed in the following table.

Offset | Bits | Mask | Name | Contents
0 | 2–0 | 07h | iOutLevel | Index to the outline level of the row
 | 3 | 08h | (Reserved) |
 | 4 | 10h | fCollapsed | = 1 if the row is collapsed in outlining
 | 5 | 20h | fDyZero | = 1 if the row height is set to 0 (zero)
0 | 6 | 40h | fUnsynced | = 1 if the font height and row height are not compatible
 | 7 | 80h | fGhostDirty | = 1 if the row has been formatted, even if it contains all blank cells
1 | 7–0 | FFh | (Reserved) |

The rw field contains the 0-based row number. The colMic and colMac fields give the range of defined columns in the row.

The miyRw field contains the row height, in units of 1/20 of a point. The miyRw field may have the 8000h (215) bit set, indicating that the row is standard height. The low-order 15 bits must still contain the row height. If you hide the row — either by setting row height to 0 (zero) or by using the Hide command — miyRw still contains the original row height. This allows Microsoft Excel to restore the original row height when you click the Unhide button.

Each row can have default cell attributes that control the format of all undefined cells in the row. By specifying default cell attributes for a particular row, you are effectively formatting all the undefined cells in the row without using memory for those cells. Default cell attributes do not affect the formats of cells that are explicitly defined.

For example, if you want all of row 3 to be left-aligned, you could define all 256 cells in the row and specify that each individual cell be left-aligned. This would require storage for each of the 256 cells. An easy alternative would be to set the default cell for row 3 to be left-aligned and not define any individual cells in row 3.

RSTRING: Cell with Character Formatting (D6h)

When part of a string in a cell has character formatting, an RSTRING record is written instead of the LABEL record.

Record Data

Offset | Name | Size | Contents
4 | rw | 2 | Row
6 | col | 2 | Column
8 | ixfe | 2 | Index to the XF record
10 | cch | 2 | Length of the string
12 | rgch | var | String
var | cruns | 1 | Count of STRUN structures
var | rgstrun | var | Array of STRUN structures

The STRUN structure contains formatting information about the string. A STRUN structure occurs every time the text formatting changes. The STRUN structure is described in the following table.

Offset | Name | Size | Contents
0 | ich | 1 | Index to the first character to which the formatting applies
1 | ifnt | 1 | Index to the FONT record

SAVERECALC: Recalculate Before Save (5Fh)

If the Recalculate Before Save option is selected in the Options dialog box, Calculation tab, then fSaveRecalc = 1.

Record Data

Offset | Name | Size | Contents
4 | fSaveRecalc | 2 | = 1 to recalculate before saving

SCENARIO: Scenario Data (AFh)

This record stores information about an individual scenario.

Record Data

Offset | Name | Size | Contents
4 | cref | 2 | Number of changing cells
6 | fLocked | 1 | = 1 if the scenario is locked for changes
7 | fHidden | 1 | = 1 if the scenario is hidden
8 | cchName | 1 | Length of the name
9 | cchComment | 1 | Length of the comment
10 | cchNameUser | 1 | Length of the user name
11 | rgch | var | Concatenation of the scenario name string, the user name string (preceded by a duplicate of cchNameUser), and the comment string (preceded by a duplicate of cchComment)
var | rgRef | var | Array of cell references that contains changing cells (see text)
var | rgst | var | Array of byte-counted strings that contains changing cell values (see text)
var | rgIfmt | var | Array of ifmt integers (see text)

The changing cells for the scenario are stored in the three arrays at the end of the record. The rgRef array contains the cell addresses, as shown in the following table.

Offset | Name | Size | Contents
0 | rw | 2 | Row number (0-based)
2 | col | 2 | Column number (0-based)

The cell values are always stored as an array of byte-counted strings, as shown in the following table.

Offset | Name | Size | Contents
0 | cch | 1 | Length of the string
1 | rgch | var | String

Finally, the cell number format indexes (ifmt) are stored as an array of 2-byte integers, following the array of cell value strings. These are stored only when the scenario contains cells with date/time number formats. If the cells contain any other number format, the rgIfmt will contain 0's (zeros).

SCENMAN: Scenario Output Data (AEh)

This records stores the general information about the set of scenarios on a worksheet.

Record Data

Offset | Name | Size | Contents
4 | csct | 2 | Number of scenarios
6 | isctCur | 2 | Index of the current scenario
8 | isctShown | 2 | Index of the last displayed scenario
10 | irefRslt | 2 | Number of reference areas in the following scenario result array
12 | rgref | var | Scenario result array (see the following table)

Each reference area in the scenario result array contains the fields listed in the following table.

Offset | Name | Size | Contents
0 | rwFirst | 2 | First row
2 | rwLast | 2 | Last row
4 | colFirst | 1 | First column
5 | colLast | 1 | Last column

SCENPROTECT: Scenario Protection (DDh)

This record stores the scenario protection flag.

Record Data

Offset | Name | Size | Contents
4 | fScenProtect | 2 | = 1 if scenarios are protected

SCL: Window Zoom Magnification (A0h)

This record stores the window zoom magnification.

Record Data

Offset | Name | Size | Contents
4 | nscl | 2 | Numerator of a reduced fraction
6 | dscl | 2 | Denominator of a reduced fraction

The magnification is stored as a reduced fraction. For example, if the magnification is 75%, nscl = 03h and dscl = 04h (3/4 = 0.75 = 75%). If the magnification is 11%, nscl = 0Bh (11 decimal) and dscl = 64h (100 decimal). If the BIFF file does not contain the SCL record, the magnification is 100%.

SELECTION: Current Selection (1Dh)

The SELECTION record stores the selection.

Record Data

Offset | Name | Size | Contents
4 | pnn | 1 | Number of the pane described
5 | rwAct | 2 | Row number of the active cell
7 | colAct | 2 | Column number of the active cell
9 | irefAct | 2 | Ref number of the active cell
11 | cref | 2 | Number of refs in the selection
13 | rgref | var | Array of refs

The pnn field indicates which pane is described. It contains one of the following values:

0 = lower-right
1 = upper-right
2 = lower-left
3 = upper-left

For a window that has no splits, the pnn field = 3.

The rwAct and colAct fields specify the active cell.

The irefAct field is a 0-based index into the array of ref structures (refs), specifying which ref contains the active cell. The rgref is an array because it is possible to create a multiple selection. In the case of a multiple selection, each selection is described by a ref, including the active cell (even if it is included in one of the other selections).

The selection (of cells) is described by the rgref array. The number of refs in the rgref field is equal to cref. Each ref in the array is 6 bytes long and contains the fields listed in the following table.

Offset | Name | Size | Contents
0 | rwFirst | 2 | First row in the reference
2 | rwLast | 2 | Last row in the reference
4 | colFirst | 1 | First column in the reference
5 | colLast | 1 | Last column in the reference

If a selection is so large that it exceeds the maximum BIFF record size, it is broken down into multiple consecutive SELECTION records. Each record contains a portion of the larger selection. Only the cref and rgref fields vary in the multiple records; the pnn, rwAct, colAct, and irefAct fields are the same across all records in the group.

SETUP: Page Setup (A1h)

The SETUP record stores options and measurements from the Page Setup dialog box.

Record Data

Offset | Name | Size | Contents
4 | iPaperSize | 2 | Paper size (see fNoPls in the following table)
6 | iScale | 2 | Scaling factor (see fNoPls in the following table)
8 | iPageStart | 2 | Starting page number
10 | iFitWidth | 2 | Fit to width; number of pages
12 | iFitHeight | 2 | Fit to height; number of pages
14 | grbit | 2 | Option flags (see the following table)
16 | iRes | 2 | Print resolution (see fNoPls in the following table)
18 | iVRes | 2 | Vertical print resolution (see fNoPls in the following table)
20 | numHdr | 8 | Header margin (IEEE number)
28 | numFtr | 8 | Footer margin (IEEE number)
36 | iCopies | 2 | Number of copies (see fNoPls in the following table)

The grbit field contains the option flags listed in the following table.

Offset | Bits | Mask | Name | Contents
0 | 0 | 01h | fLeftToRight | Print over, then down.
 | 1 | 02h | fLandscape | = 0, Landscape mode = 1, Portrait mode (see fNoPls below).
 | 2 | 04h | fNoPls | = 1, then the iPaperSize, iScale, iRes, iVRes, iCopies, and fLandscape data have not been obtained from the printer, so they are not valid.
 | 3 | 08h | fNoColor | = 1, print black and white.
 | 4 | 10h | fDraft | = 1, print draft quality.
 | 5 | 20h | fNotes | = 1, print notes.
 | 6 | 40h | fNoOrient | = 1, orientation not set.
 | 7 | 80h | fUsePage | = 1, use custom starting page number instead of Auto.
1 | 7–0 | FFh | (Unused) |

SHRFMLA: Shared Formula (BCh)

The SHRFMLA record is a file size optimization. It is used with the FORMULA record to compress the amount of storage required for the parsed expression (rgce). In earlier versions of Microsoft Excel, if you read an FORMULA record in which the rgce field contained a ptgExp parse token, the FORMULA record contained an array formula. In Microsoft Excel version 5.0, this could indicate either an array formula or a shared formula.

If the record following the FORMULA is an ARRAY record, the FORMULA record contains an array formula. If the record following the FORMULA is a SHRFMLA record, the FORMULA record contains a shared formula. You can also test the fShrFmla bit in the FORMULA record's grbit field to determine this.

When reading a file, you must convert the FORMULA and SHRFMLA records to an equivalent FORMULA record if you plan to use the parsed expression. To do this, take all of the FORMULA record up to (but not including) the cce field, and then append to that the SHRFMLA record from its cce field to the end. You must then convert some ptgs; this is explained later in this article.

Following the SHRFMLA record will be one or more FORMULA records containing ptgExp tokens that have the same rwFirst and colFirst fields as those in the ptgExp in the first FORMULA. There is only one SHRFMLA record for each shared-formula record group.

To convert the ptgs, search the rgce field from the SHRFMLA record for any ptgRefN, ptgRefNV, ptgRefNA, ptgAreaN, ptgAreaNV, or ptgAreaNA tokens. Add the corresponding FORMULA record's rw and col fields to the rwFirst and colFirst fields in the ptgs from the SHRFMLA. Finally, convert the ptgs as shown in the following table.

Convert this ptg | To this ptg
ptgRefN | ptgRef
ptgRefNV | ptgRefV
ptgRefNA | ptgRefA
ptgAreaN | ptgArea
ptgAreaNV | ptgAreaV
ptgAreaNA | ptgAreaA

For more information about ptgs and parsed expressions, see Microsoft Excel Formulas.

Remember that STRING records can appear after FORMULA records if the formula evaluates to a string.

If your code writes a BIFF file, always write standard FORMULA records; do not attempt to use the SHRFMLA optimization.

Record Data

Offset | Name | Size | Contents
4 | rwFirst | 2 | First row
6 | rwLast | 2 | Last row
8 | colFirst | 1 | First column
9 | colLast | 1 | Last column
10 | (Reserved) | 2 |
12 | cce | 2 | Length of the parsed expression
14 | rgce | var | Parsed expression

SORT: Sorting Options (90h)

This record stores options from the Sort and Sort Options dialog boxes.

Record Data

Offset | Name | Size | Contents
4 | grbit | 2 | Option flags
6 | cchKey1 | 1 | Length of the string for sort key 1
7 | cchKey2 | 1 | Length of the string for sort key 2
8 | cchKey3 | 1 | Length of the string for sort key 3
9 | rgchKey1 | var | String for sort key 1
var | rgchKey2 | var | String for sort key 2
var | rgchKey3 | var | String for sort key 3

The grbit field contains the option flags listed in the following table.

Offset | Bits | Mask | Name | Contents
0 | 0 | 0001h | fCol | = 1 if the Sort Left To Right option is on.
 | 1 | 0002h | fKey1Dsc | = 1 if key 1 sorts in descending order.
 | 2 | 0004h | fKey2Dsc | = 1 if key 2 sorts in descending order.
 | 3 | 0008h | fKey3Dsc | = 1 if key 3 sorts in descending order.
 | 4 | 0010h | fCaseSensitive | = 1 if the sort is case-sensitive.
 | 9–5 | 03E0h | iOrder | Index to the table in the First Key Sort Order option. The Normal sort order corresponds to iOrder = 0.
 | 10 | 0400h | fAltMethod | Used only in Far East versions of Microsoft Excel.
 | 15-11 | F800h | (Reserved) |

SOUND: Sound Note (96h)

The SOUND record contains the complete description of a sound note.

Record Data

Offset | Name | Size | Contents
4 | cf | 2 | Clipboard format; 4257h (16983 decimal) for sound notes
6 | env | 2 | Environment from which the file was written: = 1, Microsoft Windows = 2, Apple Macintosh
8 | lcb | 4 | Length of the sound data
12 | data | var | Sound data

STANDARDWIDTH: Standard Column Width (99h)

The STANDARDWIDTH record records the measurement from the Standard Width dialog box.

Record Data

Offset | Name | Size | Contents
4 | DxGCol | 2 | Standard column width, in increments of 1/256 of a character width

STRING: String Value of a Formula (207h)

When a formula evaluates to a string, a STRING record occurs after the FORMULA record. If the formula is part of an array, the STRING record occurs after the ARRAY record.

Record Data

Offset | Name | Size | Contents
4 | cch | 2 | Length of the string
6 | rgch | var | String

STYLE: Style Information (293h)

Each style in a Microsoft Excel workbook, whether built-in or user-defined, requires a style record in the BIFF file. When Microsoft Excel saves the workbook, it writes the STYLE records in alphabetic order, which is the order in which the styles appear in the drop-down list box.

Record Data — Built-In Styles

Offset | Name | Size | Contents
4 | ixfe | 2 | Index to the style XF record. Note: ixfe uses only the low-order 12 bits of the field (bits 11–0). Bits 12, 13, and 14 are unused, and bit 15 (fBuiltIn) is 1 for built-in styles.
6 | istyBuiltIn | 1 | Built-in style numbers: = 00h Normal = 01h RowLevel_n = 02h ColLevel_n = 03h Comma = 04h Currency = 05h Percent = 06h Comma[0] = 07h Currency[0]
7 | iLevel | 1 | Level of the outline style RowLevel_n or ColLevel_n (see text).

Record Data — User-Defined Styles

Offset | Name | Size | Contents
4 | ixfe | 2 | Index to the style XF record. Note: ixfe uses only the low-order 12 bits of the field (bits 11–0). Bits 12, 13, and 14 are unused, and bit 15 (fBuiltIn) is 0 for user-defined styles.
6 | cch | 1 | Length of the style name.
7 | rgch | 1 | Style name.

The automatic outline styles — RowLevel_1 through RowLevel_7, and ColLevel_1 through ColLevel_7 — are stored by setting istyBuiltIn to 01h or 02h and then setting iLevel to the style level minus 1. If the style is not an automatic outline style, ignore this field.

SUB: Subscriber (91h)

The SUB record contains information about the publisher/subscriber feature. This record can be created only by Microsoft Excel for the Macintosh. However, if Microsoft Excel for any other platform encounters the SUB record in a BIFF file, it leaves the record in the file, unchanged, when the file is saved.

Record Data

Offset | Name | Size | Contents
4 | ref | 6 | Reference structure describing the subscribed area on the worksheet.
10 | drwReal | 2 | Actual number of rows in the subscribed area.
12 | dcolReal | 2 | Actual number of columns in the subscribed area.
14 | grbit | 2 | Option flags.
16 | cbAlias | 2 | Size of rgbAlias.
18 | sec | 36 | Section record associated with the subscribed area.
54 | rgbAlias | var | Contents of the alias pointed to by the section record.
xvar | stz | var | Null-terminated string containing the path of publisher. The first byte is a length byte, which does not count the terminating null byte.

The grbit field contains the option flags listed in the following table.

Offset | Bits | Mask | Name | Contents
0 | 0 | 01h | (Reserved) |
 | 1 | 02h | fObj | = 1 if subscribed in the object layer
 | 7–2 | FCh | (Reserved) |
1 | 7–0 | FFh | (Reserved) |

SXDI: Data Item (C5h)

This record contains information about the PivotTable data item.

Record Data

Offset | Name | Size | Contents
4 | isxvdData | 2 | Field that this data item is based on.
6 | iiftab | 2 | Index to the aggregation function: = 00h, Sum = 01h, Count = 02h, Average = 03h, Max = 04h, Min = 05h, Product = 06h, Count Nums = 07h, StdDev = 08h, StdDevp = 09h, Var = 0Ah, Varp
8 | df | 2 | Data display format: = 00h, Normal = 01h, Difference from = 02h, Percentage of = 03h, Percentage difference from = 04h, Running total in = 05h, Percentage of row = 06h, Percentage of column = 07h, Percentage of total = 08h, Index
10 | isxvd | 2 | Index to the SXVD record used by the data display format.
12 | isxvi | 2 | Index to the SXVI record used by the data display format.
14 | ifmt | 2 | Index to the format table for this item.
16 | cchName | 2 | Length of the name; if the name = FFFFh, rgch is null and the name in the PivotTable cache storage is used.
18 | rgch | var | Name.

SXEXT: External Source Information (DCh)

This record stores information about the SQL query string that retrieves external data for a PivotTable. The record is followed by SXSTRING records that contain the SQL strings and then by a SXSTRING record that contains the SQL server connection string.

Record Data

Offset | Name | Size | Contents
4 | id | 2 | Connection ID of the SQL server
6 | fError | 2 | = 1 if an error occurred during the last attempt to communicate with the server
8 | cstSQL | 2 | Number of SXSTRING records that follow

SXIDSTM: Stream ID (D5h)

This record is a header record for a group of SXVS, SXEXT, and SXSTRING records that describe the PivotTable streams in the SX DB storage (the PivotTable cache storage). The idstm field identifies the stream.

Record Data

Offset | Name | Size | Contents
4 | idstm | 2 | Stream ID

SXIVD: Row/Column Field IDs (B4h)

This record stores an array of field ID numbers (2-byte integers) for the row fields and column fields in a PivotTable. Two SXIVD records appear in the file: the first contains the array of row field IDs, and the second contains the array of column field IDs.

Record Data

Offset | Name | Size | Contents
4 | rgisxvd | var | Array of 2-byte integers; contains either row field IDs or column field IDs

SXLI: Line Item Array (B5h)

The SXLI record stores an array of variable-length SXLI structures, which describe the row and column items in a PivotTable. There are two SXLI records for each PivotTable: the first stores row items, and the second stores column items.

Record Data

Offset | Name | Size | Contents
4 | rgsxli | var | Array of SXLI structures

The SXLI structure has variable length but will always be at least 10 bytes long, with one element in the rgisxvi array (the index to the SXVI record for the item). The SXLI structure is shown in the following table.

Offset | Name | Size | Contents
0 | cSic | 2 | Count of items that are identical to the previous element in rgsxvi; for 0 <= i < cSic, rgisxvi[i] is the same as the previous line.
2 | itmtype | 2 | Item type: = 00h, Data = 01h, Default = 02h, SUM = 03h, COUNTA = 04h, COUNT = 05h, AVERAGE = 06h, MAX = 07h, MIN = 08h, PRODUCT = 09h, STDEV = 0Ah, STDEVP = 0Bh, VAR = 0Ch, VARP = 0Dh, Grand total
4 | isxviMac | 2 | Maximum index to the rgisxvi[i] array.
6 | grbit | 2 | Option flags; see the following table.
8 | rgisxvi | 2 | Array of indexes to SXVI records; the number of elements in the array is (isxviMac + 1).

The grbit field contains the flags listed in the following table.

Offset | Bits | Mask | Name | Contents
0 | 0 | 0001h | fMultiDataName | = 1, use the data field name for the subtotal (instead of using "Total").
 | 8–1 | 01F7h | iData | For a multi-data subtotal, iData is the index to the data field.
 | 9 | 0200h | fSbt | = 1, this item is a subtotal.
 | 10 | 0400h | fBlock | = 1, this item is a block total.
 | 11 | 0800h | fGrand | = 1, this item is a grand total.
 | 12 | 1000h | fMultiDataOnAxis | = 1, this axis contains multi-data.
 | 15–13 | E000h | (Reserved) | Reserved; must be 0 (zero).

SXPI: Page Item (B6h)

This record contains information about the PivotTable page item.

Record Data

Offset | Name | Size | Contents
4 | isxvi | 2 | Index to the SXVI record for the page item
6 | isxvd | 2 | Index to the SXVD record for the page item
8 | idObj | 2 | Object ID for the page item drop-down arrow

SXSTRING: String (CDh)

This record contains an SQL query string, an SQL server connection string, or a page item name from a multiple-consolidation PivotTable.

Record Data

Offset | Name | Size | Contents
4 | cch | 2 | Length of the string
6 | rgch | var | String

SXTBL: Multiple Consolidation Source Info (D0h)

This record stores information about multiple-consolidation PivotTable source data.

Record Data

Offset | Name | Size | Contents
4 | cdref | 2 | Count (1-based) of DCONREF or DCONNAME records that follow the SXTBL record
6 | csxtbpg | 2 | Count (1-based) of SXTBPG records that follow the DCONREF or DCONNAME records
8 | grbitPages | 2 | (See the following table)

The grbitPages field contains an encoded count of page fields, as shown in the following table.

Offset | Bits | Mask | Name | Contents
0 | 14–0 | 7FFFh | cPages | Count (1-based) of page fields
 | 15 | 8000h | fAutoPage | = 1 if the user selected the Create A Single Page Field For Me option in the PivotTable Wizard dialog box

SXTBPG: Page Item Indexes (D2h)

This record stores an array of page item indexes that represent the table references for a multiple-consolidation PivotTable.

Record Data

Offset | Name | Size | Contents
4 | rgiitem | var | Array of 2-byte indexes to page items (iitem)

SXTBRGIITM: Page Item Name Count (D1h)

This record stores the number of page item names in a multiple-consolidation PivotTable. The names are stored in SXSTRING records that follow the SXTBRGIITM.

Record Data

Offset | Name | Size | Contents
4 | cItems | 2 | Number of page item names (number of SXTBRGIITM records that follow)

SXVD: View Fields (B1h)

This record contains PivotTable view fields and other information.

Record Data

Offset | Name | Size | Contents
4 | sxaxis | 2 | Axis: = 0, no axis = 1, row = 2, column = 4, page = 8, data
6 | cSub | 2 | Number of subtotals attached.
8 | grbitSub | 2 | Item subtotal type (see the following table).
10 | cItm | 2 | Number of items.
12 | cchName | 2 | Length of the name; if the name = FFFFh, rgch is null and the name in the cache is used.
14 | rgch | var | Name.

The subtotal type (grbitSub) bits are defined as shown in the following table.

Name | Contents
bitFNone | 0000h
bitFDefault | 0001h
bitFSum | 0002h
bitFCounta | 0004h
bitFAverage | 0008h
bitFMax | 0010h
bitFMin | 0020h
bitFProduct | 0040h
bitFCount | 0080h
bitFStdev | 0100h
bitFStdevp | 0200h
bitFVar | 0400h
bitFVarp | 0800h

SXVI: View Item (B2h)

This record contains information about a PivotTable item.

Record Data

Offset | Name | Size | Contents
4 | itmtype | 2 | Item type: = FEh, Page = FFh, Null = 00h, Data = 01h, Default = 02h, SUM = 03h, COUNTA = 04h, COUNT = 05h, AVERAGE = 06h, MAX = 07h, MIN = 08h, PRODUCT = 09h, STDEV = 0Ah, STDEVP = 0Bh, VAR = 0Ch, VARP = 0Dh, Grand total
6 | grbit | 2 | Option flags
8 | iCache | 2 | Index to the PivotTable cache.
10 | cchName | 2 | Length of the name; if the name = FFFFh, rgch is null and the name in the cache is used.
12 | rgch | var | Name.

The grbit field contains the option flags listed in the following table.

Offset | Bits | Mask | Name | Contents
0 | 0 | 01h | fHidden | = 1 if the item is hidden
 | 1 | 02h | fHideDetail | = 1 if detail is hidden
 | 7–2 | FCh | (Reserved) | Reserved, must be 0 (zero)
1 | 7–0 | FFh | (Reserved) | Reserved, must be 0 (zero)

SXVIEW: View Definition (B0h)

This record contains top-level PivotTable information.

Record Data

Offset | Name | Size | Contents
4 | rwFirst | 2 | First row of the PivotTable
6 | rwLast | 2 | Last row of the PivotTable
8 | colFirst | 2 | First column of the PivotTable
10 | colLast | 2 | Last column of the PivotTable
12 | rwFirstHead | 2 | First row containing PivotTable headings
14 | rwFirstData | 2 | First row containing PivotTable data
16 | colFirstData | 2 | First column containing PivotTable data
18 | iCache | 2 | Index to the cache
20 | (Reserved) | 2 | Reserved; must be 0 (zero)
22 | sxaxis4Data | 2 | Default axis for a data field
24 | ipos4Data | 2 | Default position for a data field
26 | cDim | 2 | Number of fields
28 | cDimRw | 2 | Number of row fields
30 | cDimCol | 2 | Number of column fields
32 | cDimPg | 2 | Number of page fields
34 | cDimData | 2 | Number of data fields
36 | cRw | 2 | Number of data rows
38 | cCol | 2 | Number of data columns
40 | grbit | 2 | Option flags
42 | itblAutoFmt | 2 | Index to the PivotTable autoformat
44 | cchName | 2 | Length of the PivotTable name
46 | cchData | 2 | Length of the data field name
48 | rgch | var | PivotTable name, followed by the name of a data field

The grbit field contains the option flags listed in the following table.

Offset | Bits | Mask | Name | Contents
0 | 0 | 0001h | fRwGrand | = 1 if the PivotTable contains grand totals for rows
 | 1 | 0002h | fColGrand | = 1 if the PivotTable contains grand totals for columns
 | 2 | 0004h | (Reserved) | Reserved; must be 0 (zero)
 | 3 | 0008h | fAutoFormat | = 1 if the PivotTable has an autoformat applied
 | 4 | 0010h | fWH | = 1 if the width/height autoformat is applied
 | 5 | 0020h | fFont | = 1 if the font autoformat is applied
 | 6 | 0040h | fAlign | = 1 if the alignment autoformat is applied
 | 7 | 0080h | fBorder | = 1 if the border autoformat is applied
 | 8 | 0100h | fPattern | = 1 if the pattern autoformat is applied
 | 9 | 0200h | fNumber | = 1 if the number autoformat is applied
 | 15–10 | FC00h | (Reserved) | Reserved; must be 0 (zero)

SXVS: View Source (E3h)

This record contains an integer that defines the data source for a PivotTable.

Record Data

Offset | Name | Size | Contents
4 | vs | 2 | Data source: = 01h, Microsoft Excel list or database = 02h, External data source (Microsoft Query) = 04h, Multiple consolidation ranges = 08h, Another PivotTable = 10h, A Scenario Manager summary report

TABID: Sheet Tab Index Array (13Dh) (New for BIFF7)

This record contains an array of sheet tab index numbers. The record is used by the Shared Lists feature.

The sheet tab indexes have type short int (2 bytes each). The index numbers are 0-based and are assigned when a sheet is created; the sheets retain their index numbers throughout their lifetime in a workbook. If you rearrange the sheets in a workbook, the rgiTab array will change to reflect the new sheet arrangement.

This record does not appear in BIFF5 files.

Record Data

Offset | Name | Size | Contents
4 | rgiTab | var | Array of tab indexes

TABIDCONF: Sheet Tab ID of Conflict History (EAh)
(new for BIFF7)

This record contains the sheet tab index for the Conflict History worksheet. The record is used by the Shared Lists feature.

This record does not appear in BIFF5 files.

Record Data

Offset | Name | Size | Contents
4 | itabConf | 2 | Sheet tab index for the Conflict History worksheet. If =FFFFh, the user has stopped sharing the workbook.

TABLE: Data Table (236h)

A TABLE record describes a data table created with the Table command (Data menu).

Record Data

Offset | Name | Size | Contents
4 | rwFirst | 2 | First row of the table
6 | rwLast | 2 | Last row of the table
8 | colFirst | 1 | First column of the table
9 | colLast | 1 | Last column of the table
10 | grbit | 2 | Option flags
12 | rwInpRw | 2 | Row of the row input cell
14 | colInpRw | 2 | Column of the row input cell
16 | rwInpCol | 2 | Row of the column input cell
18 | colInpCol | 2 | Column of the column input cell

The grbit field contains the option flags listed in the following table.

Offset | Bits | Mask | Name | Contents
0 | 0 | 01h | fAlwaysCalc | Always calculate the formula.
 | 1 | 02h | fCalcOnLoad | Calculate the formula when the file is opened.
 | 2 | 04h | fRw | = 1 input cell is a row input cell. = 0 input cell is a column input cell.
 | 3 | 08h | fTbl2 | = 1 if two-input data table. = 0 if one-input data table.
 | 7–4 | F0h | (Unused) |
1 | 7–0 | FFh | (Unused) |

The area (range of cells) in which the table is entered is defined by the rwFirst, rwLast, colFirst, and colLast fields. This area is the interior of the table and does not include the outer row or column (these contain the table formulas and/or input values).

In cases where the input cell is a deleted reference (the cell displays #REF!), the rwInp field is –1. The colInp field is not used in this case.

TEMPLATE: Workbook Is a Template (60h)

This record has no record data field. If the TEMPLATE record is present in the Book stream, it signifies that the workbook is a template. The TEMPLATE record, if present, must immediately follow the BOF record.

TOPMARGIN: Top Margin Measurement (28h)

The TOP MARGIN record specifies the top margin in inches when a sheet is printed. The num field is in 8-byte IEEE floating-point format.

Record Data

Offset | Name | Size | Contents
4 | num | 8 | Top margin

UDDESC: Description String for Chart Autoformat (DFh)

This record stores the description string for a custom chart autoformat. The record is written only in the chart autoformat file (XL5GALRY.XLS in Microsoft Excel for Windows).

Record Data

Offset | Name | Size | Contents
4 | cch | 1 | Length of the description string
5 | rgch | var | Description string

UNCALCED: Recalculation Status (5Eh)

If the UNCALCED record is present in the Book stream, it indicates that the Calculate message was in the status bar when Microsoft Excel saved the file. This occurs if the sheet changed, the Manual calculation option was on, and the Recalculate Before Save option was off (Options dialog box, Calculation tab).

Record Data

Offset | Name | Size | Contents
4 | (Reserved) | 2 | Reserved; must be 0 (zero)

VCENTER: Center Between Vertical Margins (84h)

If the Center On Page Vertically option is on in the Page Setup dialog box, Margins tab, then fVCenter = 1.

Record Data

Offset | Name | Size | Contents
4 | fVCenter | 2 | = 1 if the sheet is to be centered between the vertical margins when printed

VERTICALPAGEBREAKS: Explicit Column Page Breaks (1Ah)

The VERTICALPAGEBREAKS record contains a list of explicit column page breaks. The cbrk field contains the number of page breaks. rgcol is an array of
2-byte integers that specifies columns. Microsoft Excel sets a page break before each column contained in the list of columns in the rgcol field. The columns must be sorted in ascending order.

Record Data

Offset | Name | Size | Contents
4 | cbrk | 2 | Number of page breaks
6 | rgcol | var | Array of columns

WINDOW1: Window Information (3Dh)

The WINDOW1 record contains workbook-level window attributes. The xWn and yWn fields contain the location of the window in units of 1/20 of a point, relative to the upper-left corner of the Microsoft Excel window client area. The dxWn and dyWn fields contain the window size, also in units of 1/20 of a point.

Record Data

Offset | Name | Size | Contents
4 | xWn | 2 | Horizontal position of the window
6 | yWn | 2 | Vertical position of the window
8 | dxWn | 2 | Width of the window
10 | dyWn | 2 | Height of the window
12 | grbit | 2 | Option flags
14 | itabCur | 2 | Index of the selected workbook tab (0-based)
16 | itabFirst | 2 | Index of the first displayed workbook tab (0-based).
18 | ctabSel | 2 | Number of workbook tabs that are selected.
20 | wTabRatio | 2 | Ratio of the width of the workbook tabs to the width of the horizontal scroll bar; to obtain the ratio, convert to decimal and then divide by 1000.

The grbit field contains the option flags listed in the following table.

Offset | Bits | Mask | Name | Contents
0 | 0 | 01h | fHidden | = 1 if the window is hidden
 | 1 | 02h | fIconic | = 1 if the window is currently displayed as an icon
 | 2 | 04h | (Reserved) |
 | 3 | 08h | fDspHScroll | = 1 if the horizontal scroll bar is displayed
 | 4 | 10h | fDspVScroll | = 1 if the vertical scroll bar is displayed
 | 5 | 20h | fBotAdornment | = 1 if the workbook tabs are displayed
 | 7-6 | C0h | (Reserved) |
1 | 7-0 | FFh | (Reserved) |

WINDOW2: Sheet Window Information (23Eh)

The WINDOW2 record contains window attributes for a sheet in a workbook.

Record Data

Offset | Name | Size | Contents
4 | grbit | 2 | Option flags
6 | rwTop | 2 | Top row visible in the window
8 | colLeft | 2 | Leftmost column visible in the window
10 | rgbHdr | 4 | Row/column heading and gridline color

The grbit field contains the option flags shown in the following table.

Offset | Bits | Mask | Name | Contents
0 | 0 | 01h | fDspFmla | = 1 if the window should display formulas = 0 if the window should display value
 | 1 | 02h | fDspGrid | = 1 if the window should display gridlines
 | 2 | 04h | fDspRwCol | = 1 if the window should display row and column headings
 | 3 | 08h | fFrozen | = 1 if the panes in the window should be frozen
 | 4 | 10h | fDspZeros | = 1 if the window should display 0 (zero) values = 0 if the window should suppress display of 0 (zero) values
 | 5 | 20h | fDefaultHdr | = 1 (see the following explanation) = 0 use rgbHdr color
 | 6 | 40h | fArabic | = 1 for the Arabic version of Microsoft Excel
 | 7 | 80h | fDspGuts | = 1 if outline symbols are displayed
1 | 0 | 01h | fFrozenNoSplit | = 1 if the panes in the window are frozen but there is no split
 | 1 | 02h | fSelected | = 1 if the sheet tab is selected
 | 2 | 04h | fPaged | = 1 if the sheet is currently being displayed in the workbook window
 | 7–3 | F8h | (Reserved) |

fDefaultHdr is 1 if the window's row and column headings and gridlines should be drawn in the window's default foreground color. If this field is 0, the RGB color in the rgbHdr field is used instead.

WINDOWPROTECT: Windows Are Protected (19h)

The WINDOWPROTECT record stores an option from the Protect Workbook dialog box.

Record Data

Offset | Name | Size | Contents
4 | fLockWn | 2 | = 1 if the workbook windows are protected

WRITEACCESS: Write Access User Name (5Ch)

This record contains the user name, which is the name you type when you install Microsoft Excel. The stName field is always padded with spaces (20h) to make the field 31 characters long; however, only the first cch bytes contain the actual user name data.

Record Data

Offset | Name | Size | Contents
4 | cch | 1 | Length of the user name
5 | stName | 31 | User name, padded with spaces (20h)

WRITEPROT: Workbook Is Write-Protected (86h)

This record is 4 bytes long, and it has no record data field. If the WRITEPROT record is present in the Book stream, it signifies that the worksheet has a Write Reservation password (File menu, Save As command, Options dialog box). For information about the password (wResPass), see FILESHARING.

WSBOOL: Additional Workspace Information (81h)

This record stores information about workspace settings.

Record Data

Offset | Name | Size | Contents
4 | grbit | 2 | Option flags

The grbit field contains the option flags listed in the following table.

Offset | Bits | Mask | Name | Contents
0 | 0 | 01h | fShowAutoBreaks | = 1 if automatic page breaks are visible
 | 3–1 | E0h | (Unused) |
 | 4 | 10h | fDialog | = 1 if the sheet is a dialog sheet
 | 5 | 20h | fApplyStyles | = 0 if automatic styles are applied to an outline
 | 6 | 40h | fRwSumsBelow | = 1 if summary rows appear below detail in an outline
 | 7 | 80h | fColSumsRight | = 1 if summary columns appear to the right of detail in an outline
1 | 0 | 01h | fFitToPage | = 1 if the Fit option is on (Page Setup dialog box, Page tab)
 | 1 | 02h | (Reserved) |
 | 3–2 | 06h | fDspGuts | = 1 if outline symbols are displayed
 | 5–4 |  | (Reserved) |
 | 6 |  | fAee | = 1 if the Alternate Expression Evaluation option is on (Options dialog box, Calculation tab)
 | 7 |  | fAfe | = 1 if the Alternate Formula Entry option is on (Options dialog box, Calculation tab)

XCT: CRN Record Count (59h)

For BIFF files that contain CRN records, ccrn is the number of CRN records (type 5Ah) in the file. The CRN records immediately follow the XCT record.

Record Data

Offset | Name | Size | Contents
4 | ccrn | 2 | Count of CRN records that follow

XF: Extended Format (E0h)

The XF record stores formatting properties for cells and styles. The ixfe of a cell record (BLANK, LABEL, NUMBER, RK, and so on) points to a cell XF record, and the ixfe of a STYLE record points to a style XF record. Note that in previous BIFF versions, the record number for the XF record was 43h.

A BIFF file can contain as many XF records as are necessary to describe the different cell formats and styles in a workbook. The XF records are written in a table in the workbook stream, and the index to the XF record table is a 0-based number called ixfe.

The workbook stream must contain a minimum XF table consisting of 15 style XF records and one cell XF record (ixfe=0 through ixfe=15). The first XF record (ixfe=0) is the XF record for the Normal style. The next 14 records (ixfe=1 through ixfe=14) are XF records that correspond to outline styles RowLevel_1, ColLevel_1, RowLevel_2, ColLevel_2, and so on. The last record (ixfe=15) is the default cell XF for the workbook.

Following these XF records are five additional style XF records (not strictly required) that correspond to the Comma, Comma [0], Currency, Currency [0], and Percent styles.

Cell XF Record

Record Data

Offset | Bits | Mask | Name | Contents
4 | 15–0 | FFFFh | ifnt | Index to the FONT record.
6 | 15–0 | FFFFh | ifmt | Index to the FORMAT record.
8 | 0 | 0001h | fLocked | = 1 if the cell is locked.
 | 1 | 0002h | fHidden | = 1 if the cell is hidden.
 | 2 | 0004h | fStyle | = 0 for cell XF. = 1 for style XF.
 | 3 | 0008h | f123Prefix | If the Transition Navigation Keys option is off (Options dialog box, Transition tab), f123Prefix = 1 indicates that a leading apostrophe (single quotation mark) is being used to coerce the cell's contents to a simple string. If the Transition Navigation Keys option is on, f123Prefix = 1 indicates that the cell formula begins with one of the four Lotus 1-2-3 alignment prefix characters: ' left " right ^ centered \ fill
 | 15–4 | FFF0h | ixfParent | Index to the XF record of the parent style. Every cell XF must have a parent style XF, which is usually ixfeNormal = 0.
10 | 2–0 | 0007h | alc | Alignment: 0 = general 1 = left 2 = center 3 = right 4 = fill 5 = justify 6 = center across selection
 | 3 | 0008h | fWrap | = 1 wrap text in cell.
10 | 6–4 | 0070h | alcV | Vertical alignment: 0 = top 1 = center 2 = bottom 3 = justify
 | 7 | 0080h | fJustLast | (Used only in Far East versions of Microsoft Excel)
 | 9–8 | 0300h | ori | Orientation of text in cell: = 0 no rotation = 1 text appears top-to-bottom; letters are upright = 2 text is rotated 90 degrees counterclockwise = 3 text is rotated 90 degrees clockwise
 | 10 | 0400h | fAtrNum | = 1 if the ifmt is not equal to the ifmt of the parent style XF
 | 11 | 0800h | fAtrFnt | = 1 if the ifnt is not equal to the ifnt of the parent style XF
 | 12 | 1000h | fAtrAlc | = 1 if either the alc or the fWrap field is not equal to the corresponding field of the parent style XF
 | 13 | 2000h | fAtrBdr | = 1 if any border line field (dgTop, and so on) is not equal to the corresponding field of the parent style XF
 | 14 | 4000h | fAtrPat | = 1 if any pattern field (fls, icvFore, icvBack) is not equal to the corresponding field of the parent style XF
 | 15 | 8000h | fAtrProt | = 1 if either the fLocked field or the fHidden field is not equal to the corresponding field of the parent style XF
12 | 6–0 | 007Fh | icvFore | Index to the color palette for the foreground color of the fill pattern
 | 12–7 | 1F80h | icvBack | Index to the color palette for the background color of the fill pattern
 | 13 | 2000h | fSxButton | = 1 if the XF record is attached to a PivotTable button
 | 15–14 | C000h | (Reserved) |
14 | 5–0 | 003Fh | fls | Fill pattern
 | 8–6 | 01C0h | dgBottom | Border line style (see the following illustration)
 | 15–9 | FE00h | icvBottom | Index to the color palette for the bottom border color
16 | 2–0 | 0007h | dgTop | Border line style (see the following illustration)
 | 5–3 | 0038h | dgLeft | Border line style (see the following illustration)
 | 8–6 | 01C0h | dgRight | Border line style (see the following illustration)
 | 15–9 | FE00h | icvTop | Index to the color palette for the top border color
18 | 6-0 | 007Fh | icvLeft | Index to the color palette for the left border color
 | 13-7 | 3F80h | icvRight | Index to the color palette for the right border color
 | 15–14 | C000h | (Reserved) |

Border Line Styles

The border line style fields — dgTop, dgLeft, dgBottom, dgRight — correspond to the options in the Format Cells dialog box, Border tab, as shown in the following illustration.

Style XF Record

The style XF record is identical to the cell XF record, except that some of the fields have slightly different meanings.

Record Data

Offset | Bits | Mask | Name | Contents
6 | 15–0 | FFFFh | ifmt | Index to the FORMAT record
8 | 0 | 0001h | fLocked | = 1 if the cell is locked
 | 1 | 0002h | fHidden | = 1 if the cell is hidden
 | 2 | 0004h | fStyle | = 0 for cell XF. = 1 for style XF.
 | 3 | 0008h | f123Prefix | This bit is always = 0 for style XF.
 | 15–4 | FFF0h | ixfParent | For style XF records, this field equals FFFh (ixfNULL).
10 | 2–0 | 0007h | alc | Alignment: 0 = general 1 = left 2 = center 3 = right 4 = fill 5 = justify 6 = center across selection
 | 3 | 0008h | fWrap | = 1 wrap text in cell.
 | 6–4 | 0070h | alcV | Vertical alignment: 0 = top 1 = center 2 = bottom 3 = justify
 | 7 | 0080h | fJustLast | (Used only in Far East versions of Microsoft Excel.)
 | 9–8 | 0300h | ori | Orientation of text in cell: = 0 no rotation. = 1 text appears top-to-bottom; letters are upright. = 2 text is rotated 90 degrees counterclockwise. = 3 text is rotated 90 degrees clockwise.
 | 10 | 0400h | fAtrNum | = 0 if the style includes Number (Style dialog box).
 | 11 | 0800h | fAtrFnt | = 0 if the style includes Font (Style dialog box).
 | 12 | 1000h | fAtrAlc | = 0 if the style includes Alignment (Style dialog box).
 | 13 | 2000h | fAtrBdr | = 0 if the style includes Border (Style dialog box).
 | 14 | 4000h | fAtrPat | = 0 if the style includes Patterns (shading) (Style dialog box).
 | 15 | 8000h | fAtrProt | = 0 if the style includes Protection (cell protection) (Style dialog box).
12 | 6–0 | 007Fh | icvFore | Index to the color palette for the foreground color of the fill pattern.
 | 12–7 | 1F80h | icvBack | Index to the color palette for the background color of the fill pattern.
 | 13 | 2000h | fSxButton | This bit always = 0 for style XF.
 | 15–14 | C000h | (Reserved) |
14 | 5–0 | 003Fh | fls | Fill pattern.
 | 8–6 | 01C0h | dgBottom | Border line style (see the previous illustration).
 | 15–9 | FE00h | icvBottom | Index to the color palette for the bottom border color.
16 | 2–0 | 0007h | dgTop | Border line style (see the previous illustration).
 | 5–3 | 0038h | dgLeft | Border line style (see the previous illustration).
 | 8–6 | 01C0h | dgRight | Border line style (see the previous illustration).
 | 15–9 | FE00h | icvTop | Index to the color palette for the top border color.
18 | 6–0 | 007Fh | icvLeft | Index to the color palette for the left border color.
 | 13–7 | 3F80h | icvRight | Index to the color palette for the right border color.
 | 15–14 | C000h | (reserved) |

Finding Cell Records in BIFF Files

Microsoft Excel uses the INDEX and DBCELL records to optimize the lookup of cell records (RK, FORMULA, and so on). You can use these records to optimize your code when reading a BIFF file, or you can just read the entire workbook stream to find the cell values you want. The unoptimized method may be slower, depending on the size, structure, and complexity of the file.

If your code writes a BIFF file, you must include the INDEX and DBCELL records with correct values in the record fields. If you do not do this, Microsoft Excel will not be able to optimize lookup, and the program's performance will suffer, especially when the user tries to copy data out of the file that your application has written.

Microsoft Excel stores cell records in blocks that have at most 32 rows. Each row that contains cell records has a corresponding ROW record in the block, and each block contains a DBCELL record at the end of the block.

The following illustration shows how to use the INDEX record to locate the DBCELL records at the end of the record blocks. Notice that the stream position at the start of the first BOF record in the workbook stream is 6F1h. To find the start of each DBCELL record, add this number to each member of the rgibRw array in the INDEX record.

After your code has computed the location of the DBCELL records, you can use the dbRtrw field to find the location of the start of the first ROW record for each block. This field is stored as a positive long integer, although the offset is really a "negative" offset to an earlier position in the file. See the following illustration for details.

Finally, your code can compute the start of each cell record in the block by using the members in the rgdb array in the DBCELL record. The offsets in this array use the start of the second ROW record in the block as the initial offset. This is because the code has to read the first ROW record to know what the row number is (and then to make a decision based on the row number), and the stream pointer is at the start of the second ROW record after this. See the following illustration for details.

Microsoft Excel Formulas

This section describes how Microsoft Excel stores formulas. Formulas most commonly appear in rgce fields in FORMULA, ARRAY, and NAME records. In this section, formula is a synonym for parsed expression, which is the internal tokenized representation of a Microsoft Excel formula.

There are no changes to the tokenized representation of a Microsoft Excel formula from BIFF5 to BIFF7, therefore this information applies to both versions.

Parsed Expressions and Tokens

Microsoft Excel uses a modified reverse-Polish technique to store parsed expressions. A parsed expression contains a sequence of parse tokens, each of which is either an operand, an operator token, or a control token. Operand tokens push operands onto the stack. Operator tokens perform arithmetic operations on operands. Control tokens assist in formula evaluation by describing properties of the formula.

A token consists of two parts: a token type and a token value. A token type is called a ptg (parse thing) in Microsoft Excel. A ptg is 1 byte long and has a value from 01h to 7Fh. The ptgs above 7Fh are reserved.

The ptg specifies only what kind of information a token contains. The information itself is stored in the token value, which immediately follows the ptg. Some tokens consist of only a ptg, without an accompanying token value. For example, to specify an addition operation, only the token type ptgAdd is required. But to specify an integer operand, you must specify both ptgInt and the token value, which is an integer.

For example, assume that the formula =5+6 is in cell A1. The parsed expression for this formula consists of three tokens: two integer operand tokens (<token 1> and <token 2>) and an operator token (<token 3>), as shown in the following table.

<token 1> | <token 2> | <token 3>
ptgInt 0005h | ptgInt 0006h | ptgAdd

Notice that each ptgInt is immediately followed by the integer token value.

If you type this formula in cell A1 and then examine the FORMULA record (using the BiffView utility), you'll see the following:

00000  06 00 1d 00 00 00 00 00 0f 00 00 00 00 00 00 00
00010  26 40 00 00 00 00 e0 fc 07 00 1e 05 00 1e 06 00
00020  03 -- -- -- -- -- -- -- -- -- -- -- -- -- -- --

The first 26 bytes of the hex dump contain the record number, record length, rw, col, ixfe, num, grbit, chn, and cce fields. The remaining 7 bytes contain the two ptgInt (1Eh) tokens — which contain the token values that represent the integers 5 and 6 (0005h and 0006h) — and the ptgAdd (03h) token. If the formula were changed to =5*6, the third token would be ptgMul (05h). For more information about the FORMULA record, see FORMULA.

In many cases, the token value consists of a structure of two or more fields. In these cases, offset-0 (zero) is assumed to be the first byte of the token value — that is, the first byte immediately following the token type.

Microsoft Excel ptgs

The following table contains all ptgs that appear in BIFF files. All other ptgs are reserved.

The ptgSheet and ptgEndSheet tokens are no longer used. The external sheet references are contained in the ptgNameX, ptgRef3d, and ptgArea3d tokens.

Name | Ptg | Type
ptgExp | 01h | control
ptgTbl | 02h | control
ptgAdd | 03h | operator
ptgSub | 04h | operator
ptgMul | 05h | operator
ptgDiv | 06h | operator
ptgPower | 07h | operator
ptgConcat | 08h | operator
ptgLT | 09h | operator
ptgLE | 0Ah | operator
ptgEQ | 0Bh | operator
ptgGE | 0Ch | operator
ptgGT | 0Dh | operator
ptgNE | 0Eh | operator
ptgIsect | 0Fh | operator
ptgUnion | 10h | operator
ptgRange | 11h | operator
ptgUplus | 12h | operator
ptgUminus | 13h | operator
ptgPercent | 14h | operator
ptgParen | 15h | control
ptgMissArg | 16h | operand
ptgStr | 17h | operand
ptgAttr | 19h | control
ptgSheet | 1Ah | (ptg DELETED)
ptgEndSheet | 1Bh | (ptg DELETED)
ptgErr | 1Ch | operand
ptgBool | 1Dh | operand
ptgInt | 1Eh | operand
ptgNum | 1Fh | operand
ptgArray | 20h | operand, reference class
ptgFunc | 21h | operator
ptgFuncVar | 22h | operator
ptgName | 23h | operand, reference class
ptgRef | 24h | operand, reference class
ptgArea | 25h | operand, reference class
ptgMemArea | 26h | operand, reference class
ptgMemErr | 27h | operand, reference class
ptgMemNoMem | 28h | control
ptgMemFunc | 29h | control
ptgRefErr | 2Ah | operand, reference class
ptgAreaErr | 2Bh | operand, reference class
ptgRefN | 2Ch | operand, reference class
ptgAreaN | 2Dh | operand, reference class
ptgMemAreaN | 2Eh | control
ptgMemNoMemN | 2Fh | control
ptgNameX | 39h | operand, reference class
ptgRef3d | 3Ah | operand, reference class
ptgArea3d | 3Bh | operand, reference class
ptgRefErr3d | 3Ch | operand, reference class
ptgAreaErr3d | 3Dh | operand, reference class
ptgArrayV | 40h | operand, value class
ptgFuncV | 41h | operator
ptgFuncVarV | 42h | operator
ptgNameV | 43h | operand, value class
ptgRefV | 44h | operand, value class
ptgAreaV | 45h | operand, value class
ptgMemAreaV | 46h | operand, value class
ptgMemErrV | 47h | operand, value class
ptgMemNoMemV | 48h | control
ptgMemFuncV | 49h | control
ptgRefErrV | 4Ah | operand, value class
ptgAreaErrV | 4Bh | operand, value class
ptgRefNV | 4Ch | operand, value class
ptgAreaNV | 4Dh | operand, value class
ptgMemAreaNV | 4Eh | control
ptgMemNoMemNV | 4Fh | control
ptgFuncCEV | 58h | operator
ptgNameXV | 59h | operand, value class
ptgRef3dV | 5Ah | operand, value class
ptgArea3dV | 5Bh | operand, value class
ptgRefErr3dV | 5Ch | operand, value class
ptgAreaErr3dV | 5Dh | operand, value class
ptgArrayA | 60h | operand, array class
ptgFuncA | 61h | operator
ptgFuncVarA | 62h | operator
ptgNameA | 63h | operand, array class
ptgRefA | 64h | operand, array class
ptgAreaA | 65h | operand, array class
ptgMemAreaA | 66h | operand, array class
ptgMemErrA | 67h | operand, array class
ptgMemNoMemA | 68h | control
ptgMemFuncA | 69h | control
ptgRefErrA | 6Ah | operand, array class
ptgAreaErrA | 6Bh | operand, array class
ptgRefNA | 6Ch | operand, array class
ptgAreaNA | 6Dh | operand, array class
ptgMemAreaNA | 6Eh | control
ptgMemNoMemNA | 6Fh | control
ptgFuncCEA | 78h | operator
ptgNameXA | 79h | operand, array class (NEW ptg)
ptgRef3dA | 7Ah | operand, array class (NEW ptg)
ptgArea3dA | 7Bh | operand, array class (NEW ptg)
ptgRefErr3dA | 7Ch | operand, array class (NEW ptg)
ptgAreaErr3dA | 7Dh | operand, array class (NEW ptg)

Expression Evaluation

Calculation of Microsoft Excel formulas is a straightforward process. A last-in, first-out (LIFO) stack, the operand stack, is maintained during calculation. When an operand is encountered, it's pushed onto the stack. When an operator is encountered, it operates on the topmost operand or operands. Operator precedence is irrelevant at evaluation time; operators are handled as soon as they're encountered.

There are three kinds of operators: unary, binary, and function. Unary operators, such as the minus sign that negates a number, operate only on the top operand. Binary operators, such as the addition operator, operate on the top two operands. Function operators, which implement Microsoft Excel functions, operate on a variable number of operands, depending on how many arguments the function accepts.

All operators work by popping the required operands from the stack, performing calculations, and then pushing the result back onto the operand stack.

Scanning a Parsed Expression

One fairly common operation you can perform on parsed expressions is to scan them, taking appropriate actions at each ptg. You can do this with a loop by using a pointer variable that points to the next ptg to scan. However, you must increment this pointer carefully, because different ptgs may have token values of different lengths.

One approach is to maintain an array with one element per ptg. Each element contains the size of the token value. To increment the pointer, add the array element corresponding to the current ptg to the pointer. One way of reducing the array size is to limit the array indexes to the range 0–3Fh and then index it using the reference-class ptg (the base ptg) instead of the value-class or array-class ptg. This is possible because the token value is the same for all classes of a particular ptg. For more information about operand classes, see ptg Values for Operand Tokens.

There are two tokens, ptgStr and ptgAttr (when bitFAttrChoose is true), that have variable length and are therefore exceptions to the preceding description. The first token, ptgStr, is followed by a variable-length string. The token value specifies the length of the string, so the pointer can be incremented by reading the string length (cch) and then adding the string length to the pointer.

The other token is ptgAttr when bitFAttrChoose is true. In this case, the token value contains an optimized CHOOSE function, which contains a variable-length sequence of word offsets in the cases (value1, value2, … arguments) for the CHOOSE function. For these, you can use the wCases field to calculate the pointer increment.

Unary Operator Tokens

The unary operator tokens for Microsoft Excel are described in the following paragraphs. These operators pop the top argument from the operand stack, perform a calculation, and then push the result back onto the operand stack.

ptgUplus: Unary Plus (ptg = 12h)

Has no effect on the operand.

ptgUminus: Unary Minus (ptg = 13h)

Negates the operand on the top of the stack.

ptgPercent: Percent Sign (ptg = 14h)

Divides the top operand by 100.

Binary Operator Tokens

There are several binary operator ptgs. All binary operator ptgs pop the top two arguments from the operand stack, perform the associated calculation, and then push the result back onto the operand stack.

ptgAdd: Addition (ptg = 03h)

Adds the top two operands.

ptgSub: Subtraction (ptg = 04h)

Subtracts the top operand from the second-to-top operand.

ptgMul: Multiplication (ptg = 05h)

Multiplies the top two operands.

ptgDiv: Division (ptg = 06h)

Divides the top operand by the second-to-top operand.

ptgPower: Exponentiation (ptg = 07h)

Raises the second-to-top operand to the power of the top operand.

ptgConcat: Concatenation (ptg = 08h)

Appends the top operand to the second-to-top operand.

ptgLT: Less Than (ptg = 09h)

Evaluates to TRUE if the second-to-top operand is less than the top operand; evaluates to FALSE otherwise.

ptgLE: Less Than or Equal (ptg = 0Ah)

Evaluates to TRUE if the second-to-top operand is less than or equal to the top operand; evaluates to FALSE otherwise.

ptgEQ: Equal (ptg = 0Bh)

Evaluates to TRUE if the top two operands are equal; evaluates to FALSE otherwise.

ptgGE: Greater Than or Equal (ptg = 0Ch)

Evaluates to TRUE if the second-to-top operand is greater than or equal to the top operand; evaluates to FALSE otherwise.

ptgGT: Greater Than (ptg = 0Dh)

Evaluates to TRUE if the second-to-top operand is greater than the top operand; evaluates to FALSE otherwise.

ptgNE: Not Equal (ptg = 0Eh)

Evaluates to TRUE if the top two operands are not equal; evaluates to FALSE otherwise.

ptgIsect: Intersection (ptg = 0Fh)

Computes the intersection of the top two operands. This is the Microsoft Excel space operator.

ptgUnion: Union (ptg = 10h)

Computes the union of the top two operands. This is the Microsoft Excel comma operator.

ptgRange: Range (ptg = 11h)

Computes the minimal bounding rectangle of the top two operands. This is the Microsoft Excel colon operator.

Operand Tokens: Constant

These operand tokens push a single constant operand onto the operand stack.

ptgMissArg: Missing Argument (Operand, ptg = 16h)

Indicates a missing argument to a Microsoft Excel function. For example, the second (missing) argument to the function DCOUNT(Database,,Criteria) would be stored as a ptgMissArg.

ptgStr: String Constant (Operand, ptg = 17h)

Indicates a string constant ptg followed by a string length field (00 to FFh) and the actual string.

Offset | Name | Size | Contents
0 | cch | 1 | The length of the string
1 | rgch | var | The string

ptgStr requires special handling when parsed expressions are scanned. For more information, see Scanning a Parsed Expression.

ptgErr: Error Value (Operand, ptg = 1Ch)

This ptg is followed by the 1-byte error value (err). For a list of error values, see BOOLERR.

Offset | Name | Size | Contents
0 | err | 1 | An error value

ptgBool: Boolean (Operand, ptg = 1Dh)

This ptg is followed by a byte that represents TRUE or FALSE.

Offset | Name | Size | Contents
0 | f | 1 | = 1 for TRUE = 0 for FALSE

ptgInt: Integer (Operand, ptg = 1Eh)

This ptg is followed by a word that contains an unsigned integer.

Offset | Name | Size | Contents
0 | w | 2 | An unsigned integer value

ptgNum: Number (Operand, ptg = 1Fh)

This ptg is followed by an 8-byte IEEE floating-point number.

Offset | Name | Size | Contents
0 | num | 8 | An IEEE floating-point number

Operand Tokens

Operand tokens push operand values onto the operand stack. These values fall into one of three classes — reference class, value class, or array class — depending on what type of value the formula expects from the operand. The type of value is determined by the context of the operand when the formula is parsed by Microsoft Excel.

Reference Class

Some operands are required by context to evaluate to references. In this case, the term "reference" is a general term meaning one or more areas on a Microsoft Excel worksheet.

When the Microsoft Excel expression evaluator encounters a reference class operand, it pushes only the reference itself onto the operand stack; it doesn't dereference it to return the underlying value or values. For example, the function CELL("width",B5) pushes the reference class operand ptgRef (24h) for the second argument. This function returns the column width of cell B5; therefore, only the reference to B5 is required, and there's no need to dereference to the value stored in cell B5.

Value Class

This is the most common type of operand. Value class operands push a single dereferenced value onto the operand stack. For example, the formula =A1+1 pushes a value class operand ptgRefV (44h) for the cell reference A1.

Array Class

This operand pushes an array of values onto the operand stack. You can specify the values in an array constant or in a reference to cells. For example, the formula =SUM({1,2,3;4,5,6}) pushes an array class ptgArrayA (60h) to represent the arguments to the function.

ptg Values for Operand Tokens

The three classes of operand tokens are divided numerically, as shown in the following table.

Operand class | Ptg values
Reference | 20h–3Fh
Value | 40h–5Fh
Array | 60h–7Fh

The arithmetic difference between ptg classes is 20h. This is the basis for forming the class variants of ptgs. Class variants of ptgs are formed from the reference class ptg, also known as the base ptg. To form the value class ptg from the base ptg, add 20h to the ptg and append V (for "value") to the ptg name. To form the array class ptg from the base ptg, add 40h to the ptg and append A (for "array") to the ptg name. These rules are summarized in the following table for a sample base ptg, ptgRef.

Class | Name | Ptg
Reference | ptgRef | 24h
Value | ptgRefV | 44h
Array | ptgRefA | 64h

The following example is a suggested method for calculating the base ptg from any class variant.

    if (ptg & 40h)
        {
        /* Value class ptg. Set the 20h bit to
           make it Reference class, then strip
           off the high-order bits. */
        ptgBase = (ptg | 20h) & 3Fh;
        }
    else
        {
        /* Reference or Array class ptg. The 20h bit
           is already set, so just have to strip off
           the high-order bits. */
        ptgBase = ptg & 3Fh;
        }

A more efficient implementation would define a macro that computes the base ptg, as in the following example.

#define PtgBase(ptg) (((ptg & 0x40) ? (ptg | 0x20): ptg) & 0x3F)

Operand Tokens: Base

This section describes the operand tokens in their base form (also known as reference class operand tokens).

ptgArray: Array Constant (Operand, ptg = 20h)

Array constant followed by 7 reserved bytes.

The token value for ptgArray consists of the array dimensions and the array values. ptgArray differs from most other operand tokens in that the token value doesn't follow the token type. Instead, the token value is appended to the saved parsed expression, immediately following the last token. The format of the token value is shown in the following table.

Offset | Name | Size | Contents
0 | ccol | 1 | The number of columns in the array constant
1 | crw | 2 | The number of rows in the array constant
3 | rgval | var | The array values

An array with 256 columns is stored with a ccol = 0, because a single byte cannot store the integer 256. This is unambiguous, because a zero-column array constant is meaningless.

The number of values in the array constant is equal to the product of the array dimensions, crw*ccol. Each value is either an 8-byte IEEE floating-point number or a string. The two formats for these values are shown in the following tables.

IEEE Floating-Point Number

Offset | Name | Size | Contents
0 | grbit | 1 | = 01h
1 | num | 8 | IEEE floating-point number

String

Offset | Name | Size | Contents
0 | grbit | 1 | = 02h
1 | cch | 1 | The length of the string
2 | rgch | var | The string

If a formula contains more than one array constant, the token values for the array constants are appended to the saved parsed expression in order: first the values for the first array constant, then the values for the second array constant, and so on.

If a formula contains very long array constants, the FORMULA, ARRAY, or NAME record containing the parsed expression may overflow into CONTINUE records (to accommodate all of the array values). In such cases, an individual array value is never split between records, but record boundaries are established between adjacent array values.

The reference class ptgArray never appears in a Microsoft Excel formula; only the ptgArrayV and ptgArrayA classes are used.

ptgName: Name (Operand, ptg = 23h)

This ptg stores the index to a name. The ilbl field is a 1-based index to the table of NAME records in the workbook.

Offset | Name | Size | Contents
0 | ilbl | 2 | Index to the NAME table
2 | (reserved) | 12 | Reserved; must be 0 (zero)

ptgRef: Cell Reference (Operand, ptg = 24h)

This ptg specifies a reference to a single cell. It's followed by references for the row and column that contain the cell. The row number is encoded.

Offset | Name | Size | Contents
0 | grbitRw | 2 | (See the following table)
2 | col | 1 | The column of the reference

Only the low-order 14 bits of the grbitRw field store the row number of the reference. The 2 MSBs specify whether the row and column references are relative or absolute. The following table shows the bit structure of the grbitRw field.

Bits | Mask | Name | Contents
15 | 8000h | fRwRel | = 1 if the row offset is relative = 0 otherwise
14 | 4000h | fColRel | = 1 if the column offset is relative = 0 otherwise
13–0 | 3FFFh | rw | The row number or row offset (zero-based)

For example, cell C5 is row number 4, column number 2 (Microsoft Excel stores zero-based cell references). Therefore, the absolute reference $C$5 is stored in a ptgRef, as shown in the following file fragment.

24 04 00 02

In this case, grbitRw = 0004h and col = 02h. Notice that bits 14 and 15 of grbitRw are both 0 (zero).

The relative reference C5 is stored in a ptgRef, as shown in the following file fragment.

24 04 C0 02

In this case, where grbitRw = C004h and col = 02h, bits 14 and 15 of grbitRw are both 1.

Mixed references are stored in the same way, with appropriate coding in grbitRw.

ptgArea: Area Reference (Operand, ptg = 25h)

This ptg specifies a reference to a rectangle (range) of cells. ptgArea is followed by 6 bytes that define the first row, last row, first column, and last column of the rectangle. The numbers of the first and last rows are encoded.

Offset | Name | Size | Contents
0 | grbitRwFirst | 2 | (See the following table)
2 | grbitRwLast | 2 | (See the following table)
4 | colFirst | 1 | The first column of the reference
5 | colLast | 1 | The last column of the reference

Only the low-order 14 bits of the grbitRwFirst and grbitRwLast fields store the row offsets of the reference. The 2 MSBs of each field specify whether the row and column offset are relative or absolute. The following table shows the bit structure of the grbitRwFirst and grbitRwLast fields.

Bits | Mask | Name | Contents
15 | 8000h | fRwRel | = 1 if the row offset is relative = 0 otherwise
14 | 4000h | fColRel | = 1 if the column offset is relative = 0 otherwise
13–0 | 3FFFh | rw | The row number or row offset (zero-based)

ptgMemArea: Constant Reference Subexpression (Operand, ptg = 26h)

This ptg is used to optimize reference expressions. A reference expression consists of operands — usually references to cells or areas — joined by reference operators (intersection, union, and range). Three examples of reference expressions are given in the following table.

Reference expression | Evaluates to
(A1,C3,D3:D5) | Two single cells and a 3x1 area
(A1:C3) (B2:D4) | A 2x2 area (the space character is the intersection operator)
(Name C3) | The smallest area that contains both C3 and all the cells referenced in Name (the space character is the intersection operator)

Many reference expressions evaluate to constant references. In the preceding examples, the first two expressions always evaluate to the same reference. The third example doesn't evaluate to a constant reference because the name's definition may change, which might cause the reference expression to evaluate differently.

When a reference expression evaluates to a constant reference, Microsoft Excel stores the constant reference in the parsed formula through a ptgMemArea token. This saves time during expression evaluation, because the constant part of the expression is pre-evaluated. This part of the expression is known as a reference subexpression.

The token value for ptgMemArea consists of two parts: the length of the reference subexpression, and the value of the reference subexpression. The length is stored immediately following the ptgMemArea, whereas the value is appended to the saved parsed expression, immediately following the last token.

The format of the length is shown in the following table.

Offset | Name | Size | Contents
0 | (reserved) | 4 |
4 | cce | 2 | The length of the reference subexpression

Immediately following this part of the token value is the reference subexpression itself.

The rest of the token value (that is, the value of the reference subexpression) is appended to the parsed expression in the format shown in the following table.

Offset | Name | Size | Contents
0 | cref | 2 | The number of rectangles to follow
2 | rgref | var | An array of rectangles

Each rgref rectangle is 6 bytes long and contains the fields listed in the following table.

Offset | Name | Size | Contents
0 | rwFirst | 2 | The first row
2 | rwLast | 2 | The last row
4 | colFirst | 1 | The first column
5 | colLast | 1 | The last column

If a formula contains more than one ptgMemArea, the token values are appended to the saved parsed expression in order: first the values for the first ptgMemArea, then the values for the second ptgMemArea, and so on.

If a formula contains very long reference expressions, the BIFF record containing the parsed expression may be too long to fit in a single record. Microsoft Excel will use CONTINUE records to store long formulas. However, an individual rgref rectangle is never split between records; record boundaries occur between successive rectangles. For more information about the CONTINUE records, see CONTINUE.

ptgMemErr: Erroneous Constant Reference Subexpression (Operand, ptg = 27h)

This ptg is closely related to ptgMemArea. It's used for pre-evaluating reference subexpressions that don't evaluate to references.

For example, consider the formula =SUM(C:C 3:3), which is the sum of the intersection of column C and row 3 (the space between C:C and 3:3 is the intersection operator). The argument to the SUM function is a valid reference subexpression that generates a ptgMemArea for pre-evaluation. However, if you delete column C, the formula adjusts to =SUM(#REF! 3:3). In this case, the argument to SUM is still a constant reference subexpression, but it doesn't evaluate to a reference. Therefore, a ptgMemErr is used for pre-evaluation.

The token value consists of the error value and the length of the reference subexpression. Its format is shown in the following table.

Offset | Name | Size | Contents
0 | (reserved) | 4 |
4 | cce | 2 | The length of the reference subexpression

The reference subexpression will contain a ptgRefErr or ptgAreaErr.

ptgRefErr: Deleted Cell Reference (Operand, ptg = 2Ah)

This ptg specifies a cell reference that was adjusted to #REF! as a result of worksheet editing (such as cutting, pasting, and deleting). The ptgRefErr is followed by3 unused bytes.

Offset | Name | Size | Contents
0 | (reserved) | 3 |

The original base type of the adjusted ptg is ptgRef or ptgRefN.

ptgAreaErr: Deleted Area Reference (Operand, ptg = 2Bh)

This ptg specifies an area reference that was adjusted to #REF! as a result of worksheet editing (such as cutting, pasting, and deleting). The ptgAreaErr is followed by 6 unused bytes.

Offset | Name | Size | Contents
0 | (reserved) | 6 |

The original base type of the adjusted ptg is ptgArea or ptgAreaN.

ptgRefN: Cell Reference Within a Shared Formula (Operand, ptg = 2Ch)

Similar to its ptgRef counterpart, the ptgRefN specifies a reference to a single cell. It's followed by references for the row and column that contain the cell; the row number of the cell is encoded as bit fields.

In BIFF5 and later, ptgRefN is used only in shared formulas. In earlier versions of Microsoft Excel, ptgRefN was used in names.

Offset | Name | Size | Contents
0 | grbitRw | 2 | (See the following table)
2 | col | 1 | The column (or column offset) of the reference

Only the low-order 14 bits of the grbitRw field store the row number of the reference. The 2 MSBs specify whether the row and column references are relative or absolute. The following table shows the bit structure of the grbitRw field.

Bits | Mask | Name | Contents
15 | 8000h | fRwRel | = 1 if the row offset is relative = 0 otherwise
14 | 4000h | fColRel | = 1 if the column offset is relative = 0 otherwise
13–0 | 3FFFh | rw | The row number or row offset (zero-based)

The only difference between ptgRefN and ptgRef is in the way relative references are stored. Relative references in shared formulas are stored as offsets, not as row and column numbers (as in ptgRef). For more information, see SHRFMLA.

ptgAreaN: Area Reference Within a Shared Formula (Operand, ptg = 2Dh)

The ptgAreaN token specifies a reference to a rectangle of cells. Both the first row and last row are stored as bit fields.

In BIFF5 and later, ptgAreaN is used only in shared formulas. In earlier versions, it was used in names.

Offset | Name | Size | Contents
0 | grbitRwFirst | 2 | The first row of the absolute reference or relative reference offset bit fields
2 | grbitRwLast | 2 | The last row of the absolute reference or relative reference offset bit fields
4 | colFirst | 1 | The first column of the reference or column offset
5 | colLast | 1 | The last column of the reference or column offset

Only the low-order 14 bits of the grbitRwFirst and grbitRwLast fields store the row offsets of the reference. The 2 MSBs of each field specify whether the row and column offset are relative or absolute. The following table shows the bit structure of the grbitRwFirst and grbitRwLast fields.

Bits | Mask | Name | Contents
15 | 8000h | fRwRel | = 1 if the row offset is relative = 0 otherwise
14 | 4000h | fColRel | = 1 if the column offset is relative = 0 otherwise
13–0 | 3FFFh | rw | The row number or row offset (zero-based)

The only difference between ptgAreaN and ptgArea is in the way relative references are stored.

ptgNameX: Name or External Name (Operand, ptg = 39h)

This ptg stores the index to a name. If the name is in the current workbook (in which case ixals is negative), the ilbl field is a 1-based index to the table of NAME records. If the name is in another workbook (that is, if it's an external name), the ilbl field is a 1-based index to the table of EXTERNNAME records.

Offset | Name | Size | Contents
0 | ixals | 2 | The index to the EXTERNSHEET records. If ixals is negative (for example, FFFFh), the name is in the current workbook.
2 | (reserved) | 8 |
10 | ilbl | 2 | The index to the NAME or EXTERNNAME table (1-based).
12 | (reserved) | 12 |

ptgRef3d: 3-D Cell Reference (Operand, ptg = 3Ah)

This ptg stores a 3-D cell reference (for example, Sheet1:Sheet3!$A$1). If the reference is to another workbook (in which case ixals is positive), itabFirst isn't used (it will be 0000h), and itabLast is the ixals for the last sheet in the 3-D reference. If either itabFirst or itabLast is equal to FFFFh, that sheet is a deleted sheet.

Offset | Name | Size | Contents
0 | ixals | 2 | The index to the EXTERNSHEET records. If ixals is negative (for example, FFFFh), the reference is in the current workbook.
2 | (reserved) | 8 |
10 | itabFirst | 2 | The index to the first sheet in the 3-D reference (zero-based); see the text.
12 | itabLast | 2 | The index to the last sheet in the 3-D reference (zero-based); see the text.
14 | grbitRw | 2 | (See the following table.)
16 | col | 1 | The column of the reference, or the column offset.

Only the low-order 14 bits of the grbitRw field store the row number of the reference. The 2 MSBs specify whether the row and column references are relative or absolute. The following table shows the bit structure of the grbitRw field.

Bits | Mask | Name | Contents
15 | 8000h | fRwRel | = 1 if the row offset is relative = 0 otherwise
14 | 4000h | fColRel | = 1 if the column offset is relative = 0 otherwise
13–0 | 3FFFh | rw | The row number or row offset (zero-based)

ptgArea3d: 3-D Area Reference (Operand, ptg = 3Bh)

This ptg stores a 3-D area reference (for example, Sheet1:Sheet3!A1:E9).

Offset | Name | Size | Contents
0 | ixals | 2 | The index to the EXTERNSHEET records. If ixals is negative (for example, FFFFh), the reference is on another sheet in the same workbook.
2 | (reserved) | 8 |
10 | itabFirst | 2 | The index to the first sheet in the 3-D reference (zero-based).
12 | itabLast | 2 | The index to the last sheet in the 3-D reference (zero-based).
14 | grbitRwFirst | 2 | The first row in the area; see the following table.
16 | grbitRwLast | 2 | The last row in the area; see the following table.
18 | colFirst | 1 | The first column of the reference, or the column offset.
19 | colLast | 1 | The last column of the reference, or the column offset.

Only the low-order 14 bits of the grbitRwFirst and grbitRwLast fields store the row offsets of the reference. The 2 MSBs of each field specify whether the row and column offset are relative or absolute. The following table shows the bit structure of the grbitRwFirst and grbitRwLast fields.

Bits | Mask | Name | Contents
15 | 8000h | fRwRel | = 1 if the row offset is relative = 0 otherwise
14 | 4000h | fColRel | = 1 if the column offset is relative = 0 otherwise
13–0 | 3FFFh | rw | The row number or row offset (zero-based)

ptgRefErr3d: Deleted 3-D Cell Reference (Operand, ptg = 3Ch)

This ptg stores a 3-D cell reference that was adjusted to #REF! as a result of worksheet editing (such as cutting, pasting, and deleting). The ptgRefErr3d is identical to ptgRef3d.

ptgAreaErr3d: Deleted 3-D Area Reference (Operand, ptg = 3Dh)

This ptg stores a 3-D area reference that was adjusted to #REF! as a result of worksheet editing (such as cutting, pasting, and deleting). The ptgAreaErr3d is identical to ptgArea3d.

Control Tokens

ptgExp: Array Formula or Shared Formula (ptg = 01h)

This ptg indicates an array formula or a shared formula. When ptgExp occurs in a formula, it's the only token in the formula. This indicates that the cell containing the formula is part of an array or part of a shared formula. The actual formula is found in an ARRAY record.

The token value for ptgExp consists of the row and column of the upper-left corner of the array formula.

Offset | Name | Size | Contents
0 | rwFirst | 2 | The row number of the upper-left corner
2 | colFirst | 2 | The column number of the upper-left corner

ptgTbl: Data Table (ptg = 02h)

This ptg indicates a data table. When ptgTbl occurs in a formula, it's the only token in the formula. This indicates that the cell containing the formula is an interior cell in a data table; the table description is found in a TABLE record. Rows and columns that contain input values to be substituted in the table don't contain ptgTbl.

The token value for ptgTbl consists of the row and column of the upper-left corner of the table's interior.

Offset | Name | Size | Contents
0 | rwFirst | 2 | The row number of the upper-left corner
2 | colFirst | 2 | The column number of the upper-left corner

ptgParen: Parenthesis (ptg = 15h)

This ptg is used only when Microsoft Excel unparses a parsed expression (for example, to display it in the formula bar). This ptg isn't used to evaluate parsed expressions. It indicates that the previous token in the parsed expression should be in parentheses. If the previous token is an operand, only that operand is in parentheses. If the previous token is an operator, the operator and all of its operands are in parentheses.

For example, the formula =1+(2) is stored as follows:

ptgInt    0001h
ptgInt    0002h
ptgParen
ptgAdd

In this case, only the integer operand 2 is in parentheses.

The formula =(1+2) is stored as follows:

ptgInt    0001h
ptgInt    0002h
ptgAdd
ptgParen

In this example, the parenthesized quantity consists of the ptgAdd operator and both of its operands.

ptgAttr: Special Attribute (ptg = 19h)

This ptg is used for several different purposes. In all cases, the token value consists of a group of flag bits and a data word.

BIFF3 and BIFF4

Offset | Name | Size | Contents
0 | grbit | 1 | Option flags
1 | w | 2 | Data word

BIFF4 when bifFAttrSpace = 1

Offset | Name | Size | Contents
0 | grbit | 1 | Option flags
1 | bAttrSpace | 1 | Spacing attribute
2 | bSpace | 1 | Number of spaces

The grbit field contains the option flags listed in the following table.

Bits | Mask | Name | Contents
0 | 01h | bitFAttrSemi | = 1 if the formula contains a volatile function
1 | 02h | bitFAttrIf | = 1 to implement an optimized IF function
2 | 04h | bitFAttrChoose | = 1 to implement an optimized CHOOSE function
3 | 08h | bitFAttrGoto | = 1 to jump to another location within the parsed expression
4 | 10h | bitFAttrSum | = 1 to implement an optimized SUM function
5 | 20h | bitFAttrBaxcel | = 1 if the formula is a BASIC-style assignment statement
6 | 40h | bifFAttrSpace | = 1 if the macro formula contains spaces after the equal sign (BIFF3 and BIFF4 only)
7 | 80 | (Unused) |

ptgAttr requires special handling when parsed expressions are scanned. For more information, see Scanning a Parsed Expression.

bitFAttrSemi

Set to 1 if the formula contains a volatile function — that is, a function that's calculated in every recalculation. If ptgAttr is used to indicate a volatile function, it must be the first token in the parsed expression. If grbit = bitFAttrSemi, then the b (or w) field is don't-care.

bitFAttrIf

Indicates an optimized IF function. An IF function contains three parts: a condition, a TRUE subexpression, and a FALSE subexpression. The syntax of an associated Microsoft Excel formula would be IF(condition, TRUE subexpression, FALSE subexpression).

bitFAttrIf immediately follows the condition portion of the parsed expression. The b (or w) field specifies the offset to the FALSE subexpression; the TRUE subexpression is found immediately following the ptgAttr token. At the end of the TRUE subexpression, there's a bitFAttrGoto token that causes a jump to beyond the FALSE subexpression. In this way, Microsoft Excel evaluates only the correct subexpression instead of evaluating both of them and discarding the wrong one.

The FALSE subexpression is optional in Microsoft Excel. If it's missing, the b (or w) field specifies an offset to beyond the TRUE subexpression.

bitFAttrChoose

Indicates an optimized CHOOSE function. The cCases (or wCases) field specifies the number of cases in the CHOOSE function. It's followed by an array of word offsets to those cases. The format of this complex token value is shown in the following table.

Offset | Name | Size | Contents
0 | grbit | 1 | bitFAttrChoose (04h).
1 | wCases | 2 | The number of cases in the CHOOSE function.
3 | rgw | var | A sequence of word offsets to the CHOOSE cases. The number of words in this field is equal to wCases + 1.

bitFAttrGoto

Instructs the expression evaluator to skip part of the parsed expression during evaluation. The b (or w) field specifies the number of bytes (or words) to skip, minus 1.

bitFAttrSum

Indicates an optimized SUM function (a SUM that has a single argument). For example, the sum of the cells in a 3-D reference — which has the formula =SUM(Sheet1:Sheet3!C11) — generates a ptgAttr with bitFAttrSum TRUE. The b (or w) field is don't-care.

bifFAttrSpace

Indicates that a formula (macro sheet or worksheet) contains spaces or carriage returns. Microsoft Excel retains spaces and returns in macro sheet and worksheet formulas (in version 3.0 and earlier, spaces and returns would have been eliminated when the formula was parsed). The bAttrSpace field contains an attribute code, and the bSpace field contains the number of spaces or returns. The attribute codes are listed in the following table.

Attribute | Value
bitFSpace | 00h
bitFEnter | 01h
bitFPreSpace | 02h
bitFPreEnter | 03h
bitFPostSpace | 04h
bitFPostEnter | 05h
bitFPreFmlaSpace | 06h

The bitFSpace and bitFEnter attributes indicate that bSpace contains the number of spaces or returns before the next ptg in the formula.

The bitFPreSpace, bitFPreEnter, bitFPostSpace, and bitFPostEnter attributes occur with a ptgParen. Because one ptgParen represents two matched parentheses, the ptgAttr must encode the position of the space or return if it occurs before either parenthesis. For example, the ptgs that express the worksheet formula = ("spaces" ), which contains four spaces before the opening and closing parentheses, would appear in a formula record as shown in the following table.

Hex dump | Ptg type | Decodes to
17 06 73 70 61 63 65 73 | ptgStr | The string "spaces" (operand)
19 40 02 04 | ptgAttr | Four spaces before the opening parenthesis
19 40 04 04 | ptgAttr | Four spaces after the closing parenthesis
15 | ptgParen | The enclose operand (ptgStr) in parentheses

The bitFPreFmlaSpace attribute provides compatibility with BIFF3, where spaces can occur only after the equal sign (before the formula) in macro formulas. If the spaces in a BIFF5/BIFF7 formula are also acceptable in a BIFF3 formula, Microsoft Excel writes a bitFPreFmlaSpace attribute to indicate as much.

ptgMemNoMem: Incomplete Constant Reference Subexpression (ptg = 28h)

This ptg is closely related to ptgMemArea. It's used to indicate a constant reference subexpression that couldn't be pre-evaluated because of insufficient memory.

The token value consists of the length of the reference subexpression, as shown in the following table.

Offset | Name | Size | Contents
0 | (reserved) | 4 |
4 | cce | 2 | The length of the reference subexpression

ptgMemFunc: Variable Reference Subexpression (ptg = 29h)

This ptg indicates a reference subexpression that doesn't evaluate to a constant reference. Any reference subexpression that contains one or more of the following items will generate a ptgMemFunc.

Subexpression contains | Example
A function | OFFSET(ACTIVE.CELL(),1,1):$C$2
A name | INDEX(first_cell:$D$2,1,1)
An external reference | SALES.XLS!$A$1:SALES.XLS!$C$3

The token value consists of the length of the reference subexpression.

Offset | Name | Size | Contents
0 | cce | 2 | The length of the reference subexpression

ptgMemAreaN: Reference Subexpression Within a Name (ptg = 2Eh)

This ptg contains a constant reference subexpression within a name definition. Unlike ptgMemArea, ptgMemAreaN isn't used to pre-evaluate the reference subexpression.

The token value consists of the length of the reference subexpression.

Offset | Name | Size | Contents
0 | cce | 2 | The length of the reference subexpression

ptgMemNoMemN: Incomplete Reference Subexpression Within a Name (ptg = 2Fh)

This ptg is closely related to ptgMemAreaN. It's used to indicate a constant reference subexpression within a name that couldn't be evaluated because of insufficient memory.

The token value consists of the length of the reference subexpression, as shown in the following table.

Offset | Name | Size | Contents
0 | cce | 2 | The length of the reference subexpression

Function Operators

The following paragraphs describe the function operator ptgs. All of these operators pop arguments from the operand stack, compute a function, and then push the result back onto the operand stack. The number of operands popped from the stack is equal to the number of arguments passed to the Microsoft Excel function. Some Microsoft Excel functions always require a fixed number of arguments, whereas others accept a variable number of arguments. The SUM function, for example, accepts a variable number of arguments.

Although they're operators, function tokens also behave like operands in that they can occur in any of the three ptg classes: reference, value, or array.

ptgFunc: Function, Fixed Number of Arguments (Operator, ptg = 21h)

This ptg indicates a Microsoft Excel function with a fixed number of arguments. The ptgFunc is followed by the index to the function table.

Offset | Name | Size | Contents
0 | iftab | 2 | The index to the function table

ptgFuncVar: Function, Variable Number of Arguments (Operator, ptg = 22h)

This ptg indicates a Microsoft Excel function with a variable number of arguments. The ptgFuncVar is followed by the number of arguments (1 byte) and then the index to the function table (2 bytes).

Offset | Bits | Mask | Name | Contents
0 | 6–0 | 7Fh | cargs | The number of arguments to the function
 | 7 | 80h | fPrompt | = 1, function prompts the user (macro functions that end with a question mark)
1 | 14–0 | 7FFFh | iftab | The index to the function table
 | 15 | 8000h | fCE | The function is a command-equivalent


Microsoft Excel Chart Records

Microsoft Office Technical Documentation Group

Created: November, 1995

This article describes the Microsoft Excel chart BIFF file format. The chart BIFF is combined with other sheet BIFF records into the Book stream of a Microsoft Excel workbook file. This article documents only those records unique to charts; these records have record numbers greater than 1000h. Chart BIFF also uses a few records below this range; for information on those records, see Microsoft Excel File Format.

The chart BIFF usually does not contain a complete description of a Microsoft Excel chart but rather a description of how the chart differs from an internal default chart (the simple column chart). Therefore, many of the records in the chart BIFF modify the default chart description. The internal default chart is not the same as the default chart that you set in the Options dialog box.

Although the information contained in BIFF records varies, every record has the same basic format. For more information about the BIFF record format, see BIFF Record Information.

Chart BIFF Hierarchy

The chart BIFF contains a hierarchical series of records that defines the chart format. Much of the chart data is defined as objects; an object starts with a BEGIN record and ends with a matching END record. For example, a series object definition starts with a SERIES record immediately followed by a BEGIN record. All subsequent records up to the matching END record apply to the specified series.

Objects can be nested within objects; nested BEGIN and END records are used as required to describe objects that are part of other objects. The outer object is called the "parent;" the nested object is called a "child."

The BIFF structure is flexible; it varies depending on the chart type and the elements included in the chart. You can examine the record structure of an existing BIFF file with the BiffView utility.

Series and Categories

All charts, whether in column, bar, line, pie, area, or scatter format, contain series data, category data, and value data. The following column chart explains the difference between series and categories.

When Microsoft Excel creates a chart from a worksheet, it assigns either the worksheet rows as the series data (and the columns as the category data), or the worksheet columns as the series data (and the rows as categories). If there are fewer rows than columns, then the rows become the series. However, if there are fewer columns than rows, then the columns become the series. If there are an equal number of rows and columns in the range of cells, then the rows become the series.

This algorithm minimizes the number of series on the chart. For example, the following column chart . . .

. . . can be created from either of the two following worksheets.

In the second worksheet shown here, January and February are the series (because there are fewer rows than columns), and Chicago, Dallas, and Boston are the categories. In these two worksheets, values for each series appear at three locations on the chart.

If you add sales data for March and April, the series are now Chicago, Dallas, and Boston, and the categories are January, February, March, and April. Microsoft Excel automatically exchanges the series and categories to minimize the number of series.

Chart BIFF Records: Alphabetical Order

Number | Record
103A | 3D: Chart Group Is a 3-D Chart Group
1051 | AI: Linked Data
1050 | ALRUNS: Text Formatting
101A | AREA: Chart Group Is an Area Chart Group
100A | AREAFORMAT: Colors and Patterns for an Area
100C | ATTACHEDLABEL: Series Data/Value Labels
1046 | AXESUSED: Number of Axes Sets
101D | AXIS: Axis Type
1021 | AXISLINEFORMAT: Defines a Line That Spans an Axis
1041 | AXISPARENT: Axis Size and Location
1017 | BAR: Chart Group is a Bar or Column Chart Group
1033 | BEGIN: Defines the Beginning of an Object
1020 | CATSERRANGE: Defines a Category or Series Axis
1002 | CHART: Location and Overall Chart Dimensions
1014 | CHARTFORMAT: Parent Record for Chart Group
1022 | CHARTFORMATLINK: Not Used
101C | CHARTLINE: Drop/Hi-Lo/Series Lines on a Line Chart
1006 | DATAFORMAT: Series and Data Point Numbers
1024 | DEFAULTTEXT: Default Data Label Text Properties
103D | DROPBAR: Defines Drop Bars
1034 | END: Defines the End of an Object
1026 | FONTX: Font Index
1032 | FRAME: Defines Border Shape Around Displayed Text
104E | IFMT: Number-Format Index
1015 | LEGEND: Legend Type and Position
1043 | LEGENDXN: Legend Exception
1018 | LINE: Chart Group Is a Line Chart Group
1007 | LINEFORMAT: Style of a Line or Border
1009 | MARKERFORMAT: Style of a Line Marker
1027 | OBJECTLINK: Attaches Text to Chart or to Chart Item
103C | PICF: Picture Format
1019 | PIE: Chart Group Is a Pie Chart Group
100B | PIEFORMAT: Position of the Pie Slice
1035 | PLOTAREA: Frame Belongs to Plot Area
104F | POS: Position Information
103E | RADAR: Chart Group Is a Radar Chart Group
1040 | RADARAREA: Chart Group Is a Radar Area Chart Group
1048 | SBASEREF: PivotTable Reference
101B | SCATTER: Chart Group Is a Scatter Chart Group
105B | SERAUXERRBAR: Series ErrorBar
104B | SERAUXTREND: Series Trendline
105D | SERFMT: Series Format
1003 | SERIES: Series Definition
1016 | SERIESLIST: Specifies the Series in an Overlay Chart
100D | SERIESTEXT: Legend/Category/Value Text
104A | SERPARENT: Trendline or ErrorBar Series Index
1045 | SERTOCRT: Series Chart-Group Index
1044 | SHTPROPS: Sheet Properties
103F | SURFACE: Chart Group Is a Surface Chart Group
1025 | TEXT: Defines Display of Text Fields
101E | TICK: Tick Marks and Labels Format
1001 | UNITS: Chart Units
101F | VALUERANGE: Defines Value Axis Scale

Chart BIFF Records: Record Number Order

Number | Record
1001 | UNITS: Chart Units
1002 | CHART: Location and Overall Chart Dimensions
1003 | SERIES: Series Definition
1006 | DATAFORMAT: Series and Data Point Numbers
1007 | LINEFORMAT: Style of a Line or Border
1009 | MARKERFORMAT: Style of a Line Marker
100A | AREAFORMAT: Colors and Patterns for an Area
100B | PIEFORMAT: Position of the Pie Slice
100C | ATTACHEDLABEL: Series Data/Value Labels
100D | SERIESTEXT: Legend/Category/Value Text
1014 | CHARTFORMAT: Parent Record for Chart Group
1015 | LEGEND: Legend Type and Position
1016 | SERIESLIST: Specifies the Series in an Overlay Chart
1017 | BAR: Chart Group is a Bar or Column Chart Group
1018 | LINE: Chart Group Is a Line Chart Group
1019 | PIE: Chart Group Is a Pie Chart Group
101A | AREA: Chart Group Is an Area Chart Group
101B | SCATTER: Chart Group Is a Scatter Chart Group
101C | CHARTLINE: Drop/Hi-Lo/Series Lines on a Line Chart
101D | AXIS: Axis Type
101E | TICK: Tick Marks and Labels Format
101F | VALUERANGE: Defines Value Axis Scale
1020 | CATSERRANGE: Defines a Category or Series Axis
1021 | AXISLINEFORMAT: Defines a Line That Spans an Axis
1022 | CHARTFORMATLINK: Not Used
1024 | DEFAULTTEXT: Default Data Label Text Properties
1025 | TEXT: Defines Display of Text Fields
1026 | FONTX: Font Index
1027 | OBJECTLINK: Attaches Text to Chart or to Chart Item
1032 | FRAME: Defines Border Shape Around Displayed Text
1033 | BEGIN: Defines the Beginning of an Object
1034 | END: Defines the End of an Object
1035 | PLOTAREA: Frame Belongs to Plot Area
103A | 3D: Chart Group Is a 3-D Chart Group
103C | PICF: Picture Format
103D | DROPBAR: Defines Drop Bars
103E | RADAR: Chart Group Is a Radar Chart Group
103F | SURFACE: Chart Group Is a Surface Chart Group
1040 | RADARAREA: Chart Group Is a Radar Area Chart Group
1041 | AXISPARENT: Axis Size and Location
1043 | LEGENDXN: Legend Exception
1044 | SHTPROPS: Sheet Properties
1045 | SERTOCRT: Series Chart-Group Index
1046 | AXESUSED: Number of Axes Sets
1048 | SBASEREF: PivotTable Reference
104A | SERPARENT: Trendline or ErrorBar Series Index
104B | SERAUXTREND: Series Trendline
104E | IFMT: Number-Format Index
104F | POS: Position Information
1050 | ALRUNS: Text Formatting
1051 | AI: Linked Data
105B | SERAUXERRBAR: Series ErrorBar
105D | SERFMT: Series Format

Record Descriptions

The first two fields in every BIFF record are record number and record length. Because these fields have the same offset and size in every BIFF record, they are not documented in the following descriptions. For more information about the record number and record length fields, see BIFF Record Information.

3D: Chart Group Is a 3-D Chart Group (103Ah)

This record defines a 3-D chart group and also contains generic formatting information.

Record Data

Offset | Name | Size | Contents
4 | anRot | 2 | Rotation angle (0 to 360 degrees)
6 | anElev | 2 | Elevation angle (–90 to +90 degrees)
8 | pcDist | 2 | Distance from eye to chart (0 to 100)
10 | pcHeight | 2 | Height of plot volume relative to width and depth
12 | pcDepth | 2 | Depth of points relative to width
14 | pcGap | 2 | Space between series
16 | grbit | 2 | Option flags

The grbit field contains the following option flags.

Offset | Bits | Mask | Name | Contents
0 | 0 | 01h | fPerspective | 1 = use perspective transform
0 | 1 | 02h | fCluster | 1 = 3-D columns are clustered or stacked
0 | 2 | 04h | f3DScaling | 1 = use auto scaling
0 | 3 | 08h | (reserved) | Reserved; must be zero
0 | 4 | 10h | (reserved) | Reserved; must be one
0 | 5 | 20h | f2DWalls | use 2D walls and gridlines
0 | 7–2 | FAh | (reserved) | Reserved; must be zero
1 | 7–0 | FFh | (reserved) | Reserved; must be zero

AI: Linked Data (1051h)

This record specifies linked series data or text.

Record Data

Offset | Name | Size | Contents
4 | id | 1 | Link index identifier 0 = linking a series title or text 1 = linking series values 2 = linking series categories
5 | rt | 1 | Reference type 0 = use default categories 1 = text or value entered directly into the formula bar 2 = linked to worksheet 3 = not used 4 = error reported
6 | grbit | 2 | Flags
8 | ifmt | 2 | Index to number format record
10 | cce | 2 | Size of rgce (in bytes)
12 | rgce | var | Parsed formula of link

The grbit field contains the following option flags.

Offset | Bits | Mask | Name | Contents
0 | 0 | 01h | fCustomIfmt | TRUE if this object has a custom number format; FALSE if number format is linked to data source
0 | 1 | 02h | (reserved) | Reserved; must be zero
0 | 5-2 | 3Ch | st | Source type (always zero)
0 | 7-6 | C0h | (reserved) | Reserved; must be zero
1 | 7-0 | FFh | (reserved) | Reserved; must be zero

ALRUNS: Text Formatting (1050h)

This record specifies rich-text formatting (bold, italic, font changes, etc.) within chart titles and data labels.

Record Data

Offset | Name | Size | Contents
4 | cRuns | 2 | Number of rich-text runs
6 | rgwRuns | var | Array of cRuns four-byte groups. The first two bytes in each group specifies the first character in the rich-text run. The second two bytes specifies the font index for the text run (see the FONT record for more information about this index).

AREA: Chart Group Is an Area Chart Group (101Ah)

This record defines an area chart group.

Record Data

Offset | Name | Size | Contents
4 | grbit | 2 | format flags

The grbit field contains the following option flags.

Offset | Bits | Mask | Name | Contents
0 | 0 | 01h | fStacked | Series in this group are stacked
0 | 1 | 02h | f100 | Each category is broken down as a percentage
0 | 7–2 | FCh | (reserved) | Reserved; must be zero
1 | 7–0 | FFh | (reserved) | Reserved; must be zero

When fStacked is true, the value indicators (filled areas) are stacked one on top of the next. The f100 bit can be set only when the fStacked bit is set and indicates that each category is broken down into percentages.

AREAFORMAT: Colors and Patterns for an Area (100Ah)

This record describes the patterns and colors used in a filled area.

Record Data

Offset | Name | Size | Contents
4 | rgbFore | 4 | Foreground color: RGB value (high byte = 0)
8 | rgbBack | 4 | Background color: RGB value (high byte = 0)
12 | fls | 2 | Pattern
14 | grbit | 2 | Format flags

The grbit field contains the following option flags.

Offset | Bits | Mask | Name | Contents
0 | 0 | 01h | fAuto | Automatic format
0 | 1 | 02h | fInvertNeg | Foreground and background are swapped when the data value is negative
0 | 7–2 | FCh | (reserved) | Reserved; must be zero
1 | 7–0 | FFh | (reserved) | Reserved; must be zero

ATTACHEDLABEL: Series Data/Value Labels (100Ch)

The ATTACHEDLABEL record defines the data label type. The ATTACHEDLABEL record applies to the label data identified in the associated DATAFORMAT record.

Record Data

Offset | Name | Size | Contents
4 | grbit | 2 | Value label flags

The grbit field contains the following option flags.

Offset | Bits | Mask | Name | Contents
0 | 0 | 01h | fShowValue | 1 = show the actual value of the data point
0 | 1 | 02h | fShowPercent | 1 = show value as a percent of the total. This bit applies only to pie charts
0 | 2 | 04h | fShowLabPct | 1 = show category label and value as a percentage (pie charts only). Should be 1 if fShowLabel and fShowPerecent are both 1.
0 | 3 | 08h | (reserved) | Reserved; must be zero
0 | 4 | 10h | fShowLabel | 1 = show category label
0 | 7-5 | E0h | (reserved) | Reserved; must be zero
1 | 7–0 | FFh | (reserved) | Reserved; must be zero

AXESUSED: Number of Axes Sets (1046h)

This record specifies the number of axes sets (1 = primary only, 2 = primary and secondary) used on the chart (3-D charts can only have primary axes).

Record Data

Offset | Name | Size | Contents
4 | cAxes | 2 | Number of axes sets

AXIS: Axis Type (101Dh)

This record defines the axis type.

Record Data

Offset | Name | Size | Contents
4 | wType | 2 | Axis type 0 = category axis or x axis on a scatter chart 1 = value axis 2 = series axis
6 | (reserved) | 16 | Reserved; must be zero

AXISLINEFORMAT: Defines a Line That Spans an Axis (1021h)

This record usually follows an AXIS record to define the axis line as it appears on the chart.

Record Data

Offset | Name | Size | Contents
4 | id | 2 | Axis line identifier: 0 = the axis line itself 1 = major grid line along the axis 2 = minor grid line along the axis 3 = walls or floor -- walls if parent axis is type 0 or 2; floor if parent axis is type 1

AXISPARENT: Axis Size and Location (1041h)

This record specifies the location and size of the chart axes, in units of 1/4000 of the chart area.

Record Data

Offset | Name | Size | Contents
4 | iax | 2 | Axis index (0 = main, 1 = secondary)
6 | x | 4 | x coordinate of top left corner
10 | y | 4 | y coordinate of top left corner
14 | dx | 4 | length of x axis
18 | dy | 4 | length of y axis

BAR: Chart Group is a Bar or Column Chart Group (1017h)

This record defines a bar or column chart group.

Record Data

Offset | Name | Size | Contents
4 | pcOverlap | 2 | Space between bars (percent of bar width), default = 0
6 | pcGap | 2 | Space between categories (percent of bar width), default = 50
8 | grbit | 2 | Format flags

The grbit field contains the bar chart display attributes as follows.

Offset | Bits | Mask | Name | Contents
0 | 0 | 01h | fTranspose | 1 = horizontal bars (bar chart) 0 = vertical bars (column chart)
0 | 1 | 02h | fStacked | Stack the displayed values
0 | 2 | 04h | f100 | Each category is displayed as a percentage
0 | 7–3 | FCh | (reserved) | Reserved; must be zero
1 | 7–0 | FFh | (reserved) | Reserved; must be zero

When fStacked is true, the bars or columns within a category are stacked one on top of the next. The f100 bit can be set only when the fStacked bit is set, and indicates that each category is broken down into percentages.

BEGIN: Defines the Beginning of an Object (1033h)

The BEGIN record is a fixed length 4-byte record that indicates the beginning of a block of records that forms a data object. Every BEGIN record must have a corresponding END record. The BEGIN record consists of 10330000h.

CATSERRANGE: Defines a Category or Series Axis (1020h)

This record defines the scaling options for a category or series axis.

Record Data

Offset | Name | Size | Contents
4 | catCross | 2 | Value axis/category crossing point (2-D charts only)
6 | catLabel | 2 | Frequency of labels
8 | catMark | 2 | Frequency of tick marks
10 | grbit | 2 | Format flags

The catCross field defines the point on the category axis where the value axis crosses. A value of 01 indicates that the value axis crosses to the left, or in the center, of the first category (depending on the value of bit 0 of the grbit field); a value of 02 indicates that the value axis crosses to the left or center of the second category, and so on. Bit 2 of the grbit field overrides the value of catCross when set to 1.

The catLabel field defines how often labels appear along the category or series axis. A value of 01 indicates that a category label will appear with each category, a value of 02 means a label appears every other category, and so on.

The catMark field defines how often tick marks appear along the category or series axis. A value of 01 indicates that a tick mark will appear between each category or series; a value of 02 means a label appears between every other category or series, etc.

The grbit field contains the following option flags.

Offset | Bits | Mask | Name | Contents
0 | 0 | 01h | fBetween | Value axis crossing 0 = axis crosses mid-category 1 = axis crosses between categories
0 | 1 | 02h | fMaxCross | Value axis crosses at the far right category (in a line, bar, column, scatter, or area chart; 2-D charts only)
0 | 2 | 04h | fReverse | Display categories in reverse order
0 | 7–3 | F8h | (reserved) | Reserved; must be zero
1 | 7–0 | FFh | (reserved) | Reserved; must be zero

CHART: Location and Overall Chart Dimensions (1002h)

The CHART record marks the start of the chart data substream in the workbook BIFF stream. This record defines the location of the chart on the display and its overall size. The x and y fields define the position of the upper-left corner of the bounding rectangle that encompasses the chart. The position of the chart is referenced to the page.

The dx and dy fields define the overall size (the bounding rectangle) of the chart, including title, pointing arrows, axis labels, etc.

The position and size are specified in points (1/72 inch), using a fixed point format (two bytes integer, two bytes fraction).

Record Data

Offset | Name | Size | Contents
4 | x | 4 | x-position of upper-left corner
8 | y | 4 | y-position of upper-left corner
12 | dx | 4 | x-size
16 | dy | 4 | y-size

CHARTFORMAT: Parent Record for Chart Group (1014h)

This record is the parent record for the chart group format description. Each chart group will have a separate CHARTFORMAT record; followed by a BEGIN record, the chart-group description, and an END record.

Record Data

Offset | Name | Size | Contents
4 | (reserved) | 16 | Reserved; must be zero
20 | grbit | 2 | Format flags
22 | icrt | 2 | Drawing order (0 = bottom of the z-order)

The grbit field contains the following option flags.

Offset | Bits | Mask | Name | Contents
0 | 0 | 01h | fVaried | Vary color for each data point
0 | 7–1 | FEh | (reserved) | Reserved; must be zero
1 | 7–0 | FFh | (reserved) | Reserved; must be zero

CHARTFORMATLINK: Not Used (1022h)

This record is written by Microsoft Excel, but it is ignored. Applications writing chart BIFF do not need to write this record, and applications reading chart BIFF can ignore it.

CHARTLINE: Specifies Drop/Hi-Lo/Series Lines on a Line Chart (101Ch)

This record specifies drop lines, hi-lo lines, or series lines on a line chart. If the chart has both drop lines and hi-lo lines, two CHARTLINE records will be present.

Record Data

Offset | Name | Size | Contents
4 | id | 2 | Drop lines/hi-lo lines 0 = drop lines 1 = hi-lo lines 2 = series lines (the lines that connect the columns in a stacked column chart)

DATAFORMAT: Series and Data Point Numbers (1006h)

The DATAFORMAT record contains the zero-based numbers of the data point and series. The subordinate records determine the format of the series or point defined by the DATAFORMAT record.

Record Data

Offset | Name | Size | Contents
4 | xi | 2 | Point number (FFFFh means entire series)
6 | yi | 2 | Series index (file relative)
8 | iss | 2 | Series number (as shown in name box -- S1, S2, etc.). This can be different from yi if the series order has been changed.
10 | grbit | 2 | format flags

The grbit field contains the following flags.

Offset | Bits | Mask | Name | Contents
0 | 0 | 01h | fXL4iss | 1 = use Microsoft Excel 4.0 colors for automatic formatting
0 | 7–1 | FEh | (reserved) | Reserved; must be zero
1 | 7–0 | FFh | (reserved) | Reserved; must be zero

DEFAULTTEXT: Default Data Label Text Properties (1024h)

The DEFAULTTEXT record precedes a TEXT record to identify the text defined in the TEXT record as the default properties for certain chart items.

Record Data

Offset | Name | Size | Contents
4 | id | 2 | Object identifier for the text 0 = default text characteristics for "show labels" data labels 1 = default text characteristics for value and percentage data labels 2 = default text characteristics for all text in the chart

DROPBAR: Defines Drop Bars (103Dh)

This record defines drop bars on a line chart. If the chart contains drop bars, the chart BIFF will contain two DROPBAR records. The first DROPBAR record corresponds to the up bar and the second DROPBAR record corresponds to the down bar.

Record Data

Offset | Name | Size | Contents
4 | pcGap | 2 | Drop bar gap width (0 to 100%)

END: Defines the End of an Object (1034h)

This record is a fixed-length 4-byte record that indicates the end of a data object. Every END record has a corresponding BEGIN record. The END record consists of 10340000h.

FONTX: Font Index (1026h)

This record is the child of a TEXT record and defines a text font by indexing the appropriate font in the font table. The font table is built from FONT records.

Record Data

Offset | Name | Size | Contents
4 | ifont | 2 | Index number into the font table

FRAME: Defines Border Shape Around Displayed Text (1032h)

The FRAME record defines the border that is present around a displayed label as a rectangle. A displayed label can include the chart title, the legend (if not a regular rectangle), a category name, or a value amount.

Record Data

Offset | Name | Size | Contents
4 | frt | 2 | 0 = regular rectangle/no border 1–3 (reserved) 4 = rectangle with shadow
6 | grbit | 2 | Flags

The frt field defines the format of the frame border, that is, a rectangle or a rectangle with a shadow along two sides. (The format of the rectangle line and the pattern of the background within the rectangle are defined by the subordinate LINEFORMAT and AREAFORMAT records.)

The grbit field contains the following option flags.

Offset | Bits | Mask | Name | Contents
0 | 0 | 01h | fAutoSize | Microsoft Excel calculates size
0 | 1 | 02h | fAutoPosition | Microsoft Excel calculates position
0 | 7–2 | FCh | (reserved) | Reserved; must be zero
1 | 7–0 | FFh | (reserved) | Reserved; must be zero

The fAutoSize field indicates that the size of the frame is to be calculated by Microsoft Excel. The dx and dy fields in the parent record are ignored.

The fAutoPosition field indicates that the position of the frame is to be calculated by Microsoft Excel. The dx and dy fields in the parent record are ignored.

IFMT: Number-Format Index (104Eh)

This record specifies the number-format index for an axis.

Record Data

Offset | Name | Size | Contents
4 | ifmt | 2 | Number-format index (number of the FORMAT record in the BIFF, begins at zero)

LEGEND: Legend Type and Position (1015h)

The LEGEND record defines the location of the legend on the display and its overall size. The displayed legend contains all series on the chart.

Record Data

Offset | Name | Size | Contents
4 | x | 4 | x-position of upper-left corner
8 | y | 4 | y-position of upper-left corner
12 | dx | 4 | x-size
16 | dy | 4 | y-size
20 | wType | 1 | Type 0 = bottom 1 = corner 2 = top 3 = right 4 = left 7 = not docked or inside the plot area
21 | wSpacing | 1 | Spacing 0 = close 1 = medium 2 = open
22 | grbit | 2 | Option flags

The x, y, dx, and dy fields are in units of 1/4000 of the chart area.

The x and y fields define the position of the upper-left corner of the bounding rectangle that encompasses the legend. The position of the legend is referenced to the document window. The dx and dy fields define the overall size (the bounding rectangle) of the legend.

The wType field defines the location of the legend relative to the plot rectangle of the chart. The wSpacing field is always 1 for Microsoft Excel.

The grbit field contains the following option flags.

Offset | Bits | Mask | Name | Contents
0 | 0 | 01h | fAutoPosition | Automatic positioning (1 = legend is docked)
0 | 1 | 02h | fAutoSeries | Automatic series distribution (TRUE in Microsoft Excel 5.0)
0 | 2 | 04h | fAutoPosX | X positioning is automatic
0 | 3 | 08h | fAutoPosY | Y positioning is automatic
0 | 4 | 10h | fVert | 1 = vertical legend (a single column of entries) 0 = horizontal legend (multiple columns of entries) Manual sized legends always have this bit set to zero
0 | 7–5 | E0h | (reserved) | Reserved; must be zero
1 | 7–0 | FFh | (reserved) | Reserved; must be zero

LEGENDXN: Legend Exception (1043h)

This record specifies information about a legend entry which has been changed from the default legend-entry settings.

Record Data

Offset | Name | Size | Contents
4 | iss | 2 | Legend-entry index
6 | grbit | 2 | Flags

The grbit field contains the following option flags.

Offset | Bits | Mask | Name | Contents
0 | 0 | 01h | fDeleted | TRUE if the legend entry has been deleted
0 | 1 | 02h | fLabel | TRUE if the legend entry has been formatted
0 | 7-2 | FCh | (reserved) | Reserved; must be zero
1 | 7–0 | FFh | (reserved) | Reserved; must be zero

Microsoft Excel uses three legend types. On a chart where the legend lists the series names, the iss field will contain FFFF. On a single-series chart formatted to vary by category (a pie chart or column autoformat number two, for example), the legend lists the categories and the iss field contains the category number. On a surface chart, the legend lists data ranges, and the iss field contains the legend-entry number, starting at zero for the bottom range.

LINE: Chart Group Is a Line Chart Group (1018h)

This record defines a line chart group.

Record Data

Offset | Name | Size | Contents
4 | grbit | 2 | format flags

The grbit field contains the following option flags.

Offset | Bits | Mask | Name | Contents
0 | 0 | 01h | fStacked | Stack the displayed values
0 | 1 | 02h | f100 | Each category is broken down as a percentage
0 | 7–2 | FCh | (reserved) | Reserved; must be zero
1 | 7–0 | FFh | (reserved) | Reserved; must be zero

When fStacked is true, the value indicators within a category are stacked one on top of the next. The f100 bit can be set only when the fStacked bit is set, and indicates that each category is broken down into percentages.

LINEFORMAT: Style of a Line or Border (1007h)

This record defines the appearance of a line, such as an axis line or border.

Record Data

Offset | Name | Size | Contents
4 | rgb | 4 | Color of line; RGB value high byte must be set to zero
8 | lns | 2 | Pattern of line 0 = solid 1 = dash 2 = dot 3 = dash-dot 4 = dash dot-dot 5 = none 6 = dark gray pattern 7 = medium gray pattern 8 = light gray pattern
10 | we | 2 | Weight of line –1 = hairline 0 = narrow (single) 1 = medium (double) 2 = wide (triple)
12 | grbit | 2 | Format flags

The grbit field contains the following option flags.

Offset | Bits | Mask | Name | Contents
0 | 0 | 01h | fAuto | Automatic format
0 | 1 | 02h | (reserved) | Reserved; must be zero
0 | 2 | 04h | fDrawTick | 1 = draw tick labels on this axis
0 | 7–3 | F8h | (reserved) | Reserved; must be zero
1 | 7–0 | FFh | (reserved) | Reserved; must be zero

MARKERFORMAT: Style of a Line Marker (1009h)

This record defines the color and shape of the line markers that appear on scatter and line charts.

Record Data

Offset | Name | Size | Contents
4 | rgbFore | 4 | Foreground color: RGB value (high byte = 0)
8 | rgbBack | 4 | Background color: RGB value (high byte = 0)
12 | imk | 2 | Type of marker 0 = no marker 1 = square 2 = diamond 3 = triangle 4 = X 5 = star 6 = Dow-Jones 7 = standard deviation 8 = circle 9 = plus sign
14 | grbit | 2 | Format flags

The rgbBack field describes the color of the marker's background, such as the center of the square, while the rgbFore field describes the color of the border or the marker itself. The imk field defines the type of marker.

The grbit field contains the following option flags.

Offset | Bits | Mask | Name | Contents
0 | 0 | 01h | fAuto | Automatic color
0 | 3-1 | 0Eh | (reserved) | Reserved; must be zero
0 | 4 | 10h | fNotShowInt | 1 = "background = none"
0 | 5 | 20h | fNotShowBrd | 1 = "foreground = none"
0 | 7-6 | C0h | (reserved) | Reserved; must be zero
1 | 7-0 | FFh | (reserved) | Reserved; must be zero

OBJECTLINK: Attaches Text to Chart or to Chart Item (1027h)

This record links a TEXT record to an object on the chart or to the entire chart.

Record Data

Offset | Name | Size | Contents
4 | wLinkObj | 2 | Object text is linked to 1 = entire chart (chart title) 2 = y axis (y axis title) 3 = x axis (x axis title) 4 = data series or data point (data label) 5 not used 6 not used 7 = z axis (z axis title)
6 | wLinkVar1 | 2 | Link index 1, series number
8 | wLinkVar2 | 2 | Link index 2, data point number

The wLinkObj field specifies which object the text is linked to. The wLinkVar1 and wLinkVar2 fields define the linked object as a specific series number and data point in the series. The wLinkVar1 and wLinkVar2 fields have meaning only if the wLinkObj field equals 4.

PICF: Picture Format (103Ch)

This record defines the format for a picture attached to a data series or point.

Record Data

Offset | Name | Size | Contents
4 | ptyp | 2 | Picture type: = 1, stretched = 2, stacked = 3, stacked and scaled
6 | cf | 2 | Image format: = 2, Windows metafile or Macintosh PICT format = 9, Windows bitmap format
8 | grbit | 2 | Option flags
10 | numScale | 8 | Scaling value for pictures, units/picture (IEEE floating-point number)

The grbit field contains the following option flags.

Offset | Bits | Mask | Name | Contents
0 | 7–0 | FFh | env | Environment from which the file was written: = 1, Microsoft Windows = 2, Apple Macintosh
1 | 0 | 01h | fFmtOnly | Formatting only; no picture attached
1 | 7–1 | FEh | (reserved) | Reserved; must be zero

If fFmtOnly is false, then an IMDATA record, which contains the picture itself, follows the PICF record. If fFmtOnly is true, which occurs only if the parent DATAFORMAT record refers to a single data point, then there is no IMDATA record following the PICF record. In this case, the picture specified for the entire series is used, with formatting specified by the PICF record. For more information about the IMDATA record, see IMDATA.

PIE: Chart Group Is a Pie Chart Group (1019h)

This record defines a pie chart group and also specifies the angle of the first slice in the pie.

Record Data

Offset | Name | Size | Contents
4 | anStart | 2 | Angle of the first pie slice expressed in degrees
6 | pcDonut | 2 | 0 = true pie chart non-zero = size of center hole in a donut chart (as a percentage)

The angle of the pie slice has a default value of zero and can be any value in the range of 0 to 359 (0000h to 0167h).

PIEFORMAT: Position of the Pie Slice (100Bh)

The distance of an open pie slice from the center of the pie chart is expressed as a percentage of the pie diameter. For example, if the percent = 33 (21h), the pie slice is one-third of the pie diameter away from the pie center.

Record Data

Offset | Name | Size | Contents
4 | percent | 2 | Distance of pie slice from center of pie

PLOTAREA: Frame Belongs to Plot Area (1035h)

This record immediately precedes a FRAME record. It indicates that the frame record that follows belongs to the plot area.

POS: Position Information (104Fh)

This record defines manual position information for the main-axis plot area, legend, and attached text (data labels, axis labels, and chart title). The record data depends on the record's use, as shown in the following sections.

This record is used very rarely and is usually not required; for most applications, the default size and position settings are sufficient. If your application writes chart BIFF, use the default settings whenever possible. To use the default plot area, set the fManPlotArea bit in the SHTPROPS record. To use a default legend position and size, set the fAutoPosition bit in the LEGEND record, and set the fAutoSize bit in the legend FRAME record. No other settings are required to use the default position for text (data labels, axis labels, and chart title).

Plot Area

The POS record is used only for the main axis. The record describes the plot-area bounding box (the plot-area bounding box includes the plot area, tick marks, and a small border around the tick marks). The fManPlotArea bit in the SHTPROPS record must be 1, or the POS record is ignored.

The top-left position, width, and height fields use units of 1/4000 of the chart area.

Record Data

Offset | Name | Size | Contents
4 | mdTopLt | 2 | Must be 2
6 | mdBotRt | 2 | Must be 2
8 | x1 | 4 | x coordinate of bounding box top left corner
12 | y1 | 4 | y coordinate of bounding box top left corner
16 | x2 | 4 | width of the bounding box
20 | y2 | 4 | height of the bounding box

Legend

The POS record describes the legend position and size.

Record Data

Offset | Name | Size | Contents
4 | mdTopLt | 2 | Must be 5
6 | mdBotRt | 2 | 1 = use x2 and y2 for legend size 2 = autosize legend (ignore x2, y2). The fAutoSize bit of the legend FRAME record should be 1 if this field is 2.
8 | x1 | 4 | x coordinate of legend top left corner, in units of 1/4000 of the chart area
12 | y1 | 4 | y coordinate of legend top left corner, in units of 1/4000 of the chart area
16 | x2 | 4 | width of the legend, in points (1/72 inch)
20 | y2 | 4 | height of the legend, in points

Text (Chart Title)

The POS record sets the chart title position as an offset from the default position, in units of 1/4000 of the chart area.

Record Data

Offset | Name | Size | Contents
4 | mdTopLt | 2 | Must be 2
6 | mdTopRt | 2 | Must be 2
8 | x1 | 4 | offset from default horizontal position
12 | y1 | 4 | offset from default vertical position
16 | x2 | 4 | ignored (you cannot size the chart title)
20 | y2 | 4 | ignored

Text (Axis Title)

The POS record sets the axis title position as an offset from the default position.

Record Data

Offset | Name | Size | Contents
4 | mdTopLt | 2 | Must be 2
6 | mdTopRt | 2 | Must be 2
8 | x1 | 4 | offset perpendicular to the axis, in units of 1/1000 of the plot-area bounding box
12 | y1 | 4 | offset parallel to the axis, in units of 1/1000 of the axis length
16 | x2 | 4 | ignored (you cannot size the axis title)
20 | y2 | 4 | ignored

Text (Data Labels)

The POS record sets the label position as an offset from the default position.

Record Data

Offset | Name | Size | Contents
4 | mdTopLt | 2 | Must be 2
6 | mdTopRt | 2 | Must be 2
8 | x1 | 4 | Pie charts: offset angle from the default, in radians. Bar and Column charts: offset perpendicular to the bar or column, in units of 1/1000 of the plot area All other chart types: horizontal offset from the default position, in units of 1/1000 of the plot area
12 | y1 | 4 | Pie charts: radial offset, in units of 1/1000 of the pie radius. Bar and Column charts: offset parallel to the bar or column, in units of 1/1000 of the plot area All other chart types: vertical offset from the default position, in units of 1/1000 of the plot area
16 | x2 | 4 | ignored (you cannot size the data label)
20 | y2 | 4 | ignored

RADAR: Chart Group Is a Radar Chart Group (103Eh)

This record defines a radar chart group.

Record Data

Offset | Name | Size | Contents
4 | grbit | 2 | Option flags

The grbit field contains the following option flags.

Offset | Bits | Mask | Name | Contents
0 | 0 | 01h | fRdrAxLab | = 1, chart contains radar axis labels
0 | 7–1 | FEh | (reserved) | Reserved; must be zero
1 | 7–0 | FFh | (reserved) | Reserved; must be zero

RADARAREA: Chart Group Is a Radar Area Chart Group (1040h)

This record defines a radar area chart group.

Record Data

Offset | Name | Size | Contents
4 | grbit | 2 | Option flags

The grbit field contains the following option flags.

Offset | Bits | Mask | Name | Contents
0 | 0 | 01h | fRdrAxLab | 1 if chart contains radar axis labels
0 | 7–1 | FEh | (reserved) | Reserved; must be zero
1 | 7–0 | FFh | (reserved) | Reserved; must be zero

SBASEREF: PivotTable Reference (1048h)

This record specifies the PivotTable reference used for the chart.

Record Data

Offset | Name | Size | Contents
4 | rwFirst | 2 | First PivotTable row
6 | rwLast | 2 | Last PivotTable row
8 | colFirst | 2 | First PivotTable column
10 | colLast | 2 | Last PivotTable column

SCATTER: Chart Group Is a Scatter Chart Group (101Bh)

This record has no record data field. If the SCATTER record is present in the Chart BIFF, it signifies that the chart group is an XY (scatter) chart group.

SERAUXERRBAR: Series ErrorBar (105Bh)

This record defines series error bars.

Record Data

Offset | Name | Size | Contents
4 | sertm | 1 | Error-bar type: 1 = x-direction plus 2 = x-direction minus 3 = y-direction plus 4 = y-direction minus
5 | ebsrc | 1 | Error-bar value source: 1 = percentage 2 = fixed value 3 = standard deviation 4 = custom 5 = standard error
6 | fTeeTop | 1 | TRUE if the error bars are T-shaped (have a line on the top and bottom)
7 | (reserved) | 1 | Reserved; must be 1
8 | numValue | 8 | IEEE number; specifies the fixed value, percentage, or number of standard deviations for the error bars
16 | cnum | 2 | Number of values or cell references used for custom error bars

SERAUXTREND: Series Trendline (104Bh)

This record defines a series trendline.

Record Data

Offset | Name | Size | Contents
4 | regt | 1 | Regression type: 0 = polynomial 1 = exponential 2 = Logarithmic 3 = Power 4 = moving average (a linear trendline has type 0 with order 1)
5 | ordUser | 1 | Polynomial order or moving average period
6 | numIntercept | 8 | IEEE number; specifies forced intercept (#NA if no intercept is specified)
14 | fEquation | 1 | TRUE if the equation is displayed
15 | fRSquared | 1 | TRUE if the R-squared value is displayed
16 | numForecast | 8 | IEEE number; specifies number of periods to forecast forward
24 | numBackcast | 8 | IEEE number; specifies number of periods to forecast backward

SERFMT: Series Format (105Dh)

This record specifies series formatting information.

Record Data

Offset | Name | Size | Contents
0 | grbit | 2 | flags

The grbit field contains the following option flags.

Offset | Bits | Mask | Name | Contents
0 | 0 | 01h | fSmoothedLine | TRUE if the line series has a smoothed line
0 | 7-1 | FEh | (reserved) | Reserved; must be zero
1 | 7-0 | FFh | (reserved) | Reserved; must be zero

SERIES: Series Definition (1003h)

This record describes the series of the chart, and contains the type of data and number of data fields that make up the series. Series can contain 4000 points in Microsoft Excel version 5.

The sdtX and sdtY fields define the type of data that is contained in this series. At present, the two types of data used in Microsoft Excel chart series are numeric and text (date and sequence information is not used). The cValx and cValy fields contain the number of cell records in the series.

Record Data

Offset | Name | Size | Contents
4 | sdtX | 2 | Type of data in categories 0 = categories contain date information (not used) 1 = categories contain numeric information 2 = categories contain sequence information (not used) 3 = categories contain text information
8 | sdtY | 2 | Type of data in values 0 = values contain date information (not used) 1 = values contain numeric information 2 = values contain sequence information (not used) 3 = values contain text information
10 | cValx | 2 | Count of categories
12 | cValy | 2 | Count of values

SERIESLIST: Specifies the Series in an Overlay Chart (1016h)

This record is subordinate to the second CHARTFORMAT (overlay) record in a file and defines the series that are displayed as the overlay to the main chart. The first CHARTFORMAT (main chart) record in a file does not require a SERIESLIST record because all series, except those specified for the overlay, are included in the main chart.

Record Data

Offset | Name | Size | Contents
4 | cser | 2 | Count of series (size of rgiser)
6 | rgiser | var | List of series numbers (words)

SERIESTEXT: Legend/Category/Value Text (100Dh)

The value of the id field determines the assignment of the text field.

Record Data

Offset | Name | Size | Contents
4 | id | 2 | Text identifier: 0 = series name or text
6 | cch | 1 | Length of text field
7 | rgch | var | The series text string

Values greater than zero in the id field do not apply to Microsoft Excel.

SERPARENT: Trendline or ErrorBar Series Index (104Ah)

This record indicates the series index for the series that the trendline or error bar is attached to. The series index is the number of the series in the BIFF (starting with series one).

Record Data

Offset | Name | Size | Contents
4 | series | 2 | Series index for the series that the trendline or error bar is attached to

SERTOCRT: Series Chart-Group Index (1045h)

This record is part of the series specifications and indicates the chart-group index for the series. The chart-group index specifies the number of the chart group (specified by a CHARTFORMAT record) in the BIFF, starting with chart group zero.

Record Data

Offset | Name | Size | Contents
0 | chartgroup | 2 | Chart-group index

SHTPROPS: Sheet Properties (1044h)

This record specifies chart sheet properties.

Record Data

Offset | Name | Size | Contents
4 | grbit | 2 | Property flags
6 | mdBlank | 1 | Empty cells plotted as: 0 = not plotted 1 = zero 2 = interpolated

The grbit field contains the following option flags.

Offset | Bits | Mask | Name | Contents
0 | 0 | 01h | fManSerAlloc | 1 = chart type has been manually formatted (changed from the default)
0 | 1 | 02h | fPlotVisOnly | 1 = plot visible cells only
0 | 2 | 04h | fNotSizeWith | 1 = do not size chart with window
0 | 3 | 08h | fManPlotArea | 0 = use default plot area dimensions 1 = POS record describes plot-area dimensions
0 | 7-4 | F0h | (reserved) | Reserved; must be zero
1 | 7-0 | FFh | (reserved) | Reserved; must be zero

SURFACE: Chart Group Is a Surface Chart Group (103Fh)

This record defines a surface chart group.

Record Data

Offset | Name | Size | Contents
4 | grbit | 2 | Option flags

The grbit field contains the following option flags.

Offset | Bits | Mask | Name | Contents
0 | 0 | 01h | fFillSurface | = 1, chart contains color fill for surface
0 | 7–1 | FEh | (reserved) | Reserved; must be zero
1 | 7–0 | FFh | (reserved) | Reserved; must be zero

TEXT: Defines Display of Text Fields (1025h)

This record is used in conjunction with several child records (which further define the text displayed on the chart) to define the alignment, color, position, size, and so on, of text fields that appear on the chart. The fields in this record have meaning according to the TEXT record's parent (CHART, LEGEND, or DEFAULTTEXT).

Record Data

Offset | Name | Size | Contents
4 | at | 1 | Horizontal alignment of the text (1 = left, 2 = center, 3 = bottom, 4 = justify)
5 | vat | 1 | Vertical alignment of the text (1 = top, 2 = center, 3 = bottom, 4 = justify)
6 | wBkgMode | 2 | Display mode of the background 1 = transparent 2 = opaque
8 | rgbText | 4 | Color of the text; RGB value (high byte = 0)
12 | x | 4 | x-position of the text in 1/4000 of chart area
16 | y | 4 | y-position of the text in 1/4000 of chart area
20 | dx | 4 | x-size of the text in 1/4000 of chart area
24 | dy | 4 | y-size of the text in 1/4000 of chart area
28 | grbit | 2 | Display flags

The option flags in the grbit field (like the fields themselves) have meaning according to the TEXT record's parent. The grbit field contains the following option flags.

Offset | Bits | Mask | Name | Contents
0 | 0 | 01h | fAutoColor | 1 = automatic color 0 = user-selected color
0 | 1 | 02h | fShowKey | If text is an attached data label: 1 = draw legend key with data label 0 = no legend key
0 | 2 | 04h | fShowValue | 1 = text of label is the value of the data point 0 = text is the category label
0 | 3 | 08h | fVert | 1 = text is not horizontal 0 = text is horizontal
0 | 4 | 10h | fAutoText | 1 = use automatically generated text string 0 = use user-created text string Must be one for fShowValue to be meaningful.
0 | 5 | 20h | fGenerated | 1 = default or unmodified 0 = modified
0 | 6 | 40h | fDeleted | 1= an Automatic text label has been deleted by the user
0 | 7 | 80h | fAutoMode | 1 = Background is set to Automatic
1 | 2–0 | 07h | rot | 0 = no rotation (text appears left-to-right) 1 = text appears top to bottom, letters are upright 2 = text is rotated 90 degrees counterclockwise 3 = text is rotated 90 degrees clockwise
1 | 3 | 08h | fShLabPct | 1 = show category label and value as a percentage (pie charts only)
1 | 4 | 10h | fShowPct | 1 = show value as a percent. This bit applies only to pie charts
1 | 7-5 | E0h | (reserved) | Reserved; must be zero

TICK: Tick Marks and Labels Format (101Eh)

This record defines tick mark and tick label formatting.

Record Data

Offset | Name | Size | Contents
4 | tktMajor | 1 | Type of major tick mark 0 = invisible (none) 1 = inside of axis line 2 = outside of axis line 3 = cross axis line
5 | tktMinor | 1 | Type of minor tick mark 0 = invisible (none) 1 = inside of axis line 2 = outside of axis line 3 = cross axis line
6 | tlt | 1 | Tick label position relative to axis line 0 = invisible (none) 1 = low end of plot area 2 = high end of plot area 3 = next to axis
7 | wBkgMode | 1 | Background mode: 1 = transparent 2 = opaque
8 | rgb | 4 | Tick-label text color; RGB value, high byte = 0
12 | (reserved) | 16 | Reserved; must be zero
28 | grbit | 2 | Display flags

The grbit field contains the following option flags.

Offset | Bits | Mask | Name | Contents
0 | 0 | 01h | fAutoCo | Automatic text color
0 | 1 | 02h | fAutoMode | Automatic text background
0 | 4–2 | 1Ch | rot | = 0 no rotation (text appears left-to-right) = 1 text appears top to bottom, letters are upright = 2 text is rotated 90 degrees counterclockwise = 3 text is rotated 90 degrees clockwise
0 | 5 | 20h | fAutoRot | Automatic rotation
0 | 7–6 | C0h | (reserved) | Reserved; must be zero
1 | 7–0 | FFh | (reserved) | Reserved; must be zero

UNITS: Chart Units (1001h)

Microsoft Excel writes this record, but its value is always zero.

Applications writing BIFF do not need to write this record. If your application writes this record, the wUnits field must be zero.

Record Data

Offset | Name | Size | Contents
4 | wUnits | 2 | Always zero

VALUERANGE: Defines Value Axis Scale (101Fh)

This record defines the value axis.

Record Data

Offset | Name | Size | Contents
4 | numMin | 8 | Minimum value on axis
12 | numMax | 8 | Maximum value on axis
20 | numMajor | 8 | Value of major increment
28 | numMinor | 8 | Value of minor increment
36 | numCross | 8 | Value where category axis crosses
44 | grbit | 2 | Format flags

All 8-byte numbers in the preceding table are IEEE floating-point numbers.

The numMin field defines the minimum numeric value that appears along the value axis. This field is all zeros if Auto Minimum is selected on the Scale tab of the Format Axis dialog box. The numMax field defines the maximum value displayed along the value axis and is all zeros if Auto Maximum is selected.

The numMajor field defines the increment (unit) of the major value divisions (gridlines) along the value axis. The numMajor field is all zeros if Auto Major Unit is selected on the Scale tab of the Format Axis dialog box. The numMinor field defines the minor value divisions (gridlines) along the value axis and is all zeros if Auto Minor Unit is selected.

The numCross field defines the value along the value axis at which the category axis crosses. This field is all zeros if Auto Category Axis Crosses At is selected.

The grbit field contains the following option flags.

Offset | Bits | Mask | Name | Contents
0 | 0 | 01h | fAutoMin | Automatic minimum selected
0 | 1 | 02h | fAutoMax | Automatic maximum selected
0 | 2 | 04h | fAutoMajor | Automatic major unit selected
0 | 3 | 08h | fAutoMinor | Automatic minor unit selected
0 | 4 | 10h | fAutoCross | Automatic category crossing point selected
0 | 5 | 20h | fLogScale | Logarithmic scale
0 | 6 | 40h | fReverse | Values in reverse order
0 | 7 | 80h | fMaxCross | Category axis to cross at maximum value
1 | 7–0 | FFh | (reserved) | Reserved; must be zero


Microsoft Excel Workspace File Format

This chapter describes the workspace BIFF file, which is the file that Microsoft Excel writes when you choose the Save Workspace command from the File menu. The workspace file stores the position, size, filename, window attributes, and so on, of each workbook window.

The following illustration shows the workspace file for a workspace with two workbook windows. The file contains global BOF, CODEPAGE, and EOF records. There is a set of WNDESK, WINDOW1, and REVERT records for each window, and at the end of the file, an EXTERNSHEET record for each window.

The workspace BIFF file is not an OLE 2 compound file, therefore you must use the Dumpbiff.exe utility (an MS-DOS program) to examine the file. For general information about BIFF records, see BIFF Record Information.

Record Descriptions

The first two fields in every BIFF record are record number and record length. Because these fields have the same offset and size in every BIFF record, they are not documented in the following descriptions.

BOF: Beginning of File (0809h)

The BOF record marks the beginning of the file.

BOF Record Number Field

Offset | Name | Size | Contents
0 | vers | 1 | ver: = 00 BIFF2 = 02 BIFF3 = 04 BIFF4 = 08 BIFF5/BIFF7
1 | bof | 1 | 09h

Record Data

Offset | Name | Size | Contents
4 | vers | 2 | Version number (0500 for BIFF5 and BIFF7)
6 | dt | 2 | Substream type: 0005h = Workbook globals 0006h = Visual Basic module 0010h = Worksheet or dialog sheet 0020h = Chart 0040h = Microsoft Excel 4.0 macro sheet 0100h = Workspace file
8 | rupBuild | 2 | Build identifier (internal use only)
10 | rupYear | 2 | Build year (internal use only)

The rupBuild and rupYear fields contain numbers that identify the version (build) of Microsoft Excel that wrote the file. If you write a BIFF file, you can use the BiffView utility to determine the current values of these fields by examining any BOF record in a workbook file.

CODEPAGE: Default Code Page (42h)

The CODEPAGE record stores the default code page (character set) that was in use when the workspace was saved.

Record Data

Offset | Name | Size | Contents
4 | cv | 2 | Code page the file is saved in: 01B5h (437 dec.) = IBM PC (Multiplan) 8000h (32768 dec.) = Apple Macintosh 04E4h (1252 dec.) = ANSI (Microsoft Windows)

EOF: End of File (0Ah)

The EOF record marks the end of the file. It has no record data field, and is simply 0A000000h.

EXTERNSHEET: External Reference (17h)

The EXTERNSHEET record specifies an externally referenced workbook in the workspace. You should not change the order of EXTERNSHEET records.

Record Data

Offset | Name | Size | Contents
4 | cch | 1 | Length of filename
5 | rgch | var | Filename

The cch field contains the length of the source workbook filename. The rgch field contains the source workbook filename.

Filename Encoding

Whenever possible, filenames are encoded to make BIFF files transportable across file systems. Encoded filenames are identified by the first character of the rgch field. The first character of the rgch field may be any one of the following values.

Name | Value | Meaning
chEmpty | 00 | Reference to an empty workbook name (see text)
chEncode | 01 | Filename has been encoded (see following table)
chSelf | 02 | Self-referential external reference (see text)

chEmpty indicates that the filename is an external reference to an empty workbook name, as in the formula =Sheet1!$A$1.

chSelf indicates that the filename is an external reference where the dependent and source workbooks are the same. An example of this is a workbook SALES.XLS that contains the formula =SALES.XLS!$A$1.

A chEncode at the beginning of rgch indicates that the filename of the source workbook has been encoded to a less system-dependent filename. The following special keys are recognized in the rgch field.

Name | Value | PC file systems | Macintosh file system
chVolume | 01 | Represents an MS-DOS drive letter. It is followed by the drive letter. For example, the formula ='D:\SALES.XLS'!A1 generates the chVolume key when the dependent workbook is not on the D: drive. UNC filenames, such as \\server\share\myfile.xls generate an @ character after the chVolume key; this replaces the initial double backslash (\\). | Represents a single-character volume name. Because single-character volume names are uncommon on the Macintosh, the chLongVolume key is used to represent volume names that are longer than a single character.
chSameVolume | 02 | Indicates that the source workbook is on the same drive as the dependent workbook (the drive letter is omitted). For example, the formula ='\SALES.XLS'!A1 generates the chSameVolume key when the dependent workbook is not in the root directory. | Indicates that the source workbook is on the same volume as the dependent workbook (the volume name is omitted).
chDownDir | 03 | Indicates that the source workbook is in a subdirectory of the current directory. For example, the formula ='XL\SALES.XLS'!A1 generates the chDownDir key. The subdirectory name precedes the chDownDir key, and the filename follows it. | Indicates that the source workbook is in a folder in the current folder. For example, the formula =':XL:Sales1992'!A1 generates the chDownDir key. The folder name precedes the chDownDir key, and the filename follows it.
chUpDir | 04 | Indicates that the source workbook is in the parent directory of the current directory. For example, the formula ='..\SALES.XLS'!A1 generates the chUpDir key. | Indicates that the source workbook is in the parent folder of the current folder. For example, the formula ='::Sales1992'!A1 generates the chUpDir key.
chLongVolume | 05 | (not used) | The chLongVolume key is followed by the length of the name (1 byte) and then by the volume name string.
chStartupDir | 06 | Indicates that the source workbook is in the startup directory (the XLSTART subdirectory of the directory that contains EXCEL.EXE). | Indicates that the source workbook is in the Excel Startup Folder (5), which is in the System Folder.
chAltStartupDir | 07 | Indicates that the source workbook is in the alternate startup directory. | Indicates that the source workbook is in the alternate startup folder.
chLibDir | 08 | Indicates that the source workbook is in the LIBRARY directory. | Indicates that the source workbook is in the Macro Library folder.

REVERT: Revert Data (DBh)

This record stores internal data for revert-to-saved processing.

Record Data

Offset | Name | Size | Contents
4 | rgch | var | Revert array; for internal use only

WINDOW1: Window Information (3Dh)

The WINDOW1 record contains workbook-level window attributes. The xWn and yWn fields contain the location of the window in units of 1/20 of a point, relative to the upper-left corner of the Microsoft Excel window client area. The dxWn and dyWn fields contain the window size, also in units of 1/20 of a point.

Record Data

Offset | Name | Size | Contents
4 | xWn | 2 | Horizontal position of the window
6 | yWn | 2 | Vertical position of the window
8 | dxWn | 2 | Width of the window
10 | dyWn | 2 | Height of the window
12 | grbit | 2 | Option flags
14 | itabCur | 2 | Index of selected workbook tab (0-based)
16 | itabFirst | 2 | Index of first displayed workbook tab (0-based)
18 | ctabSel | 2 | Number of workbook tabs that are selected
20 | wTabRatio | 2 | Ratio of width of the workbook tabs to the width of the horizontal scroll bar; to obtain the ratio, convert to decimal and then divide by 1000.

The grbit field contains the following option flags.

Offset | Bits | Mask | Name | Contents
0 | 0 | 01h | fHidden | = 1 if the window is hidden
 | 1 | 02h | fIconic | = 1 if the window is currently displayed as an icon
 | 2 | 04h | (reserved) |
 | 3 | 08h | fDspHScroll | = 1 if horizontal scroll bar is displayed
 | 4 | 10h | fDspVScroll | = 1 if vertical scroll bar is displayed
 | 5 | 20h | fBotAdornment | = 1 if workbook tabs are displayed
 | 7-6 | C0h | (reserved) |
1 | 7-0 | FFh | (reserved) |

WNDESK: Describes Windows in the Workbook

The WNDESK record describes each window that appears in the workspace.

Record Data

Offset | Name | Size | Contents
4 | ish | 2 | Document number (zero-based)
6 | dt | 2 | Document type; always = 0005h


Converting C-API Add-Ins to 32-bit Microsoft Excel

The files included in this article will help you to build compiled add-ins for the 32-bit (Intel x86 family) versions of Microsoft Excel (Microsoft Excel 7.0 for Windows 95 and Microsoft Excel 5.0 for Windows NT). The article includes the C-API files Xlcall32.lib and Xlcall.h. Xlcall32.dll is also required, and is installed in your Windows system folder when you install Microsoft Excel.

Click to open or copy the CAPI project files

Conversion Notes

1. The 32-bit versions of the Visual C++ compiler (versions 2.0, 2.1, 2.2, and 4.0) changed the __export keyword to __declspec(dllexport). Use this keyword on your function declarations that are called from Microsoft Excel. For example:

__declspec(dllexport) int TestFunction(int iArg)
{
    ...
}

There are some issues related to using __declspec(dllexport) in 32-bit versions of Visual C++. For more information, see "Exporting PASCAL-Like Symbols in 32-bit DLLs" later in this article.

2. Ensure that Xlcall32.dll is in your Windows system folder.

3. Xlcall.h is the same file that you used in the older (16-bit) C-API.

4. Closely examine parameters, variables, and return values declared as type int in your C/C++ code. In C/C++ code the size of an int depends on the system and/or compiler. Win16 defined an int to be 16-bits, or the same as a short int or short. In Microsoft Excel the short int code used with REGISTER() is "H" or "I". Win32 defines an int to be 32-bits, or the same as a long int or long, and the Microsoft Excel registration code is "J".

System-dependent int sizing may cause a problem with internal structure sizes and numeric overflows, but in most cases it doesn't affect the program. Because, however, Microsoft Excel does not support a system-dependent int parameter or return value type, Microsoft Excel will have a problem with carelessly written Win16 code that is recompiled for Win32. Plain int parameters and return values are expanded to 32-bits, which effectively changes the registration type code from "H" to "J". Calling an incorrectly declared procedure may result in incorrect results or a protection fault. There are two solutions to this problem:

  • Leave the C/C++ code alone (it still uses system-dependent plain int) and conditionalize your calls to REGISTER() to be aware of the current operating system platform. On Win16 the type codes use 16-bit "H" and "I" codes, and on Win32 the type codes use the 32-bit "J" value.
  • Leave the XLM code alone and instead clean up the C/C++ variable declarations. All int parameters and return values are modified to be either a short int or a long int as required. The same REGISTER() type code can then be used on either platform.

5. The C-API xlGetHwnd call that retrieve the main window handle of Microsoft Excel is problematic because sizeof(HWND) on Win32 is a long but the field used to receive the HWND parameter in the XLOPER structure is a short. Consequently the high word of the actual Microsoft Excel HWND is truncated. To work around this problem call xlGetHwnd to get the low word of the actual hwnd, then iterate the list of top-level windows and look for a match with the returned low word. This code illustrates the technique:

typedef struct _EnumStruct {
    HWND        hwnd;
    unsigned short    wLoword;
} EnumStruct;

#define CLASS_NAME_BUFFER    50

BOOL CALLBACK EnumProc(HWND hwnd, EnumStruct * pEnum)
{
    // first check the class of the window. Must be "XLMAIN"
    char rgsz[CLASS_NAME_BUFFER];
    GetClassName(hwnd, rgsz, CLASS_NAME_BUFFER);
    if (!lstrcmpi(rgsz, "XLMAIN")) {
        // if that hits, check the loword of the window handle
        if (LOWORD((DWORD) hwnd) == pEnum->wLoword) {
            pEnum->hwnd = hwnd;
            return FALSE;
        }
    }

    // no luck - continue the enumeration
    return TRUE;
}

BOOL GetHwnd(HWND * pHwnd)
{
    XLOPER x;

    if (Excel4(xlGetHwnd, &x, 0) == xlretSuccess) {
        EnumStruct enm;

        enm.hwnd = NULL;
        enm.wLoword = x.val.w;

        EnumWindows((WNDENUMPROC) EnumProc, (LPARAM) &enm);

        if (enm.hwnd != NULL) {
            *pHwnd = enm.hwnd;
            return TRUE;
        }
    }
    return FALSE;
}

Exporting PASCAL-Like Symbols in 32-bit DLLs

This section is taken from Microsoft Product Support Services Knowledgebase article Q140485.

Microsoft Visual C++, 32-bit Edition, versions 2.0, 2.1, 2.2, 4.0 There is no _pascal keyword in the 32-bit editions of Visual C++. Instead the Windef.h header file has PASCAL defined as __stdcall. This creates the correct style calling convention for the function (the called function cleans up the stack) but decorates the function name differently. So, when __declspec(dllexport) is used (in a DLL, for example), the decorated name is exported instead of the desired PASCAL style name, which is undecorated and all uppercase.

PASCAL name decoration is simply the undecorated symbol name in uppercase letters. __stdcall name decoration prefixes the symbol name with an underscore (_) and appends the symbol with an at sign (@) character followed by the number of bytes in the argument list (the required stack space). Therefore, when you declare the following function:

   int  __stdcall func (int a, double b)

it is decorated as:

   _func@12

The C calling convention (__cdecl) decorates the name as _func, whereas the desired PASCAL style name is FUNC.

To get the decorated name set the Generate Mapfile option in the Linker General category setting.

Use of __declspec(dllexport) does the following:

If the function is exported with C calling convention (_cdecl), it strips the leading underscore (_) when the name is exported.

If the function being exported does not use the C calling convention (for example, __stdcall ), it exports the decorated name.

So to simulate PASCAL name decoration and calling conventions, you must have the "Called Function stack clean-up" provided by using __stdcall and the undecorated uppercase name.

Because there is no way to override who does the stack clean up, you must use __stdcall. To undecorate names with __stdcall, you must specify them by using aliases in the EXPORTS section of the .def file. This is shown below for the following function declaration:

   int  __stdcall MyFunc (int a, double b);
   void __stdcall InitCode (void);

In the .def file:

   EXPORTS
      MYFUNC=_MyFunc@12
      INITCODE=_InitCode@0


Microsoft Excel Registry Keys and Values

Microsoft Office Technical Documentation Group

Created: November, 1995

This article describes the system registry data stored by Microsoft Excel for Windows NT and Microsoft Excel for Windows 95. This article also includes documentation on the .ini file data stored by Microsoft Excel version 5.0 for Windows (16-bit version), and the preferences data stored by Microsoft Excel version 5.0 for the Macintosh.

Introduction

Microsoft Excel stores application-wide settings and other information in several different ways, depending on the operating environment and the version of Microsoft Excel, as shown in the following table.

Microsoft Excel version | Storage method
5.0 for Windows (16-bit) | Excel5.iniExcel5.ini file (and system registry for OLE file types and CLSIDs)
5.0 for Windows NT | System registry
5.0 for the Macintosh | Excel Settings (5) file
7.0 for Windows 95 | System registry
7.0 for Windows NT | System registry

For information about differences between the system registry data and the Excel5.ini file (and the Excel Settings (5) file on the Macintosh), see The Excel5.ini File and Specifying Settings in Microsoft Excel version 5.0 for the Macintosh.

Editing the Registry

The Registry Editor program is called Regedt32.exe in Windows NT and Regedit.exe in Windows 95. You can run this program by using the Run command in Program Manager (Windows NT) or the Run command on the Start menu (Windows 95). The behavior of these two versions of the Registry Editor is very similar.

Microsoft Excel registry data can be found in the keys in HKEY_CURRENT_USER\Software\Microsoft\Excel\5.0 or HKEY_CURRENT_USER\Software\Microsoft\Excel\7.0. The best way to become familiar with the organization of the registry is to start the Registry Editor and then browse the keys and values.

In both editors, you can double-click a value to edit it. You can also add new keys and values by using the Edit menu. The Registry Editor commits changes to the registry as soon as you make a change and then click the OK button in the dialog box. Therefore, there is no Save command.

Registry Keys and Values

The following sections describe all of the Microsoft Excel registry keys and values. Unless otherwise indicated, all registry keys and values in these sections apply to Microsoft Excel version 5.0 for Windows NT, version 7.0 for Windows 95, and version 7.0 for Windows NT.

Microsoft Excel Key

The following sections describe the values contained in the Microsoft Excel key.

AltStartup

The AltStartup value is a string that specifies the alternate startup folder. When you start Microsoft Excel, files located in the Xlstart folder are loaded automatically, followed by files located in the alternate startup folder.

AutoCalculate (new for version 7.0)

This value is a DWORD that stores an index to the AutoCalculation function. The values are listed in the following table.

Value | Function
0 | Count Nums
4 | Sum
5 | Average
6 | Min
7 | Max
169 | Count

AutoDec

The AutoDec value contains 16 bits expressed as a DWORD in the registry. The least-significant bit (bit 0) is a 1 if the Fixed Decimal option is on (Edit tab in the Options dialog box) and 0 (zero) if it is off. The remaining 15 bits store the value of the Places option. For example, if the Fixed Decimal option is on and the Places option is set to 2, the AutoDec value is 0000000000000101 binary or 0005h.

AutoFormat and AutoFormat Options

The AutoFormat and AutoFormat Options values are DWORD values that specify the default formatting choice to be used when the AutoFormat toolbar button is clicked.

The AutoFormat value stores a one-based index to a format. The format indexes correspond to the order in which the formats appear in the Table Format box in the AutoFormat dialog box.

The AutoFormat Options value controls which formatting attributes are applied for the format specified in the AutoFormat value. The formatting attributes correspond to the options in the AutoFormat dialog box. The values for the formatting attributes are listed in the following table.

AutoFormat Options value | Indicates
1 | Number
2 | Font
4 | Alignment
8 | Border
16 | Patterns
32 | Width or height

For example, if the AutoFormat Options value is 10, the font and border properties of a format are applied. The number 10 is the sum of 2 (font) and 8 (border). The default value for AutoFormat Options is 63, the sum of all of the numbers, indicating that all of the formatting properties are applied.

Basics (new for version 7.0)

The Setup program writes a 0 (zero) to this DWORD value, which tells Microsoft Excel to display the What's New topic the first time you start the program. When you dismiss the What's New topic, Microsoft Excel writes a 1 to this value, which prevents the What's New topic from being displayed again.

CFDDELink

The CFDDELink value is a DWORD. If the CFDDELink value is set to 1, Microsoft Excel remembers the last clipboard format used for a successful DDE operation; this is used to reduce the amount of time required for future DDE operations.

Default Chart

The Default Chart value is a string that specifies the name of the default chart format. This value stores the setting from the Chart tab in the Options dialog box. The actual default chart formats are saved as chart sheets in a workbook named "Xl5galry.xls" in the Xlstart folder.

DefaultPath

The DefaultPath value is a string that stores the Default File Location option (General tab in the Options dialog box).

DefSheets

The DefSheets value is a DWORD that specifies the number of new worksheets in each new workbook. For example, if the DefSheets is 1, each new workbook you create will contain one worksheet. This value stores the setting from the General tab in the Options dialog box.

Font

The Font value is a string that stores the default font and font size for new worksheets. For example, to specify that the default font is 10-point Arial, the value would be as follows:

Arial,10

The font name must be the name of the font spelled exactly as it appears in the font list on the Font tab in the Format Cells dialog box. The FONT value sets the default font used for the Normal style and for row and column headings.

G1Dft-DemoSpd and G1Dft-HelpType

These two values are DWORD values that correspond to options on the Transition tab in the Options dialog box.

If G1Dft-HelpType is 0 (zero), this indicates that you want Help for Lotus 1-2-3 Users to display a set of instructions. If G1Dft-HelpType is 1, this indicates that you want Help for Lotus 1-2-3 Users to give a demonstration for the Lotus 1-2-3 commands that the user types.

The G1Dft-DemoSpd value controls the speed of the demonstration when the G1Dft-HelpType option is 1. This can be a number from 1 to 5, where 1 is slow and 5 is fast.

Maximized and Pos

The Maximized value is a DWORD that indicates the size of the application window and the size of the workbook window when you start Microsoft Excel. Bit 0 (zero) controls the size of the application window, and bit 1 controls the size of the workbook window, as shown in the following table.

Maximized | Indicates that
0 | The application window size and position are set by the Pos value, and the workbook window is slightly smaller than the available space.
1 | The application window fills the screen, and the workbook window is slightly smaller than available space.
2 | The application window size and position are set by the Pos value, and the workbook window fills the available space below the toolbars.
3 | The application window fills the screen, and the workbook window fills the available space below the toolbars.

The Pos value is a string that contains window coordinates for the application window when it isn't maximized. The first two coordinates set the distance from the left and top edges of the screen to the upper-left corner of the window, respectively. The third coordinate is the window width, and the fourth coordinate is the window height. All coordinates are in points.

The following tables show typical values for Maximized and Pos as they would appear in the Registry Editor. In this example, the application window isn't maximized, and the workbook window is maximized.

Name | Data
Maximized | 0x00000002 (2)
Pos | "28,22,480,321"

MenuKey

The MenuKey value is a DWORD that indicates the ASCII value corresponding to the character used to activate Microsoft Excel menus or Help. The default is the forward slash (/), which corresponds to the menu key for Lotus 1-2-3. For example, if you changed the menu key on the Transition tab in the Options dialog box to the backslash (\) key, the MenuKey value would be 92.

MoveEnterDir (new for version 7.0)

This value is a DWORD that stores the setting of the Move Selection After Enter Direction option on the Edit tab in the Options dialog box. The values are listed in the following table.

Value | Indicates
0 | Down
1 | Right
2 | Up
3 | Left

MRUFuncs

The MRUFuncs value specifies the functions that appear in the most-recently used list in the Function Wizard. The functions are stored as their function index number (iftab).

OPEN

You can use OPEN string values to specify workbooks that you want opened automatically at startup time. The first OPEN name is OPEN, the second is OPEN1, the third is OPEN2, and so on. The OPEN string contains the full path to the file to open, and the filename must be enclosed in double quotation marks. When you view the OPEN value in the Registry Editor, the filename will have two sets of double quotation marks.

The Add-In Manager (the Add-Ins command on the Tools menu) reads and writes OPEN values. For example, if you've selected the check box to the left of the Analysis ToolPak add-in, when you quit Microsoft Excel it writes a string in an OPEN value that's similar to the following example.

/R "C:\OFFICE95\EXCEL\LIBRARY\ANALYSIS\ANALYS32.XLL"

The /R switch is described in the following section.

Option Switches for the OPEN Value

You can use the /R and /F option switches, alone or together, to modify the behavior of the OPEN value. The /R option switch opens the file as read-only. The /F (fast load) option switch places template workbooks in the New dialog box (File menu).

When you install an add-in that contains demand-loaded custom functions, there will be an OPEN value that points to the add-in workbook; this value will contain the /F switch. Demand loading means that when you start Microsoft Excel, it reads only enough information from the add-in workbook file to establish references to the custom functions in the add-in. These functions are added to the list in the Function Wizard, and they can be entered on a worksheet. However, the add-in isn't fully loaded until one of its custom functions is recalculated.

The /F switch is added to the filename string when the name __DemandLoad (the string "DemandLoad" preceded by two consecutive underscores) is defined somewhere in the add-in workbook. For more information about add-ins, see the Microsoft Excel/Visual Basic for Windows 95 Programmer's Guide, which is available from Microsoft Press. You can order any Microsoft Press book by calling Microsoft Press at 1-800-MSPRESS (1-800-677-7377).

Options, Options3, Options5, and Options95

Each of these four values contain 16 flag bits that are expressed as a DWORD in the registry. After a new installation of Microsoft Excel, the Options value doesn't appear in the registry. When you change one of the default settings stored in the Options value, Microsoft Excel will write the value to the registry.

Options

Option | Indicates
bit 0 | Show scroll bars
bit 1 | Show the formula bar
bit 2 | Show the status bar
bit 3 | (Reserved)
bit 4 | Use A1-style references
bit 5 | (Reserved)
bit 6 | DDE is enabled
bits 7 and 8 | Apple Macintosh command underlines
bits 9–15 | (Reserved)

Options3

Options3 | Indicates
bit 0 | (Reserved)
bit 1 | Alternate navigation keys are turned on
bit 2 | Lotus 1-2-3 Help is turned on
bit 3 | Cell note indicators are turned off
bit 4 | (Reserved)
bit 5 | Macros are saved in the Personal Macro Workbook
bits 6-13 | (Reserved)
bit 14 | Gridlines in new sheets are turned off
bit 15 | (Reserved)

Options5

Options5 | Indicates
bit 0 | The Tip Wizard is turned on
bit 1 | The prompt for Summary Info
bit 2 | Editing directly in cells isn't allowed
bit 3 | The status bar is visible in full-screen mode
bit 4 | The formula bar is visible in full-screen mode
bit 5 | Full-screen mode
bit 6 | The most recently used file list isn't displayed
bit 7 | Cut, copy, and sort objects with cells
bit 8 | Tool tips are turned off
bit 9 | Small toolbar buttons
bit 10 | Toolbar autosensing
bit 11 | Don't move to the next cell after the ENTER key is pressed
bit 12 | Don't warn before a drag-and-drop copy or paste action
bit 13 | Use black-and-white toolbar buttons
bit 14 | Ask to update automatic links

Options95 (new for version 7.0)

Options95 | Indicates
bit 0 | AutoComplete is turned on
bit 1 | Cell animation is turned on
bits 2-15 | (Reserved)

Randomize

If you want Microsoft Excel to generate a unique set of random numbers each time you use the RAND function, set Randomize to 1.

StickyPtX and StickyPtY

StickyPtX and StickyPtY indicate the preferred location where dialog boxes appear on the screen: They are updated every time you quit Microsoft Excel.

User

The User value is a string that stores the User Name option on the General tab in the Options dialog box.

Summary of the Values in the Microsoft Excel Key

The following table contains a summary list of the values described in this section.

Name | Data type
AltStartup | String
AutoCalculate | DWORD
AutoDec | DWORD
AutoFormat | DWORD
AutoFormat Options | DWORD
Basics | DWORD
CFDDELink | DWORD
Default Chart | String
DefaultPath | String
DefSheets | DWORD
Font | String
G1Dft-DemoSpd | DWORD
G1Dft-HelpType | DWORD
Maximized | DWORD
MenuKey | DWORD
MoveEnterDir | DWORD
MRUFuncs | String
OPEN | String
Options | DWORD
Options3 | DWORD
Options5 | DWORD
Options95 | DWORD
Pos | String
Randomize | DWORD
StickyPtX | DWORD
StickyPtY | DWORD
User | String

Spell Checker Key

The Spell Checker key contains the values listed in the following table.

Name | Data type | Description
Custom Dict | String | Path to custom dictionaries (there can be more than one custom dictionary). For Windows NT, all custom dictionaries must be placed in the Msapps\Proof subfolder of your Windows folder. For Windows 95 (with long filename support), all custom dictionaries must be placed in the \Program Files\Microsoft Shared\Proof folder.
Ignore Caps | DWORD | The state of the Ignore Caps check box; 1 = checked.
Speller | String | See the following section.
Suggest Always | DWORD | The state of the Suggest check box; 1 = checked.

The Speller value includes two arguments — Country Code and Dictionary Type — separated by a comma. Country Code specifies the proper spelling tool to use with the corresponding language version of Microsoft Excel. The following table shows the various country codes.

Country code | Language
1030 | Danish
1031 | German
1033 | U.S. English
1034 | Spanish
1036 | French
1040 | Italian
1043 | Dutch
1044 | Norwegian
1054 | Swedish
2057 | British English
2070 | Portuguese
3081 | Australian English

The Dictionary Type argument refers to five possible types of dictionaries that can be used by the spelling checker. Microsoft Excel always uses type 0 (Normal). The following table shows the five dictionary types.

Dictionary type | Description
0 | Normal
1 | Concise (subset of Normal)
2 | Complete (includes Medical and Legal)
3 | Medical
4 | Legal

Init Menus Key

The Init Menus key contains one string value for each menu that's added to a built-in menu bar. Each value name is a unique tag that identifies the added menu. The string has the following form:

menu_bar_num,menu_name,menu_position
Argument | Description
menu_bar_num | The number of the built-in menu bar to which you want to add the menu. The menu bars change, depending on the type of sheet that's active in the workbook. The menu bar numbers are as follows: 3 Nil menu bar (no open workbooks) 10 Worksheet, dialog sheet, version 4.0 macro sheet 11 Chart sheet 12 Visual Basic module
menu_name | The name of the new menu.
menu_position | The position of the new menu on the menu bar. This may be the name of the menu after which you want to place the new menu, or a number indicating the menu's position relative to the left side of the menu bar.

Init Commands Key

The Init Menus key contains one string value for each command that's added to a menu. Each value name is a unique tag that identifies the added command. The string has the following form:

menu_bar_num,menu_name,command_name,macro,
command_position,macro_key,status_text,help_reference
Argument | Description
menu_bar_num | The number of the built-in menu bar to which you want to add the menu. The menu bars change, depending on the type of sheet that's active in the workbook. The menu bar numbers are as follows: 3 Nil menu bar (no open workbooks) 10 Worksheet, dialog sheet, version 4.0 macro sheet 11 Chart sheet 12 Visual Basic module
menu_name | The name of the new menu.
command_name | The name of the new command.
macro | A reference to a procedure in an add-in workbook. Choosing the command opens the add-in and runs this procedure. The procedure should delete the command added by this registry key and then replace it with a command that runs a procedure that performs the specified command actions.
command_position | The position of the command on the menu. This may be the name of the command after which you want to place the new command, or a number indicating the command's position on the menu. If omitted, the command appears at the end of the menu.
macro_key | The key (if any) assigned to the procedure.
status_text | A message to be displayed in the status bar when the command is selected.
help_reference | The filename and topic number for a custom Help topic for the command.

Delete Commands Key

You can use the Delete Commands key to delete commands from built-in menus. The Add-In Manager (the Add-Ins command on the Tools menu) reads and writes values in the Delete Commands key. The key contains one string value for each command that's deleted from a menu. Each value name is a unique tag that identifies the deleted command. The string has the following form:

menu_bar_num,menu_name,command_position
Argument | Description
menu_bar_num | The number of the built-in menu bar from which you want to delete the command from a menu. The menu bars change, depending on the type of sheet that's active in the workbook. The menu bar numbers are as follows: 3 Nil menu bar (no open workbooks) 10 Worksheet, dialog sheet, version 4.0 macro sheet 11 Chart sheet 12 Visual Basic module
menu_name | The name of the menu.
command_position | The position of the command on the menu. This may be the name of the command or a number indicating the command's position on the menu.

Caution Don't delete the Exit command from the File menu unless you've created another way to quit Microsoft Excel!

Recent File List Key

The Recent File List key contains a string value for each of the four most recently used files, which are listed at the bottom of the File menu. The list is updated each time the user quits Microsoft Excel. The string values appear in the Registry Editor, as shown in the following example:

Value name | Data
File1 | "C:\Accounting\Closing statement.xls"
File2 | "D:\Monthly\January Sales.xls"
File3 | "C:\Office95\Excel\scratch.xls"
File4 | "\\Corp\public\assets\real\1995 depreciation.xls"

Add-In Manager Key

This key contains one string value for each add-in that the user installed but later disabled. The string value is the full path and filename of the add-in. When an add-in is installed and enabled, the add-in name appears in the Add-Ins dialog box and the check box to the left of the name is checked. When the user clears the check box, the add-in is considered to be installed but disabled.

Installed and enabled add-ins cause Microsoft Excel to write an OPEN value to the Microsoft Excel key when the program exits (see "Microsoft Excel Key" in the preceding section). If an add-in is installed and disabled, the OPEN value is removed, and a corresponding string value is then written in the Add-In Manager key.

Converters Key

This key contains the description and DLL location of external file converters such as the Microsoft Multiplan® converter. Each value name is a unique tag that identifies the converter, and each string value has the following form:

Friendly description,DLL filename and path,search filter
Token | Description
Friendly description | The text that appears in the List Files Of Type box in the Open dialog box.
DLL filename and path | The filename and path of the converter DLL. If you omit the path, the DLL must be in the same folder as Excel.exe.
Search filter | A file filter string — for example, *.XL*.

WK? Settings Key

This key contains values that control settings for opening and saving Lotus 1-2-3 files.

Name | Data type | Description
AFE | String | Controls whether Transition Formula Entry (AFE) is turned on. A value of 2 is used as the default, indicating that AFE is turned on only if a macro name exists on the Lotus 1-2-3 worksheet. Otherwise, a value of 1 causes AFE to always be turned on, while a value of 0 causes AFE to never be turned on.
Gridlines | String | If Gridlines=1, gridlines are displayed when a Lotus 1-2-3 worksheet is opened. If Gridlines=0, gridlines aren't displayed.
Load_Chart_Wnd | String | If Load_Chart_Wnd=1, Lotus 1-2-3 graphs are converted to Microsoft Excel chart sheets. If Load_Chart_Wnd=0, Lotus 1-2-3 graphs are converted to embedded charts.
Monospace | String | If Monospace=1, Lotus 1-2-3 worksheets are displayed in Microsoft Excel using a monospace font (10-point Courier). If Monospace=0, the Normal style is used.
WYSIWYG_Save | String | If WYSIWYG_Save=1, an .FMT or .FM3 formatting file is saved along with a Lotus 1-2-3 worksheet. If WYSIWYG_Save=0, an .FMT or .FM3 formatting file isn't saved.

Line Print Key

This key contains values that control settings used in Lotus 1-2-3 macro line printing. These settings are defined using the various Lotus 1-2-3 Worksheet Global Default Printer (/wgdp) commands and are updated in the registry whenever Microsoft Excel encounters a Lotus 1-2-3 Worksheet Global Default Update (/wgdu) command.

The LeftMarg, RightMarg, TopMarg, and BotMarg values are strings that contain the respective margin settings. The data for LeftMarg and RightMarg refer to numbers of characters. While these two values can be from 0 to 1000, a standard page is 80 characters wide. The data for TopMarg and BotMarg refer to numbers of lines. While these two values can be from 0 to 240, standard 11-inch paper can accommodate a maximum of 66 lines. The number of lines on the page is given by the PgLen string value.

The Setup value is equivalent to the Lotus 1-2-3 Worksheet Global Default Printer Settings (/wgdps) command and specifies the printer setup string.

The Options value contains 6 bits cast to a decimal number that's stored as a string. The following table lists the bits used in the Options value.

Bit | Lotus 1-2-3 /wgdp command
0 | Wait
1 | Formatted
2 | AutoLf
3-5 | Port (0 through 7)

The best way to determine the appropriate decimal number to use with the Options value is to construct the binary number first and then convert it to a decimal value. The default value is Options=2 ¾ or, in binary, 0000 0010 ¾ meaning that bit 1 is set while all others are cleared.

Bits 3, 4, and 5 indicate the setting used by Lotus 1-2-3 to specify the hardware port used for printing. Microsoft Excel interprets this value as a logical port. The default port setting is LPT1:, which corresponds to bits 3, 4, and 5 equal to 0 (zero). The following table shows the port settings.

Bits 5-3 | Port
000 | LPT1:
001 | COM1:
010 | LPT2:
011 | COM2:
100 | LPT1:
101 | LPT2:
110 | LPT3:
111 | LPT4:

Note that LPT1: and LPT2: are each represented twice. Either combination of bits can be used, yielding the same results.

The Excel5.ini File

Microsoft Excel version 5.0 (for 16-bit Windows) uses a combination of the Excel5.iniExcel5.ini file and the system registry. The data in the preceding section, "Registry Keys and Values," is stored in the Excel5.iniExcel5.ini file. The system registry is used only for OLE settings such as OLE file types and CLSIDs.

The organization of the Excel5.ini file is nearly identical to the organization of the Microsoft Excel keys and values in the Windows NT and Windows 95 system registries. Keys and values in the Windows NT and Windows 95 system registries correspond to sections and statements in the Excel5.ini file. The Excel5.ini file is a plain-text file; to edit it, use a text editor such as Notepad.

If you install Microsoft Excel version 5.0 (for 16-bit Windows) on a network, Setup creates an Excel5.ini file on the drive and in the folder where you installed Microsoft Excel, in addition to the Excel5.ini file it creates in the folder containing your Win.ini file. Don't edit this additional Excel5.ini file; it's there for network purposes only. To change your startup settings, edit only the Excel5.ini file that's in the same folder as your Win.ini file.

Specifying Settings in Microsoft Excel version 5.0 for the Macintosh

The Macintosh counterpart to the Excel5.ini file is the Excel Settings (5) file. This file resides in the System Folder or, if you're running system software version 7.0, in the Preferences Folder in the System Folder. To make modifications to the Excel Settings (5) file, you must use the ResEdit utility. ResEdit is available through Macintosh user groups or the Apple Programmers and Developers Association (APDA). The telephone numbers for the APDA are (800) 282-2732 (United States only) and (408) 562-3910.

The syntax of the statements used by the Excel Settings (5) file is the same as described for the Excel5.ini file, although the Macintosh file isn't a text file. Some of the resources contained in the Excel Settings (5) file are presented in hexadecimal format. The Microsoft Excel Software Development Kit includes a resource template called Settings Template to aid in the modification of the hexadecimal resources in this file.

The Excel Settings (5) file contains the sections GRID, INT, and STR, each of which contains resources that correspond to sections described in the discussion of the Excel5.ini file earlier in this article.

The STR Section

The resources in the STR section can be modified using the templates included with ResEdit. For example, the following illustration shows the window that appears when you double-click the icon representing the STR section.

The resources listed in the STR section correspond to statements listed in the [Microsoft Excel], [Init Commands], [Delete Commands], [Recent File List], and [Spell Checker] sections of Excel5.ini. Resources preceded by "IC" are Init Commands, and resources preceded by "DC" are Delete Commands. Other resources are more easily deciphered, such as "Open1," "File1," and "Spelling," which correspond to Open=, File1=, and Spelling= statements.

You can easily edit resources listed in the STR section by double-clicking them. For example, the following figure shows the window that appears when you double-click the resource named "__ICSolver Add-in."

Note that the format of the string is essentially the same as that of the equivalent Excel5.ini statement. For more information, see Init CommandsKey.

The INT Section

While ResEdit includes a template that allows you to view and edit the contents of the STR section of the Excel Settings (5) file, a similar template isn't included with ResEdit to convert the hexadecimal format of the INT section into easily understandable alphanumeric strings. For this reason, the Microsoft Excel Developer's Kit includes a file called Settings Template, which allows you to easily edit the resources listed in the INT section.

Note Your Excel Settings (5) file may not have an INT section, depending on whether you have changed certain settings in your copy of Microsoft Excel.

To Install the Settings Template

  1. 1. Start ResEdit.
  2. 2. In ResEdit, open both the Excel Settings (5) and Settings Template files.
  3. 3. Copy the resource called TMPL from the Settings Template file.
  4. 4. Paste the TMPL resource into the Excel Settings (5) file.
  5. 5. Close the Settings Template file.
  6. 6. Save the Excel Settings (5) file.

From now on, whenever you open the Excel Settings (5) file with ResEdit and attempt to modify any of the resources in the INT section, you'll be able to edit using decimal code instead of hexadecimal code.

The ALIS Section (System 7.0 Only)

An alias is a resource of the ALIS type that stores information about a particular file. It contains the filename and significant information about the file. Microsoft Excel expands an alias into an actual path that call the Alias Manager. These aliases are stored in the ALIS section of the Excel Settings (5) file.

Microsoft Excel uses the following aliases, each of which is followed in parentheses by the resource ID:

Recently Used Files (0-3)

These are aliases for the Most Recently Used file list (MRU). When Microsoft Excel saves a file, an alias is created for the file.

Excel Installation (128)

This alias is written during setup and refers to the folder where Microsoft Excel resides. All the entries in the String portion of the Excel Settings (5) file are relative (for example, ":Macro Library:Add-In Manager"); this alias is used to expand those paths completely. This solves a problem that would otherwise be created by dragging the program icon to the desktop, causing the installable commands to become disabled due to the changed path.

Spelling (511)

This alias is created the first time the Speller is run. Microsoft Excel makes this alias and uses it from then on to locate the Spelling program and its dictionaries.

Excel Help (1967)

This is the alias for the Microsoft Excel Help file. It's created the first time Help is run. It refers to the Help file in the Microsoft Excel folder.

Microsoft Help (1968)

This alias is created the first time Help is run. It refers to the Help program that Microsoft Excel installs in the System folder.

The GRID Section

The GRID section simply acts as a temporary storage space for the Microsoft Excel Setup program and therefore doesn't require modifications.


Dynamic Data Exchange and XlTable Format

Microsoft Windows provides several methods for transferring data between applications. One way to transfer data is to use Windows dynamic data exchange (DDE). DDE is a message protocol for data exchange between Windows programs. It allows software developers to design applications that share data and thereby provide the user with a more integrated Windows environment.

For complete information about DDE, see the documentation for the Microsoft Windows Software Development Kit (SDK). This article describes the DDE formats that Microsoft Excel supports, and it provides detailed information about the high-performance XlTable DDE format.

DDE Formats

Microsoft Excel supports several DDE formats. The formats are listed in the following table in the order of precedence defined by Microsoft Excel, from highest precedence (XlTable) to lowest precedence (CF_METAFILEPICT). Clipboard formats that begin with CF_ are formats that are already defined in Windows.h. Clipboard formats without CF_ must be registered before use. For more information about registering formats, see Registering Clipboard Formats.

Clipboard format | Description
XlTable | Microsoft Excel fast table format. For more information, see Fast Table Format.
Biff5 | Binary interchange file format (BIFF) for Microsoft Excel version 5.0. For more information about the file format, see Microsoft Excel File Format.
Biff4 | Binary interchange file format (BIFF) for Microsoft Excel version 4.0.
Biff3 | BIFF for Microsoft Excel version 3.0.
Biff | BIFF for Microsoft Excel version 2.x.
CF_SYLK | Microsoft symbolic link (SYLK) format. Microsoft Excel for the Apple Macintosh was originally designed to use SYLK format, and this format is now supported by Microsoft Excel on both the Windows and Macintosh platforms.
Wk1 | Lotus® 1-2-3® Release 2.01 and Release 2.2 format.
Csv | Comma-separated values format, commonly used in BASIC language I/O. This is similar to CF_TEXT format, except that Csv uses commas to separate fields.
CF_TEXT | The simplest form of Clipboard data. It is a null-terminated string containing a carriage return and linefeed at the end of each line.
Rich Text Format | A method of encoding formatted text and graphics for easy transfer between applications. Rich Text Format (RTF) is commonly used by document-processing programs such as Microsoft Word for Windows and Microsoft Word for the Macintosh.
CF_DIF | An ASCII format used by the VisiCalc™ spreadsheet program. The format is under the control of Lotus Development Corporation.
CF_BITMAP | A Windows version 2.x-compatible bitmap.
CF_METAFILEPICT | A metafile picture structure. For complete information, see the documentation for the Microsoft Windows Software Development Kit.

Registering Clipboard Formats

Whenever an application uses a private Clipboard format — such as XlTable, Biff5, Biff4, Biff3, Biff, Wk1, Csv, or Rich Text Format — it must register the format before using it. Microsoft Excel registers these private Clipboard formats, and your DDE application must also register any of these formats that you want to use to exchange data.

For example, to register XlTable, use the following Windows API function call.

wCBformat = RegisterClipboardFormat((LPSTR)"XlTable");

If the function call is successful, the return value is equal to the format value for the XlTable format. This format value (type WORD) is between 0xC000 and 0xFFFF, and it's equal to the format value that Windows returned to Microsoft Excel when it registered XlTable. If Windows cannot register XlTable, the function returns 0 (zero).

Fast Table Format

The fast table format, XlTable, is designed to maximize the DDE transfer speed of Microsoft Excel. XlTable consists of a sequence of data blocks that represent a rectangular selection of cells (a table). Each data block has three parts:

WORD tdt            /* the table data type */
WORD cb            /* the size (count of bytes) of the data */
BYTE data[cb]    /* the data */

The first data block is always of type tdtTable, which specifies the number of rows and the number of columns in the table. The data blocks that follow tdtTable represent all the cells in the table. Microsoft Excel renders the reference of the cells in the table (for example, R1C1:R2C4) as the item part of the DDE message.

The cells are always rendered row-wise. In other words, all the cells in the first row of the table appear first, then all the cells in the second row, and so on. To minimize overhead, adjacent cells of the same type (tdt) are represented together in one data block, even if the cells are in different rows. In other words, one tdtFloat can contain several numbers, one tdtString can contain several strings, one tdtBool can contain several Boolean values, and so on. For examples, see the following sections, "XlTable Example 1" and "XlTable Example 2."

The data block types are described in the following table.

Data block type | Value | Description
tdtTable | 0x0010 | The size of the table. The data (4 bytes, cb=4) consists of two words. The first word is the number of rows, and the second word is the number of columns.
tdtFloat | 0x0001 | IEEE-format floating-point number. The size of the number is 8 bytes per cell.
tdtString | 0x0002 | String in st (byte-counted) format. The first byte contains the length of the string (cch). The string isn't null-terminated.
tdtBool | 0x0003 | Boolean value: 1 = TRUE 0 = FALSE The length of the data is 2 bytes per cell.
tdtError | 0x0004 | Error value: 0 = #NULL! 7 = #DIV/0! 15 = #VALUE! 23 = #REF! 29 = #NAME? 36 = #NUM! 42 = #N/A The length of the data is 2 bytes per cell.
tdtBlank | 0x0005 | A count of the number of consecutive undefined (blank) cells. The data (2 bytes, cb=2) contains the number of consecutive blank cells.
tdtInt | 0x0006 | Unsigned integer. The length of the data is 2 bytes per cell. Microsoft Excel can read a number in this format, but it never writes a number in this format.
tdtSkip | 0x0007 | Number of cells to skip. A skipped cell is a cell that retains its previous value. In other words, a skipped cell isn't changed by a WM_DDE_DATA message. You can use tdtSkip to increase DDE performance if your application changes only one or two cells in the middle of a large table. Microsoft Excel doesn't support tdtSkip when the new cell data is part of a WM_DDE_POKE message. The length of the data is 2 bytes (cb=2).

XlTable Example 1

The following selection of three cells . . .

. . . produces the XlTable rendering shown in the following table.

Data (hexadecimal) | Description
10 00 04 00 01 00 03 00 | tdtTable, cb=4, rows=1, columns=3
02 00 10 00 | tdtString, cb=16
04 45 61 73 74 | cch=4, East (tdtString continued)
04 57 65 73 74 | cch=4, West (tdtString continued)
05 4e 6f 72 74 68 | cch=5, North (tdtString continued)

Notice that the table contains three cells, but the XlTable rendering contains only one tdtString data block.

XlTable Example 2

The XlTable format uses the tdtBlank data block to represent blank cells in a table. A sequence of several blank cells may be represented by a single tdtBlank data block.

For example, the following table . . .

. . . produces the following XlTable rendering.

Data (hexadecimal) | Description
10 00 04 00 02 00 04 00 | tdtTable, cb=4, rows=4, columns=2
06 00 08 00 02 00 03 00 04 00 05 00 | tdtInt, cb=8, int[0]=2, int[1]=3, int[2]=4, int[3]=5 (Microsoft Excel can read tdtInt as a client, but it would write tdtFloat if it were a server)
05 00 02 00 02 00 | tdtBlank, cb=2, data=2 (two cells are blank)
06 00 04 00 06 00 08 00 | tdtInt, cb=4, int[0]=6, int[1]=8

Biff5, Biff4, Biff3, and Biff Formats

The Biff5, Biff4, Biff3, and Biff Clipboard formats contain a variable number of records. The records are identical to the corresponding records in the BIFF file. For more information about the BIFF5 records, see Microsoft Excel File Format. The Biff4, Biff3, and Biff formats are available for backward compatibility with existing applications. The Biff Clipboard format corresponds to the BIFF2 file format.

If you implement one of the BIFF Clipboard formats, your code should be prepared to receive all BIFF records except file-specific records such as the following:

WRITEPROT
FILEPASS
TEMPLATE
WRITEACCESS
FILESHARING
CODEPAGE
PUB
SUB
EDG
INDEX

The requisite BIFF records that your code must provide when it writes to the Clipboard are as follows:

BOF
DIMENSIONS
Cell record or records (BLANK, BOOLERR, and so on)
EOF


Using DLLs from Visual Basic

Microsoft Office Technical Documentation Group

Created: November, 1995

Click to open or copy the ADVDLL project files

Using DLL functions from Visual Basic, Applications Edition, in Microsoft Excel is very similar to using DLL functions from Visual Basic. Chapter 26 of the Microsoft Visual Basic Programmer's Guide for version 4.0 of Visual Basic provides detailed guidelines and examples for calling DLL functions from Visual Basic. This article provides more specific information about using DLL functions from Visual Basic in Microsoft Excel.

The examples in this article were prepared and tested with Microsoft Visual C++ version 2.2, and run on Microsoft Windows 95. Visual C++ version 2.2 includes the OLE 2 header files and libraries required to create DLLs using variants, strings, objects, and arrays as described in this article.

You can use another C compiler and linker if they are capable of creating DLLs. In this case, you must also have the Microsoft OLE 2 Software Developer's Kit (SDK) to create DLLs using variants, strings, objects, or arrays.

In addition to the Help provided with Visual C++ and the OLE 2 SDK, Chapter 6 in Volume 2 of the OLE 2 Programmer's Reference provides valuable information about the functions used in the examples in this article.

Rewriting 16-bit DLL Code for Windows 95

Most 16-bit C-language DLL code will not work in Windows 95 without some modifications. The following sections discuss the changes required to run 16-bit DLL and Visual Basic code with Microsoft Excel for Windows 95. For more information about modifying 16-bit Visual Basic code and C-language DLLs, see the article "Porting 16-Bit Office-Based Solutions to 32-Bit Office" and Chapter 28 of the Microsoft Visual Basic Programmer's Guide for version 4.0 of Visual Basic.

Variable Size

In C-language DLLs written for 16-bit Windows, variables declared as integers (with the int data type) occupy 2 bytes (16 bits). In 32-bit Windows, the int data type occupies 4 bytes (32 bits). In both 16- and 32-bit Microsoft Excel VBA code, the Integer data type occupies only 16 bits, so in Microsoft Excel for Windows 95, the Integer and int data types are not equivalent.

The following table shows the data-type equivalencies for both 16- and 32-bit Windows.

Visual Basic data type

Size of variable

16-bit Windows data types

32-bit Windows data types

Integer | 2 bytes | int, short, WORD, HWND, HANDLE, WCHAR | short, WCHAR
Long | 4 bytes | long, LPSTR | int, long, HANDLE, HWND, LPSTR

If your DLL code uses the int data type with arguments either passed in or returned to Visual Basic code, you must change those arguments to use the short data type.

String Variables and Unicode

One significant difference between 16-bit and 32-bit environments is in how string data is stored and manipulated. Visual Basic in Microsoft Excel uses ANSI (American National Standards Institute) characters (a single byte represents each character) to store and manipulate strings in both 16- and 32-bit versions. Conversely, 32-bit OLE Automation and the 32-bit OLE 2 API use Unicode (two bytes represent each character) to store and manipulate strings.

Environment

Character set used

Windows 3.1 and Windows for Workgroups | ANSI
16- and 32-bit Visual Basic in Microsoft Excel, and 16-bit object libraries | ANSI
Windows 95 API | ANSI
32-bit object libraries | Unicode
Windows NT API | Unicode
OLE Automation in Windows NT | Unicode
OLE Automation in Windows 95 | Unicode

When you pass string data from Visual Basic in Microsoft Excel, the data uses ANSI characters. You can leave the strings in ANSI format if you are simply passing them back to Microsoft Excel or calling a Windows 95 system function, but you may need Unicode characters if you use OLE Automation or you call an OLE 2 API function. You can use the MultiByteToWideChar function to convert an ANSI string to Unicode, and the WideCharToMultiByte function to convert a Unicode string to ANSI.

In addition, because Microsoft Excel uses ANSI characters in BSTR variables, you cannot use the standard OLE string allocation and reallocation functions (these functions now create Unicode strings). Two new functions, SysAllocStringByteLen and SysStringByteLen, have been added to operate on single-byte character strings.

Windows API Functions

If your Visual Basic code calls a Windows API function, you will need to change the declaration in the Visual Basic code so that the correct system DLL is linked and the correct function is called. The easiest way to change the Visual Basic declaration is to look up the Windows API function in the Win32api.txt file and copy the declaration from that file into your Visual Basic code. For more information about calling 32-bit Windows system functions, see the article "Porting 16-Bit Office-Based Solutions to 32-Bit Office."

Using the Declare Statement

Before you can call a DLL function from Visual Basic, you must use the Declare statement to identify the function, the name of the DLL where it is located, and its argument types. Once the function is declared in a Visual Basic module, you can call it just as if it were part of your code.

For example, the following C-language function calculates the circumference of a circle given the circle's radius:

double __declspec(dllexport) DoubleArg(double dRadius)

{

return dRadius * 2 * 3.14159;

}

In Microsoft Windows 95 and Windows NT, DLL functions called from Microsoft Excel must be declared using the __declspec(dllexport) keywords. In 16-bit Windows, DLL functions use the FAR PASCAL calling convention, and on the Apple Macintosh, code-resource functions use the pascal calling convention. The examples in this article were written to run on Microsoft Windows 95. If you are using 16-bit Windows or the Apple Macintosh, modify the examples accordingly.

This Visual Basic code uses the DoubleArg C function to display a table of circumference values:

Declare Function DoubleArg Lib "advdll32" _

(ByVal radius As Double) As Double

Sub CircumferenceTable()

Worksheets(1).Activate

Cells(1, 1).Value = "Radius"

Cells(1, 2).Value = "Circumference"

For i = 1 To 10

Cells(i + 1, 1).Value = i

Cells(i + 1, 2).Value = DoubleArg(i)

Next

Columns("a:b").AutoFit

End Sub

The Declare statement uses the ByVal keyword because the argument is passed by value. Visual Basic coerces the variable i to type Double even though it is not explicitly declared in the code (with a Dim statement).

The REGISTER Macro Function

The REGISTER macro function and the Declare Visual Basic statement are not equivalent. Using the REGISTER function registers the DLL function only for the macro sheet or the worksheet. You cannot call the function from a Visual Basic module without using the Declare statement, even if you have already used the REGISTER function and called the same DLL function from a macro sheet. You can, however, call the function on a macro sheet by using the ExecuteExcel4Macro method to call the registered DLL function just as you would call any other Microsoft Excel macro function.

Similarly, DLL functions declared as public functions in a Visual Basic module can be called from any Visual Basic module in the workbook, but cannot be called from a macro sheet or worksheet. Public functions are those declared without either the Public or Private keywords (or explicitly declared with the Public keyword). If you declare the DLL function as Private, you can call the function only from the Visual Basic module where it is declared. You must use the REGISTER function before you can call the DLL function from a macro sheet or a worksheet, even if you have already used the Declare statement and called the same DLL function from a Visual Basic module.

To use the same DLL function in Visual Basic, on a macro sheet, and on a worksheet, you must both declare the function in a Visual Basic module and use the REGISTER function on the macro sheet and worksheet.

In addition, the REGISTER and UNREGISTER functions allow you to dynamically load and unload DLL functions. This is not possible in Visual Basic. Once a DLL function is loaded by a Visual Basic module (the first time a declared function in the DLL runs), the DLL remains loaded until you close the workbook that contains the Visual Basic module.

You can use the dynamic loading behavior of the REGISTER and UNREGISTER functions by creating a stub macro on a macro sheet. The stub macro should accept appropriate arguments for the DLL function, register the DLL function, call it, unregister it, and return the return value from the DLL function. You can then use the ExecuteExcel4Macro function to call the stub macro from Visual Basic. The stub macro in turn calls the DLL and returns to Visual Basic.

Passing Arguments by Reference

By default, Visual Basic passes arguments by reference, rather than by value. This means that the DLL function can modify the argument. When an argument is passed by reference, you must declare it as a pointer in the DLL function C-language prototype.

For example, this C-language function modifies its argument by multiplying it by two. The function returns False if the argument is less than zero.

short __declspec(dllexport) PointerArg(short *pn)

{

if (*pn < 0)

return 0; // False in Visual Basic

*pn *= 2;

return -1; // True in Visual Basic

}

The Visual Basic declaration for this function does not include the ByVal keyword. You may include the ByRef keyword, but it isn't necessary.

Declare Function PointerArg Lib "advdll32" _

(d As Integer) As Boolean

Sub TestPointerArg()

Dim n As Integer

n = CInt(InputBox("Number?"))

r = PointerArg(n)

MsgBox n & ":" & r

End Sub

Using Variants

Passing an argument of Variant data type is very similar to passing any other argument type. In the DLL, you can use the VARIANT data structure to access the data contained in the argument. See Chapter 5 in Volume 2 of the OLE 2 Programmer's Reference for descriptions of the VARIANT data type.

The VARIANT type is a C-language structure containing a single member for the variable type, three reserved members, and a large named union that is used to access the variable data depending on the type.

For example, this C-language function determines the data type contained in the VARIANT argument passed by Visual Basic:

short __declspec(dllexport) VariantArg(VARIANT vt)

{

int i;

char *pcBuf;

if (vt.vt == VT_DISPATCH) // variant is an object

return -1;

else if (vt.vt == VT_BSTR) { // variant is a string

i = SysStringLen(vt.bstrVal);

pcBuf = (char *)malloc(i + 1);

WideCharToMultiByte(CP_ACP, 0, vt.bstrVal, i, pcBuf, i, NULL, NULL);

i = atoi(pcBuf);

free(pcBuf);

return (short)i;

}

else if (vt.vt == VT_I2) // variant is an integer

return vt.iVal;

else // variant is something else

return -3;

}

Note When Microsoft Excel passes a Variant variable containing a string to a DLL, the string is in Unicode format. To use this string in functions requiring ANSI characters, you must convert the string using the WideCharToMultiByte function.

This Visual Basic code declares and calls the VariantArg function:

Declare Function VariantArg Lib "advdll32" _

(ByVal v As Variant) As Integer

Sub VariantArgTest()

MsgBox VariantArg(Worksheets(1)) ' -1

MsgBox VariantArg("25") ' 25

MsgBox VariantArg(5) ' 5

MsgBox VariantArg(3.2) ' -3

End Sub

You could use this information to implement a function that accepts either a Range object or a text description of a range. If the argument contains an object, you can use IDispatch to access properties and methods of the object directly. If the argument contains a string, you can use IDispatch to create an object and then access its properties and methods.

Visual Basic in Microsoft Excel does not support all the data types supported by the VARIANT structure. The following table shows the allowed data types and their value constants. Microsoft Excel never returns a Variant of a data type not shown on this list.

Data Type

Variant Constant

Boolean | VT_BOOL
Currency (scaled integer) | VT_CY
Date | VT_DATE
Double (double-precision floating-point) | VT_R8
Integer | VT_I2
Long (long integer) | VT_I4
Object | VT_DISPATCH
Single (single-precision floating-point) | VT_R4
String | VT_BSTR

Variants and Objects

The VariantArg function shows how you declare and call a DLL function with a Variant passed by value. A Variant passed by reference would be declared in C as a pointer to a VARIANT structure.

void VariantByRef(LPVARIANT *pvar)

While it is possible to pass an object as a Variant, it is also possible to specifically declare a function that accepts only an object. An object is passed as a dispatch pointer, either by value:

void ObjectByVal(LPDISPATCH pdisp)

or by reference:

void ObjectByRef(LPDISPATCH *ppdisp)

When you pass a variant or object by reference, remember that your DLL code must free any allocated object, string, or array before replacing it. Failure to free allocations results in memory leaks. More information about freeing allocated strings and arrays appears in the following sections.

Return Values

When your function returns an object, it is declared as returning a dispatch pointer:

LPDISPATCH ReturnsObject(void)

Returning a Variant is simple:

VARIANT ReturnsVariant(void)

Using Strings

When Visual Basic passes a string by reference to a C-language DLL, it uses a special OLE 2 data type called a BSTR. OLE Automation allows BSTR strings to be allocated and freed by any component that supports this data type.

In most cases, a BSTR can be treated like a pointer to a null-terminated string. In general, it's best if your C-language code does not directly manipulate the string data. You can dereference the pointer to copy data from the BSTR, however.

Instead of directly manipulating BSTR data, OLE Automation provides several functions that should be used to allocate, free, and reallocate BSTR values. These functions are listed in Chapter 6 in Volume 2 of the OLE 2 Programmer's Reference.

Note Because Microsoft Excel uses ANSI characters in BSTR variables, you cannot use the standard OLE string allocation and reallocation functions (these functions expect Unicode strings). Two new functions, SysAllocStringByteLen and SysStringByteLen, have been added to operate on single-byte character strings.

When you pass a string by reference, your C-language function should declare the argument as a pointer to a BSTR. The pointer will never be NULL, but if the Visual Basic string is unassigned (that is, created with the Dim statement but not assigned a value), the BSTR pointed to will be NULL. If the string is assigned but empty, the first character will be a null character, and the string length will be zero.

The pointer may also reference a NULL pointer if the original variable was created as a Variant type, but not assigned a value. Visual Basic would coerce the variant to a string when it called the DLL, but because the variant is empty, it behaves like a declared but unassigned string.

The following code example tests for these conditions:

short __declspec(dllexport) SType(BSTR *pbstr)

{

if (pbstr == NULL) // pointer is null; will never happen

return 1;

if (*pbstr == NULL) // string (or variant) is allocated by VB

// with Dim statement,

// but not yet assigned

return 2;

if (*pbstr[0] == 0) // string is allocated

// and assigned to empty string ("")

return 3;

// string has a value; ANSI characters can be accessed at *pbstr

return 4;

}

This Visual Basic code declares and calls the SType function:

Declare Function SType Lib "advdll32" _

(s As String) As Integer

Sub STypeTest()

Dim s As String

MsgBox SType(s) 'displays 2

s = ""

MsgBox SType(s) 'displays 3

s = "test"

MsgBox SType(s) 'displays 4

End Sub

Allocating BSTR Values

You should always use OLE functions to operate on BSTR values. If you need to change a BSTR value, first test the BSTR to see if it is already assigned. If it isn't, you may use the SysAllocStringByteLen function to assign a value to the BSTR. If the BSTR is already assigned, you must free the current assignment (with the SysFreeString function) before you can use SysAllocStringByteLen.

The following C-language code copies some number of characters from one BSTR into another. Notice that this example tests the second BSTR to see if it is already assigned. If it is, the example uses the SysFreeString function to free the existing string before replacing it.

short __declspec(dllexport) StringArgs(BSTR *pbstrArg1,

BSTR *pbstrArg2, int cch)

{

// return error code if requested characters

// less than zero, or input string is unassigned

// or has too few characters

if (cch < 0 || *pbstrArg1 == NULL ||

(int)SysStringByteLen(*pbstrArg1) < cch)

return -1;

if (*pbstrArg2 != NULL) { // argument string is already assigned;

// we must free before allocating

SysFreeString(*pbstrArg2);

}

if ((*pbstrArg2 = SysAllocStringByteLen((char *)*pbstrArg1, cch))

== NULL)

return -2;

return 0;

}

This Visual Basic code declares and calls the StringArgs function:

Declare Function StringArgs Lib "advdll32" _

(inpStr As String, outStr As String, _

ByVal n As Integer) As Integer

Sub StringArgsTest()

Dim newStr As String

x = StringArgs("abracadabra", newStr, 5)

MsgBox x & ":" & newStr

End Sub

Using User-Defined Data Structures

The Type statement in Visual Basic can be used to create user-defined data structures. For example, the following Visual Basic data type and C-language structure are equivalent.

In Visual Basic:

Type ARG

i as Integer

str as String

End Type

In C:

typedef struct {

int i;

BSTR str;

} ARG;

User-defined data types cannot be passed by value; they must be passed by reference. Your C function should declare the argument as a pointer to the structure. If the structure contains BSTR values (as this example does) the rules discussed above apply to those values; you must test the BSTR before you reassign it (and free it if it is already allocated).

For example, this C-language function fills a structure with a string and the length of the string:

short __declspec(dllexport) StructArg(ARG *parg, char *szArg)

{

unsigned int cch;

BSTR bstr;

if (parg == NULL)

return -1;

// allocate a local string first; if this fails,

// we have not touched the passed-in string

cch = strlen(szArg);

if ((bstr = SysAllocStringByteLen(szArg, cch)) == NULL)

return -1;

if (parg->bstr != NULL) // string is already assigned

SysFreeString(parg->bstr);

parg->s = (short)cch;

parg->bstr = bstr;

return parg->s;

}

Declared and called from Visual Basic:

Declare Function StructArg Lib "advdll32" _

(a As ARG, ByVal s As String) As Integer

Sub StructArgTest()

Dim x As ARG

MsgBox StructArg(x, "abracadabra")

MsgBox x.str & ":" & x.i 'displays string and length

End Sub

Using Arrays

OLE 2 provides a special data type for arrays passed from Visual Basic to a DLL. This data type, called a SAFEARRAY, allows both Visual Basic and the DLL to allocate, free, and access array data in a controlled way.

Your DLL should always use OLE Automation functions to allocate and access safe arrays. These functions are described in Chapter 6 in Volume 2 of the OLE 2 Programmer's Reference. When OLE Automation passes a safe array to your DLL, you receive a pointer to a pointer to the array itself. Like BSTR pointers, a SAFEARRAY pointer may point to a NULL array if the array has been declared but not yet dimensioned:

Dim a() as Integer

The pointer itself will never be NULL, however.

The following example determines the upper and lower bounds of an array and then loops through the array producing the sum of the elements in the array:

short __declspec(dllexport) SumArray(

FPSAFEARRAY *ppsa, long *plResult)

{

short sElem;

long lLb, lUb, l, lResult;

if (*ppsa == NULL) // array has not been initialized

return -4;

if ((*ppsa)->cDims != 1) // check number of dimensions

return -5;

// get the upper and lower bounds of the array

if (FAILED(SafeArrayGetLBound(*ppsa, 1, &lLb)) ||

FAILED(SafeArrayGetUBound(*ppsa, 1, &lUb)))

return -1;

// loop through the array and add the elements

for (l = lLb, lResult = 0; l <= lUb; l++) {

if (FAILED(SafeArrayGetElement(*ppsa, &l, &sElem)))

return -2;

lResult += sElem;

}

*plResult = lResult;

return 0;

}

Declared and called from Visual Basic:

Declare Function SumArray Lib "advdll32" _

(a() As Integer, r As Long) As Integer

Sub SumArrayTest()

Dim n(5) As Integer

Dim result As Long

For i = 0 To 5

n(i) = 2

Next

x = SumArray(n, result)

MsgBox x & ":" & result

End Sub

Visual Basic does minimal type checking and enforcement on array element size. Because this function was declared as accepting only an array of integers, it is safe to use an integer element in the call to the SafeArrayGetElement function in the DLL. If the function was declared as accepting an array of any type, however, the Visual Basic code might pass an array of long values; in this case, the C-language function would produce incorrect results. If your DLL function must accept an array of any type, you should use an array of variants and check the variant type in the DLL.

Static Arrays

If you declare and dimension an array:

Dim x(5) as String

The pointer you receive in your C function points to a static array (the fFeatures element of the SAFEARRAY structure has the FADF_STATIC flag set). You can read and redimension the array, but you cannot modify the pointer, and you cannot copy over the array. If you need to modify the array in the DLL (to create a new one, for example), you must not dimension it in Visual Basic.

Allocating Arrays

Your DLL can create new safe arrays or change the size of existing arrays. When you create a new array, you should use a local variable rather than modify a passed-in array pointer. Once the allocation and any subsequent operations on the array are successful, you can assign the passed-in pointer to the local pointer and return from the function.

The following example accepts an array pointer and creates an array containing 10 integer elements. If the passed-in array has already been initialized, the function redimensions the existing array.

short __declspec(dllexport) NewArray(FPSAFEARRAY *ppsa)

{

SAFEARRAY *psa;

SAFEARRAYBOUND sa;

sa.lLbound = 1;

sa.cElements = 10;

if (*ppsa == NULL) { //array not yet initialized

if ((psa = SafeArrayCreate(VT_I2, 1, &sa)) == NULL)

return -2;

*ppsa = psa;

}

else {

if ((*ppsa)->cDims != 1) // check array dimensions

return -1; // fail if multi-dimension

if (FAILED(SafeArrayRedim(*ppsa, &sa)))

return -3;

}

return 0;

}

Declared and called from Visual Basic:

Declare Function NewArray Lib "advdll32" _

(a() As Integer) As Integer

Sub NewArrayTest()

Dim a(12) As Integer

MsgBox NewArray(a) & ":" & LBound(a) & ":" & UBound(a)

End Sub

Destroying Arrays

Like BSTRs, SAFEARRAYs must be freed before they can be destroyed. When Visual Basic passes an existing array to your DLL, it is passed as a static array that cannot be destroyed. Your DLL can create its own arrays, however. When you no longer need an array, it should be destroyed.

You must be careful when you destroy an existing array. Freeing the array frees only the array memory; if the array contains any pointers (such as BSTR values) these will not be freed. In this case, you must free each BSTR element individually and then free the array. If you do not know what the array contains, you should probably not free or redimension the array.

Using Arrays of Strings

Safe arrays can contain elements of any allowable type, including BSTRs and user-defined data structures. BSTRs inside arrays should be manipulated with the same OLE Automation functions as ordinary BSTRs. Always remember to free any existing BSTR before allocating a new one, or use the reallocation function.

The following example creates or redimensions an array of strings. Any existing BSTR data in the array is freed before new data is copied into the array.

short __declspec(dllexport) StringArray(FPSAFEARRAY *ppsa)

{

LONG l;

BSTR bstr;

SAFEARRAY *psa;

SAFEARRAYBOUND sa;

sa.lLbound = 0;

sa.cElements = 3;

if ((*ppsa)->cDims != 1) // check array dimensions

return -1;

if (*ppsa == NULL) { // array not yet initialized

if ((psa = SafeArrayCreate(VT_BSTR, 1, &sa)) == NULL)

return -2;

*ppsa = psa;

}

else if (FAILED(SafeArrayRedim(*ppsa, &sa)))

return -3;

// loop through the array; get each element and free

// any existing string, then allocate the new string

// and put it in the array

for (l = sa.lLbound; l < (long)sa.cElements; l++) {

if (FAILED(SafeArrayGetElement(*ppsa, &l, &bstr)))

return -4;

SysFreeString(bstr);

if ((bstr = SysAllocStringByteLen("test string", 11)) == NULL)

return -5;

if (FAILED(SafeArrayPutElement(*ppsa, &l, bstr)))

return -6;

}

return 0;

}

Declared and called from Visual Basic:

Declare Function StringArray Lib "advdll32" _

(s() As String) As Integer

Sub StringArrayTest()

Dim s(5) As String

MsgBox StringArray(s) & ":" & s(1)

End Sub

'start NewArray

Sub NewArrayTest()

Dim a(12) As Integer

MsgBox NewArray(a) & ":" & LBound(a) & ":" & UBound(a)

End Sub

Using Arrays of Data Structures

You cannot use the SafeArrayCreate function to create a new array of user-defined structures. Instead, you must use the SafeArrayAllocDescriptor function to create the array descriptor, then use the SafeArrayAllocData function to allocate space for the array data, and finally use the SafeArrayAccessData function to return a pointer to the data. The SafeArrayAccessData function locks the array data; when you are done with the array, you should call the SafeArrayUnaccessData function to unlock it.

You cannot replace an existing array, so if your Visual Basic code passes a dimensioned array you must redimension it. Remember to free any existing BSTR pointers in the array before overwriting them.

The following example creates or redimensions an array of data structures then copies an array of strings into the structures, adding the string length to each structure. Any existing BSTR data in the array is freed before new data is copied into the array.

short __declspec(dllexport) StructArray(FPSAFEARRAY *ppsaArg,

FPSAFEARRAY *ppsaStr)

{

ARG *parg;

SAFEARRAY *psa;

BSTR *pbstr;

ULONG i, cElements;

if (*ppsaStr == NULL)

return -1;

cElements = (*ppsaStr)->rgsabound[0].cElements;

if (*ppsaArg == NULL) { // create a new array

if (FAILED(SafeArrayAllocDescriptor(1, &psa)))

return -3;

// set up the SAFEARRAY structure

// and allocate data space

psa->fFeatures = 0;

psa->cbElements = sizeof(ARG);

psa->rgsabound[0].cElements = cElements;

psa->rgsabound[0].lLbound = (*ppsaStr)->rgsabound[0].lLbound;

if (FAILED(SafeArrayAllocData(psa))) {

SafeArrayDestroyDescriptor(psa);

return -4;

}

// get a pointer to the new data

if (FAILED(SafeArrayAccessData(psa,

(void **)&parg))) {

SafeArrayDestroy(psa);

return -5;

}

}

else { // redimension the old array

if (FAILED(SafeArrayRedim(*ppsaArg,

(*ppsaStr)->rgsabound)))

return -6;

// get a pointer to the old data

if (FAILED(SafeArrayAccessData(*ppsaArg,

(void **)&parg)))

return -7;

}

// get a pointer to the string array data

if (FAILED(SafeArrayAccessData(*ppsaStr,

(void **)&pbstr)))

return -8;

// allocate strings in the structure array and

// fill them with strings from the string array.

// free any old BSTRs in the structure

for (i = 0; i < cElements; i++) {

SysFreeString(parg[i].bstr);

parg[i].s = strlen((char *)pbstr[i]);

parg[i].bstr =

SysAllocStringByteLen((char *)pbstr[i], parg[i].s);

}

// release pointers and move the structure

// array pointer to the new array if we created one

SafeArrayUnaccessData(*ppsaStr);

if (*ppsaArg == NULL) {

SafeArrayUnaccessData(psa);

*ppsaArg = psa;

}

else

SafeArrayUnaccessData(*ppsaArg);

return 0;

}

Declared and called from Visual Basic:

Declare Function StructArray Lib "advdll32" _

(x() As ARG, s() As String) As Integer

Sub StructArrayTest()

Dim x() As ARG

Dim s(1 To 4) As String

s(1) = "yellow"

s(2) = "orange"

s(3) = "blue"

s(4) = "green"

n = StructArray(x, s)

If n = 0 Then

Worksheets(1).Activate

Range("a1:c25").Clear

For i = LBound(x) To UBound(x)

Cells(i + 1, 1) = i

Cells(i + 1, 2) = x(i).str

Cells(i + 1, 3) = x(i).i

Next

Else

MsgBox "StructArray failed, returned" & n

End If

End Sub

Using the Microsoft Excel C API and Visual Basic

When you call a DLL function from Visual Basic in Microsoft Excel, the DLL function can use the Microsoft Excel C Applications Programming Interface (C API) functions to call back into Microsoft Excel. You cannot use the C API across processes, however. The DLL using the C API must be called from Visual Basic running in Microsoft Excel (a DLL called from Microsoft Project or Microsoft Visual Basic Professional cannot call the C API). In addition, the C API can only be called after Microsoft Excel has called the DLL. This qualification is met when Visual Basic in Microsoft Excel calls the DLL, and the DLL in turn calls the C API. When the DLL function is called by an external event (such as a DDE command from another application or a Windows timer), the DLL function cannot call the C API.

Type Libraries

You can create a type library for your DLL. The type library can contain constant and function declarations and other information about the DLL. Once you have created a type library, you can use the References command on the Tools menu in Microsoft Excel to load the type library. Once loaded, the constant and function declarations are available in Visual Basic without using Declare statements.

Visual Basic in Microsoft Excel does not support user-defined data-structure declarations in type libraries (user-defined data structures are those declared with the Visual Basic Type statement or the C/C++ struct statement). To use the structures in your Visual Basic code, you will have to add their declarations to the module.

For more information about creating type libraries, see Chapter 7 in Volume 2 of the OLE 2 Programmer's Reference.


File Converter API

Microsoft Office Technical Documentation Group

Created: November, 1995

Microsoft Excel provides a file converter application programming interface (API) with which you can write a custom input file converter. For example, the Quattro Pro for Windows file converter that is included with Microsoft Excel 7.0 uses the file converter API.

Although the file converter API is identical across operating environments, a converter is platform-specific, which means that it must be compiled into a 32-bit DLL for Windows NT and Windows 95, a 16-bit DLL for Windows 3.1, and a code resource for the Macintosh.

This kit includes a sample file converter that converts the text file created by the BiffView utility. The sources and the compiled 32-bit DLL are in the \Sample\Undump folder. The 32-bit Undump project was developed and tested with Microsoft Visual C++ version 2.2.

Click to open or copy the FILECONV project files

File Converter Background

This section describes the file converter user interface, the file converter selection algorithm, file converter internals and error handling, and system registry settings that expose the converter to Microsoft Excel.

File Converter User Interface

File converters are seamlessly integrated into the Open dialog box (File menu). To expose the converter to the user, you add a filter option to the List Files Of Type box in the Open dialog box. This additional option is created by a key in the System Registry. If you installed the Quattro Pro for Windows converter when you installed Microsoft Excel, you can see the Quattro Pro for Windows (*.wb1) filter option in the List Files Of Type box in the Open dialog box.

If you didn't install the Quattro Pro for Windows converter, you can run the Microsoft Excel setup program to add it. You can also manually add the option for the Undump.dll converter to the System Registry, as described in Exposing the Converter to Microsoft Excel.

File Converter Selection Algorithm

Microsoft Excel tries to detect the file format automatically when you open a file, as shown in the following pseudocode.

For Each built-in file format except TEXT and CSV

Test the first n bytes of the file until either a format is

recognized or until all built-in formats have been tried

(except TEXT and CSV)

If file format is still not recognized Then

For each file format in InstallableInputConvertersList

Tell input converter DLL to sniff the first n bytes of the

file until either a format is recognized or all of the

installable input converters have been tried

If file is still not recognized Then

Assume the file is TEXT format and start the Text Import Wizard

You can force Microsoft Excel to try a particular file converter first by selecting the converter's filter option in the List Files Of Type box. In this case, Microsoft Excel attempts to detect the file format only if the file converter doesn't recognize the file format.

In Undump.c, the IsFormatOk function detects the file format by comparing the passed-in string to the string in the variable szBIFF5.

Inside the File Converter

The file recognition function (in Undump.c, the IsFormatOk function) is the first converter function that Microsoft Excel calls. If your converter recognizes the file format, Microsoft Excel then calls the converter's initialization function to give you an opportunity to do any necessary initialization. The initialization function in Undump.c is called InitLoad.

After initialization, Microsoft Excel repeatedly calls your converter to get BIFF records. Your code must provide the BIFF records in the format shown in the article Microsoft Excel File Format. Your code is also responsible for the actual conversion from the non-native data format to BIFF format. Conversion ends when your converter returns the last EOF record in the file.

The converter is called three times for each BIFF record: the first call returns the BIFF record type, the second call returns the number of bytes in the record data, and the third call returns the data. To see examples of these calls in Undump.c, look for the following three functions: RtNextRecord, CbNextRecord, and DataNextRecord.

To help you write a robust converter, Microsoft Excel exposes a callback function that your converter should use for memory management and for file input and output. For more information, see Callback Function.

You can compile a debug build of Undump.dll and then use the Visual C++ debugger to watch the entire conversion process. Undump is a very straightforward example of a converter, because there is a one-to-one correspondence between Undump "records" and BIFF records. The records can be processed sequentially, as they are read from the BiffView-created text file.

Error Handling

If Microsoft Excel encounters an error during file conversion, it calls your converter before displaying an error message to the user. This mechanism gives your code an opportunity to do last-minute cleanup (for example, freeing allocated buffers). Because Microsoft Excel provides the file input/output services, your code doesn't have to handle file cleanup. In Undump.c, the error handler is the function AbortLoad (although there is no error handling in the program, just a short cleanup function).

Your converter can notify Microsoft Excel of a fatal error by returning the special BIFF record type rtNil, which is defined in the header file Biff.h in the \Sample\Undump\Win32 folder. This record causes Microsoft Excel to call your error handler and then stop the file load. The rtNil record has no record data field.

Exposing the Converter to Microsoft Excel

To expose the file converter in 32-bit Windows products, you add a value to the System Registry. To expose the file converter in 16-bit Windows products, you edit the Excel5.ini file, and on the Macintosh, you edit the Excel Settings (5) file.

Win32

In Microsoft Excel for Windows NT and Windows 95, you add a string value entry to the HKEY_CURRENT_USER\Software\Microsoft\Excel\7.0\Converters key. For example, Setup adds the following string value entry when you install the Quattro Pro for Windows file converter. The value name is QPro:

Quattro Pro for Windows (*.wb1), C:\MSOffice\Excel\xlqpw.dll, *.wb1

The string value entries are in the following form:

<Friendly description>, <DLL filename, including path>,

<Search filter>

Token | Description
<Friendly description> | The text that appears in the List Files Of Type box in the Open dialog box (File menu).
<DLL filename, including path> | The filename and path of the converter DLL. If you omit the path, the DLL must be in the same folder as Excel.exe.
<Search filter> | A file-filter string — for example, *.xl*

Note If you did not install any file converters during Microsoft Office setup (or Microsoft Excel setup), then the Converters key will not exist. In this case, you can use the Registry Editor to add the key manually, or create a .reg file to add the key automatically.

Win16

In Microsoft Excel for 16-bit Windows, the [Converters] section of Excel5.ini contains a line for each converter. The line is very similar to the string value entry in the Win32 system registry, except that a tag name is added to the string.

<ConverterTag> = <Friendly description>, <DLL filename, including path>,

<Search filter>

Token | Description
<ConverterTag> | A unique tag name in the [Converters] section; ignored by Microsoft Excel.
<Friendly description> | The text that appears in the List Files Of Type box in the Open dialog box (File menu).
<DLL filename, including path> | The filename and path of the converter DLL. If you omit the path, the DLL must be in the same folder as Excel.exe.
<Search filter> | A file-filter string — for example, *.xl.*

Macintosh

On the Macintosh, file extensions (for example, .xls) are replaced by one or more four-character file types (for example, XCEL). To add file converters to the Excel Preferences (5) file, you must use ResEdit to add a GRID resource. If a GRID resource named Converters doesn't exist, then create one. Each GRID resource is an array of words that are actually string resource IDs.

Each GRID resource has the following form:

<name that appears in drop-down>,"<full path to file converter>",

<list of 4-letter file types separated by ;>

For example:

Undump BiffView Files,"HD80:Excel5:undump.res",lttr;XLS5

The "full path to file converter" token must contain the full path and filename of the converter code resource, and it must be enclosed in quotation marks, as shown in the preceding example. Quotation marks are optional for the other two tokens.

For more information about editing the Excel Preferences (5) file, see Specifying Settings in Microsoft Excel version 5.0 for the Macintosh.

File Converter API Functions

This section describes the EFCP structure, the XlConverter function, and the callback function EfcCallBack.

The EFCP Structure

When Microsoft Excel calls the file converter, it passes a pointer to an EFCP data structure, which is defined in Xlconv.h, as shown in the following examples and table.

Windows

typedef struct _efcParam

{

long lcb;

BYTE FAR *lprgb;

FARPROC lpfn;

} EFCP, FAR * LPEFCP;

Macintosh

typedef struct _efcParam

{

long lcb;

unsigned char *lprgb;

ProcPtr lpfn;

} EFCP, * PEFCP;

Member | Description
lcb | Byte count
lprgb | Pointer to a buffer
lpfn | Pointer to a Microsoft Excel callback function

For more information about using this structure, see the following sections, "Converter Entry Point" and "Callback Function."

Converter Entry Point

The file converter should export a single function as its entry point, as shown in the following examples.

Win32

short FAR PASCAL XlConverter(iAction, lpefcp)

16-bit Windows

short FAR PASCAL __export XlConverter(short iAction, LPEFCP lpefcp)

The __export keyword is required for 16-bit DLLs.

Macintosh

short PASCAL XlConverter(short iAction, LPEFCP lpefcp)

The lpefcp parameter is the pointer to the EFCP structure. The command ID, iAction, is the converter opcode. Its values, defined in Xlconv.h, are listed in the following table.

Value | Description
iActionIsFormatOk | Returns TRUE if the converter recognizes the file format.
iActionInitLoad | Initializes the converter; returns TRUE if successful.
iActionRtNextRecord | Returns the record type of the next BIFF record; the record types are defined in BIFF.H.
iActionCbNextRecord | Returns the number of bytes in the data field of the next BIFF record.
iActionDataNextRecord | Returns the data for the next BIFF record; see the article Microsoft Excel File Format.
iActionAbortLoad | Indicates that Microsoft Excel has detected a fatal error; clean up now.

The following sections describe the opcodes in more detail.

iActionIsFormatOk

Microsoft Excel asks the converter whether it recognizes the format of the file that the user is opening.

This is the first opcode sent to the converter. If the converter returns FALSE, Microsoft Excel doesn't call the converter again for this file.

Input

Member | Description
lcb | Size of the file-recognition string
lprgb | Pointer to the buffer containing the file-recognition string
lpfn | Pointer to the callback function

Output

None.

Return value

TRUE if the converter recognizes this file format.

FALSE if the converter doesn't recognize this file format.

iActionInitLoad

Microsoft Excel asks the converter to do any preconversion initialization. This opcode is sent after the iActionIsFormatOk call returns TRUE.

Input

Member | Description
lcb | Size of the input file.
Lprgb | Pointer to a buffer containing the locale ID (LCID).
Lpfn | NULL

Output

None.

Return value

TRUE if the converter initialized successfully.

FALSE if the converter encountered a fatal error. This return value causes Microsoft Excel to call the converter a final time, using the iActionAbortLoad opcode.

iActionRtNextRecord

Microsoft Excel asks for the record type of the next BIFF record to be received from the converter. Record types are defined in Biff.h.

This is one of the three calls (along with iActionCbNextRecord and iActionDataNextRecord) in the main conversion loop.

Input

Member | Description
lcb | Unused
lprgb | Unused
lpfn | Unused

Output

None.

Return value

BIFF record type as defined in Biff.h. The first record type must be rtBOF. Return rtEOF to indicate the end of the conversion.

iActionCbNextRecord

Microsoft Excel asks the converter for the length of the data in the next BIFF record. The return value is used to allocate buffer storage for the following iActionDataNextRecord call.

This is one of the three calls (along with iActionRtNextRecord and iActionDataNextRecord) in the main conversion loop.

Input

Member | Description
lcb | Unused
lprgb | Unused
lpfn | Unused

Output

None.

Return value

The size of the next BIFF record, in bytes. This value must be <=cbBiffMax as defined in Biff.h; if it is greater than this, Excel calls iActionAbortLoad.

iActionDataNextRecord

Microsoft Excel asks the converter for the BIFF record data.

This is one of the three calls (along with iActionRtNextRecord and iActionCbNextRecord) in the main conversion loop.

Input

Member | Description
lcb | Length of data
lprgb | Pointer to the buffer for the BIFF record data. (the size of the buffer is cbBiffMax)
lpfn | Unused

Output

Member | Description
lprgb | Pointer to the actual data in the BIFF record; for BIFF record descriptions, see the article Microsoft Excel File Format. The record data starts at offset 4 in the record descriptions in that article.

Return value

An integer from 0 to 100 that indicates the percentage-complete status of the conversion. Microsoft Excel uses this value to update the load progress indicator in the status bar. The return value should equal 100 when your converter returns rtEOF. See the DataNextRecord function in Undump.c for an example of the percentage-complete calculation.

iActionAbortLoad

Microsoft Excel informs the converter that it has detected a fatal load error; called after the converter returns FALSE for the iActionInitLoad call to the converter. This is the only chance for the converter to do any necessary cleanup. Because Microsoft Excel provides file input/output services, your code doesn't have to handle file cleanup.

Input

Member | Description
lcb | Unused
lprgb | Unused
lpfn | Unused

Output

None.

Return value

Ignored.

Callback Function

Your converter should always use the callback function for memory management and for file input/output. This helps ensure peaceful coexistence with Microsoft Excel. The callback function is declared within Microsoft Excel as follows:

short FAR PASCAL EfcCallBack( short int iefccmd,

BYTE FAR *lpb,

long int lcb)

The command ID, iefccmd, is the callback opcode. Its values, defined in Xlconv.h, are listed in the following table.

Value | Description
iefccmdCbFromFile | Asks Microsoft Excel to read lcb bytes from the input file stream
iefccmdAllocCb | Asks Microsoft Excel to allocate a buffer
iefccmdFreeCb | Asks Microsoft Excel to free a buffer
iefccmdGetPos | Asks Microsoft Excel to get the current stream position of the file pointer
iefccmdSetPos | Asks Microsoft Excel to set the current stream position of the file pointer

The lpb and lcb parameters take on different meanings, as described in the following sections.

iefccmdCbFromFile

Asks Microsoft Excel to read lcb bytes from the input file stream.

Input

Member | Description
lpb | Pointer to a buffer to hold file data (remember, the converter is responsible for allocating this buffer)
lcb | Size of a file buffer

Output

Member | Description
lpb | Pointer to the buffer that contains the file data

Return value

The actual byte count written to the file buffer. Microsoft Excel attempts to fill the buffer completely; the actual count will be less than the requested size if an EOF is encountered in the input stream before the buffer is full.

iefccmdAllocCb

Asks Microsoft Excel to allocate a buffer for the converter.

Input

Member | Description
lpb | Pointer to a 32-bit variable (DWORD or long) that stores the address of the allocated buffer
lcb | Requested buffer size

Output

Member | Description
lpb | Pointer to a 32-bit variable (DWORD or long) that stores the address of the allocated buffer

Return value

The actual count of bytes allocated. Returns 0 to indicate an out-of-memory condition and to give your converter an opportunity to request a smaller amount of memory instead.

Note With the 16-bit Windows version 3.1, you can allocate only a 64K buffer (actually slightly less than 64K because of system overhead). With 32-bit Windows NT, you can allocate a buffer up to either the available memory limit or 4 GB — whichever is smaller.

iefccmdFreeCb

Asks Microsoft Excel to free a buffer that was previously allocated using an iefccmdAllocCb call.

Input

Member | Description
lpb | Pointer to a 32-bit variable (DWORD or long) that stores the address of the buffer to be freed
lcb | Size of the buffer to be freed

Output

None.

Return value

None. The converter should assume that this call always succeeds.

iefccmdGetPos

Asks Microsoft Excel to get the current (zero-based) offset in the input file stream.

Input

Member | Description
lpb | lPointer to a 32-bit variable (DWORD or long) to store the stream offset
lcb | lUnused

Output

Member | Description
lpb | Pointer to a 32-bit variable (DWORD or long) that contains the current input stream offset

Return value

Unused.

iefccmdSetPos

Asks Microsoft Excel to set the current (zero-based) offset in the input file stream.

Input

Member | Description
lpb | Pointer to a 32-bit variable (DWORD or long) that contains the offset you want
lcb | Unused

Output

None; lpb is unchanged.

Return value

Unused.

Using File Converters from the Macro Languages

In Visual Basic for applications, you can use the FileConverters property to return an n x 3 array that contains information about installed converters, where n is equal to the number of installed converters. The other dimension contains the three strings from the entry in the Excel5.ini (or equivalent) file.

In the Microsoft Excel version 4.0 macro language, you can use the GET.WORKSPACE(62) macro function to list the installed converters. Array-enter this function in enough cells to store the maximum number of expected converters. Uninstalled converters correspond to the #N/A error value in the cells.

The Open method (Visual Basic) and the OPEN() macro function both contain a Converter argument that can be used to override the converter automatic detection algorithm. The argument is a 1-based index to the table of converters (as given by the FileConverters property or the GET.WORKSPACE(62) macro function).


AppleScript Reference Help

If you are using AppleScript with Microsoft Excel, install the helpfile in this article to obtain the Microsoft Excel AppleScript reference.

Click to open or copy the ASCRIPT help file


Introduction

Welcome to Visual Basic® for applications — the programming language used in Microsoft® Excel. Using Visual Basic, you can automate everyday tasks, add custom features and functions to suit your needs, and even create complete applications.

In Microsoft Excel, you automate tasks with macros. A macro is a sequence of instructions, written in Visual Basic, that tells Microsoft Excel what to do.

Microsoft Excel provides a feature called the macro recorder, which writes macros for you by storing the actions you take and the commands you choose as you work with Microsoft Excel. Later you can play back, or run, the macro to repeat your recorded actions automatically, saving yourself time and effort.

After you learn to record and run macros, you'll discover how useful they can be, and you'll want to make them even more powerful by adding your own Visual Basic code and improving the recorded code.

Whether you're a new user or an experienced macro developer, Visual Basic can make you more productive. With Visual Basic, you can create custom commands, menus, dialog boxes, messages, and buttons — and you can display custom Help topics for all of these items. From automating repetitive tasks to developing powerful, full-featured applications, Visual Basic's tools enable you to customize Microsoft Excel so that it fits your specific needs.


Getting Started

This introduction describes the printed and online documentation you'll use as you learn more about Visual Basic. The following sections will help you determine how this book can best serve your needs.


Where Are You?

This book assumes that you already know how to use Microsoft Excel. If you're new to Microsoft Excel, you should set this book aside for now. For general information about Microsoft Excel, see Getting Results with Microsoft Excel for Windows 95 or Getting Results with Microsoft Office for Windows 95.

You can record and use macros in Microsoft Excel without learning Visual Basic. If you've never recorded or run a Visual Basic macro, see the topics listed under "Recording and Running Macros" on the Contents tab in Help.

Note

If you clicked Typical when you installed Microsoft Excel, you'll need to run Setup again to install the Visual Basic Help file. For more information, see "Using Online Help" later in this introduction.

This book is designed for intermediate users of Visual Basic in Microsoft Excel. It provides information based on subject area rather than specific tasks. If you're new to Visual Basic in Microsoft Excel, or if you prefer a more task-oriented approach, you might want to start by reading Microsoft Excel Visual Basic Step by Step, a self-paced tutorial available from Microsoft Press®; then you can use this book to customize and optimize what you've learned.

Note

You can order Microsoft Excel Visual Basic Step by Step and the Microsoft Excel Visual Basic Reference (a printed version of the online Visual Basic Help) directly from Microsoft Press. To place a credit card order, call 615-793-5090, or call 1-800-MS-PRESS toll-free. Please be sure to have your reference code FXL ready for faster order processing. CompuServe® subscribers can also order through the Microsoft Press Electronic Book Store by typing GO MSP.


Tips on How to Learn Visual Basic

The following are suggestions for getting the most from the time you spend learning Visual Basic.

Learn Microsoft Excel first

The more you know about Microsoft Excel, the better prepared you'll be to venture into Visual Basic. Most macros perform a sequence of actions in Microsoft Excel, and most instructions in a macro are equivalent to commands or actions in Microsoft Excel. Consequently, working with Visual Basic is a little like working with Microsoft Excel without a user interface; instead of commands and dialog boxes, you use Visual Basic instructions. The statements and functions you use to write instructions are much easier to understand if you're familiar with the features they represent in Microsoft Excel.

Also, if you know Microsoft Excel well, you can better answer the question you're most likely to ask when writing a macro: "What's the best way to do this?" People have been known to write long macros for tasks that could have been handled by a single Microsoft Excel command.

Learn what you need, when you need it

Learn what you need for the task at hand. Visual Basic can seem overwhelming at first, particularly if you haven't had experience with a macro programming language. A great way to learn the language is to investigate how to implement a particular macro idea you have. As you gain experience writing different types of macros, you'll cover a lot of ground.

Use the macro recorder

The macro recorder can record the Visual Basic instruction for virtually every action you take in Microsoft Excel. You can use the macro recorder to see how actions in Microsoft Excel translate into Visual Basic instructions, and vice versa. Also, you'll find that recording part of a macro is often faster and easier than writing out the instructions.

Use Visual Basic Help

Help is a powerful tool for learning Visual Basic. In a Visual Basic module, you can type a Visual Basic keyword and — with the insertion point somewhere in the keyword — press F1 to immediately display Visual Basic Help for that keyword. The Visual Basic Help topic for most keywords includes an example you can copy and paste into your macro. For more information, see "Using Online Help" later in this introduction.


How This Book Is Organized

The chapters in this book describe major feature areas of Visual Basic and techniques for using those features. The first three chapters — "Modules and Procedures," "Variables, Constants, and Data Types," and "Controlling Program Flow" — provide an introduction to the mechanics of writing Visual Basic code.

Chapter 4, "Objects and Collections," discusses the Microsoft Excel object model in detail and gives useful examples of manipulating and referencing objects to accomplish tasks in Visual Basic macros.

Chapter 5, "Optimizing for Size and Speed," shows you several easy techniques that can make your Visual Basic code faster and more concise.

Chapter 6, "Debugging," and Chapter 7, "Handling Run-Time Errors," show you how to find and eliminate bugs in your code before you run it and how to handle errors that occur while your code is running.

Chapter 8, "Controls and Dialog Boxes," and Chapter 9, "Menus and Toolbars," show you how to add custom user-interface elements to your Visual Basic macros.

Chapter 10, "Communicating with Other Applications," details using OLE Automation to communicate with and control other applications.

Chapter 11, "Automatic Procedures and OnEvent Procedures," shows you how to write procedures that run whenever a specific event — such as opening a workbook or clicking a control — occurs.

Chapter 12, "Creating Add-Ins," provides information about creating and using add-ins to distribute your macros.

Chapter 13, "Accessing External Data," discusses using Data Access Objects (DAOs) to import and export information stored in a database.

Appendixes A through D explain how to write international applications, provide helpful information for experienced Microsoft Excel users who are switching to Visual Basic, list all the toolbar buttons in Microsoft Excel, and diagram the Microsoft Excel object model.


Code Samples

Your Microsoft Excel package includes code samples you can open and run. You can copy any part of the samples into your own applications, modifying them as necessary. These code samples are located in the Samples.xls workbook in the Examples folder in your Microsoft Excel folder.


Using Online Help

Microsoft Excel provides an extensive Help system for the Visual Basic language, the objects that Microsoft Excel supports, and the properties and methods of those objects.

If you clicked Typical when you installed Microsoft Excel, you'll need to run Setup again to install Help forVisual Basic for Microsoft Excel.

You can access Visual Basic Help in any of the following four ways:

  • In a Visual Basic module, place the insertion point anywhere in an object, property, method, function, or other keyword, and then press F1 to get context-sensitive Help.
  • On the Help menu, click Microsoft Excel Help Topics. You can then either click "Getting Started with Visual Basic" on the Contents tab, look up a specific topic or Visual Basic term on the Index tab, or perform a full-text search from the Find tab.
  • On the Help menu, click Microsoft Excel Help Topics. You can then ask a question on the Answer Wizard tab and read the topics displayed in the Programming and Language Reference section of the dialog box.
  • With a Visual Basic module active, click Object Browser on the View menu, and then click the Element Help button (appears as a question mark below the Objects/Modules box) for information about an object, method, property, or function.


Document Conventions

This book uses the typographic conventions shown in the following table. You might not recognize all the terms or Visual Basic keywords, but you'll learn more about them later.

Example of convention | Description
setup | Words or characters you're instructed to type appear in bold.
Sub, If, ChDir, MsgBox, True, Add, Height, Application, Range, Row | Words in bold with the initial letter capitalized indicate a a language-specific term: a property, method, or object name; or another Visual Basic keyword.
object | In text, italic type indicates important new terms, usually the first time they occur in the book.
propertyname | In code syntax, italic type indicates placeholders for information you supply.
ENTER | Small capital letters are used for the names of keys and key combinations, such as ENTER and CTRL+R.
CTRL+V | A plus sign (+) between key names indicates a combination of keys. For example, CTRL+V means to hold down the CTRL key while pressing the V key.
DOWN ARROW | Individual arrow keys are referred to by the direction of the arrow on the key (LEFT, RIGHT, UP, or DOWN). The phrase "arrow keys" is used when describing these keys collectively.
Backspace, HOME | Other navigational keys are referred to by their specific names.
myVar | This font is used for example code.
Sub StockSale ( ) . . . End Sub | A column or row of three periods tells you that part of an example program has been intentionally omitted.


Programming Style

This book uses the following programming style guidelines for code examples. For more information about Visual Basic code, see Chapter 1, "Modules and Procedures."

  • The following font is used for code.

    Sub HelloWorld
    Cells(1,1).Value = "Hello, world!"
End Sub
  • An apostrophe (') introduces comments in code.

    ' This is a comment; these two lines
' are ignored when the program is running.
  • Names of macros and user-defined functions appear with initial letters capitalized throughout this book. Note that macro and function names cannot include spaces, so if a name consists of more than one word, the other words in the name also have their initial letters capitalized.

    ' The AuditResult user-defined function is in the Finance module.
Function AuditResult(latestIncome, expenses, taxes, commissions)

    Argument and variable names appear with initial letters lowercase (to distinguish them from macro, function, property, method, and object names).

  • Keywords appear with initial letters capitalized, whereas built-in constants appear with an initial lowercase "xl" or "vb."

    ' Sub is a keyword.
Sub Title(titleText)

' xlManual is a built-in constant.
Application.Calculation = xlManual
  • Control-flow blocks and statements in Sub and Function procedures are indented within the code that surrounds them.

    Sub CheckRecordSound
    SoundRecordCapable = Application.CanRecordSounds
    If SoundRecordCapable Then
        Cells(1,1).SoundNote.Record
    End If
End Sub
  • The line-continuation character — an underscore ( _ ) — indicates that code continued from one line to the next is part of the same logical line. You can type these statements all on one line in the Visual Basic module. You can also divide lines of code and add the line-continuation character yourself.

    ActiveSheet.Rectangles.Add _
    width:=200, _
    height:=200, _
    left:=50, _
    top:=50


Microsoft Product Support Services

Microsoft offers a variety of support options to help you get the most from your Microsoft product. For more information about Microsoft Product Support Services, see Getting Results with Microsoft Excel for Windows 95 or Getting Results with Microsoft Office for Windows 95.

Outside the United States, contact Microsoft Product Support Services at the Microsoft subsidiary office that serves your area. Microsoft subsidiary offices and the countries they serve are listed in Getting Results with Microsoft Excel for Windows 95 and Getting Results with Microsoft Office for Windows 95.


Chapter 1 Modules and Procedures

Modules and procedures are the basic structural units of a Visual Basic program. By learning how to break complex tasks down into a set of simple procedures, how to invoke one procedure from within another procedure, and how to pass data between procedures, you can create modular code that's easy to write, read, debug, and modify.

Contents
  • Structuring a Visual Basic Program
  • Creating Procedures
  • Calling Procedures
  • Communicating with Procedures Using Arguments


Structuring a Visual Basic Program

One of the goals in modern programming is to produce modular programs — that is, programs composed of small, discrete units of code, each of which acts independently to accomplish a particular task. Toward this end, Visual Basic enables you to organize your code into procedures, modules, and workbooks.

A program built from small, reliable components has many advantages over a program built as a single structure. Well-structured modular programs are:

  • Easy to write, because complex problems are broken down into a series of discrete, easy-to-understand tasks.
  • Easy to read, because a top-level procedure typically contains only a series of calls to descriptively named lower-level procedures.
  • Easy to debug, because each task is accomplished in one procedure, and you can easily isolate the source of a problem.
  • Efficient, because code that accomplishes a common task appears in only one procedure that's called many times, rather than being duplicated in many places throughout a program.
  • Easy to modify, because code that accomplishes a specific task appears in only one place in a program. Therefore, if you need to modify this code, you need only make the change in one place.
  • Reliable, because you can build up a library of dependable procedures and then construct your programs using these tested, proven components.
  • Robust, because you can hide data from all parts of a program that don't require access to the data, and thereby reduce the risk of accidentally making changes to the data.
  • Easy to manage and distribute, because you can store and distribute sets of related or frequently used procedures as a unit.

The rest of this chapter will describe how to organize your code into these components and how to control the interaction among procedures stored in different parts of a program.


Breaking Code Down into Procedures

A procedure is a unit of code enclosed either between the Sub and End Sub statements or between the Function and End Function statements. A procedure should accomplish a simple, well-defined task. Procedures are often used for performing repeated or shared tasks.

If your code contains a procedure that performs a complicated task, break that procedure down into several smaller procedures, and then write a separate procedure to call these procedures in order. Continue to examine and break down each procedure in your code until each procedure is simple and specific. The simpler the task performed by a procedure, the easier it will be for you to write and debug it. The more specific the task performed by a procedure, the more versatile the procedure will be.


Understanding the Structure of a Module

Modules are workbook sheets that contain code. Each module can contain a declarations section, followed by procedures. The declarations section at the top of the module can contain:

  • Option statements. If your module contains any Option statements, which set various module-level options, these statements must appear before any procedures. For more information, see "option" in Help.
  • User-defined type definitions. If your module contains any user-defined types, their definitions must appear before any procedures. For more information about user-defined types, see Chapter 2, "Variables, Constants, and Data Types."
  • Declarations. Any variable or constant declarations that aren't contained within a procedure must be placed before any procedures in the module. For more information about declaring variables and constants, see Chapter 2, "Variables, Constants, and Data Types."

Except for Option statements, user-defined type definitions, and declarations, all code in Visual Basic must be contained within procedures; Visual Basic modules cannot contain free-floating (uncontained) commands.


Grouping Procedures into Modules and Workbooks

So that you can easily find a particular procedure or set of procedures that access common data or provide a cohesive set of services, you can group procedures into modules with descriptive names. For example, if you've written a set of procedures that perform various accounting tasks, you could group them into a module and name the module "Accounting_Procedures." You would then know where to find any accounting procedure.

You can further group related modules into a single workbook. This makes it easier to turn the program into an add-in and distribute it. For more information about creating add-ins, see Chapter 12, "Creating Add-Ins."

Although you may want to store procedures in different modules or workbooks for organizational reasons, you may still want to be able to exchange information between them. To support data exchange across modules and workbooks, Visual Basic allows a procedure to access code and data stored in another module or workbook. For more information about accessing data in other modules or workbooks, see Chapter 2, "Variables, Constants, and Data Types." For more information about accessing code in other modules or workbooks, see "Calling Procedures in Other Modules" later in this chapter.

Simple applications can consist of just a single module; all of the code in the application resides in that module. As your applications get larger and more sophisticated, you add additional modules. Eventually you might find that there's common code you want to execute in several modules. You don't want to duplicate the code in both modules, so you create a separate module containing a procedure that implements the common code. Over time, you can build up a library of modules containing shared procedures, as described in the following section.


Creating Library Workbooks

You can organize frequently used procedures into modules you store in
libraries — workbooks that contain only modules — and make these procedures visible throughout a program without having to copy them into every module or workbook that calls them. You can make the procedures in a library workbook visible to procedures in another workbook by creating a reference from the workbook that contains the calling procedure to the library workbook. For more information about creating a reference to a library workbook, see "Creating a Reference to a Workbook" later in this chapter.

After you've created a reference to the library workbook, procedures in other workbooks can call procedures stored in the library workbook. For more information about calling procedures in other modules and workbooks, see "Calling Procedures in Other Modules" later in this chapter.


Creating Procedures

When you create a procedure, you must decide how widely accessible you want the procedure to be, what you want to name the procedure, what task you want the procedure to perform, what sort of information the procedure will need to perform this task, what types of data you want the procedure to accept and return, and whether you want the procedure to affect data in other parts of the program. The following sections describe how Visual Basic allows you to specify this information for each procedure you write.


Specifying Procedure Scope

The term scope means the areas in a program from which a particular program item — such as a variable, constant, user-defined data type, or procedure — is accessible, or "visible." Procedures in Visual Basic can have either private or public scope. A procedure with private scope is visible only to the other procedures in the module where it's declared; a procedure with public scope is visible to all procedures in every module in the workbook in which the procedure is declared, and in all workbooks that contain a reference to that workbook. If you don't specifically indicate otherwise, procedures have public scope.

If you want to limit the availability of a procedure to the module in which it's declared, use the Private keyword. Because procedures are public by default, you don't need to use the Public keyword to declare a public procedure; however, doing so makes it easier to see immediately which program elements have public scope and which ones have private scope. The following code declares two public procedures and one private procedure.

Public Sub CalcPayments()
    ' place statements here
    MsgBox "I'm public!"
End Sub

Sub CalcIncome()        ' Public by default
    ' place statements here
    MsgBox "I'm public, too!"
End Sub

Private Sub CalcSavings()
    ' place statements here
    MsgBox "I'm private!"
End Sub

Note

A procedure that's declared as Private cannot run as a stand-alone procedure. It can be called only from another procedure.

To limit the availability of a procedure to the workbook in which it's declared, declare the procedure itself as Public, but make the module private by adding the Option Private Module statement to the declarations section of the module.


Naming Procedures

When naming your procedures, you must follow certain guidelines. A procedure name:

  • Must begin with a letter.
  • Cannot contain embedded periods, mathematical or comparison operators, or type-declaration characters.
  • Must not exceed 255 characters.
  • Must be unique within its scope.
  • Cannot be the name of a Visual Basic method, property, function, argument name, or other restricted keyword. For a list of restricted keywords, see "restricted keywords" in Help.

Tip

To avoid having to use module qualifiers when calling procedures, use each procedure name only once.


Types of Procedures

Visual Basic allows you to create two types of procedures: Sub procedures and Function procedures.

A Sub procedure is a unit of code enclosed between the Sub and End Sub statements that performs a task but doesn't return a value.

A Function procedure is a unit of code enclosed between the Function and End Function statements. Like a Sub procedure, a Function procedure performs a specific task. However, a Function procedure also returns a value you can use in an expression, as shown in the following example.

totalSales = CalculateTotal(x)    'CalculateTotal is a Function procedure

You can also use Function procedures in place of complex worksheet formulas, just as you use built-in Visual Basic functions such as Sqr, Cos, and Chr.

Note

A Function procedure you call from a formula on a worksheet shouldn't make changes to the data in a workbook or change the Microsoft environment in any way. For more information, see "Using Function Procedures on Worksheets" later in this chapter.


Returning a Value from a Function

For a function to return a value, it must include a function assignment statement that assigns a value to the name of the function, as shown in the following example. The value assigned to ConeSurface will be the value returned by the function.

Function ConeSurface(radius, height)
    Const Pi = 3.14159
    coneBase = Pi * radius ^ 2
    coneCirc = 2 * Pi * radius
    coneSide = Sqr(radius ^ 2 + height ^ 2) * coneCirc / 2
    ConeSurface = coneBase + coneSide
End Function

When the Function procedure returns a value, this value can then become part of a larger expression. For example, the following line in another procedure incorporates the return value of the ConeSurface and ScoopSurface functions into its calculations.

totalSurface = ConeSurface(3, 11) + 2 * ScoopSurface(3)

The information that must be supplied to a procedure for it to perform its task (radius and height in the preceding example) is passed in the form of arguments. For more information about arguments, see "Communicating with Procedures Using Arguments" later in this chapter.


Specifying the Data Type for a Function's Return Value

If you want to restrict the return value of a Function procedure to a particular data type, declare the return value's type using the As keyword after the parentheses that follow the function name.

Function CalcPay(hours, rate) As Currency

In the absence of an As clause, the return value will have the Variant type by default.

Note

You can also use the As keyword within the parentheses enclosing the argument list to specify the data types of procedure arguments, as in this example: Function CalcPay(hours As Integer, rate As Currency) As Currency. For more information, see "Specifying Argument Data Types" later in this chapter.


Using Function Procedures on Worksheets

Function procedures you can use to replace long worksheet formulas in a worksheet cell — just as you use built-in worksheet functions — are called user-defined worksheet functions.

For example, suppose that the workbook named "MyBook" contains the function ConeSurface, which was defined in "Returning a Value from a Function" earlier in this chapter. If you want a cell on a worksheet in MyBook — a cell in any workbook that has a reference to MyBook — to contain the surface area of a cone with a radius of 5 and a height of 10, you should place the formula =ConeSurface(5,10) in the cell. If you want to use the ConeSurface function in a worksheet cell in a workbook that doesn't contain a reference to MyBook, you should precede the function name with the name of the workbook and an exclamation mark — for example, =MYBOOK.XLS!ConeSurface(5,10) — and MyBook must be open.

Note

You can call functions in loaded add-ins without opening the add-in workbook and without specifying the workbook name. For information about creating add-ins, see Chapter 12, "Creating Add-Ins."

A user-defined worksheet function must not change any data in a workbook or change the Microsoft Excel environment in ways such as the following:

  • Inserting, deleting, or formatting cells
  • Changing cell values
  • Moving, renaming, deleting, or adding sheets
  • Changing the calculation mode or screen view

In addition, names of procedures you intend to use as user-defined functions in Microsoft Excel cannot have names that resemble A1-style or R1C1-style cell addresses.

If you cannot remember the exact name of a user-defined function or the name or number of its arguments, you can use the Function Wizard to examine the function and its arguments.

To insert a user-defined function using the Function Wizard

1. On the Insert menu, click Function.

2. In the Function Category box, click User Defined.

3. In the Function Name box, click the name of the function you want to insert.

4. Follow the rest of the Wizard steps. Where appropriate, the Wizard will give you a chance to fill in arguments.

If you want a user-defined function to appear in a category other than User Defined, assign it to a different function category.

To specify a user-defined function's category

1. With a module active, click Object Browser on the View menu.

2. In the Methods/Properties box, click the function you want to specify a category for.

3. Click Options to display the Macro Options dialog box.

4. In the Function Category box, click the category where you want the function to appear.


Calling Procedures

The simplest way to call a procedure is to name it in your code, just as you do with built-in keywords. The following sections describe how to call Sub and Function procedures from other procedures.

Note

If you want a particular procedure to run automatically, without being called explicitly, at every occurrence of a specific event — such as opening a file, clicking an object, or activating a sheet — you should make the procedure an automatic procedure or an OnEvent procedure. For information about creating automatic and OnEvent procedures, see Chapter 11, "Automatic Procedures and OnEvent Procedures."


Calling Sub Procedures

There are two ways to call a Sub procedure:

' Both of these statements call a Sub named MyProc.
Call MyProc (firstArgument, secondArgument)
MyProc firstArgument, secondArgument

Note that when you use the Call syntax, arguments must be enclosed in parentheses. If you omit the Call keyword, you must also omit the parentheses around the arguments. For more information about arguments, see "Communicating with Procedures Using Arguments" later in this chapter.

Unlike a Function procedure, a Sub procedure cannot be called by using its name within an expression, and it doesn't return a value.


Calling Function Procedures

Usually, you call a function procedure you've written yourself the same way you call a built-in Visual Basic function such as Abs — that is, by using its name in an expression. For example, the following is a function that calculates the rate of single-occupancy vehicle users in a community.

Function PercentSOV(SOV, sharedMotorized, nonMotorized)
    Const nmFactor = 0.2
    totalSOV = SOV - nmFactor * nonMotorized
    totalPossibleTrips = SOV + sharedMotorized + nonMotorized
    PercentSOV = (totalSOV / totalPossibleTrips) * 100
End Function

All of the following statements call the PercentSOV function.

If PercentSOV(SOV, Bus, BikeOrWalk) > 72 Then Debug.Print "Too high"
Application.StatusBar = 100 - PercentSOV(SOV, Bus, BikeOrWalk)
X = PercentSOV(SOV, Bus, BikeOrWalk)

The information that must be supplied to a procedure for it to perform its task — SOV, Bus, and BikeOrWalk in the preceding example — is passed in the form of arguments. For more information about arguments, see "Communicating with Procedures Using Arguments" later in this chapter.


Calling Procedures in Other Modules

For a procedure to be called from outside the module in which it resides, two conditions must be met:

  • The workbook that contains the calling procedure must contain a reference to the workbook that contains the called procedure.
  • The called procedure must be visible outside the module in which it's declared; that is, the procedure must have public scope.

If procedures with duplicate names exist in different modules or workbooks, you may also need to include a module qualifier in front of the procedure name to distinguish between procedures.

The following sections describe how to create a reference to a workbook and how to use module qualifiers. For more information about specifying procedure scope, see "Specifying Procedure Scope" earlier in this chapter.

Creating a Reference to a Workbook

If you want to call a procedure in another workbook, you must create a reference to the workbook that contains the procedure. A referenced workbook need not be visible, or even open, for you to be able to call procedures in it.

To create a reference to a workbook

1. Open the workbook that contains the calling procedure, and activate a module sheet.

2. On the Tools menu, click References.

3. The Available References box shows all open workbooks and all workbooks referenced by an open workbook.

4. Select the check box next to the name of the workbook you want to create a reference to.

5. To select a workbook that's not listed in the Available References box, click Browse, and then locate the workbook you want to create a reference to.

If one workbook has an indirect reference link to another workbook, Visual Basic allows the procedures in the first workbook to call procedures in the other workbook by specifying the name of the referenced workbook in the calling statement. For example, suppose that the workbook FirstBk has a reference link to SecondBk, which has a reference link to ThirdBk. A procedure in FirstBk could call the procedure TestProc in ThirdBk using the code in the following example.

[THIRDBK.XLS].TestProc

You cannot have circular references to workbooks. That is, a workbook that references another workbook cannot in turn be referenced by that other workbook.

Tip

You cannot create a link to a workbook programmatically; you must manually create a reference link in each workbook that needs access to procedures in another workbook. One way around this is to create a template that contains a link to the library workbook and then create new workbooks based on that template. Each new workbook will already contain a link to the library workbook.

If you want every new workbook you create to contain a reference link to a certain workbook, create a template that contains a link to that workbook, and save the template as Book.xlt in your Xlstart folder or your alternate startup folder. Every new workbook you create will then be based on this template by default.

Using Module Qualifiers

If there are procedures with duplicate names in different modules or in different workbooks, you may need to include a module qualifier before the procedure name when calling the procedure. If the procedures are in different modules in the same workbook, the module qualifier should have the syntax shown in the following line.

[modulename].procedurename

For example, the following code calls two procedures — both named "TotalToDate" — stored in different modules in the same workbook.

[East Coast].TotalToDate
MidWest.TotalToDate

The square brackets around the module name are optional if the module name obeys Visual Basic naming conventions (no spaces, no periods, and so on).

If the procedures are in different workbooks, the module qualifier has the syntax shown in the following line.

[workbookname].[modulename].procedurename

For example, the following code calls two procedures — both named "TotalToDate" — stored in different workbooks.

[REGION.XLS].[Total Sales].TotalToDate
[STATE.XLS].[Total Sales].TotalToDate

A module qualifier must refer to a module in a workbook referenced by the workbook that contains the calling procedure.

If you don't include a module qualifier to indicate which of the identically named procedures you want to run, Visual Basic searches through modules in the following order, running the first module with that name that it finds: the current module, then other modules in the current workbook, and then modules in referenced workbooks.


Communicating with Procedures Using Arguments

If you need to supply a procedure with information so that it can perform its task, you pass that information in the form of arguments. When you declare an argument, you can specify the data type of the argument, whether or not the procedure can change the argument's value, and whether an argument is required or optional. For more information, see the following sections.

To indicate that a given procedure takes arguments, include an argument list between the parentheses that follow the procedure name in the procedure declaration. The argument list can contain multiple argument declarations, separated by commas.

The following example shows the declaration line of a Sub procedure that takes two arguments.

Sub UpdateRecord(custId, custName)

The following code calls UpdateRecord.

Dim newId As Integer
Dim newName As String

newId = 3452
newName = "Mary Boyd"
UpdateRecord newId, newName

Note that the name of the variable you pass from the calling procedure doesn't have to match the name of the argument declared in the called procedure.

If you pass an array as an argument, you must include empty parentheses after the array name. Because you don't specify the dimensions of the array, the procedure can accept arrays of any size. The following example shows a declaration line for a Sub procedure that takes an array as an argument.

Sub PrintList(custArray())

Arguments have the same scope as variables declared within a procedure — that is, local (procedure-level) scope. They're not accessible outside the procedure in whose argument list they're declared.


Specifying Argument Data Types

Procedure arguments have the Variant data type by default. However, you can declare other data types for arguments, using the As keyword in the argument declaration. For example, the following function accepts a string and an integer:

Function Reverse (S As String, ByVal n As Integer)
    ' Reverses the first n characters in S.
    Dim Temp As String, i As Integer
    If n > Len(S) Then n = Len(S)
    For i = n To 1 Step -1
        Temp = Temp & Mid(S, i, 1)
    Next
    Reverse = Temp & Right(S, Len(S) - n)
End Function

You can declare a procedure argument with a user-defined data type, as shown in the following code.

Type custInfo
    custName As String
    custCompany As String
    custId As Integer
End Type

Sub PrintList(newCust As custInfo)
    'place statements here
End Sub

Note that you can pass an argument with a user-defined data type only by reference. For more information, see the following section. For more information about fundamental data types and user-defined data types, see Chapter 2, "Variables, Constants, and Data Types," or see the specific data type in Help.


Passing Arguments by Reference

If you pass an argument by reference when calling a procedure, the procedure has access to the actual variable in memory. As a result, the variable's value can be changed by the procedure. Passing by reference is the default in Visual Basic, so if you don't explicitly specify to pass an argument by value, Visual Basic will pass it by reference. Each of the following lines indicates that an argument is passed by reference.

Sub AddThree(ByRef passedVar As Integer)
Sub AddThree(passedVar As Integer)        'ByRef is the default

The AddThree procedure accepts arguments passed by reference. Because the AddThree procedure changes the value stored in the varToPass variable that's passed to the procedure, the MsgBox function in TestPassingArgs will display the value 10.

Sub TestPassingArgs()
    Dim varToPass As Integer
    varToPass = 7
    AddThree varToPass
    MsgBox varToPass        ' displays 10
End Sub

Sub AddThree(ByRef passedVar As Integer)
    passedVar = passedVar + 3
End Sub

Note that if you specify a data type for an argument passed by reference, you must pass a value of that type for the argument. Failure to do this will result in a type mismatch error. For more information about declaring data types, see Chapter 2, "Variables, Constants, and Data Types."

Passing a variable by reference requires less memory and time than passing by value but increases accessibility to the value stored in the variable and therefore increases the chance that the value will be accidentally changed.


Passing Arguments by Value

If you pass an argument by value when calling a procedure, the called procedure only receives a copy of the variable passed from the calling procedure. If the called procedure changes the value, the change affects only the copy and not the variable in the calling procedure. Passing by value therefore protects data from being accidentally changed by the called procedure. Use the ByVal keyword to indicate that a variable is passed by value. For example, the following AddThree procedure accepts arguments passed by value. Because the AddThree procedure can only work with a copy of the varToPass variable and cannot access the actual value stored in the varToPass variable, the MsgBox function in TestPassingArgs will display the value 7.

Sub TestPassingArgs()
    varToPass = 7
    AddThree varToPass
    MsgBox varToPass        ' displays 7
End Sub

Sub AddThree(ByVal passedVar As Integer)
    passedVar = passedVar + 3
End Sub

Note that if you specify a data type for an argument passed by value, you don't need to pass a value of that type for the argument. In the preceding example, the varToPass variable is a Variant variable (because it hasn't been assigned any other data type), but Visual Basic passes a copy of it to the AddThree procedure as an integer. For more information about declaring data types, see Chapter 2, "Variables, Constants, and Data Types."

Note that your code cannot pass an argument with a user-defined type by value.


Using Parentheses to Pass an Argument by Value

You may at some point want to pass a variable to a procedure by value, even though the procedure indicates that the argument is passed by reference. You can do this by enclosing the variable to pass in parentheses. For example, the following AddThree procedure accepts arguments passed by reference. However, by enclosing the varToPass variable in parentheses in the calling procedure, you cause the variable to be passed by value. Therefore, in this example, the MsgBox function in TestPassingArgs will display the value 7 instead of the value 10.

Sub TestPassingArgs()
    varToPass = 7
    AddThree (varToPass)
    MsgBox varToPass        ' displays 7
End Sub

Sub AddThree(ByRef passedVar As Integer)
    passedVar = passedVar + 3
End Sub

Note

Make sure that you don't accidentally pass a variable by value when you mean to pass it by reference. If you accidentally use parentheses around an argument when the syntax doesn't require it — that is, if you use parentheses around an argument to a procedure you call without the Call keyword, or around an argument to a Function procedure whose return value you're not using — you'll pass the variable by value. For more information about the syntax for calling procedures, see "Calling Procedures" earlier in this chapter.


Using Optional Arguments

You can specify that arguments to a procedure be optional by using the Optional keyword in the argument list. If you specify an optional argument, all subsequent arguments in the argument list must also be optional and must be declared with the Optional keyword. Optional arguments must be of the Variant data type.

For example, the following procedure takes two required arguments and two optional arguments. The procedure selects a range of cells on the worksheet named "SampleText" and then optionally makes the text red and sorts the range by the values in the first column.

Sub FormatList(startRow As Integer, startCol As Integer, _
        Optional redText, Optional sortList)
    If IsMissing(redText) Then
        redText = False
    Else
        redText = CBool(redText)
    End If
    If IsMissing(sortList) Then
        sortList = False
    Else
        sortList = CBool(sortList)
    End If
    Set myCells = Worksheets("SampleText") _
        .Cells(startRow, startCol).CurrentRegion
    If redText Then
        textColor = 3
    Else
        textColor = xlAutomatic
    End If
    myCells.Font.ColorIndex = textColor
    If sortList Then myCells.Sort key1:=myCells.Cells(1, 1)
End Sub

The IsMissing function is used to determine whether an optional argument was passed to the procedure. For more information, see "IsMissing" in Help.

The following example calls FormatList, providing both the required and optional arguments.

Sub DoList()
    FormatList 2, 2, False, True
End Sub

The following example provides the second optional argument.

Sub DoList()
    FormatList 2, 2, , True
End Sub

If your procedure has several optional arguments, you may want to use named arguments so that you can provide any or all of the arguments, in any order. For more information, see the following section.

Note

Sub procedures with optional arguments won't appear in the Macro dialog box (Tools menu). (No Function procedures appear in the Macro dialog box.) You can, however, see procedures with optional arguments in the Object Browser.


Using Named Arguments

Many built-in functions, statements, and methods take more than one argument. For example, the Open method, which opens a workbook, takes 12 arguments. If you want to write code that opens the workbook Book2.xls, which has the protection password "drowssap", you could write the following code.

Workbooks.Open "BOOK2.XLS", , , , "drowssap"

However, this code is difficult to write correctly without introducing bugs, because you have to count the number of commas to insert between the arguments. The code is also very difficult to read, and it gives no clues about what the arguments represent. The following example shows a better way to write this code.

Workbooks.Open fileName:="BOOK2.XLS", password:="drowssap"

Because every argument has a name, you can use the name and the := operator to assign a value to an argument. When you use named arguments, you don't have to remember the order of the arguments. For example, the preceding code could have been written with the order of the arguments reversed, as in the following example.

Workbooks.Open password:="drowssap", fileName:="BOOK2.XLS"

You can use named arguments with the procedures you create, too. Visual Basic automatically associates argument names with their corresponding procedures. For example, the FormatList procedure in the preceding section takes two required arguments and two optional arguments, as shown in the following declaration line.

Sub FormatList(startRow As Integer, startCol As Integer, _
        Optional redText, Optional sortList)

The following DoList procedure calls the FormatList procedure using named arguments.

Sub DoList()
    FormatList redText:=True, startCol:=2, startRow:=2
End Sub

The arguments are given out of order, and one of the optional arguments was omitted. Using named arguments is especially useful if your procedures have several optional arguments you don't always need to specify.

Note

You cannot use named arguments to avoid entering required arguments.


Using an Indefinite Number of Arguments

Generally, the number of arguments in the procedure call must be the same as in the procedure specification. Using the ParamArray keyword with an argument allows you to specify that a procedure will accept an arbitrary number of arguments. The argument used with ParamArray must be an array of Variant variables. For example, you could write the following AddInts procedure, using the ParamArray keyword with the array argument intNums() to allow the procedure to handle any number of arguments passed to it.

Function AddInts(ParamArray intNums())
    Dim x As Integer
    Dim y As Variant

    For Each y In intNums
        x = x + y
    Next y
    AddInts = x
End Function

Note that a For Each control variable in an array — y in the preceding example — must be a Variant variable.

You can subsequently call AddInts with any number of arguments, as shown in the following example.

Sub ShowSum()
    MsgBox AddInts(1, 3, 5)
    MsgBox AddInts(1, 3, 5, 7, 8, 9, 34, 98, 123)
End Sub

You can use the ParamArray keyword only with the last argument in an argument list.


Inserting Procedures and Arguments with the Object Browser

If you forget the names of your arguments or would like to paste them in rather than type them, you can use the Object Browser. The Object Browser lists all the Sub procedures and Function procedures in all currently open workbooks, including hidden workbooks.

To locate and insert a procedure using the Object Browser

1. On the View menu, click Object Browser.

2. In the Libraries/Workbooks box, click the name of a workbook.

3. In the Objects/Modules box, click the name of the module, and then click the name of the procedure in the Methods/Properties box.

4. To view the code for a procedure, click Show.

This is the easiest way to view the code for a function without actually opening the module that contains it. (You can view and execute procedures from the Macro dialog box, but not functions. The Macro dialog box lists only Sub procedures with no optional arguments. It doesn't list Sub procedures with optional arguments or any Function procedures.)

5. To paste the procedure into your code, click Paste.

It may help you remember details about a procedure if you enter a description that will appear at the bottom of the Object Browser dialog box when you click that procedure.

To enter a procedure description

1. With a procedure selected in the Object Browser, click Options.

2. In the Macro Options dialog box, type a description in the Description box.


Chapter 2 Variables, Constants,and Data Types

Chapter 2 Variables, Constants,
and Data Types

This chapter describes a variety of strategies for managing data storage that enhance different aspects of macro performance:

  • Using constants, variables, or structured groups of variables instead of literal values in code. This technique allows you to make single-point changes, and it makes code easier to read, modify, and debug.
  • Specifying the parts of a program where specific data is available by defining the scope of the data. This technique reduces the number of procedures from which data can be manipulated and therefore reduces both the possibility that the data can be corrupted and the number of places you must look for the cause of a particular problem.
  • Specifying the length of time to keep data in a variable or constant by defining the lifetime of the data. This technique prevents unexpected reinitialization of variables and allows retention of a variable's value between calls to a procedure.
  • Specifying the amount of space to allocate in memory for the data and how to organize the data by declaring the data type. This technique makes your macros use less memory and run faster.
  • Grouping related data together by creating an array or user-defined data type. Grouping data makes it easier to work with many related variables at once. User-defined types can also make your code easier to read and modify.

This chapter first discusses the basic data storage concepts mentioned above and then describes in detail how to put these concepts to work in your macros.

Contents
  • Variables
  • Constants
  • Data Types


Variables

Variables are named areas in memory where you store data while the workbook containing your code is open. If you've written Visual Basic code, you've probably already used variables without really thinking about it. Variables can be useful for keeping track of running counts, storing input from a user or another source, or storing a value that subsequent macro instructions will change.


Choosing Variable Names

There are a few simple rules to follow when naming your variables. A variable name:

  • Must begin with a letter.
  • Cannot contain an embedded period, mathematical or comparison operator, or type-declaration character.
  • Must not exceed 255 characters.
  • Must be unique within its scope.
  • Cannot be the name of a Visual Basic method, property, function, argument name, or other reserved keyword.

Tip

To reduce the amount of time you spend deciphering and debugging code, use each variable for only one purpose.


Using Variables Without Declaring Them

Unless you specify otherwise, Visual Basic allows you to create variables simply by using them in your code (other programming languages, such as C and Pascal, require that you explicitly declare variables before you use them). The following example assigns the value of cell A1 to the variable tempVal.

tempVal = Worksheets(1).Range("A1").Value

This is called an implicit variable declaration. When you use this feature, Visual Basic automatically creates a variable and gives it the Variant data type. Variables with the Variant data type can contain any data, including strings, numbers, and dates. Until you assign a value to the new Variant variable, it has the special value Empty. As soon as you assign the Variant variable a value, it takes the data type of the assigned value. You'll learn more about Variant variables, data types, and the Empty value later in this chapter.

A Variant variable works well in this example because you may not know what kind of information cell A1 contains. Keep in mind that although it's convenient to allow Visual Basic to create variables whenever you use them, this can lead to subtle errors in your macro if you misspell a variable name, as shown in the following example.

Sub SwapCells()
    With Worksheets(1)
        tempVal = .Range("a1").Value
        .Range("a1").Value = .Range("a2").Value
        .Range("a2").Value = temVal
    End With
End Sub

At first glance, it looks as if this procedure should swap the contents of cells A1 and A2, but if you look carefully, you'll see that the tempVal variable is misspelled the second time it's used. Visual Basic doesn't know that you made a mistake and assumes that you meant to introduce a new variable, temVal. Visual Basic creates this new (empty) variable and assigns the value of cell A2 to it. After you run this procedure, the value that was in cell A2 has been moved into cell A1, and cell A2 is empty.


Declaring Variables

Whereas implicit variable declaration can initially make your code easier to write, explicit variable declaration ultimately makes the code easier to read, modify, debug, and run. To explicitly declare a variable, you use the Dim, Private, Public, or Static keyword to specify the variable's scope (what parts of your macro can use the variable), lifetime (how long Visual Basic keeps data in the variable), and data type (what kind of information the variable contains).

Explicit variable declaration:

  • Makes code easier to understand by grouping all variable names at the beginning of modules and procedures, where you can keep track of them.
  • Helps prevent you from inadvertently creating a new variable by misspelling the name of an existing variable.
  • Helps prevent you from inadvertently using an existing variable when meaning to create a new one, thereby erasing the initial value stored in the variable.
  • Speeds code execution by specifying the exact data type of each variable. Your code runs faster when Visual Basic doesn't have to determine the data type for each variable while the code is running.
  • Matches the capitalization of each variable to the capitalization of the variable in the declaration statement and makes your code easier to read.

To reduce t

Tip

To reduce the amount of time you spend deciphering, debugging, and running code, explicitly declare each variable and specify as much information as you can about the data to be stored in it.

The simplest form of explicit variable declaration creates a new variable with the Variant data type and procedure-level scope. The value in the variable is preserved only while the procedure is running. The following example declares two variables — radius and area.

Sub CircleArea()
    Dim radius, area
    radi    us = InputBox("Circle Radius?")
    area = 3.14159 * radius ^ 2
    MsgBox "The area is " & area
End Sub

You'll learn more about using declaration statements to specify variable scope, lifetime, and data type later in this chapter.


Requiring Explicit Variable Declarations

To avoid the problem of inadvertently creating new variables by misspelling the names of existing variables, you can stipulate that Visual Basic generate an error message whenever it encounters a name used as a variable but not previously declared explicitly as a variable. To require explicit variable declarations, place the following statement at the top of each module in which you want Visual Basic to enforce explicit declarations.

Option Explicit

You must manually add this line to the top of each existing module in which you want this option to be turned on, but you can have Visual Basic automatically add the line to new modules.

To have Visual Basic automatically add the Option Explicit statement to new modules

  • On the Tools menu, click Options, and then select the Require Variable Declaration check box on the Module General tab.

With Option Explicit in effect for the module containing the SwapCells procedure, Visual Basic requires that variables be declared before you can use them. The following example shows the procedure with the added variable declaration.

Sub SwapCells()
    Dim tempVal
    With Worksheets(1)
        tempVal = .Range("a1").Value
        .Range("a1").Value = .Range("a2").Value
        .Range("a2").Value = temVal
    End With
End Sub

When you try to run this procedure, Visual Basic generates an error message telling you that the temVal variable is undeclared. Recognizing that this error means you've misspelled the variable name, you can fix the name before it causes the procedure to fail.

Tip

Because the Option Explicit statement helps you catch errors in variable names, and because it encourages you to use explicit data types, you should use it all the time.


Specifying Variable Scope and Lifetime

When you declare a variable within a procedure, only code within that procedure can access or change the value of that variable — that is, the variable has a scope that's local to that procedure. Sometimes, however, you need to use a variable with a broader scope, such as one whose value is available to all the procedures within the same module, or even to all the procedures in your entire application. Visual Basic allows you to specify the scope of a variable when you declare it.

Depending on how it's declared, a variable is scoped in one of three ways, as shown in the following table.

Scope | Declaration
Procedure | Dim or Static within the procedure
Private | Dim or Private at the top of the module
Public | Public at the top of the module

Tip

It's generally a good idea to use the narrowest possible scope for your variables. For example, if you're using a temporary variable inside a procedure, use procedure (local) scope instead of private scope or public scope. Limiting the scope of your variables makes your macros more modular and helps reduce bugs.

A variable's lifetime is the time during which Visual Basic preserves the value in the variable. The values in private and public variables are preserved while the workbook is open, unless you edit a Visual Basic module in that workbook. When you edit a Visual Basic module, all modules in that workbook are recompiled and all variables are reset.

Although variables declared inside a procedure have the same scope level whether they're declared with Dim or Static, they have different lifetimes. Local variables declared with Static exist the entire time that the workbook where they're declared is open; that is, the variables retain their values between calls to the procedure. Local variables declared with Dim exist only while the procedure where they're declared is running. When a procedure ends, the values of its local variables aren't preserved and the memory used by the local variables is reclaimed. The next time the procedure runs, all its local variables are reinitialized.

Procedure-Level Variables

Procedure-level (or local) variables are recognized only in the procedure where they're declared. Local variables are a good choice for any kind of temporary calculation. All implicitly declared variables have local scope. You declare local variables explicitly by using the Dim or Static keyword inside the procedure, as shown in the following example.

Sub DoTheWork
    Dim intTemp As Integer
    Static intPermanent As Integer
.
.
.
End Sub

Tip

Although you can use local variables with the same name in several procedures, it's usually best to use unique variable names. Using the same name in several procedures can make your macro harder to debug.

Preserving the Value of a Local Variable

If you want to preserve the value stored in a local variable between calls to the procedure that contains it, you should declare the variable using the Static keyword, as in the following example.

Static depth

The following function calculates a running total by adding a new value to the total of previous values stored in the static variable accumulate.

Function RunningTotal(num)
    Static accumulate
    accumulate = accumulate + num
    RunningTotal = accumulate
End Function

If accumulate were declared with Dim instead of Static, the previously accumulated values would not be preserved across calls to the function, and the function would simply return the value it was called with.

You could produce the same result by declaring accumulate in the declarations section of the module, making it available to any procedure in the module. After you've changed the scope of a variable in this way, however, the procedure no longer has exclusive access to it. Because other procedures can access and change the value of the variable, the running totals might be unreliable and the macro is more difficult to maintain.

Tip

Use static variables if you need to preserve the value of a local variable each time a procedure is called. For example, you could use a static variable to record the number of times the procedure has been called or to record a running total, as shown in the preceding example.

Declaring All Local Variables as Static

To make all local variables in a procedure static, place the Static keyword at the beginning of a procedure heading, as in the following example.

Static Function RunningTotal(num)

This makes all local variables in the procedure static, regardless of whether they're declared explicitly with Static or Dim or declared implicitly. You can place Static in front of any Sub or Function procedure heading.

Note

After you edit a module, Visual Basic recompiles all modules in the workbook and resets all variables the next time you run any Visual Basic procedure or function. If you need to preserve values when the workbook is compiled or saved, use a hidden worksheet to store the values.

Private Variables

Private variables are available to all the procedures in the module where they're declared, but not to code in other modules. You create private variables by declaring them with Dim or Private in the declarations section of a module (the top section, above procedure definitions), as in the following example.

Dim intTemp As Integer
Private intTemp2 As Integer

Tip

Because variables declared at the top of a module are private by default, there is no difference between variables declared with Private and those declared with Dim. However, Private is preferred because it readily contrasts with Public and makes your macros easier to read. You cannot declare variables in a procedure using the Private keyword.

Public Variables

Public variables are available to every procedure in every module in the workbook where they're declared, as well as in all other workbooks that contain a reference link to the workbook where those variables are declared. (For information about creating a reference link to a workbook, see Chapter 1, "Modules and Procedures.")

You use the Public keyword to declare a public variable. Like private variables, public variables are declared in the declarations section at the top of the module; you cannot declare private or public variables inside a procedure.

Public intX As Integer

A public variable exists and retains its value from the time a value is assigned to the variable until the workbook closes (or until you edit a procedure, thus causing Visual Basic to recompile).

Note

To create a variable that's available to all modules in a given workbook but not to any other workbooks, make the variable public by declaring it with the Public keyword, but make the module itself private to the workbook that contains it by using the Option Private Module statement in the module.


Specifying Variable Data Type

When you declare a variable, you can also supply a data type for it. The data type specifies the kind of information you can store in the variable. If you don't supply a data type, Visual Basic automatically gives the variable the Variant data type.

The Variant data type handles all types of fundamental data and converts between them automatically. If you want to create concise, fast macros, however, use other data types whenever you know that a variable will always contain the same type of data. For example, if a variable always contains small integer values, you can save several bytes (and speed up your macro significantly when performing arithmetic operations on the variable) by declaring that variable as Integer instead of Variant. For information about specific data types, see "Data Types" later in this chapter.

Before you can use a non-variant variable, you must explicitly declare it using the As keyword in a declaration statement. For example, the following statements declare variables as Long, Integer, Double, String, and Currency, respectively.

Dim x as Long
Private i As Integer
Private amt As Double
Static yourName As String
Public billsPaid As Currency

A declaration statement can combine multiple type declarations, separated by commas, as in the following statements.

Private i As Integer, amt As Double
Private yourName As String, billsPaid As Currency
Private test, amount, j As Integer    ' test and amount are Variants

Note

If you don't specify a data type for a variable, Visual Basic assigns the Variant data type. In the preceding example, the variables test and amount have the Variant data type. This may surprise you if your experience with other programming languages leads you to expect all the variables in one declaration statement to have the same specified data type (in this case, Integer).


Arrays

If you've programmed in other languages, you're probably familiar with the concept of arrays. An array is a named collection of variables of the same data type. Each array element can be distinguished from other elements by one or more integer indexes. For example, if the sheetNames array contains three names, you can set and return the names as shown in the following example.

sheetNames(1) = "sheet1"
sheetNames(2) = "module1"
sheetNames(3) = "sheet2"

MsgBox sheetNames(2)

Arrays allow you to group related variables in a way that makes it easier for you to keep track of, access, and manipulate them all at once, while still being able to access each variable individually. This helps you create smaller and simpler macros in many situations, because you can set up loops using index numbers to deal efficiently with any number of cases.

When you create an array, its size is determined by the number of dimensions it has and the by the upper and lower bounds for the index numbers in each dimension. Arrays in Visual Basic can have up to 60 dimensions; the number of elements is limited by the amount of available memory. The sheetNames array in the earlier example has one dimension and three elements; the lower bound is one and the upper bound is three.

Because Visual Basic allocates space for every possible element in a declared array, whether or not you actually store a value in that element, you should avoid declaring an array any larger than is necessary. If you know ahead of time what size your array needs to be, you can declare a fixed-size array, or static array, and stipulate the exact dimensions and upper and lower bounds from the outset. If you don't know how many values you'll need to store in an array, you can declare a dynamic array without specifying the number of dimensions or the size of each dimension.

All the elements in an array must have the same data type. If you want to create an array whose elements can contain different kinds of data (objects, strings, numbers, and so on), you should declare an array of the Variant type. You can declare an array of any of the fundamental data types, including user-defined types (described in "User-Defined Data Types" later in this chapter) and object variables (described in Chapter 4, "Objects and Collections").

Declaring Arrays

You must explicitly declare an array before you can use it; you cannot implicitly declare an array. The procedure for declaring an array is very similar to the procedure for declaring a variable. You use the Private, Public, Dim, and Static keywords to specify the array scope and lifetime, you use integer values to specify the upper and lower bounds for each dimension, and you use the As keyword to specify the data type for the array elements.

The rules for determining the scope of an array are identical to those for variables. For more information, see "Specifying Variable Scope and Lifetime" earlier in this chapter.

Setting Upper and Lower Bounds

When you declare an array, you specify the upper and lower bounds for each dimension within the parentheses following the array name. The upper and lower bounds must be integers. The values can be positive, negative, or 0 (zero). You must use constant values to specify the bounds of fixed-size arrays (for information about using variables to specify the bounds of a dynamic array, see "Creating Dynamic Arrays" later in this chapter).

If you specify only one value for a dimension, Visual Basic interprets the value as the upper bound and supplies a default lower bound. The default lower bound is 0 (zero) unless you set it to 1 using the Option Base statement. For example, the following code declares one-dimensional arrays containing 15 and 21 elements, respectively.

Dim counters(14) As Integer
Dim sums(20) As Double

If you haven't changed the default lower bound, the index numbers in these arrays range from 0 to 14 and from 0 to 20, respectively. If you wish the index numbers to start at 1 instead of 0, you can change the default lower bound to 1 by placing an Option Base statement in the declarations section of a module:

Option Base 1

Tip

You should always include Option Base 1 in your modules. Microsoft Excel collections are always 1-based, and any arrays that Microsoft Excel methods or properties return are also 1-based. If you assign a 1-based array to a 0-based array, the same information exists in both arrays, but each element is off by one index. This can make your macros confusing and hard to debug.

You can also specify the lower bound of a dimension explicitly. To do this, separate the lower and upper bounds with the To keyword, as in the following examples.

Dim counters(1 To 15) As Integer
Dim sums(100 To 120) As String

In the preceding declarations, the index numbers of counters range from 1 to 15, and the index numbers of sums range from 100 to 120.

Tip

You can use the Visual Basic LBound and UBound functions to determine the existing lower and upper bounds of an array.

Using Arrays

After you've declared an array, you can use it in your code. You access each individual element in the array by using the element's index value. For example, the following code fills a 10-element array with random numbers and then displays the fourth element in the array.

Sub RandomArray()
    Dim i As Integer, rnums(10) As Integer

    For i = 1 To 10
        rnums(i) = Int(Rnd() * 6) + 1
    Next
    MsgBox rnums(4)
End Sub

Creating Dynamic Arrays

If you don't know how large to make an array, or if you want to be able to change the size of the array at run time, you can use a dynamic array. A dynamic array can be resized at any time. Dynamic arrays are among the most flexible and convenient features in Visual Basic, helping you manage memory efficiently. For example, you can use a large dynamic array for a short time and then free up system memory when you're no longer using the array.

To create a dynamic array

1. Declare the array just as you would declare a fixed-size array, but without specifying dimension sizes within the parentheses following the array name. For example:

Dim dynArray()

2. Later in the macro, allocate the actual number of elements with a ReDim statement, as in the following example.

ReDim dynArray(X + 1)

The ReDim statement can appear only in a procedure. Unlike the Dim and Static statements, ReDim is an executable statement — that is, it makes the application carry out an action at run time. Each ReDim statement can change the number of elements, the lower and upper bounds for each dimension, and the number of dimensions in the array.

The following example first declares the dynamic array ovalLeftCoords, allocates space in the array based on the number of ovals on Worksheet 1, and fills the array with the left coordinates of the ovals.

Sub FillArray()
    Dim ovalLeftCoords() As Integer
    Dim i As Integer, ovalCount As Integer, ovs As Ovals
    Set ovs = Worksheets(1).Ovals
    ovalCount = ovs.Count
    ReDim ovalLeftCoords(ovalCount)
    For i = 1 To ovalCount
        ovalLeftCoords(i) = ovs(i).Left
    Next
End Sub

Preserving the Contents of Dynamic Arrays

Each time you use the ReDim statement, all the values currently stored in the array are lost. Visual Basic resets the values to the Empty value (for Variant arrays), to 0 (zero) (for numeric arrays), to a zero-length string (for string arrays), or to Nothing (for arrays of objects).

This is useful when you want to prepare the array for new data, or when you want to reduce the size of the array so that it occupies minimal memory. However, sometimes you may want to change the size of the array without losing the data in it. You can do this by using ReDim with the Preserve keyword. For example, you can enlarge an array by one element without losing the values of the existing elements.

ReDim Preserve myArray(UBound(myArray) + 1)

The UBound function returns the value of the upper bound for the specified dimension of an array. For more information, see "UBound" in Help.

Only the upper bound of the last dimension in a multidimensional array can be changed when you use the Preserve keyword; if you change either bound of any of the other dimensions, or the lower bound of the last dimension, a run-time error occurs. Thus, you can do the following:

ReDim Preserve matrix(10, UBound(matrix, 2) + 1)

But you cannot do this:

ReDim Preserve matrix(UBound(matrix, 1) + 1, 10)

Creating Multidimensional Arrays

With Visual Basic, you can declare arrays of up to 60 dimensions simply by specifying the size of each dimension within the parentheses following the array name. Separate the sizes of different dimensions with commas. For example, the following statement declares a two-dimensional, 10-by-10 array within a procedure.

Static matrixA(10, 10) As Double

Either dimension, or both, can be declared with explicit lower bounds.

Static matrixA(1 To 10, 1 To 10) As Double

You can extend this to more than two dimensions, as in the following example.

Dim multiD(4, 1 To 10, 1 To 15)

The preceding declaration creates an array with three dimensions, whose sizes are 4, 10, and 15. The total number of elements is the product of these three dimensions, or 600.

Tip

When you start adding dimensions to an array, the total storage needed by the array increases dramatically, so use multidimensional arrays with care. Be especially careful with Variant arrays, because they're larger than arrays of other data types.

Using Loops to Manipulate Multidimensional Arrays

You can efficiently process a multidimensional array by using nested For...Next loops. For example, these statements initialize every element in matrixA to a value based on its location in the array.

Dim i As Integer, j As Integer
Static matrixA(1 To 10, 1 To 10) As Double
For i = 1 To 10
    For j = 1 To 10
        matrixA(i, j) = I * 10 + J
    Next j
Next i


Constants

Often, you'll find that your macro contains constant values that reappear again and again. Or you may find that the macro depends on certain numbers that are difficult to remember — numbers that, in and of themselves, have no obvious meaning.

In these cases, you can greatly improve the readability of your macro — and make it easier to maintain — by using constants. A constant is a meaningful name that takes the place of a number or string that doesn't change. Although a constant somewhat resembles a variable, you cannot modify a constant or assign a new value to it as you can do with a variable. There are two sources for constants:

  • Built-in constants — also called intrinsic or system-defined constants — are provided by applications. Microsoft Excel constants are listed in the Microsoft Excel object library in the Object Browser. Other applications that provide object libraries, such as Microsoft Access and Microsoft Project, also provide a list of constants you can use with their objects, methods, and properties. For information about using the Object Browser, see Chapter 4, "Objects and Collections."

    Intrinsic constant names have a mixed-case format, with a two-character prefix indicating the object library that defines the constant. Constants from the Microsoft Excel object library are prefaced with "xl" — for instance, xlAbsolute. Constants from the data access object library are prefaced with "db" — for instance, dbRelationUnique.

  • Symbolic constants, or user-defined constants, are declared with the Const statement. User-defined constants are described in the next section, "Declaring User-Defined Constants."

Tip

Use constants when you need to use the same value several times in your macro, or when you want to make your macro more readable by assigning a meaningful name to a value that doesn't change.


Declaring User-Defined Constants

You declare a constant using the Const statement. You can specify private or public scope and assign a value to the constant. If you don't specify scope, the constant has private scope by default. When naming constants, you must follow the same rules as when naming variables (for more information, see "Choosing Variable Names" earlier in this chapter).

A constant can represent data of any type, as shown in the following examples.

Const conPi = 3.14159265358979
Const conMaxPlanets = 9
Const conReleaseDate = #1/1/95#
Const conCodeName As String = "Enigma"

You can place two or more constant declarations on a single line if you separate them with commas.

Const conPi = 3.14, conMaxPlanets = 9, _
    conWorldPop = 6000000000#

The expression on the right side of the equal sign ( = ) is often a numeric value or string literal, but it can also be an expression that results in a number or string (although that expression cannot contain calls to functions). You can even define constants in terms of previously defined constants, as in the following example.

Const conPi2 = conPi * 2

After you've defined a constant, you can place it in your macro to make the macro more readable, as in the following example.

Static solarSystem(1 To conMaxPlanets)
If numPeople > conWorldPop Then Exit Sub


Specifying Constant Scope

A Const statement can specify scope the same way a variable declaration can, and the same rules apply:

  • To create a constant that exists only within a procedure, declare it within that procedure, using only the Const keyword.

    Const conPi = 3.14159
  • To create a constant that's available to all procedures within a given module but not to any code outside that module, declare it in the declarations section of the module, using the Private keyword before Const.

    Private Const conMax = 4096
  • To create a constant that's available to all modules in all workbooks, declare it in the declarations section of the module, using the Public keyword.

    Public Const conMin = 0

    As with any other type of data, public constants are available only in the workbook where they're declared and in any workbooks with a reference link to the workbook where they're declared. In addition, you can limit the scope of a public constant to a single workbook by using the Option Private Module statement in the module where the constant is declared.


Specifying Constant Data Type

If you don't explicitly specify a data type when you declare a constant, Visual Basic gives the constant the data type that best matches the expression assigned to the constant. You may occasionally want to override a constant's default data type to improve the efficiency or accuracy of your calculations. For example, Visual Basic treats constants containing real numbers with a fractional component as Double values by default. If you want to speed up your code execution, you could explicitly declare a constant as Single; if you want to avoid rounding errors, you could declare it as Currency. You may also need to declare a constant as a particular data type to ensure that the result of a computation has a specific data type.

You declare a data type for a constant the same way you declare a type for a variable, using the As keyword.

Const conTemp As Currency = 3.45


Avoiding Circular References

Because constants can be defined in terms of other constants, you must be careful not to set up a circular reference between two or more constants. A circular reference occurs when you have two or more public constants that are defined in terms of each other, as in the following example.

' In Module 1:
Public Const conA = conB * 2

' In Module 2:
Public Const conB = conA / 2

Visual Basic generates an error when you attempt to run a macro that contains a circular reference. You cannot run the macro until you resolve the circular reference. To avoid creating a circular reference, restrict all your public constants to a single module or a small number of modules. This way, it will be easier for you to keep track of your constants and catch this kind of mistake.


Data Types

Visual Basic recognizes a number of fundamental data types, such as Integer, Currency, String, and Boolean. Each data type takes up a specific amount of memory, allows a specific range of values, and is best suited for storing specific kinds of data. All data must have a type in order for Visual Basic to work with it.

If you don't explicitly declare a type, Visual Basic assigns a default type. For variables, the default type is Variant; for constants, it's the data type that most closely matches the value assigned to the constant.

You can improve macro performance in several ways by specifying data types yourself. You can make your code run faster by specifying the exact type of each variable, as Visual Basic won't have to spend time examining each Variant variable to detect the exact type of the value stored there. You can save memory, because the specific data types use less memory than the Variant type. You can avoid rounding and overflow errors by specifying a data type appropriate to the values you'll be using and the calculations you'll be making. For more information about selecting data types to improve performance, see Chapter 5, "Optimizing for Size and Speed."

The fundamental data types in Visual Basic, including Variant, are shown in the following table. For more information about the specific types, see the following sections of this chapter.

Type name | Storage size | Range
Integer | 2 bytes | –32,768 to 32,767
Long | 4 bytes | –2,147,483,648 to 2,147,483,647
Single | 4 bytes | – 3.402823E38 to – 1.401298E-45 (negative values) 1.401298E-45 to 3.402823E38 (positive values)
Double | 8 bytes | – 1.79769313486232E308 to – 4.94065645841247E – 324 (negative values) 4.94065645841247E – 324 to 1.79769313486232E308 (positive values)
Currency | 8 bytes | – 922337203685477.5808 to 922337203685477.5807
String | 1 byte per character | 0 to approximately 65,500 characters 0 to 2E32 on 32-bit systems
Boolean | 2 bytes | True or False
Date | 8 bytes | January 1, 100 to December 31, 9999
Object | 4 bytes | Any Object reference
Variant | 16 bytes + 1 byte for each character | Null, Error, any numeric value valid for any numeric data type, or any text, object, or array.


Numeric Data Types

If you know that a variable will always contain whole numbers (such as 12) rather than fractional numbers (such as 3.57), declare it as an Integer or Long type.

Private memSize As Long
Dim loopCounter As Integer

Operations are faster with Integer variables, which consume less memory than Variant variables. Integer variables are especially useful as the counter variables in For...Next loops. For more information about For...Next loops and other control structures, see Chapter 3, "Controlling Program Flow."

If a variable will always contain fractional numbers, declare it as a Single, Double, or Currency type.

Public radius As Single
Private area As Double
Dim costOfGoods As Currency

The Currency data type supports up to four digits to the right of the decimal separator and 15 digits to the left of it, making Currency an accurate fixed-point data type suitable for monetary calculations. Floating-point (Single and Double) numbers have much larger ranges than Currency, but can be subject to small rounding errors.

Note

Floating-point values can be expressed as mmmEeee or mmmDeee, where mmm is the mantissa and eee is the exponent (a power of 10). The highest positive value of a Single data type is 3.402823E+38, or 3.4 times 10 to the 38th power; the highest positive value of a Double data type is 1.79769313486232D+308, or about 1.8 times 10 to the 308th power. Using D to separate the mantissa and exponent in a numeric literal causes the value to be treated as a Double data type. Likewise, using E in the same fashion causes the value to be treated as a Single data type.

A variable or constant of any numeric data type (or the Variant data type) can contain any numeric data. For example, assigning the value 3.14 to a variable of the Integer data type doesn't generate an error, even though 3.14 isn't an integer. Visual Basic rounds off rather than truncates the fractional part of a floating-point number before assigning it to an integer.

A variable with one of the numeric data types is initialized to 0 (zero) after it's declared and before you assign another value to it. When you edit any Visual Basic module, all variables in the workbook that contains that module are reinitialized. Procedure-level variables are reinitialized when the procedure starts running.


The String Data Type

A variable that will always contain a string and never a numeric value can be declared with the String data type.

Private dataName As String

Before you assign data, a string variable contains an empty string (""). You can then assign strings to this variable and manipulate it using string functions. You use string literals in Visual Basic by enclosing the string within double quotation marks.

dataName = "Database"
dataName = Left(dataName, 4)

By default, a string variable or argument is a variable-length string; the string grows or shrinks as you assign new data to it. You can also declare strings that have a fixed length. You specify a fixed-length string with the following syntax.

String * size

For example, to declare a string that's always 50 characters long, use code such as the following:

Dim empName As String * 50

If you assign a string of fewer than 50 characters, empName is padded with enough trailing spaces to total 50 characters (before any assignment, the variable contains 50 spaces). If you assign a string that's too long for the fixed-length string, Visual Basic truncates the characters, as in the following example.

Dim tempString As String * 4, dataName As String

dataName = "Database"
tempString = dataName
MsgBox tempString & " : " & dataName

The preceding code produces the following output.

Database : Data

Because fixed-length strings are padded with trailing spaces, you may find the Trim, LTrim, and RTrim functions useful when working with fixed-length strings. For more information, see "Trim," "LTrim," or "RTrim" in Help.


The Boolean Data Type

A variable that contains a logical value (simple true/false, yes/no, or on/off information) can be declared with the Boolean data type. The default value for the Boolean type is False. In the following example, creditExceeded is a Boolean variable that stores a yes/no setting.

Dim creditExceeded as Boolean

' Ask if the credit limit is exceeded.
If amt > Limit Then creditExceeded = True


The Date Data Type

A variable that contains date and time values should be declared with the Date data type.

Private today As Date

You can perform calculations on date/time values. Adding or subtracting integers adds or subtracts whole days; adding or subtracting fractions adds or subtracts fractions of days (expressed in hours and minutes). Thus, adding 20 adds 20 days, and subtracting 1/24 subtracts one hour.

You can use date/time literals in a macro by enclosing them within number signs (#), the same way you enclose string literals within double quotation marks. Visual Basic accepts a wide variety of date and time formats in literals. The following are all valid date/time values.

someDate = #3-6-93 13:20#
someDate = #March 27, 1993 1:20am#
someDate = #Apr-2-93#
someDate = #4 April 1993#

Date variables are initialized to 12:00:00 A.M. (midnight) on December 30, 1899. If you don't include a time in a date/time literal, Visual Basic sets the time part of the value to midnight (the beginning of the day). If you don't include a date in a date/time literal, Visual Basic sets the date part of the value to December 30, 1899. For more information about the various date/time functions and formats, see "Date" and "date formats" in Help.


The Object Data Type

A variable that contains a reference to an object within Microsoft Excel or within some other application can be declared with the Object data type. You can assign an object variable (using the Set statement) to represent any actual object recognized by the application.

Dim wk As Object
Set wk = Worksheets(1)

Object variables are initialized to the special value Nothing. You can test for this value using the Is function.

If wk Is Nothing Then    'object variable not set

Whenever possible, declare data as the most specific object type possible. For example, declare a variable that will represent a collection of ovals as Ovals instead of DrawingObjects; or, in the preceding code , declare the variable that will represent a worksheet as Worksheet instead of Object. Visual Basic can resolve references to the properties and methods of objects with specific types before you run the application (properties and methods for objects declared with the Object type must be resolved at run time; this slows down your macro). Specific object types are listed in the Object Browser.

When working with objects contained in other applications, instead of using the Variant type or the generic Object type, declare objects as they're listed in the Objects/Modules box in the Object Browser. This ensures that Visual Basic recognizes the specific type of object you're referencing, allowing the reference to be resolved at compile time.

For more information about creating and assigning objects and object variables, see Chapter 4, "Objects and Collections."


The Variant Data Type

The Variant data type allows you to store most types of data. You don't have to convert between these data types when assigning them to a Variant variable; Visual Basic automatically performs any necessary conversion, as in the following example.

Private someValue        ' Variant by default.
someValue = "17"
    ' someValue contains "17" (a two-character string).
someValue = someValue - 15
    ' someValue now contains the numeric value 2.
someValue = "U" & someValue
    ' someValue now contains "U2" (a two-character string).

Tip

A Variant variable isn't a variable with no data type; rather, it's a variable that can freely change its type to accommodate the data stored in the variable. An uninitialized Variant variable contains the special Empty value. As soon as you assign data to the Variant variable, the variable assumes the data type most appropriate for the assigned data.

Storing Values in Variant Variables

The Variant data type maintains an internal representation of stored values. This internal representation corresponds to one of the non-variant data types discussed earlier in this chapter, and it determines how Visual Basic treats the stored value when performing comparisons and other operations.

Numeric Values Stored in Variant Variables

When you store numbers in a Variant variable, Visual Basic uses the most compact representation possible. For example, if you store a small number without a decimal fraction, the variant uses an Integer representation for the value. If you then assign a larger number, Visual Basic uses a Long value. If the value is very large or has a fractional component, Visual Basic uses a Double value. (Visual Basic automatically uses the Double internal representation instead of the Single or Currency type to store a number with a fractional component in a variant.)

Sometimes you want to use a specific representation for a number. For example, you might want a variant to store a numeric value as Currency to avoid round-off errors in later calculations. Visual Basic provides several conversion functions that you can use to convert values into a specific type (see "Converting Data Types" later in this chapter). To convert a value to Currency, for example, you use the CCur function:

payPerWeek = CCur(hours * hourlyPay)

An error occurs if you attempt to perform a mathematical operation or function on a Variant variable that doesn't contain a number or something that can be interpreted as a number. For example, you cannot perform any arithmetic operations on the value "U2" even though it contains a numeric character, because the entire value isn't a valid number. Likewise, you cannot perform any calculations on the value "1040EZ." However, you can perform calculations on the values "+10" and " – 1.7E6" because they're valid numbers. For this reason, you'll often want to determine whether a variant contains a value that can be used as a number. The IsNumeric function performs this task, as shown in the following example.

Do
    anyNumber = InputBox("Enter a number")
Loop Until IsNumeric(anyNumber)
MsgBox "The square root is: " & Sqr(anyNumber)

If you assign a Variant variable containing a number to a String variable, Visual Basic automatically converts the representation of the number to a string. If you want to explicitly convert a number to a string, use the CStr function. You can also use the Format function to convert a number to a string that includes formatting such as currency, thousands separator, and decimal separator symbols.

For more information, see "Format" in Help. For information about writing macros for applications that will be distributed in foreign markets, see Appendix A, "Writing Code for International Use."

Strings Stored in Variant Variables

Generally, storing and using strings in Variant variables poses few problems. However, the result of the + operator can be ambiguous when it's used with two Variant values. If both of the Variant variables contain numbers, the + operator performs addition. If both of the Variant variables contain strings, the + operator performs string concatenation.

If one of the values is represented as a number and the other is represented as a string, the situation becomes more complicated. Visual Basic first attempts to convert the string into a number. If the conversion is successful, the + operator adds the two values; if the conversion is unsuccessful, it generates a "Type mismatch" error message.

To make sure that concatenation occurs, regardless of the representation of the value in the variables, use the & operator, as shown in the following example.

Sub StringCat()
    Dim x, y

    x = "6"
    y = "7"
    With Worksheets(1)
        .Range("a1") = x + y        'concatenates values
        .Range("b1") = x & y        'concatenates values
        x = 6
        .Range("a2") = x + y        'adds values
        .Range("b2") = x & y        'concatenates values
    End With
End Sub

The preceding example produces the following result on the worksheet:

67        67
13        67

When you type your code, make sure that you leave a space between any variable name and the & operator. If you don't leave a space, Visual Basic assumes you intended to use the ampersand (&) as the type-declaration character for the variable name. For more information about type-declaration characters, see "type-declaration character" in Help.

Date/Time Values Stored in Variant Variables

Variant variables can also contain date/time values. Several functions return date/time values. For example, the Now function returns the current date and time.

In the same way that you can use the IsNumeric function to determine whether a Variant variable contains a value that can be considered a valid numeric value, you can use the IsDate function to determine whether a Variant variable contains a value that can be considered a valid date/time value. You can then use the CDate function to convert the value into a date/time value. For more information, see "The Date Data Type" earlier in this chapter.

Objects Stored in Variant Variables

Variant variables can contain objects. This can be useful when you need to gracefully handle a variety of data types, including objects. For example, all the elements in an array must have the same data type. Setting the data type of an array to Variant allows you to store objects along with other data types in an array.

Errors Stored in Variant Variables

If you create your own error values using the CVErr function and you want to store them in variables, those variables must be of the Variant type. After you've assigned error values to those Variant variables, the variables have the Error subtype (Error is a subtype because there is no explicit Error data type). In the following example, myError is a Variant variable of subtype Error.

Dim myError
myError = CVErr(2010)

Even though myError is a Variant variable, if you use it as an argument to the TypeName function, TypeName returns "Error," not "Variant." Using the TypeName function in this situation tells you whether a variable contains a user-defined error. You can also use the IsError function to test for error values.

For more information about user-defined errors, see Chapter 7, "Handling Run-Time Errors," or see "CVErr" or "IsError" in Help.

The Empty Value

A Variant variable contains the Empty value until it's assigned a value. The Empty value is a special value that's different from 0 (zero), a zero-length string (""), or the Null value. You can test for the Empty value using the IsEmpty function.

If IsEmpty(z) Then z = 0

When a Variant variable contains the Empty value, you can use it in expressions; it's treated as either 0 (zero) or a zero-length string (""), depending on the expression.

The Empty value in a Variant variable disappears as soon as any value is assigned to that variable (including the value of 0 (zero), the zero-length string, and the Null value). You can set a Variant variable back to the Empty value by assigning the keyword Empty to the Variant variable.

z = Empty

The Null Value

The Variant data type can contain one other special value: Null. Null is commonly used in database applications to indicate unknown or missing data. Because of the way it's used in databases, Null has some unique characteristics:

  • Expressions involving Null always result in Null; Null "propagates" through expressions. If any part of an expression evaluates to Null, the entire expression evaluates to Null.
  • Passing Null, a Variant variable containing Null, or an expression that evaluates to Null as an argument to most functions causes the function to return Null.
  • Null values propagate through intrinsic functions that return Variant data types.

You can also assign Null with the Null keyword.

z = Null

You can use the IsNull function to test for whether a Variant variable contains Null.

If IsNull(x) And IsNull(y) Then
    z = Null
Else
    z = 0
End If

Note

Variables aren't set to Null unless you explicitly assign Null to them, so if you don't use Null in your application, you don't have to write code that tests for it and handles it.

For more information about using Null in expressions, see "Null" in Help.

Determining the Data Type of a Variant

Most of the time, you don't have to be concerned with what internal representation Visual Basic is using for a particular stored value; Visual Basic handles conversions automatically. If you want to know what representation Visual Basic is using, however, you can use the TypeName or VarType function. The TypeName function returns a string for the data type; the VarType function returns a numeric value.

For example, if you store values with decimal fractions in a Variant variable, Visual Basic always uses the Double internal representation. If you know that your application doesn't need the high degree of accuracy (and slower speed) that a Double value entails, you can speed up your calculations by converting the values to Single, or even to Currency.

If TypeName(x) = "Double" Then x = CSng(x) ' Convert to Single.

For information about converting data types, see the following section, "Converting Data Types." For more information about the TypeName and VarType functions, see "TypeName" and "VarType" in Help.


Converting Data Types

Visual Basic provides several conversion functions you can use to convert values into specific data types. To convert a value to Currency, for example, you use the CCur function.

payPerWeek = CCur(hours * hourlyPay)

Conversion function | Converts an expression to
CBool | Boolean
CCur | Currency
CDate | Date
CDbl | Double
CInt | Integer
CLng | Long
CSng | Single
CStr | String
CVar | Variant
CVErr | Error

For more information, see the specific conversion function in Help.


User-Defined Data Types

You can combine variables of several different data types to create user-defined data types (known as structures in the C programming language). A user-defined type is useful when you want to create a single variable that records several related pieces of information. The user-defined type encapsulates the information and makes it easier to process; for example, you can pass the entire structure to a procedure or assign all the values at once by assigning one variable to another if they're both of the same user-defined type.

Tip

Because the Variant data type can store many different types of data, a Variant array can be used in many situations where you might expect to use a user-defined type. A Variant array is actually more flexible than a user-defined type because you can change the type of data you store in each element at any time, and you can make the array dynamic so that you can change its size as necessary. However, a Variant array always uses more memory than an equivalent user-defined type.

Declaring a User-Defined Data Type

You create a user-defined type using the Type statement, which must be placed in the declarations section of a module. User-defined types can be declared as either Private or Public with the appropriate keyword, as in the following example.

Private Type yourDataType
Public Type myDataType

For example, you could create a user-defined type that records information about a computer system.

Private Type systemInfo
    cpu As Variant
    memory As Long
    videoColors As Integer
    cost As Currency
    purchaseDate As Variant
End Type

Declaring Variables That Have a User-Defined Type

You can declare local, private, or public variables of the same user-defined type.

Dim mySystem As systemInfo, yourSystem As systemInfo

The rules for determining the scope and lifetime of a variable with a user-defined type are identical to those for other types of variables. For more information, see "Specifying Variable Scope and Lifetime" earlier in this chapter.

Note

Notice the difference between declaring the user-defined data type (using the Type statement) and declaring a variable of the user-defined type (using the Dim statement). Declaring the user-defined type simply tells Visual Basic how the data type is structured; declaring a variable actually reserves space for information organized according to the user-defined type. The scope of the Type declaration and the scope of the declared variable are completely independent; for example, you can declare a local variable using a data type that has been declared as Public.

Using Variables That Have a User-Defined Type

You access an individual variable within a structure by writing the name of the variable that has a user-defined type, followed by a period and the name of the individual variable.

mySystem.cpu = "486"
If mySystem.purchaseDate > #1/1/92# Then

You can also assign one variable to another if they're both of the same user-defined type. This assigns all the elements of one variable to the same elements in the other variable, as in the following example.

yourSystem = mySystem

User-Defined Types That Contain Arrays

A user-defined type can contain a static (fixed-size) array, as in the following example.

Type systemInfo
    cpu As Variant
    memory As Long
    diskDrives(25) As String        ' Fixed-size array.
    videoColors As Integer
    cost As Currency
    purchaseDate As Variant
End Type

It can also contain a dynamic array.

Type systemInfo
    cpu As Variant
    memory As Long
    diskDrives() As String        ' Dynamic array.
    videoColors As Integer
    cost As Currency
    purchaseDate As Variant
End Type

You can access an array within a user-defined type just as you access any individual variable within the user-defined type, that is, by writing the name of the structured variable that contains the array, followed by a period and then the name of the array. You can then specify an individual element in the array with index numbers, just as you normally access an array member.

Dim mySystem As systemInfo
mySystem.diskDrives(0) = "1.44 MB"

You can also declare an array of user-defined types.

Dim allSystems(100) As systemInfo

Follow the same rules to access the components of this data structure.

allSystems(5).CPU = "386SX"
allSystems(X).DiskDrives(2) = "100M SCSI"

User-Defined Types That Contain Objects

User-defined types can contain objects.

Private Type inputData
    wkInput as Worksheet
    rInput as Range
End Type

Nesting User-Defined Types

User-defined types can contain other user-defined types, as shown in the following example. To make your macros more readable and easier to debug, try to keep all the code that defines user-defined data types in one module.

Type driveInfo
    type As String
    size As Long
End Type

Type systemInfo
    cpu As Variant
    memory As Long
    diskDrives(26) As driveInfo
    cost As Currency
    purchaseDate As Variant
End Type

Dim allSystems(100) As systemInfo
allSystems(1).diskDrives(0).type = "Floppy"


Chapter 3 Controlling Program Flow

In this chapter, you'll learn about decision making — how to write procedures that test conditions and then run only certain statements based on the results of those tests. You'll also learn about looping, or running a group of statements several times; and you'll learn about nesting, or placing one control structure inside another.

The statements that control decision making and looping in Visual Basic are called control structures. Without control structures, a procedure's logic flows through statements from left to right and from top to bottom. Although you can write some very simple procedures with this unidirectional flow, most of the power and flexibility of any programming language comes from its ability to use control structures to change the order in which statements are run.

Contents
  • Making Decisions
  • Looping
  • Nesting Control Structures
  • Exiting Loops and Procedures


Making Decisions

Visual Basic procedures can test conditions and then, depending on the results of that test, perform different operations. Visual Basic decision structures include the following statements.

To test | Use
A single condition and run a single statement or a block of statements | If...Then
A single condition and choose between two statement blocks | If...Then...Else
More than one condition and run one of several statement blocks | If...Then...ElseIf
A single condition and run one of several statement blocks | Select Case


If...Then

Use the If...Then statement to run one or more statements when a specified condition is True. You can use either a single-line syntax or a multiple-line "block" syntax; the following pair of examples illustrates both of these types of syntax.

If thisVal < 0 Then thisVal = 0

If thisVal > 5 Then
    thatVal = thisVal + 25
    thisVal = 0
End If

Notice that the single-line form of the If...Then statement doesn't use an End If statement. If you want to run more than one line of code when the condition is True, you must use the multiple-line If...Then...End If syntax.

Note

When the condition you're evaluating contains two expressions joined by an Or operator — for example, If (thisVal > 5 Or thatVal < 9) — both expressions are tested, even if the first one is True. In rare circumstances, this behavior can affect the outcome of the statement; for example, it can cause a run-time error if a variable in the second expression contains an error value.


If...Then...Else

Use the If...Then...Else statement to define two blocks of statements; one of them runs when a specified condition is True, and the other one runs when the condition is False.

If age < 16 Then
    MsgBox "You are not old enough for a license."
Else
    MsgBox "You can be tested for a license."
End If


If...Then...ElseIf

You can add ElseIf statements to test additional conditions without using nested If...Then statements, making your code shorter and easier to read. For example, suppose that you need to calculate employee bonuses using bonus rates that vary according to job classification. The following Function procedure uses a series of ElseIf statements to test the job classification before calculating the bonus.

Function Bonus(jobClass, salary, rating)
    If jobClass = 1 Then
        Bonus = salary * 0.1 * rating / 10
    ElseIf jobClass = 2 Then
        Bonus = salary * 0.09 * rating / 10
    ElseIf jobClass = 3 Then
        Bonus = salary * 0.07 * rating / 10
    Else
        Bonus = 0
    End If
End Function

The If...Then...ElseIf statement block is very flexible. You can start with a simple If...Then statement and add Else and ElseIf clauses as necessary. However, this approach is unnecessarily tedious if each ElseIf statement compares the same expression with a different value. For this situation, you can use the Select Case statement.


Select Case

You can use the Select Case statement instead of multiple ElseIf statements in an If...Then structure when you want to compare the same expression with several different values. A Select Case statement provides a decision-making capability similar to the If...Then...Else statement, but it makes code more efficient and readable.

For instance, to add several more job classifications to the example in the preceding section, you can add more ElseIf statements, or you can write the function using a Select Case statement, as in the following code.

Function Bonus(jobClass, salary, rating)
    Select Case jobClass
        Case 1
            Bonus = salary * 0.1 * rating / 10
        Case 2
            Bonus = salary * 0.09 * rating / 10
        Case 3
            Bonus = salary * 0.07 * rating / 10
        Case 4, 5    'The expression list can contain several values...
            Bonus = salary * 0.05 * rating / 5
        Case 6 To 8    '...or be a range of values
            Bonus = 150
        Case Is > 8    '...or be compared to other values
            Bonus = 100
        Case Else
            Bonus = 0
    End Select
End Function

Notice that the Select Case structure evaluates a single expression at the top of the structure. In contrast, the If...Then...ElseIf structure can evaluate a different expression for each ElseIf statement. You can replace an If...Then...ElseIf structure with a Select Case structure only if each ElseIf statement evaluates the same expression.


Looping

You can use loop structures to repeatedly run a section of your macro. Visual Basic loop structures include the following statements.

To | Use
Test a condition at the start of the loop, run the loop only if the condition is True, and continue until the condition becomes False | Do While...Loop
Test a condition at the start of the loop, run the loop only if the condition is False, and continue until the condition becomes True | Do Until...Loop
Always run the loop once, test a condition at the end of the loop, continue while the condition is True, and stop when the condition becomes False | Do...Loop While
Always run the loop once, test a condition at the end of the loop, continue while the condition is False, and stop when the condition becomes True | Do...Loop Until
Run a loop a set number of times, using a loop counter that starts and ends at specified values and that changes value by a specified amount each time through the loop | For...Next
Run a loop once for each object in a collection | For Each...Next


Do...Loop

Use a Do...Loop statement to run a block of statements an indefinite number of times. There are several variations of the Do...Loop statement, but each one evaluates a condition to determine whether or not to continue running. As with an If...Then statement, the condition must be a value or an expression that evaluates to True or False. The different variations are described in this section. For more information about the Do...Loop statement, see "Do...Loop" in Help.

Do While...Loop

Use the Do While...Loop statement when you want to test a condition before you run the loop and then continue to run the loop while the condition is True.

Do While condition
 statements
Loop

The statements must eventually cause the condition to become False, or the loop will run forever (this is called an infinite loop). To stop an infinite loop, press Esc or CTRL+BREAK.

The following Function procedure counts the occurrences of a target string within another string by looping as long as the target string is found. Because the test is at the beginning of the loop, the loop runs only if the string contains the target string.

Function CountStrings(longstring, target)
    position = 1
    Do While InStr(position, longstring, target) 'Returns True/False
        position = InStr(position, longstring, target) + 1
        Count = Count + 1
    Loop
    CountStrings = Count
End Function

Do Until...Loop

Use the Do Until statement if you want to test the condition at the beginning of the loop and then run the loop until the test condition becomes True. If the condition is initially True, the statements inside the loop never run.

Do Until condition
statements
Loop

With the test at the beginning of the loop in the following example, the loop doesn't run if Response is equal to vbNo.

Response = MsgBox("Do you want to process more data?", vbYesNo)
Do Until Response = vbNo
    ProcessUserData    'Call procedure to process data
    Response = MsgBox("Do you want to process more data?", vbYesNo)
Loop

Do...Loop While

When you want to make sure that the loop will run at least once, you can put the test at the end of the loop. The statements run as long as the condition is True.

Do
 statements
Loop While condition

This variation guarantees that your procedure will run the loop at least once.

Sub MakeBlue()
    Set rSearch = Worksheets("sheet1").Range("a1:a10")
    Set c = rSearch.Find("test")
    If Not c Is Nothing Then
        first = c.Address
        Do
            c.Font.ColorIndex = 5
            Set c = rSearch.FindNext(c)
        Loop While (Not c Is Nothing) And (c.Address <> first)
    Else
        MsgBox "not found"
    End If
End Sub

Do...Loop Until

With the Loop Until test at the end of the loop, the loop runs at least once and stops running when the condition becomes True.

Do
 statements
Loop Until condition

Do
    ProcessUserData    'Call procedure to process data
    response = MsgBox("Do you want to process more data?", vbYesNo)
Loop Until response = vbNo


For...Next

When you don't know how many times you need to run the statements in a loop, use a Do loop. When you know that you must run the statements a specific number of times, use a For...Next loop. Unlike a Do loop, a For...Next loop uses a counter variable that increases or decreases in value during each repetition of the loop. Whereas a Do loop ends when a test condition becomes True or False, a For...Next loop ends when the counter variable reaches a specified value.

For example, the following Sub procedure sounds a tone however many times you specify.

Sub BeepSeveral()
    numBeeps = InputBox("How many beeps?")
    For counter = 1 To numBeeps
        Beep
    Next counter
End Sub

Because you didn't specify otherwise, the counter variable in the preceding example increases by 1 each time the loop repeats. You can use the Step keyword to specify a different increment for the counter variable (if you specify a negative number, the counter variable decreases by the specified value each time through the loop). In the following Sub procedure, which replaces every other value in an array with 0 (zero), the counter variable increases by 2 each time the loop repeats.

Sub ClearArray(ByRef ArrayToClear())
    For i = LBound(ArrayToClear) To UBound(ArrayToClear) Step 2
        ArrayToClear(i) = 0
    Next i
End Sub

Note

The variable name after the Next statement is optional, but it can make your code easier to read, especially if you have several nested For loops.


For Each...Next

A For Each...Next loop is similar to a For...Next loop, except that it repeats a group of statements for each element in a collection of objects or in an array, instead of repeating the statements a specified number of times. This is especially useful if you don't know how many elements are in a collection, or if the contents of the collection might change as your procedure runs.

For Each element In group
statements
Next element

When Visual Basic runs a For Each...Next loop, it follows these steps:

1. It defines element as naming the first element in group (provided that there is at least one element).

2. It runs the statements.

3. It tests to see whether element is the last element in group. If so, Visual Basic exits the loop.

4. It defines element as naming the next element in group.

5. It repeats steps 2 through 4.

Keep the following restrictions in mind when using the For Each...Next statement:

  • For collections, element can only be a Variant variable, a generic Object variable, or any specific OLE Automation object variable. (For information about OLE Automation objects, see Chapter 10, "Communicating with Other Applications.") For arrays, element can only be a Variant variable.
  • You cannot use the For Each...Next statement with an array of user-defined types because a Variant variable cannot contain a user-defined type. For more information about data types, see Chapter 2, "Variables, Constants, and Data Types."

The following example examines each cell in the current region for cell A1 on the worksheet named "sheet3" and deletes the cell if its value is less than -1.

For Each c In Worksheets("sheet3").Range("a1").CurrentRegion.Cells
    If c.Value < -1 Then c.Delete
Next c

For more information about collections and more examples of the For Each...Next statement, see Chapter 4, "Objects and Collections."

Note

The variable name after the Next statement is optional, but it can make your code easier to read, especially if you have several nested For loops.


Nesting Control Structures

As the preceding example demonstrates, you can place control structures inside other control structures (for instance, an If...Then block within a For Each...Next loop within another If...Then block, and so on). A control structure placed inside another control structure is said to be nested.

The following example searches the range of cells you specify with an argument and counts the number of cells matching the value you specify.

Function CountValues(rangeToSearch, searchValue)
    If TypeName(rangeToSearch) <> "Range" Then
        MsgBox "You can search only a range of cells."
    Else
        For Each c in rangeToSearch.cells
            If c.Value = searchValue Then
                counter = counter + 1
            End If
        Next c
    End If
    CountValues = counter
End Function

Notice that the first End If statement closes the inner If...Then block and that the last End If statement closes the outer If...Then block. Likewise, in nested For...Next and For Each...Next loops, the Next statements automatically apply to the nearest prior For or For Each statement. Nested Do...Loop structures work in a similar fashion, with the innermost Loop statement matching the innermost Do statement.


Exiting Loops and Procedures

Usually, your macro will run through loops and procedures from beginning to end. There may be situations, however, when leaving a loop or procedure earlier than normal can save you time by avoiding unnecessary repetition.

For example, if you're searching for a value in an array using a For...Next loop and you find the value the first time through the loop, there's no reason to search the rest of the array — you can stop repeating the loop and continue with the rest of the procedure immediately. If an error occurs in a procedure that makes the remainder of the procedure unnecessary, you can leave the procedure immediately. You can cut a control structure off early by using one of the Exit statements.

While the Exit statements can be convenient, you should use them only where absolutely necessary and only as a response to an extraordinary condition (not in the normal flow of a loop or procedure). Overusing Exit statements can make your code difficult to read and debug.

There may be better ways to avoid portions of your macro. For example, instead of using an Exit statement inside a For...Next loop searching for a value in an array, you could use a Do loop to search the array only while an incremented index value is smaller than the array's upper bound and a Boolean variable value is False. When you find the array value, setting the Boolean value to True causes the loop to stop.

i = LBound(searchArray)
ub = UBound(searchArray)
foundIt = False
Do
    If searchArray(i) = findThis Then foundIt = True
    i = i + 1
Loop While i <= ub And Not foundIt

You use the Exit For statement to exit directly from a For loop, and you use the Exit Do statement to exit directly from a Do loop.

For Each c in rangeToSearch
    If c.Value = searchValue Then
        found = True
        Exit For
    End If
Next

You use the Exit Sub and Exit Function statements to exit a procedure.

For Each c in rangeToSearch
    If c.Value = searchValue Then
        counter = counter + 1
    ElseIf c.Value = "Bad Data" Then
        countValues = Null
        Exit Function    'Stop testing and exit immediately.
    End If
Next c


Chapter 4 Objects and Collections

Objects are the fundamental building blocks of Visual Basic; nearly everything you do in Visual Basic involves manipulating objects. Every element in Microsoft Excel — each workbook, worksheet, chart, cell, and so on — can be represented by an object in Visual Basic. By creating procedures that manipulate these objects, you automate tasks in Microsoft Excel.

Contents
  • Introduction to Objects
  • Building an Expression to Return an Object
  • Applying Properties and Methods to an Object
  • Using Microsoft Excel Objects
  • Using the Object Browser


Introduction to Objects

An object is a special type of variable that contains both data and code and that represents a specific element in Microsoft Excel. Objects exist only in the memory of the computer; they don't appear in the code you write.

Objects have types, just as other kinds of variables have data types. Object types are called classes; Workbook, Worksheet, and Range are a few of the Microsoft Excel object classes. When you know an object's class, you can use Help to find the object's properties and methods.

Visual Basic supports a set of objects that correspond directly to elements in Microsoft Excel, most of which you're familiar with from the user interface. For example, the Workbook object represents a workbook, the Worksheet object represents a worksheet, and the Range object represents a range of cells. To perform a task using Visual Basic, you return an object that represents the appropriate Microsoft Excel element and then manipulate it using that object's properties and methods. For example, the following illustration shows how Visual Basic sets the value of a cell, using the Value property of the Range object.

It's important to remember that the Worksheet and Range objects in this example never appear in the Visual Basic code — they exist only in the memory of the computer. However, the Worksheets method and the Range method, which return the objects, do appear in the code.


Understanding Collections

A collection is an object that contains a group of related objects. For example, the Worksheets collection object contains Worksheet objects. Each object within a collection is called an element of that collection. Because collections are objects, they have properties and methods, just as singular objects do.

In the preceding illustration, the Worksheets method returns a Worksheet object. The method actually returns one member of the Worksheets collection. When you want to work with a single object, you usually return one from a collection. The property or method you use to return the object is called an accessor.

Many accessors take an argument that chooses, or indexes, an object in the collection. For example, the Worksheets method takes an argument that refers to a single worksheet. The argument can be a worksheet name, or it can be a number that corresponds to the position of the worksheet tabs in a workbook, as shown in the following illustration.


Understanding the Object Hierarchy

Objects can contain other objects, just as elements in Microsoft Excel can contain other elements. For example, a workbook contains worksheets and charts, and a Workbook object contains a Worksheets collection and a Charts collection. This hierarchical arrangement of objects is called the object hierarchy, or the object model. For the complete object model, see "Microsoft Excel Object Model" in Help.


Building an Expression to Return an Object

There are two ways to build an expression to return an object. The first method is to write the expression from scratch, using Help to navigate the object model. The second method is to use the macro recorder to record an expression and then to modify the expression as necessary.


Building an Expression from Scratch

A few simple rules will help you build expressions from scratch. You can use Help to see the object model and to find the accessors for the objects you want to return. Remember the following guidelines when you build expressions from scratch:

  • Many accessors have the same name as the collection they apply to (Workbooks collection and Workbooks method, for example).
  • Each object topic in Help contains a partial view of the object model so that you can locate the object in the hierarchy. The topics also contain information about the accessors, plus sample code showing how to use the object.
  • The Application property (which returns the Application object) is usually optional.
  • If you omit the Workbooks accessor method, the expression uses the active workbook.
  • If you omit the Worksheets (or Sheets) accessor method as well as the Workbooks accessor method, the expression uses the active sheet in the active workbook.


Using the Macro Recorder to Build an Expression

The macro recorder is probably the best way to learn how to build expressions that return objects. The recorder is especially useful when you work with the complex object hierarchies of charts, charts embedded on worksheets, and PivotTables®. Use the macro recorder to build an expression that contains the properties and methods you need, and then modify the expression if necessary.

For example, suppose that you need help building an expression that changes the font style and font size for the title of a chart. You don't remember the object model, so you use the recorder to produce the following code.

Sub Macro1()
    ActiveChart.ChartTitle.Select
    With Selection.Font
        .Name = "Times New Roman"
        .FontStyle = "Bold"
        .Size = 24
        .Strikethrough = False
        .Superscript = False
        .Subscript = False
        .OutlineFont = False
        .Shadow = False
        .Underline = xlNone
        .ColorIndex = xlAutomatic
        .Background = xlAutomatic
    End With
End Sub

The recorder navigated the object model for you, recording the accessors for the Chart, ChartTitle, and Font objects. You can now modify the recorded code to:

  • Change the ActiveChart property to the Charts method and use a chart name as the argument. This allows you to run the macro from any sheet in the workbook, not just from the chart sheet.
  • Remove the selection-based code. You don't need the Select method or the Selection property. You also need to move the With keyword after you make this change.
  • Remove the properties of the Font object that the macro should not change (it should change only the FontStyle property and the Size property; it should not change any other property).
  • Change the procedure name.

The following example shows the code after modification.

Sub FormatChartTitle()
    With Charts("Chart1").ChartTitle.Font
        .FontStyle = "Bold"
        .Size = 24
    End With
End Sub

When you record actions on cells and ranges, be sure to record using relative references (on the Tools menu, point to Record Macro, and then click Use Relative References). This ensures that the recorded code contains offsets to cells instead of absolute references to cells, which makes the code more general and more easily adaptable to your specific requirements.


Applying Properties and Methods to an Object

You change attributes of an object by setting its properties. For example, you can set the Formula property of the Range object that refers to cell A1, which sets the formula in the cell.

You can also get the value of a property. For example, you can get the Value property of the Range object that refers to cell A1. This returns the value of cell A1 to your code, where you can use the value to make decisions or perform calculations.

Methods perform actions on objects. For example, you can save the active workbook by applying the SaveAs method to the Workbook object that refers to the active workbook. The difference between properties and methods is that properties have values you set or return, whereas methods are actions you want an object to perform.

Accessors are properties and methods you use to return an object. For example, the ActiveWorkbook property returns a Workbook object that refers to the active workbook, and the Range method returns a Range object that refers to a range of cells.

Note

In some object-oriented programming languages, distinguishing a property from a method is very straightforward. In Visual Basic, the distinction isn't so clear in some cases. For example, properties generally don't take arguments, but in Microsoft Excel the International property does take an argument. Don't worry about whether a keyword is a property or a method; instead, concentrate on finding the correct keyword for the task you want to accomplish.


Setting and Getting Properties

With most properties, you can either set or return their values; these are called read-write properties. With other properties, you can only return their values; these properties are called read-only properties. Each property description in Help tells you whether a property is read-write or read-only.

Setting a Property Value

For an assignment statement to set the value of a property, the expression that contains the property must appear on the left side of the equal sign. For example, to set the Value property of the Range object that refers to cell A1 on Sheet1, you would write the following code.

Worksheets("Sheet1").Range("A1").Value = 3.14159

You can also set a property value to another property value, as shown in the following code. This example copies the value from cell B2 on Sheet2 to cell A1 on Sheet1.

Worksheets("Sheet1").Range("A1").Value = _
    Worksheets("Sheet2").Range("B2").Value

Getting a Property Value

For an assignment statement to get the value of a property, the expression that contains the property must appear on the right side of the equal sign. A variable typically appears on the left side of the equal sign.

For example, the following code gets the Value property of the Range object that refers to cell A1 on Sheet1 and assigns it to the variable myValue.

myValue = Worksheets("Sheet1").Range("A1").Value

You can also get a property value without assigning the property to a variable. For example, the following code gets the Value property of the Range object that refers to cell A1 on Sheet1 and then passes this value to the MsgBox function.

MsgBox Worksheets("Sheet1").Range("A1").Value

Using Built-in Constants as Property Values

Many properties have built-in constants as their values. For example, you can set the HorizontalAlignment property to xlCenter, xlLeft, xlRight, and so on. The Help topic for any given property contains a list of built-in constants you can use. You should always use the built-in constant, not the value that the constant represents, because the value may change in future versions of Visual Basic.


Using Methods

When you use a method in your procedure, the expression that contains the method can have several different forms. Some methods, such as the AutoFit method, take no arguments, whereas other methods take several arguments. These variations are described in the following sections.

Methods That Take No Arguments

To use a method that takes no arguments, build an expression to return the object, and then apply the method. For example, to automatically adjust the column width of columns A through D on Sheet1 to fit the contents of the cells, you could write the following code.

Worksheets("Sheet1").Columns("A:D").AutoFit

Methods That Take Arguments

When a method takes arguments, the way you write your code depends on whether you want to use the value returned by the method. If you don't want to use the return value of a method, don't enclose the arguments in parentheses. For example, to sort the contents of cells A1:A10 on Sheet1, you could write the following code.

Worksheets("Sheet1").Range("A1:A10").Sort _
    Worksheets("Sheet1").Range("A1")

In the preceding code, the first argument to the Sort method is the expression Worksheets("Sheet1").Range("A1"); it isn't enclosed in parentheses because you aren't using the Sort method's return value.

On the other hand, if you use the return value, you must enclose the argument in parentheses. Suppose that you use the CheckSpelling method to check the spelling of a single word. The word becomes the argument to the method, which returns True if the word is spelled correctly or False if it isn't. You could write the following procedure.

Sub CheckWord()
    returnValue = Application.CheckSpelling("recieve")
    If returnValue = True Then
        MsgBox "The word is spelled correctly"
    Else
        MsgBox "The word is misspelled!"
    End If
End Sub

Notice that the argument is enclosed in parentheses. If you run this code, you will get the second message box, because the word is intentionally misspelled.

Using Named Arguments in Methods

Many methods take more than one argument. For example, the Open method, which opens a workbook, takes 12 arguments. If you want to write code that opens the workbook BOOK2.XLS, which has the protection password "drowssap", you could write the following code.

Workbooks.Open "BOOK2.XLS", , , , "drowssap"

However, this code is difficult to write correctly without introducing bugs, because you have to count the number of commas to insert between the arguments. The code is also very difficult to read, and it gives no clues about what the arguments represent. The following example shows a better way to write this code.

Workbooks.Open fileName:="BOOK2.XLS", password:="drowssap"

Because every argument has a name, you can use the name and the := operator to assign a value to an argument. When you use named arguments, you don't have to remember the order of the arguments. For example, the preceding code could have been written with the order of the arguments reversed.

Workbooks.Open password:="drowssap", fileName:="BOOK2.XLS"

The preceding section's rules about parentheses apply to named arguments also. For example, the CheckWord procedure could use a named argument for the CheckSpelling method, as shown in the following code.

Sub CheckWord()
    returnValue = Application.CheckSpelling(word:="recieve")
    If returnValue = True Then
        MsgBox "The word is spelled correctly"
    Else
        MsgBox "The word is misspelled!"
    End If
End Sub

Using Built-in Constants as Argument Values

Many methods take built-in constants as their argument values. For example, the ActivateMicrosoftApp method takes as its argument values xlMicrosoftAccess, xlMicrosoftWord, and so on. The Help topic for any given method contains a list of built-in constants you can use for argument values. You should always use the built-in constant, not the value that the constant represents, because the value may change in future versions of Visual Basic.


Using Properties and Methods That Are Unique to Collections

Collections have a Count property, an Add method, and an Item method. This section describes how to use these language elements.

Using the Count Property

The Count property returns the number of elements in a collection. For example, the following code uses the Count property to display the number of worksheets in the active workbook.

Sub NumWorksheets()
    MsgBox "Number of worksheets in this workbook: " & _
        ActiveWorkbook.Worksheets.Count
End Sub

The Count property is useful when you want to loop on the elements in a collection, although in most cases a For Each...Next loop is recommended instead. The following example shows how you can use the Count property to loop on the worksheets in the active workbook, hiding every other worksheet.

Sub HideEveryOther()
    For i = 1 To Worksheets.Count
        If i Mod 2 = 0 Then
            Worksheets(i).Visible = False
        End If
    Next i
End Sub

Using the Add Method

The Add method creates a new element in a collection. This results in a new element in Microsoft Excel also. For example, when you use the Add method on the Worksheets collection, Visual Basic adds a new Worksheet object to the collection, and Microsoft Excel adds a new worksheet to the workbook.

The Add method takes different arguments, depending on the collection it's applied to. For example, the Add method for the Workbooks collection takes one argument (template), but the Add method for the Worksheets collection takes four arguments (before, after, count, and type). You can find the arguments for the Add method in the Object Browser or in Help.

Using the Add Method's Return Value

The Add method returns a reference to the new object it creates. If you need to refer to the new object in your code, you should set an object variable to the return value and then use the object variable to refer to the new object.

For example, the first procedure in the following code creates a new worksheet in the active workbook and then hides the worksheet by setting its Visible property to the constant xlVeryHidden. The public object variable newSheet is set to the return value of the Add method. The variable newSheet can be used by any procedure in any module of the active workbook. Hidden worksheets are an excellent place for a macro to temporarily store numbers and other data, as shown in the other two procedures in the following example.

Public newSheet As Object

Sub CreateScratchWorksheet()
    Set newSheet = Worksheets.Add
    newSheet.Visible = xlVeryHidden
End Sub

Sub FillRanges()
    newSheet.Range("F9").Value = "some text"
    newSheet.Range("A1:D4").Formula = "=RAND()"
End Sub

Sub ShowValue()
    MsgBox newSheet.Range("A1").Value
End Sub

Using the Item Method

Most of the code you see in this book and in Help uses a shorthand syntax for accessor methods. The following two lines of code, which perform the same action in Microsoft Excel, demonstrate the shorthand syntax.

Worksheets("Sheet1").Range("A1").Value = 3        ' shorthand

Worksheets.Item("Sheet1").Range("A1").Value = 3    ' same action

You may see the Item method used occasionally in other books about Visual Basic. For brevity in code, you can always omit the Item method and use the shorthand syntax. The shorthand syntax occurs because the Item method is the default method for a collection object.


Using Default Properties and Methods

Many objects in Microsoft Excel have a default property or method. Visual Basic applies the default property or method to a given object to resolve an expression that would not be valid otherwise. For example, the following code would not be valid if the Range object did not have a default property, because you cannot set an object equal to a number.

Worksheets("Sheet1").Range("A1") = 3

Because the Range object's default property is the Value property, the preceding expression correctly sets the value of cell A1 on Sheet1 to the number 3. The preceding code is equivalent to the following code.

Worksheets("Sheet1").Range("A1").Value = 3

Although you can use the default property or method to save yourself some typing, this may create code that's difficult to debug and maintain. Using fully qualified expressions instead of using default properties and methods is highly recommended.


Using Microsoft Excel Objects

This section describes some very common programming tasks, such as using object variables, looping on the objects in a collection, and setting multiple properties of an object. This section also describes how to use two of the most common objects in Microsoft Excel — the Range and Workbook objects.


Using Object Variables

In addition to storing values, a variable can store a reference to an object. You assign an object to a variable for the same reasons you assign any other value to a variable:

  • Variable names are often shorter and easier to remember than the values they contain (or, in this case, the objects they refer to).
  • Variables can be changed to refer to other objects while your code is running.
  • Referring to a variable that contains an object is more efficient than repeatedly referring to the object itself.

Declaring Object Variables

You declare an object variable the same way you declare other types of variables. For example, to declare the object variable mySheet, you could write the following code.

Dim mySheet As Object

This declaration uses the generic Object type specifier. Generic object variables are useful when you don't know the specific type of object the variable will contain, or when the variable must at different times contain objects from several different classes. For example, if you set mySheet to an object returned from the Sheets collection, it could be one of four classes: Worksheet, Chart, Module, or DialogSheet.

You can also declare an object variable using a specific class name, as shown in the following code.

Dim mySheet As Worksheet

In this example, if the code tries to set mySheet to an object other than a Worksheet object, a run-time error occurs (error 13, "Type mismatch"). You can see this by running the following Sub procedure.

Sub ListSheetTypes()
    Dim mySheet As Worksheet
    For Each mySheet In ActiveWorkbook.Sheets
        MsgBox TypeName(mySheet)
    Next
End Sub

The run-time error occurs when the For Each...Next loop tries to set mySheet to a member of the Sheets collection that's not a Worksheet object.

Declaring object variables as specific classes can help you find bugs in your code, because the run-time error indicates that the code is doing something other than what you expected.

Assigning Object Variables

You assign an object to an object variable using the Set statement.

Set variable = object

For example, the following code sets the object variable myRange to the object that refers to cell A1 on Sheet1.

Set myRange = Worksheets("Sheet1").Range("A1")

You must use the Set statement whenever you want an object variable to refer to an object. If you forget the Set statement, several different errors can occur. For example, if you previously declared the object variable, a run-time error occurs (error 91, "Object variable not set") when you run the following code.

Dim myRange As Object
myRange = Worksheets("Sheet1").Range("A1")    ' error 91 occurs here

If you haven't previously declared the object variable, it will be a Variant variable by default. In this case, if you forget the Set statement, Visual Basic attempts to use the default property of the object to assign a value to the variable. For example, the following code causes Visual Basic to use the default property of the Range object (which is the Value property) to assign myRange the value of cell A1.

myRange = Worksheets("Sheet1").Range("A1")    ' forgot the Set statement!

In this example, no error occurs in the line of code in which you forgot the Set statement. However, several different run-time errors can occur later, depending on how your code uses the variable myRange. The most common errors in this case will be error 424, "Object required" and error 13, "Type mismatch." When you see either of these errors, check your code for missing Set statements.


Looping on a Collection

There are several different ways you can loop on the elements of a collection. However, the recommended method for looping on a collection is to use the For Each...Next loop. In this structure, Visual Basic automatically sets an object variable to return every object in the collection. The following illustration shows the essential components of the For Each...Next loop.

The following procedure shows how you could use a For Each...Next loop to close every workbook except the workbook that contains the running procedure.

Sub CloseWorkbooks()
    Dim wb As Workbook
    For Each wb In Application.Workbooks
        If wb.Name <> ThisWorkbook.Name Then
            wb.Close
        End If
    Next wb
End Sub

The For Each...Next loop is also the recommended method for looping on a range of cells; for more information, see "Looping on a Range of Cells" later in this chapter. For more information about looping in Visual Basic, see Chapter 3, "Controlling Program Flow."


Performing Multiple Actions on an Object

Procedures often need to perform several different actions on the same object. For example, you might need to set several properties for the same cell. One way to do this is to use several statements, as in the following example.

ActiveSheet.Cells(1, 1).Formula = "=SIN(180)"
ActiveSheet.Cells(1, 1).Font.Name = "Arial"
ActiveSheet.Cells(1, 1).Font.Bold = True
ActiveSheet.Cells(1, 1).Font.Size = 8

Notice that all these statements use the same object reference. You can make this code easier to enter, easier to read, and more efficient by using the With...End With statement.

With ActiveSheet.Cells(1, 1)
    .Formula = "=SIN(180)"
    .Font.Name = "Arial"
    .Font.Bold = True
    .Font.Size = 8
End With

You can also nest With...End With statements. The following example shows how you can rewrite the preceding code using one With...End With statement nested inside another one.

With ActiveSheet.Cells(1, 1)
    .Formula = "=SIN(180)"
    With .Font
        .Name = "Arial"
        .Bold = True
        .Size = 8
    End With
End With

The object reference following the With...End With statement can be a reference to either a single object or a collection. The following example sets the font properties of all the text boxes on the active sheet.

With ActiveSheet.TextBoxes
    .Font.Name = "Arial"
    .Font.Size = 8
End With


Working with the Range Object

The Range object can represent a single cell, a range of cells, an entire row or column, a selection containing multiple areas, or a 3-D range. The Range object is somewhat unusual in that it can represent both a single cell and multiple cells. There is no separate collection object for the Range object; you can think of it as being both a single object and a collection. There are many different properties and methods that return a Range object, as shown in the following list.

  • ActiveCell
  • BottomRightCell
  • Cells
  • ChangingCells
  • CircularReference
  • Columns
  • CurrentArray
  • CurrentRegion
  • Dependents
  • DirectDependents
  • DirectPrecedents
  • EntireColumn
  • EntireRow
  • Next
  • Offset
  • PageRange
  • Precedents
  • Range
  • RowFields
  • RowRange
  • Rows
  • Selection
  • TableRange1
  • TableRange2
  • TopLeftCell
  • UsedRange
  • VisibleRange

For more information about these properties and methods, see the individual property and method topics in Help.

Using the Range Method

One of the most common ways to return a Range object is to use the Range method. The argument to the Range method is a string that's either an A1-style reference or the name of a range. The examples in the following table show several different ways to use the Range method.

To do this | Use the following code
Set the value of cell A1 on Sheet1 | Worksheets("Sheet1").Range("A1").Value = 3
Set the formula for cell B1 on the active sheet | Range("B1").Formula = "=5-10*RAND()"
Set the value of each cell in the range C1:E3 on the active sheet | Range("C1:E3").Value = 6
Clear the contents of the range A1:E3 on the active sheet | Range("A1", "E3").ClearContents
Set the font for the range named "myRange" (a workbook-level name) to bold | Range("myRange").Font.Bold = True
Set the value of each cell in the range named "yourRange" (a sheet-level name) to bold | Range("Sheet1!yourRange").Value = 3
Set an object variable to refer to a range | Set objRange = Range("myRange")

Remember that expressions such as Range("C1:E3").Value = 6 assume that the Range method operates on the active sheet. If you try to run this code from the module that contains it, a run-time error occurs (error 1004, "Range method of Application class failed").

Another cause for errors can be using the Range method in an argument to another method, without fully qualifying the Worksheet object to which the Range method applies. For example, the following code, which is supposed to sort a range of cells on Sheet1, also causes run-time error 1004.

Sub SortRange()
Worksheets("Sheet1").Range("A1:B10").Sort _
    key1:=Range("A1"), order1:=xlDescending
End Sub

This error is more difficult to find, because the line that contains the Sort method is correct. The error is caused by the second line, which contains the key1 argument. This code will run correctly if Sheet1 is the active sheet, but it will fail when it's run from another worksheet or from a module. To correct the error, use the Worksheets method in the argument.

Sub SortRange()
    Worksheets("Sheet1").Range("A1:B10").Sort _
        key1:=Worksheets("Sheet1").Range("A1"), order1:=xlDescending
End Sub

Using the Cells Method

The Cells method is similar to the Range method except that it takes numeric arguments instead of string arguments. When you use this method to return a single cell, the first argument is the row number of the cell, and the second argument is the column number of the cell. The examples in the following table show several different ways to use the Cells method.

To do this | Use the following code
Set the value of cell A1 on Sheet1 | Worksheets("Sheet1").Cells(1, 1).Value = 3
Set the formula for cell B1 on the active sheet | Cells(1, 2).Formula = "=5-10*RAND()"
Set an object variable | Set objRange = Worksheets("Sheet1").Cells(1, 1)

The Cells method is very useful when you want to refer to cells using loop counters. For example, the following code loops through cells A1:D10 on Sheet1. If any of the cells has a value less than 0.01, the example replaces the value with 0 (zero).

Sub RoundToZero()
    For rwIndex = 1 to 4
        For colIndex = 1 to 10
            If Worksheets("Sheet1").Cells(rwIndex, colIndex) < .01 Then
                Worksheets("Sheet1").Cells(rwIndex, colIndex).Value = 0
            End If
        Next colIndex
    Next rwIndex
End Sub

The following example shows a quick and easy way to display items in a multicolumn list. The code creates a new worksheet and sets the object variable newSheet to refer to the worksheet. The code then creates a list of all the names in the active workbook and shows their formulas in A1-style notation.

Sub ListNames()
    Set newSheet = Worksheets.Add
    i = 1
    For Each nm In ActiveWorkbook.Names
        newSheet.Cells(i, 1).Value = nm.Name
        newSheet.Cells(i, 2).Value = "'" & nm.RefersTo
        i = i + 1
    Next nm
    newSheet.Columns("A:B").AutoFit
End Sub

Combining the Range and Cells Methods

In some situations, you may need to create a Range object based on a top row, a bottom row, a left column, and a right column, given as numbers. You can return Range objects by combining the Range and Cells methods in a single statement. The following code returns a Range object that refers to cells A1:D10 on Sheet1. The two Cells method calls define cells A1 and D10, and then the Range method call returns an object bounded by these two cells.

Set myObj = Worksheets("Sheet1").Range(Cells(1, 1), Cells(10, 4))

The following code uses a Range object that refers to the range bounded by row 1 and column 1 at the upper left and by row 10 and column 6 at the lower right. The range bounds are variables in this example (rwMin, rwMax, and so on).

Sub DemoCells()
    rwMin = 1   ' the top row
    rwMax = 10  ' the bottom row
    colMin = 1  ' the left column
    colMax = 6  ' the right column
    Set TLCell = Worksheets("Sheet1").Cells(rwMin, colMin)
    Set BRCell = Worksheets("Sheet1").Cells(rwMax, colMax)
    Set myRange = Worksheets("Sheet1").Range(TLCell, BRCell)
    myRange.Value = "abc"
End Sub

Using the Offset Method

You often need to return a range of cells that's a certain number of rows or columns from another range of cells. The Offset method takes an input Range object, a RowOffset argument, and a ColumnOffset argument to return a new range. For example, the following code determines the type of data in each cell of a range. The code writes the data types in the column to the right of the input cells.

Sub ScanColumn()
    For Each c In Worksheets("Sheet1").Range("A1:A10").Cells
        If Application.IsText(c.Value) Then
            c.Offset(0, 1).Formula = "Text"
        ElseIf Application.IsNumber(c.Value) Then
            c.Offset(0, 1).Formula = "Number"
        ElseIf Application.IsLogical(c.Value) Then
            c.Offset(0, 1).Formula = "Boolean"
        ElseIf Application.IsError(c.Value) Then
            c.Offset(0, 1).Formula = "Error"
        ElseIf c.Value = "" Then
            c.Offset(0, 1).Formula = "(blank cell)"
        End If
    Next c
End Sub

Using the CurrentRegion and UsedRange Properties

These two properties are very useful when your code operates on ranges whose size you have no control over. The current region is a range of cells bounded by empty rows and empty columns, or by a combination of empty rows, empty columns, and the edges of the worksheet.

The CurrentRegion property applies to a Range object. There can be many different current regions on a worksheet, depending on the Range object to which you apply the CurrentRegion property.

Suppose that Sheet1 contains a list to which you want to apply a number format. The only thing you know about the list is that it begins at cell A1 — you don't know how many rows or columns it contains. The following code shows how to format the list using the CurrentRegion property.

Sub FormatRange()
    Set myRange = Worksheets("Sheet1").Range("A1").CurrentRegion
    myRange.NumberFormat = "0.0"
End Sub

The used range is bounded by the upper-left and lower-right nonempty cells on a worksheet. It's a range that contains every nonempty cell on the worksheet, as well as all the empty cells that are interspersed among them. There can be only one used range on a worksheet; the UsedRange property applies to a Worksheet object, not to a Range object.

Suppose that the active worksheet contains data from a timed experiment. The used range contains the dates in the first column, the times in the second column, and the measurements in the third and fourth columns. You want to write code that combines each separate date and time into a single value, converts that value from Greenwich Mean Time (GMT) to Pacific Standard Time, and then applies a date format. The raw data appears as in the following example.

Notice that the table can contain empty rows and columns. You can use the UsedRange property to return the entire used range, including the two embedded blank rows. The following code shows one way to convert and format the dates and times.

Sub ConvertDates()
    Set myRange = ActiveSheet.UsedRange
    myRange.Columns("C").Insert
    Set dateCol = myRange.Columns("C")
    For Each c In dateCol.Cells
        If c.Offset(0, -1).Value <> "" Then
            c.FormulaR1C1 = "=RC[-2]+RC[-1]-(8/24)"
        End If
    Next c
    dateCol.NumberFormat = "mmm-dd-yyyy hh:mm"
    dateCol.Copy
    dateCol.PasteSpecial Paste:=xlValues
    myRange.Columns("A:B").Delete
    dateCol.AutoFit
End Sub

The formatted worksheet appears as in the following example.

Notice that the code uses the expression ActiveSheet.UsedRange.Columns("C") to return the third column from the used range (although this is the third column in the used range, it appears in column D on the worksheet because column A is empty). You can use other Range object properties and methods in a similar way to build complex expressions that return sub-ranges or super-ranges of an input Range object. Some properties and methods commonly used in this way are Areas, Cells, Columns, EntireColumn, EntireRow, Range, and Rows.

Looping on a Range of Cells

There are several different ways to loop on the cells in a range. This section shows examples of the For Each...Next statement and the Do...Loop statement applied to looping on a range of cells.

Using For Each...Next

The recommended way to loop on the cells in a range is to use the For Each...Next loop, which is also the recommended way to loop on the elements in a collection.

The following example shows how to loop through the range A1:D10 on Sheet1, setting any number whose absolute value is less than 0.01 to 0 (zero).

Sub RoundToZero()
    For Each r In Worksheets("Sheet1").Range("A1:D10").Cells
        If Abs(r.Value) < 0.01 Then
            r.Value = 0
        End If
    Next r
End Sub

Suppose that you want to modify this code to loop over a range of cells that a user selects. One way of doing this is to use the InputBox method to prompt the user to select a range of cells. The InputBox method returns a Range object that represents the selection. By using the type argument and error handling, you can ensure that the user selects a valid range of cells before the input box is dismissed.

Sub RoundToZero()
    Worksheets("Sheet1").Activate
    On Error GoTo PressedCancel
    Set r = Application.InputBox( _
            prompt:="Select a range of cells", _
            Type:=8)
    On Error GoTo 0
    For Each c In r.Cells
        If Abs(c.Value) < 0.01 Then
            c.Value = 0
        End If
    Next c
    Exit Sub

PressedCancel:
    Resume
End Sub

If you don't want the user to select the range, you may be able to use the CurrentRegion property or the UsedRange property to return a Range object. For example, if you know that the data on Sheet1 begins at cell A1 and has no empty rows or columns, you can use the CurrentRegion property to return the entire range automatically.

Sub RoundToZero()
    Set r = Worksheets("Sheet1").Range("A1").CurrentRegion
    For Each c In r.Cells
        If Abs(c.Value) < 0.01 Then
            c.Value = 0
        End If
    Next c
End Sub

The following two examples show two different ways to hide every other column in the used range on Sheet1. The first example shows a For Each...Next loop in which the Column property of the object variable is tested.

Sub HideColumns()
    Set r = Worksheets("Sheet1").UsedRange
    For Each col In r.Columns
        If col.Column Mod 2 = 0 Then
            col.Hidden = True
        End If
    Next col
End Sub

The second example shows a For Each...Next loop using a loop counter in which the loop counter is tested.

Sub HideColumns()
    Set r = Worksheets("Sheet1").UsedRange
    For i = 1 To r.Columns.Count
        If i Mod 2 = 0 Then
            r.Columns(i).Hidden = True
        End If
    Next i
End Sub

Using Do...Loop

Occasionally, the For Each...Next loop isn't the best way to loop on a range. Suppose that you have a column of data and you want to write a macro that sorts the data and then deletes rows that contain duplicate data. You could try to use a For Each...Next loop, as shown in the following code.

Sub BuggyRemoveDuplicates()    ' DON'T USE THIS CODE!
    Worksheets("Sheet1").Range("A1").Sort _
        key1:=Worksheets("Sheet1").Range("A1")
    Set r = Worksheets("Sheet1").Range("A1").CurrentRegion.Columns("A")
    For Each c In r.Cells
        If c.Offset(1, 0).Value = c.Value Then
            c.Offset(1, 0).EntireRow.Delete
        End If
    Next c
End Sub

Unfortunately, this code doesn't work correctly because the Delete method is modifying the range over which the For Each...Next loop is iterating. This causes duplicates not to be deleted in some cases.

A better solution is to use a Do...Loop structure, as shown in the following code.

Sub GoodRemoveDuplicates()
    Worksheets("Sheet1").Range("A1").Sort _
            key1:=Worksheets("Sheet1").Range("A1")
    Set currentCell = Worksheets("Sheet1").Range("A1")
    Do While Not IsEmpty(currentCell)
        Set nextCell = currentCell.Offset(1, 0)
        If nextCell.Value = currentCell.Value Then
            currentCell.EntireRow.Delete
        End If
        Set currentCell = nextCell
    Loop
End Sub

The loop tests the object variable currentCell, exiting when it encounters an empty cell at the bottom of the column of data. You could build an equivalent loop by testing the value in currentCell against an empty string, as shown in the following code.

    Do While currentCell.Value <> ""
        ' code here
    Loop

In either case, don't forget to increment the cell (Set currentCell = nextCell, for example) at the bottom of the Do...Loop structure.

Using the Address Property to Debug Range Object Code

You can apply the Address property to any Range object. The Address property returns the cell address of a range, as a string. The following example shows how to use the Address property to debug the HideColumns code.

Sub HideColumns()
    Set r = Worksheets("Sheet1").UsedRange
    MsgBox r.Address  ' debugging only!
    For i = 1 To r.Columns.Count
        If i Mod 2 = 0 Then
            r.Columns(i).Hidden = True
            MsgBox r.Columns(i).Address  ' debugging only!
        End If
    Next i
End Sub

You can also set watch expressions instead of using message boxes. For the preceding example, you could set two watch expressions — r.Address and r.Columns(i).Address — and then examine the values of the watch expressions in the Immediate pane of the Debug window. For more information about debugging, see Chapter 6, "Debugging."


Working with the Workbook Object

When you open or save a file in Microsoft Excel, you're actually opening and saving a workbook. In Visual Basic, the methods for manipulating files are methods of the Workbook object or its collection.

Opening Workbooks

When you open a workbook, you use the Open method. The Open method always applies to the Workbooks collection, which you return using the Workbooks method. The following code opens the file BOOK1.XLS (in the current folder) and then displays the value that's in cell A1 of the first worksheet in the workbook.

Sub OpenBook1()
    Set myBook = Workbooks.Open(Filename:="BOOK1.XLS")
    MsgBox myBook.Worksheets(1).Range("A1").Value
End Sub

Notice that the return value of the Open method is a Workbook object that refers to the workbook that was just opened.

The filename in this example doesn't contain a path; therefore, the file is assumed to be in the current folder. This is guaranteed to cause a run-time error, because as soon as the user changes the current folder, Visual Basic can no longer find the file.

There are two relatively safe places to store a workbook you want to open programmatically. One place is the folder that contains the executable file for Microsoft Excel. The other place is the Library folder, which is created automatically during setup; this folder is one level down from the folder that contains the executable file.

If you want to open a workbook that's saved in the folder that contains the executable file, you can use the Path property to return a string that specifies the folder. The PathSeparator property returns the correct separator character for the current file system (for example, "\" for MS-DOS®/Windows® FAT or ":" for the Macintosh®). The following example shows file-system-independent code you can use to open BOOK1.XLS, assuming that BOOK1.XLS is saved in the executable file's folder.

Sub OpenBook1()
    EXEPath = Application.Path & Application.PathSeparator
    fName = EXEPath & "BOOK1.XLS"
    Set myBook = Workbooks.Open(Filename:=fName)
    MsgBox myBook.Worksheets(1).Range("A1").Value
End Sub

The other relatively safe place to store a workbook is in the Library folder. You can use the LibraryPath property instead of the Path property to return a string that specifies the Library folder. The following code shows how you would alter the preceding example to use the LibraryPath property.

Sub OpenBook1()
    LibPath = Application.LibraryPath & Application.PathSeparator
    fName = LibPath & "BOOK1.XLS"
    Set myBook = Workbooks.Open(Filename:=fName)
    MsgBox myBook.Worksheets(1).Range("A1").Value
End Sub

Instead of hard-coding a filename in the Open method, you may want to allow a user to select a file to open. The GetOpenFilename method displays the standard Open dialog box, but it returns a string instead of opening a file. The string contains the fully qualified path and filename. The following example demonstrates the GetOpenFilename method by displaying the return value in a message box and then opening the file.

Sub DemoGetOpenFilename()
    Do
        fName = Application.GetOpenFilename
    Loop Until fName <> False
    MsgBox "Opening " & fName
    Set myBook = Workbooks.Open(Filename:=fName)
End Sub

Creating and Saving Workbooks

You create a new workbook by applying the Add method to the Workbooks collection. Remember to set the return value of the Add method to an object variable so that you can refer to the new workbook in your code.

When you save a new workbook for the first time, use the SaveAs method. For subsequent saves, use the Save method. The GetSaveAsFilename method is very similar to the GetOpenFilename method described in the preceding section. The following code shows how to create a new workbook and then save it using the GetSaveAsFilename method.

Sub CreateAndSave()
    Set newBook = Workbooks.Add
    Do
        fName = Application.GetSaveAsFilename
    Loop Until fName <> False
    newBook.SaveAs Filename:=fName
End Sub

Closing Workbooks

To close a workbook, use the Close method of the Workbook object. You can close a workbook without saving changes, as shown in the following code.

Sub OpenChangeClose()
    Do
        fName = Application.GetOpenFilename
    Loop Until fName <> False
    Set myBook = Workbooks.Open(Filename:=fName)
    '
    ' make some changes to myBook
    '
    myBook.Close savechanges:=False
End Sub

This code uses the GetOpenFilename method to select the workbook to open, makes some changes to the workbook (indicated by the comments), and then closes the workbook without saving the changes.

When to Use the ThisWorkbook Property

Suppose that you're developing a small application using Visual Basic and that you want to save the workbook as a Microsoft Excel add-in when you finish. The macro contains a custom dialog box, Dialog1, and you display the dialog sheet using the following code.

Public DlgValue

Sub DisplayDialog()
    DlgValue = DialogSheets("Dialog1").Show
End Sub

You finish writing and debugging the application, and then you click Make Add-In on the Tools menu, creating an add-in named MYADDIN.XLA. However, when your add-in runs the DisplayDialog procedure, a run-time error occurs (error 1004, "DialogSheets method of Application class failed"). What happened?

In the DisplayDialog procedure, the DialogSheets method applies to the active workbook because you omitted the object qualifier. However, the active workbook isn't MYADDIN.XLA; it's whichever workbook is displayed by Microsoft Excel. You could try the following fix.

DlgValue = Workbooks("MYADDIN.XLA").DialogSheets("Dialog1").Show

This introduces the potential for more bugs, however, because the filename is hard-coded and must be in the current folder. You could use the folder management techniques described in "Opening Workbooks" earlier in this chapter, but there is a much safer and more robust way to fix this bug.

The ThisWorkbook property returns a Workbook object that refers to the workbook containing the code that's running. Therefore, you should use ThisWorkbook whenever you write code you intend to save as an add-in. The following example shows the robust code for the DisplayDialog procedure.

Public DlgValue

Sub DisplayDialog()
    DlgValue = ThisWorkbook.DialogSheets("Dialog1").Show
End Sub


Using the Object Browser

While writing your Visual Basic procedures, you might want to see what objects are available in the active workbook, including the names of procedures you've already written. You can look at this information using the Object Browser.

The Object Browser performs three important functions:

  • It gives you a quick way to navigate in your code.
  • It shows you what objects are available for your procedures, including the properties and methods of those objects.
  • It gives you a way to paste code templates into a module. You can edit the pasted code to make writing procedures faster and less prone to typing errors.

To display the Object Browser

  • On the View menu, click Object Browser.

Object Browser button

You can also click the Object Browser button on the Visual Basic toolbar or press F2 from within a module.

What Appears in the Object Browser

The Object Browser dialog box displays either of two sets of information:

  • The names of all the objects in a library, in addition to all the properties and methods of each object
  • The names of all the Visual Basic modules in a workbook, in addition to the names of all the procedures in each module

The Object Browser contains a box that lists the names of all the object libraries and all the workbooks referenced by the workbook that contains the module you're creating. An object library is a file or a part of an application that provides Visual Basic with information about objects. Libraries and workbooks identify the objects you can use in your procedures. For more information about references to libraries and workbooks, see "Creating a Reference to a Workbook" in Chapter 1.

The list in the Libraries/Workbooks box includes:

  • Microsoft Excel, which provides a library of objects specific to Microsoft Excel
  • VBA (Visual Basic for applications), which provides functions and other language features you can use in Microsoft Excel
  • The open workbook, which contains your code
  • Any other libraries referenced by the code in your workbook

Below the Libraries/Workbooks box is the Objects/Modules box. The contents of this box depend on whether the selection in the Libraries/Workbooks box is an object library name or a workbook name, as described in the following table.

> If the Libraries/Workbooks box shows | > The Objects/Modules box shows
>
> The name of an object library | > The available objects in the library, or the categories of available functions
> The name of a workbook | > The names of all the modules in the workbook

To the right of the Objects/Modules box is the Methods/Properties box. The contents of this box depend on whether the items listed in the Objects/Modules box are the objects in a library or the modules in a workbook, as described in the following table.

> If the Objects/Modules box shows | > The Methods/Properties box shows
>
> The objects in an object library | > The properties and methods of each object in the library
> The modules in a workbook | > The names of the procedures in each module, including property procedures

Moving Between Procedures

You can use the Object Browser to move quickly from one procedure in a workbook to another.

To move to a procedure in a workbook

1. Switch to a Visual Basic module.

2. On the View menu, click Object Browser.

3. In the Libraries/Workbooks box, click the name of the workbook that contains the procedure you want to use.

4. In the Objects/Modules box, click the name of the module that contains the procedure you want.

5. In the Methods/Properties box, click the name of the procedure.

6. Click Show.

The Object Browser moves you to the module that contains the procedure you selected. The insertion point appears to the left of the line immediately following the procedure declaration line.

Browsing Objects

You can also use the Object Browser to see:

  • The objects available in the libraries referenced by your workbook.
  • The properties and methods of those objects.

To find the properties and methods of objects

1. On the View menu, click Object Browser.

2. In the Libraries/Workbooks box, click the name of the object library you want to browse or that contains the object you want to use.

3. In the Objects/Modules box, click the name of the object for which you want to see properties and methods.

Pasting Code

When you finish using the Object Browser to find an object with a property or method you want to use, you can paste a fragment of Visual Basic code from that property or method into your procedure. You can then edit the code fragment to fit the needs of your procedure. The Object Browser pastes the code fragment at the insertion point in the active module.

The code fragment includes syntax for named arguments when appropriate. After you paste the code fragment into your procedure, you can delete any arguments you don't need and then add the appropriate values for the arguments you want to use.

To paste a code fragment into a procedure

1. In a Visual Basic module, place the insertion point at the location in the code where you want to paste the code fragment.

2. On the View menu, click Object Browser.

3. In the appropriate boxes, click the library and the object whose property or method you want to use.

4. In the Methods/Properties box, click the property or method you want to paste into the procedure.

5. Click Paste.


Chapter 5 Optimizing for Size and Speed

Visual Basic is an extremely flexible programming language: there are often several ways to accomplish the same task. When you first start to program, or when you write a macro that will run only once, you'll probably be satisfied with simply "getting the job done." When you write a macro that will be used many times — such as a macro that prepares a weekly report, or an Auto_Open macro that runs every time you open a workbook — or when you write a macro that will be used by other people, you'll probably want to optimize the macro so that it requires less time and memory to run. The techniques described in this chapter will help you write smaller, faster macros.

Contents
  • Minimizing OLE References
  • Using Collection Index Numbers
  • Minimizing Object Activation and Selection
  • Removing Unnecessary Recorded Expressions
  • Minimizing the Use of Variant Variables
  • Using Specific Object Types
  • Using Constants
  • Using Worksheet Functions
  • Using Special-Purpose Visual Basic Methods
  • Turning Off Screen Updating

For information about accessing external data, see Chapter 13, "Accessing External Data."


Minimizing OLE References

Every Visual Basic method or property call requires one or more calls through the OLE IDispatch interface. These OLE calls take time. Minimizing the number of method or property calls is one of the best ways to make your macro run faster.


Using Object Variables

If you find that you're using the same object reference many times, you can set a variable for the object and subsequently use the variable in place of the object reference. This way, you'll only need to call the object accessor once, when you set the variable, instead of calling it each time you want to refer to the object. The following example calls the Workbooks method and the Sheets method twice each.

Workbooks(1).Sheets(1).Range("c5").Value = 10
Workbooks(1).Sheets(1).Range("d10").Value = 12

You can optimize this example by setting an object variable. The following example calls the Workbooks method and the Sheets method only once each.

Set sheet = Workbooks(1).Sheets(1)
sheet.Range("c5").Value = 10
sheet.Range("d10").Value = 12


Using the With Statement

You can use the With statement to eliminate the need for repetitive object references, without setting an explicit object variable. The example in the preceding section could be rewritten as follows, using the With statement. This example calls the Workbooks method and the Sheets method only once each.

With Workbooks(1).Sheets(1)
    .Range("c5").Value = 10
    .Range("d10").Value = 12
End With

Using the With statement eliminates the need for the intermediate variable used in the example in the preceding section; otherwise, this code is the same as in that example.


Using a For Each...Next Loop

Using a For Each...Next loop to iterate through a collection or array is faster than using an indexed loop. In most cases, using a For Each...Next loop is also more convenient and makes your macro smaller and easier to read and debug.

The following code is slow because it sets the row variable thisRow by calling r.Rows(i) each time through the loop.

Set r = Worksheets(1).Range("a1:a200")
For i = 1 To r.Rows.Count
    Set thisRow = r.Rows(i)
    If thisRow.Cells(1, 1).Value < 0 Then
        thisRow.Font.Color = RGB(255, 0, 0)
    End If
Next

The following code is faster and smaller because the For Each...Next loop keeps track of the row count and position.

For Each thisRow In Worksheets(1).Range("a1:a200").Rows
    If thisRow.Cells(1, 1).Value < 0 Then
        thisRow.Font.Color = RGB(255, 0, 0)
    End If
Next

For information about object variables, the With statement, and For Each...Next loops, see Chapter 3, "Controlling Program Flow," and Chapter 4, "Objects and Collections."


Keeping Properties and Methods Outside Loops

Your code can get variable values faster than it can get property values. Therefore, if your code gets the value of a property within a loop, it will run faster if you assign the property to a variable outside the loop and use the variable instead of the property inside the loop. The following example is slow because it gets the Value property each time through the loop.

For iLoop = 2 To 200
    Cells(iLoop, 1).Value = Cells(1, 1).Value
Next I

The following example is faster because the value of one property has been assigned to the variable cv before the loop begins. Visual Basic must therefore access only one property value, instead of two, each time through the loop.

cv = Cells(1, 1).Value
For iLoop = 2 To 200
    Cells(iLoop, 1).Value = cv
Next i

If you're using an object accessor inside a loop, try to move it outside the loop. The following example calls the ActiveWorkbook property, the Sheets method, and the Cells method each time through the loop.

For c = 1 To 1000
    ActiveWorkbook.Sheets(1).Cells(c, 1) = c
Next

Rewriting this example using the With statement moves the ActiveWorkbook property and Sheets method calls outside the loop. You could also move these calls outside the loop using an object variable.

With ActiveWorkbook.Sheets(1)
    For c = 1 To 1000
        .Cells(c, 1) = c
    Next
End With


Using Arrays to Specify Multiple Objects

Some of the methods that operate on objects in collections allow you to specify an array when you want to operate on a subset of objects in a collection. The following example calls the Worksheets method and the Delete method three times each.

Worksheets("sheet1").Delete
Worksheets("sheet2").Delete
Worksheets("sheet4").Delete

You can use an array to reduce this to one Worksheets method call and one Delete method call.

Worksheets(Array("sheet1", "sheet2", "sheet4")).Delete


Using Collection Index Numbers

Most object accessor methods allow you to specify an individual object in a collection either by name or by number. Using the object's index number is usually faster. If you use the object's name, Visual Basic must resolve the name to the index value; if you use the index value, you avoid this extra step.

There are, however, some significant advantages to specifying an object in a collection by name. One advantage is that using an object's name makes your code easier to read and debug. In addition, specifying an object by name is safer than specifying it by index number, because the index value for an object can change while your code is running. For example, a menu's index number represents the menu's position on the menu bar; therefore, the index number can change if menus are added to or deleted from the menu bar. This is one instance where faster isn't necessarily better. You should use this technique only when you're sure that the index value cannot change.


Minimizing Object Activation and Selection

Most of the time, your code can operate on objects without activating them. If you learned Visual Basic programming by using the macro recorder, you're probably accustomed to activating or selecting an object before you do anything to that object. The macro recorder does this because it must follow your keystrokes as you select and activate sheets and cells. However, you can usually write much simpler and faster Visual Basic code that produces the same results without activating or selecting each object before working with it. For example, filling cells C1:C20 on Sheet5 with random numbers (using the AutoFill method) produces the macro recorder output shown in the following example.

Sheets("Sheet5").Select
Range("C1").Select
ActiveCell.FormulaR1C1 = "=RAND()"
Selection.AutoFill Destination:=Range("C1:C20"), Type:=xlFillDefault
Range("C1:C20").Select

All of the Select method calls are unnecessary. You can use the With statement to write code that operates directly on the worksheet and range, as shown in the following example.

With Sheets("Sheet5")
    .Range("C1").FormulaR1C1 = "=RAND()"
    .Range("C1").AutoFill Destination:=.Range("C1:C20"), _
        Type:=xlFillDefault
End With

Keep in mind that the macro recorder records exactly what you do — it cannot optimize anything on its own. The recorded macro uses the AutoFill method because that's how the user entered the random numbers. This isn't the most efficient way to fill a range with random numbers. You can do the same thing with a single line, as shown in the following example.

Sheets("Sheet5").Range("C1:C20").Formula = "=RAND()"

When you optimize recorded code, think about what you're trying to do with the macro. Some of the operations you can perform in the user interface (such as dragging a formula from a single cell into a range) are recorded as methods (such as AutoFill) that can be eliminated in the optimized code because there is a faster way to perform the same operation in Visual Basic.


Removing Unnecessary Recorded Expressions

Another reason the macro recorder produces inefficient code is that it cannot tell which options you've changed in a dialog box. The recorder therefore explicitly sets all available options when you close the dialog box. For example, selecting cells B2:B14 and then changing the font style to bold using the Format Cells dialog box produces the recorded macro shown in the following example.

Range("B2:B14").Select
With Selection.Font
    .Name = "Arial"
    .FontStyle = "Bold"
    .Size = 10
    .Strikethrough = False
    .Superscript = False
    .Subscript = False
    .OutlineFont = False
    .Shadow = False
    .Underline = xlNone
    .ColorIndex = xlAutomatic
End With

Setting the cell format to bold can be done with a single line of code without selecting the range, as shown in the following example.

Range("B2:B14").FontStyle = "Bold"

Again, if you think about what you're trying to do with the macro and you look through the lists of properties and methods that apply to the Font object, you'll see that you could also write this macro using the Bold property, as shown in the following example.

Range("B2:B14").Font.Bold = True

You can also experiment with the macro recorder by recording the same operation done different ways in the user interface. For example, if you format a range using the Bold button on the Standard toolbar, the macro recorder uses the Bold property.


Minimizing the Use of Variant Variables

Although you may find it convenient to use Variant variables in your code, Visual Basic requires more time to process a value stored in a Variant variable than it needs to process a value stored in a variable declared with an explicit data type. Your code can perform mathematical computations that don't involve fractional values faster if you use Integer or Long variables rather than Variant variables. Integer or Long variables are also the best choice for the index variable in For...Next loops. The speed you gain using explicit variable types can come at the expense of flexibility. For example, when using explicit data types, you may encounter cases of overflow that Variant variables handle automatically.

For more information about data types, see Chapter 2, "Variables, Constants, and Data Types."


Using Specific Object Types

References to objects and their methods and properties are resolved either when your macro is compiled or when it runs. References that are resolved when the macro is compiled are faster than references that must be resolved while the macro is running.

If you declare variables and arguments as specific object types (such as TextBox or Worksheet), Visual Basic can resolve references to the properties and methods of those objects when your macro is compiled. For a list of specific object types, see the Object Browser.

If you declare variables and arguments with the generic Object data type, Visual Basic may have to resolve references to their properties and methods when it encounters them at run time, resulting in a significantly slower process.

For information about object types, see Chapter 4, "Objects and Collections." For more information about declaring object variables, see Chapter 2, "Variables, Constants, and Data Types."


Using Constants

Using constants in an application makes the application run faster. Constants are evaluated once and are stored when your code is compiled. Variables can change, though, so Visual Basic must get the current variable value each time the macro runs. Constants also make your macros more readable and easier to maintain. If there are strings or numbers in a macro that don't change, declare them as constants. For more information about creating constants, see "Constants" in Chapter 2.


Using Worksheet Functions

A Microsoft Excel worksheet function that operates on a range of cells is usually faster than a Visual Basic macro that accomplishes the same task. For example, the SUM worksheet function is much faster than Visual Basic code that iterates a range and adds the values in the range's cells. For example, the following code runs relatively slowly.

For Each c In Worksheets(1).Range("A1:A200")
    totVal = totVal + c.Value
Next

The following code runs faster than the preceding example.

totVal = Application.Sum(Worksheets(1).Range("a1:a200"))

Aggregating worksheet functions (such as PRODUCT, COUNT, COUNTA, and COUNTIF) are good candidates for replacing slower Visual Basic code, as are worksheet functions (such as MATCH and LOOKUP) that can take a range as an argument. For more information, see "Worksheet Functions" in Help.


Using Special-Purpose Visual Basic Methods

There are also several special-purpose Visual Basic methods that offer a concise way to perform a specific operation on a range of cells. Like worksheet functions, these specialized methods are faster than the general-purpose Visual Basic code that accomplishes the same task.

For example, the following code changes the value in each cell in a range in a relatively slow way.

For Each c In Worksheets(1).Range("a1:a200").Cells
    If c.Value = 4 Then c.Value = 4.5
Next

The code in the following example, which uses the Replace method, performs the same operation much faster.

Worksheets(1).Range("a1:a200").Replace "4", "4.5"

The following example shows a relatively slow way to add a blue oval to each cell in the range A1:A500 that contains the value 4.

For Each c In Worksheets(1).Range("a1:a500").Cells
    If c.Value = 4 Then
        With Worksheets(1).Ovals.Add(c.Left, c.Top, c.Width, c.Height)
            .Interior.Pattern = xlNone
            .Border.ColorIndex = 5
        End With
    End If
Next

The code in the following example, which uses the Find and FindNext methods, performs the same task much faster.

With Worksheets(1).Range("a1:a500")
    Set c = .Find(4)
    If Not c Is Nothing Then
        firstAddress = c.Address
        Do
            With Worksheets(1).Ovals.Add(c.Left, c.Top, _
                    c.Width, c.Height)
                .Interior.Pattern = xlNone
                .Border.ColorIndex = 5
            End With
            Set c = .FindNext(c)
        Loop While Not c Is Nothing And c.Address <> firstAddress
    End If
End With

For more information about special-purpose Visual Basic methods, see the topic in Help that covers object you're working with, and examine the list of that object's methods. You can also examine the list of all Visual Basic methods on the Contents tab of Help.


Turning Off Screen Updating

A macro that makes changes to the appearance of a worksheet or chart — such as a macro that changes the color of every other cell in a large range or that creates a large number of graphic objects — will run faster when screen updating is turned off. You won't be able to watch the macro run (the changes will appear all at once when you turn screen updating back on), but it will run much faster. You may want to leave screen updating turned on while you write and debug the macro, and then turn it off.

To turn off screen updating, set the ScreenUpdating property to False, as shown in the following example.

Application.ScreenUpdating = False

Microsoft Excel automatically sets the ScreenUpdating property back to True when your macro ends.

Tip

You can sometimes achieve the same effect by not activating the object you're changing. For example, if you create graphic objects on a sheet without first activating the sheet, you don't need to turn screen updating off because the changes won't be visible.


Chapter 6 Debugging

Visual Basic provides debugging tools to help you analyze how your macros operate. These tools are particularly useful in locating the sources of errors (bugs). You can also use them to experiment with changes to your macros or to learn how macros created by others work.

This chapter shows you how to use the debugging tools included in Visual Basic.

Contents
  • Avoiding Bugs
  • Using Debugging Tools and Break Mode
  • Entering Break Mode at a Problem Statement
  • Stepping Through Code
  • Monitoring Data with Watch Expressions
  • Using the Calls Dialog Box to Trace Nested Procedures
  • Inspecting Code and Data in the Immediate Pane


Avoiding Bugs

The first step in avoiding or fixing bugs is understanding the three kinds of errors you can encounter:

  • Language errors These errors, which are also called syntax errors, are the result of an incorrectly constructed statement. You may have misspelled a reserved word, omitted some necessary punctuation (especially parentheses around arguments to methods), or forgotten to balance statement blocks, such as If and End If or For and Next. Visual Basic detects these errors either when you type the statement or during compilation, before the code executes.
  • Run-time errors These errors occur, and are detected by Visual Basic, when a statement attempts an impossible operation while the code is executing. An example of an impossible operation is division by 0 (zero). Suppose you have the following statement:

    Speed = Miles / Hours

    If Hours = 0 (zero), division is an invalid operation even though the statement itself is syntactically correct. The error is a run-time error because the code must execute before Visual Basic can detect the error. Not all run-time errors are easily anticipated or fixed. For example, a "Disk full" error that occurs when you use the Save method could be very difficult to fix.

  • Program logic errors Code that contains a program logic error can be both syntactically valid and capable of performing operations that are entirely valid, but still produce incorrect results. Visual Basic cannot detect program logic errors; you must test the code and analyze the results to verify that the code is performing correctly.

Debugging tools are designed to help you analyze run-time errors and Visual Basic code in general, but they're particularly helpful in analyzing program logic errors. These errors can be far more elusive than language errors or run-time errors. For example, an incorrect result may inexplicably be produced at the end of a long series of calculations. When you're debugging, your task is to determine where something went wrong. Perhaps you chose the wrong operator, used the wrong function somewhere, or forgot to initialize a variable.

There are no magic tricks to debugging, and there is no fixed sequence of steps that works every time. Essentially, debugging involves understanding what's going on when your code executes. The better you understand how your code works, the faster you can find and fix bugs. Debugging is easier if you:

  • Design your modules carefully by breaking up your code into Sub and Function procedures, with each procedure having a specific, well-defined purpose.
  • Include numerous comments. As you go back and analyze your code, you'll understand it much better if you've written comments that describe the purpose of each procedure.
  • Use the Option Explicit statement in the declarations section of each of your modules. One of the most common sources of errors is misspelling a variable name. If you have an Option Explicit statement in each module, Visual Basic generates an error message when it discovers a variable that hasn't been explicitly declared. This helps you quickly find misspelled variable names.
  • Examine your code to try to find statements that may be causing the problem. Set breakpoints at these statements, and then restart the code. Breakpoints are described in "Entering Break Mode at a Problem Statement" later in this chapter.
  • Use the Immediate pane of the Debug window (described later in this chapter) to examine variables and expressions when a breakpoint occurs.


Using Debugging Tools and Break Mode

You work with modules when you write a macro (design time) and when you run it (run time). This chapter introduces a third state for modules — when execution is suspended. This is called break mode. In this state, the code is running but is suspended between executing statements. In break mode, you can use the debugging tools to examine your code.

Four buttons on the Visual Basic toolbar provide shortcuts to commands you use when debugging your code. The following illustration shows this part of the toolbar.

The following table briefly describes the function of each button. The following sections in this chapter explain how each of these buttons can help you debug or analyze code more efficiently.

Debugging button | Function
Toggle Breakpoint | Creates or removes a breakpoint. A breakpoint is a location in the code where Visual Basic halts execution.
Instant Watch | Displays the current value of an expression while the code is in break mode.
Step Into | Runs only the next executable line of code. If the code calls another procedure, your view into the code shifts to the called procedure until it ends.
Step Over | Runs the next executable line of code. If the code calls another procedure, runs the entire procedure without shifting your view of the code to the called procedure.


Using the Debug Window

Sometimes you can find the cause of a problem by executing portions of code. More often, however, you have to analyze what's happening to the data as well. For example, you might isolate a problem in a variable or property with an incorrect value. Then you must determine how and why that variable or property was assigned an incorrect value.

In the Debug window, you can monitor the values of expressions and variables while stepping through the statements in your code. You can also use the Debug window to change the value of variables and properties in break mode to see how different values affect your code.

You display the Debug window by doing one of the following:

  • Entering break mode. The Debug window automatically appears when Visual Basic enters break mode.
  • Clicking Debug Window on the View menu.

The Debug window has two halves: The upper half is either the Watch pane or the Immediate pane; the lower half is the Code pane. In the Code pane, the current execution point in the code has a rectangular outline around it. You can scroll through the Code pane to look at other parts of the code.

The Watch pane displays the current watch expressions — expressions whose values you decide to monitor as the code runs. The Immediate pane displays information that results from debugging statements in your code or information you request by typing commands directly in the pane. The first time you display the Debug window, the Immediate pane is on top; thereafter, the last pane you chose is on top.

In the Watch pane, the Context column indicates the procedure, module, and workbook in which each watch expression is evaluated. The Watch pane can display a value for a watch expression only if the current statement is in the specified context; otherwise, the Value column displays a message indicating that the statement is out of context. For example, if you set a watch expression on a statement in a procedure, the statement is out of context until you run the procedure. For more information about using watch expressions, see "Monitoring Data with Watch Expressions" later in this chapter.


Entering Break Mode at a Problem Statement

To use debugging tools, you must be in break mode. If you suspect that the problem you're debugging occurs at a certain place in the code, you'll probably want to enter break mode at that location. This is why Visual Basic enables you to use breakpoints and the Stop statement. A breakpoint is a statement at which Visual Basic automatically enters break mode.

Visual Basic enters break mode at a line if one or more of the following conditions exist:

  • The line is a breakpoint.
  • There is a Stop statement on that line.
  • A statement on the line generates a run-time error. (This is true only if there is no error trapping in effect.)
  • You've set a watch expression of the type Break When Value Is True, and a statement on the line causes the value of the watch expression to change and evaluate to True.
  • You've set a watch expression of the type Break When Value Changes, and a statement on the line causes the value of the watch expression to change.

You can also enter break mode by pressing ESC or CTRL+BREAK while code is running.


Using a Breakpoint

When Visual Basic encounters a breakpoint while executing a procedure, it enters break mode just before executing the breakpoint line. You can set or remove a breakpoint when you're writing code in a module or whenever you're in break mode. When you set a breakpoint, Visual Basic highlights the breakpoint line with a dark red background. Visual Basic also displays a rectangular outline around the statement at which the procedure is suspended. This outline indicates the current statement, or the next statement to be executed.

To set a breakpoint

1. In the module, move the insertion point to a line of code that isn't already a breakpoint.

Toggle Breakpoint
button

2. On the Run menu, click Toggle Breakpoint, or click the Toggle Breakpoint button on the Visual Basic toolbar.

To clear a breakpoint

1. In the module, move the insertion point to the line of code that's the breakpoint you want to clear.

2. On the Run menu, click Toggle Breakpoint, or click the Toggle Breakpoint button on the Visual Basic toolbar.

After a breakpoint occurs, you can examine what's happened up to that point by inspecting code and data in the Immediate pane of the Debug window and by using the Calls dialog box. For more information about the Calls dialog box, see "Using the Calls Dialog Box to Trace Nested Procedures" later in this chapter.

If the problem you're trying to solve has already occurred, you know that a previously executed line of code is causing the problem. If not, a line of code that has not executed yet is causing the problem. If the breakpoint line is the cause, the problem won't occur until you execute at least one more statement. After you enter break mode, you can step through your code line by line to find the problem, as discussed later in this chapter.

Important

The problem may be something other than a line of code. A statement can be the indirect cause of the problem if it assigns an incorrect value to a variable. You can examine the values of variables while you're in break mode. For more information, see "Inspecting Code and Data in the Immediate Pane" later in this chapter.


Using a Stop Statement

As an alternative to setting a breakpoint, you can put a Stop statement in a procedure. Visual Basic enters break mode whenever it encounters a Stop statement. A Stop statement is very similar to a breakpoint, but it isn't set or cleared the same way a breakpoint would be.

Note

There is one important difference between a Stop statement and a breakpoint. If you close the workbook or quit Microsoft Excel, all breakpoints are cleared. Stop statements are more permanent; they stay in the code until you remove them.


Fixing a Run-Time Error

Some run-time errors result from simple oversights while you're writing the code; these errors are easily fixed. Suppose, for example, that you try to customize the title bar of the main application window by setting the Name property, as in the following code.

Application.Name = "My Custom Application"

When you run the code, a run-time error occurs. In this case, the solution is to fix the problem statement so that it uses the correct property, the Caption property, as in the following example.

Application.Caption = "My Custom Application"

You can use error handling to correct run-time errors that result from conditions other than simple coding errors. Error handling is discussed in the next chapter, "Handling Run-Time Errors."


Stepping Through Code

If you know exactly which statement caused an error, the use of a single breakpoint may be sufficient. More often, however, you can only guess the general vicinity of the statement that caused the error. Setting a breakpoint helps you get to that general area; when you get there, you can step through your code and execute it line by line to see the effect of each statement.

You can also step through each line of code in a called procedure (a procedure the current procedure calls) or step over the called procedure code.


Stepping Through Statements

Stepping is the process of executing one statement at a time. Stepping through statements is sometimes referred to as tracing. After executing each statement, you can see how the statement affected the variables and objects in your macro.

To step through code one statement at a time

Step Into button

  • On the Run menu, click Step Into, or click the Step Into button on the Visual Basic toolbar.

    • When the Step Into command is carried out, Visual Basic executes the current statement and then automatically advances to the next statement and enters break mode.

    A line of code can contain two or more statements separated by a colon (:). You can step from one statement to the next even if they're in the same line. However, the breakpoint is always the first statement in the line.


Stepping Over Procedures

Step Over button

If you don't want to step through the lines of code in a called procedure, you can step over the entire procedure by clicking Step Over on the Run menu (or clicking the Step Over button on the Visual Basic toolbar). The Step Over command is identical to the Step Into command except when the current statement contains a call to a procedure. The Step Into command steps into the procedure that was called and lets you step through it line by line, whereas the Step Over command executes the called procedure as a unit and then steps into the next statement in the calling procedure. In the following example, the current statement calls the procedure GetQueryCriteria.

GetQueryCriteria Criteria

If you choose the Step Into command, the Debug window displays the GetQueryCriteria procedure, and the first statement in that procedure is the current statement. The Step Into command is the best choice if you want to analyze the code within GetQueryCriteria.

If you choose the Step Over command, the module continues to display the calling procedure while Visual Basic executes the GetQueryCriteria procedure. Execution then advances to the statement immediately after the call to GetQueryCriteria. Step Over is a better choice than Step Into if you want to stay at the same level of code and you don't need to analyze how GetQueryCriteria works.

You can freely alternate between the Step Into and Step Over commands. The command you choose depends on which portions of code you want to analyze at any given time.


Monitoring Data with Watch Expressions

As you debug your code, you might find that a problem occurs only when a certain variable or property assumes a particular value or range of values. Or you might learn that a calculation isn't producing the desired result. Many debugging problems aren't immediately traceable to a single statement, so you might need to observe the behavior of a variable or expression throughout a procedure.

You can monitor the value of a particular variable or expression in a watch expression. Visual Basic monitors watch expressions for you. In break mode, watch expressions appear in the Watch pane of the Debug window, where you can observe their values.

You can also direct a watch expression to enter break mode whenever the watched expression's value changes or becomes True. For example, instead of using Step Into to move through hundreds of loops, you can use a watch expression to put the code in break mode when a loop counter reaches a specific value. Or you can enter break mode each time a certain variable changes value.


Adding a Watch Expression

You can add a watch expression before running a procedure or after entering break mode. You use the Add Watch dialog box to add watch expressions.

In the Expression box, enter the expression you want the watch expression to evaluate. The expression can be a variable, a property, a function call, or any other valid expression.

Under Context, click items in the list boxes to set the scope of the variables you want watched in the expression. Use these options if you have variables of the same name with different scope. You can also use these options to restrict the scope of watch variables. Visual Basic can evaluate a variable in a narrow context more quickly.

Under Watch Type, click an option button to set how you want Visual Basic to respond to the watch expression. Visual Basic can watch the expression and display its value in the Watch pane when the code enters break mode. Or you can have the code enter break mode automatically when the expression evaluates to True or when the value of the expression changes.

To add a watch expression

1. On the Tools menu, click Add Watch.

2. In the Expression box, type the expression you want to evaluate.

3. To set the scope of the expression to be watched, click the procedure or module name in the appropriate box under Context.

4. To determine how you want Visual Basic to respond to the watch expression, click an option button under Watch Type.


Editing or Deleting a Watch Expression

You can edit or delete any watch expression you select in the Watch pane of the Debug window. When you click Edit Watch on the Tools menu, the Edit Watch dialog box appears. This dialog box looks just like the Add Watch dialog box with a Delete button added.

To edit a watch expression

1. In the Watch pane of the Debug window, click the watch expression you want to edit.

2. On the Tools menu, click Edit Watch.

3. In the Edit Watch dialog box, make any changes you want to the expression, the scope for evaluating variables, or the watch type.

Tip

You can also edit any watch expression displayed in the Debug window by double-clicking the watch expression in the Watch pane. Visual Basic displays the selected watch expression in the Edit Watch dialog box.

To delete a watch expression

1. In the Watch pane of the Debug window, click the watch expression you want to delete.

2. On the Tools menu, click Edit Watch.

3. In the Edit Watch dialog box, click Delete.

Tip

If your keyboard has a DEL key, you can delete a watch expression by selecting it in the Watch pane of the Debug window and then pressing del.

Identifying Watch Types

To the left of each watch expression in the Watch pane of the Debug window is an icon that identifies the watch type of that expression. The following illustration shows the icons for the three watch types.


Using Instant Watch

While in break mode, you can check the value of an expression for which you haven't defined a watch expression. You can check such expressions in the Instant Watch dialog box.

The Instant Watch dialog box displays the value of an expression you select from either of the following:

  • A Visual Basic module
  • The Code pane of the Debug window

To continue watching this expression, click Add. If Visual Basic cannot evaluate the current expression, an error message appears.

To add a watch expression from the Instant Watch dialog box

1. Select the expression you want to watch.

Instant Watch button

2. On the Tools menu, click Instant Watch.

You can also click the Instant Watch button on the Visual Basic toolbar.

3. Click Add.


Using the Calls Dialog Box to Trace Nested Procedures

The Calls dialog box displays a list of all active procedure calls. Active procedure calls are the procedures that have started but haven't finished executing. For example, you can use the Calls dialog box to trace the procedure calls in the following code.

Sub Demo1()
    Call Demo2
End Sub

Sub Demo2()
    Call Demo3
End Sub

Sub Demo3()
    MsgBox "Demo3 is running"
    Stop
End Sub

The Calls dialog box lists three active procedure calls when execution is suspended by the Stop statement in the Demo3 procedure.

To display the Calls dialog box

  • In the Debug window, click the button to the right of the Procedure box (the box containing the name of the current procedure).

The Calls dialog box is especially helpful if you want to trace nested procedures. For example, a procedure can call a second procedure, which can call a third procedure — all before the procedure that started this chain has finished executing. In the preceding illustration, the Demo1 procedure called the Demo2 procedure, which called the Demo3 procedure.

The Calls dialog box lists all the active procedure calls in a series of nested procedure calls. It places the most recently started procedure call at the top of the list; earlier procedure calls appear in order below that. The information given for each procedure includes the name of the workbook and module that contains the procedure, followed by the name of the procedure.

You can click Show to display the statement that calls the next procedure listed in the Calls dialog box.

To display the statement that calls the next procedure in the Calls dialog box

1. In the Calls dialog box, click the procedure call you want to display.

2. Click Show.

Visual Basic displays the procedure in the module. The insertion point indicates the statement that calls the next procedure in the Calls dialog box (the procedure above the displayed procedure).

If you click the current (top) procedure in the Calls dialog box and then click Show, Visual Basic displays the current statement (the statement at which execution is suspended).


Inspecting Code and Data in the Immediate Pane

When you're creating and testing Visual Basic code, you may often want to check the results of an expression, the value of a property, and so on. You can do this in the Immediate pane of the Debug window. The Immediate pane is a kind of "scratch pad" window in which expressions are evaluated immediately.

To view the Immediate pane

1. Enter break mode, or click Debug Window on the View menu. The Debug window appears.

2. If the Immediate pane isn't on top, click the Immediate tab.

There are several uses for the Immediate pane: checking the values of properties; evaluating expressions; printing the results of expressions; and printing the values of properties. You can also test your Sub and Function procedures by calling them from the Immediate pane. And when you're in break mode, you can use the Immediate pane to examine the values of variables and arguments in a procedure.


Testing Procedures Using the Immediate Pane

In the Immediate pane, you can evaluate any valid Visual Basic executable expression or statement, including calls to Sub and Function procedures. You can evaluate an expression or Function procedure by printing the value it returns in the Immediate pane. You can also test the possible effect of a Sub procedure with any given set of arguments by entering it as a statement in the Immediate pane just as you would in a module.

From a module, you can print a value to the Immediate pane by using the Print method of the Debug object (the Debug object refers to the Immediate pane). The following example prints the name of the active workbook in the Immediate pane.

Sub DebugExample()
    Debug.Print ActiveWorkbook.Name
End Sub

Note

The Immediate pane doesn't open automatically when Visual Basic encounters Debug.Print. If you don't have the Immediate pane open, you won't see the values displayed by Debug.Print.

From the Immediate pane, you can use the Print method without the Debug object qualifier. You can also use a question mark (?) as shorthand for the Print method. When you type the following code in the Immediate pane and then press ENTER, Visual Basic displays the same result as it does when you run the preceding code example from a module.

? ActiveWorkbook.Name

You can test a Sub procedure by typing it and its arguments in the Immediate pane, as in the following example.

SizeIt 5000, 3000

Note

You cannot use the Print method or a question mark in the preceding example because a Sub procedure doesn't return a value to display.

You can execute any built-in function or statement in the Immediate pane. However, a control structure is valid only if it can be completely expressed on one line. For example, the following For Each...Next loop can be executed in the Immediate pane.

For Each s In Sheets : Print s.Name : Next s


Printing to the Immediate Pane from Code

While you're testing your code, you may want to display the results of expressions in your code as it's running. You can use Debug.Print to display the results in the Immediate pane. For example, you could add Debug.Print to the DueDate function, as shown in the following code.

Function DueDate(ByVal AnyDate As Variant) As Variant
' This function calculates and returns the date of the first day
' of the month that follows the supplied date.

    Debug.Print "Year "; Year(AnyDate); "Month "; Month(AnyDate)
    DueDate = DateSerial(Year(AnyDate), Month(AnyDate) + 1, 1)
End Function

Now whenever this function is called, it will display the year and month of the passed-in value in the Immediate pane. For example, you can call the DueDate function from the Immediate pane, passing in the current date using the Now statement. The value of the year and month, and the function's return value, will be displayed as shown in the following illustration.

Debug.Print always sends its output to the Immediate pane. You can use the function from the preceding example in any expression in Microsoft Excel (including formulas on a worksheet), and it will always display the value of the year and month in the Immediate pane.

The advantage of printing to the Immediate pane from code is that the feedback is displayed in a separate area (the Immediate pane), so it doesn't interfere with output you want users to see.

When you're sure that your code is working correctly, you can remove the Debug.Print statements. Printing to the Immediate pane slows your code slightly, so you don't want to leave Debug.Print in your code when you don't need to use it.

Finally, you can print debugging messages to the status bar using the StatusBar property. The advantage of the status bar is that you don't need to display the Debug window to read the debugging messages. The text you display in the status bar remains there until you set the StatusBar property to another string, or until you set the StatusBar property to False, which returns control of the status bar to Microsoft Excel. If you don't set the StatusBar property to False, the text displayed there remains after the macro ends.


Using the Immediate Pane in Break Mode

In break mode, you can use the Immediate pane to examine the values of expressions and variables in the suspended procedure. As shown in the following illustration, if you place a breakpoint in the DueDate function and then call the function, the Debug window is displayed when the breakpoint occurs, and you can use the Immediate pane to examine the value of the function's argument.

Notice that you can display a variable's value only if the variable has the appropriate scope relative to the current statement. Whenever Visual Basic enters break mode, the Debug window identifies:

  • The current workbook and module (indicated in the title bar of the Debug window).
  • The procedure that's currently executing (displayed in the window).
  • The current statement (identified by a rectangular outline in the Code pane).

Only variables defined in the current module and the procedure that's currently executing can be displayed in the Immediate pane. For example, suppose that the Immediate pane indicates that Module1 is the current module. In this case, you can display the value of any of the module variables from Module1. You can also display local variables in the procedure that's currently executing. But you cannot use or display the variables in other modules or procedures.

You can always display the value of public variables.

Scope applies to procedure calls just as it does to variables. In the Immediate pane, you can call any procedure in the current module, and you can call any public procedure from any other module in the workbook. However, you cannot call a private procedure from another module.


Assigning Values to Properties and Variables

In addition to using the Immediate pane to examine the values of variables and expressions, you can use it to assign new values to properties and variables. This is useful when you're debugging code; as you develop hypotheses about the cause of an error, you may want to test the effects of particular values.


Tips on Using the Immediate Pane

You can use the following shortcuts in the Immediate pane:

  • After you've executed a statement in the Immediate pane, you can execute it repeatedly by placing the insertion point anywhere in the statement and then pressing ENTER.
  • Before pressing ENTER, you can edit the statement the insertion point is located in.
  • You can use either the mouse or the arrow keys to move the insertion point in the Immediate pane. Press ENTER only if the insertion point is in a statement you want to execute.
  • You can use the PAGE UP and PAGE DOWN keys to move through your code one page at a time. Pressing CTRL+PAGE DOWN always moves the insertion point to the end of the Immediate pane.
  • You can use the Home key to move the insertion point to the beginning of the current line and the end key to move the insertion point to the end of the current line.


Chapter 7 Handling Run-Time Errors

This chapter explains how to handle run-time errors — errors that occur while your code is running. A run-time error occurs when your code attempts to perform an invalid operation, such as opening a file that was deleted, using a property that doesn't exist, or setting the value of a read-only property. Although you can prevent many run-time errors by being careful and thorough when writing and checking your code, there will always be a potential for unforeseeable errors cropping up. To prevent one of these unexpected errors from stopping your code prematurely and leaving your data in an unpredictable state, you can add error-handling code to your procedures.

Contents
  • How to Handle Errors
  • Designing an Error Handler
  • Defining Your Own Error Values
  • Using Worksheet Error Values
  • Advanced Error-Handling Techniques


How to Handle Errors

If you haven't set up a mechanism to handle errors, run-time errors in your code can lead to a variety of unfortunate outcomes. Some errors may abruptly halt the execution of your code, leaving the user no way to recover data, correct the source of the error, or resume execution. Other errors might allow execution to continue but will cause your code to act unpredictably.

For example, the following FileExists function, which contains no error-handling code, returns True if the specified file exists or False if it doesn't exist.

Function FileExists(filename)
    FileExists = (Dir(filename) <> "")
End Function

The Dir function returns the first file that matches the specified filename; it returns a zero-length string if no matching file is found. Therefore, the code Dir(filename) <> "" returns True if Dir returns a filename or False if Dir returns a zero-length string.

Although this code appears to cover either of the possible outcomes of the Dir call, if the drive letter specified in the argument doesn't refer to a valid drive, error 68 ("Device unavailable") occurs. Also, if the specified drive is a floppy disk drive, the code will work correctly only if there is a disk in the drive and the drive door is closed. If not, Visual Basic generates error 71 ("Disk not ready") and halts execution of your code.

To avoid this situation, you can use the error-handling features in Visual Basic to intercept errors and take corrective action. (Intercepting an error is also known as trapping it.) For example, the disk-drive errors described in the preceding paragraph could be handled by the following code.

Function FileExists (filename)
On Error GoTo CheckError        ' Turn on error trapping so error handler
                            ' responds if any error is detected.
    FileExists = (Dir(filename) <> "")
    Exit Function            ' Avoid executing error handler
                            ' if no error occurs.

CheckError:                    ' Branch here if error occurs.
    ' Define constants to represent Visual Basic error code.
    Const ERR_DISKNOTREADY = 71, ERR_DEVICEUNAVAILABLE = 68
    FileExists = False
    If Err = ERR_DISKNOTREADY Then
        Msg = "Put a floppy disk in the drive and close the drive door."
        ' Display message box with an exclamation mark icon and with OK
        ' and Cancel buttons.
        If MsgBox(Msg, vbExclamation + vbOKCancel) = vbOK Then
            Resume
        Else
            Resume Next
        End If
    ElseIf Err = ERR_DEVICEUNAVAILABLE Then
        Msg = "This drive or path doesn't exist: " & filename
        MsgBox Msg, vbExclamation
        Resume Next
    Else
        Msg = "Unexpected error #" & Str(Err) & ": " & Error(Err)
        ' Display message box with Stop sign icon and OK button.
        MsgBox Msg, vbCritical
        End
    End If
End Function

In the preceding code, the Err function returns the error number associated with the run-time error that occurred. When Visual Basic generates error 71, the FileExists function displays a message that tells the user to insert a floppy disk in the floppy disk drive and allows the user to click either OK or Cancel to dismiss the message box.

If the user clicks OK, the Resume statement returns program control to the statement at which the error occurred — in this case, the line containing the Dir function — and attempts to reexecute that statement. This statement succeeds if the user has corrected the problem; otherwise, the program returns to the error-handling code.

If the user clicks Cancel, the Resume Next statement returns program control to the statement following the one at which the error occurred — in this case, the Exit Function statement.

If error 68 occurs, Visual Basic displays a message describing the problem. The Resume Next statement then causes the function to continue execution at the statement following the one at which the error occurred.

If an unanticipated error occurs, Visual Basic displays an alternative message and halts the code at the End statement.

Note

In the preceding example, the error numbers that the Err function returns are compared with constants that you've defined. For a list of the error numbers, see "Trappable errors" in Help.

The constants that begin with the letters "vb" are built-in constants that pertain to dialog boxes displayed by the MsgBox function. For more information about the MsgBox function, see "MsgBox" in Help.


Designing an Error Handler

The example in the preceding section contains an error handler called CheckError. The code in the example includes three steps you can apply to most error handlers:

  • Setting an error trap
  • Writing an error handler
  • Exiting an error handler


Setting an Error Trap

Visual Basic enables an error trap whenever it encounters the On Error statement, which specifies an error handler (the routine within a procedure that handles the error). The error trap remains enabled while the procedure that contains it is active — that is, until an Exit Sub, Exit Function, End Sub, or End Function statement is run in that procedure.

Although only one error trap can be enabled at any one time in any given procedure, you can create several alternative error traps and enable different ones at different times. You can also disable an error trap by using a special form of the On Error statement — On Error GoTo 0. For more information about disabling error handling, see "Turning Off Error Handling" later in this chapter.


Writing an Error Handler

A common convention is to add the error handler code at the end of the procedure, before the End Function or End Sub statement. Add an Exit Sub or Exit Function statement immediately before the error handler line label, to prevent the error handler from running when no error has occurred.

To branch within the error handler, use the Err function, which returns the error number, in conjunction with either the Select Case statement or the If...Then...Else statement. The following section includes an example of this technique.


Exiting an Error Handler

The FileExists function presented earlier in this chapter uses the Resume statement within the error handler to rerun the statement that originally caused the error, and it uses the Resume Next statement to run the statement following the statement at which the error occurred.

You can use one of a number of statements to exit an error handler. The statement you use on any given occasion depends on the circumstances, as explained in the following table.

Statement | Description
Resume Next | Resumes execution at the statement immediately following the one that caused the error. Use this statement to skip over the statement that caused the error.
Resume | Resumes execution at the statement that caused the error. Use this statement to repeat an operation after you've corrected the error.
Resume line | Resumes execution at the label specified by line, where line is a nonzero line number or line label that's in the same procedure as the error handler. Because jumping to specific line numbers results in unstructured code, using this statement isn't recommended.
Error Err | Triggers the most recent run-time error again. When this statement is run within the error handler, Visual Basic searches the calls list for another error handler.

The preceding table assumes that the error occurred in the same procedure as the error handler. If this isn't the case, Visual Basic searches the procedures in the calls list for another error handler. For more information about this situation, see the following section, "Handling Unanticipated Errors."

The following illustration shows how the Resume and Resume Next statements differ.

Generally, you use Resume whenever the user must correct the situation that caused the error before program execution can continue. Use Resume Next whenever a correction by the user isn't required, and you want to continue program execution without trying again to run the statement that caused the error. With Resume Next, you can write an error handler that never reveals run-time errors to the user.

For example, the following function uses an error handler to perform "safe" division on its arguments without revealing errors that might occur. Null is returned if errors do occur.

Function Divide(numer, denom)
Const ERR_DIV0 = 11, ERR_OVERFLOW = 6, ERR_ILLFUNC = 5
On Error GoTo MathHandler
    Divide    = numer / denom
    Exit Function
MathHandler:
    If Err = ERR_DIV0 Or Err = ERR_OVERFLOW Or Err = ERR_ILLFUNC Then
        Divide = Null        ' If error was Division by zero, Overflow,
                            ' or Illegal function call, return Null.
    Else
        MsgBox "Unanticipated error " & Err & ": " & Error, _
          vbExclamation
        Divide = Null
    End If                    ' In all cases, Resume Next continues
    Resume Next                ' execution at the Exit Function statement.

End Function


Handling Unanticipated Errors

When an error occurs in a procedure that doesn't have an enabled error handler, or within an error handler that's currently running, Visual Basic searches the calls list for another enabled error handler.

For example, suppose the following sequence of calls occurs:

1. Procedure A calls Procedure B.

2. Procedure B calls Procedure C.

3. Procedure C calls Procedure D.

If an error occurs in Procedure D and this procedure doesn't have an enabled error handler, Visual Basic searches backward through the calls list — first Procedure C, then Procedure B, and then Procedure A — and executes the first enabled error handler it finds. If it doesn't encounter an enabled error handler anywhere in the calls list, it displays the appropriate run-time error message and halts your procedure.

Tip

The effect of the search backward through the calls list is hard to predict, because if a Resume or Resume Next statement is encountered in the error handler, execution continues in the procedure where the error handler is found, which isn't necessarily the procedure where the error occurred. To avoid this situation, write a fail-safe error handler that all your error handlers can call as a last resort for errors they cannot handle themselves. This fail-safe procedure can both save the user's data and close your application in an orderly way.


Turning Off Error Handling

If an error trap has been enabled in a procedure, it's automatically disabled when the procedure finishes running. However, you might want to turn off an error trap earlier. To turn off an enabled error trap, use the On Error GoTo 0 statement. You can use On Error GoTo 0 to turn off error handling anywhere in a procedure — even within an error handler.

For example, try single stepping through the following procedure.

Sub ErrDemoSub()
On Error GoTo SubHandler
' Error trapping is enabled.
' Errors need to be caught and corrected here.
    Kill "OLDFILE.XYZ"
On Error GoTo 0                ' Error trapping is turned off here.
    Kill "OLDFILE.XYZ"
On Error GoTo SubHandler        ' Error trapping is enabled again.
    Kill "OLDFILE.XYZ"
Exit Sub
SubHandler:                    ' Error handler goes here.
    MsgBox "Caught error."
    Resume Next
End Sub


Defining Your Own Error Values

The preceding section explains how you can use run-time error values to diagnose problems in your code and respond appropriately to the problems. There may be times, however, when you want to detect and respond to situations that don't cause Visual Basic to generate errors. To do this, you need to create your own user-defined error values for those situations.

This type of error value is commonly used in procedures that accept several arguments and then return a value. Suppose the return value is valid only if the arguments fall within certain ranges. Your procedure can test the arguments that the user provides; if they aren't in the acceptable range, you can have the procedure return an appropriate error value.

The following sections describe how to create a user-defined error value using the CVErr function and how to test for an error value using the IsError function.


Creating Error Values

You use the CVErr function to create error values. For example, he following code creates two error values.

NoRadius = CVErr(50000)

NotANumber = 50001
InvalidArgument = CVErr(NotANumber)

User-defined error values are always stored in a variable of the Error data type, which is a subtype of the Variant data type. For more information about the Error data type, see "Storing Values in Variant Variables" in Chapter 2.


Checking for Error Values

Each error value you create must be associated with a specific error. After you've done this you can use the IsError function to test whether a particular error has occurred. You can test for specific user-defined error values the same way you test for specific built-in errors, using the Select Case statement or the If...Then...Else statement.

The following example uses the CVErr function to return an error value. The AreaOfCircle procedure asks for a radius value. The CheckData function checks the Radius variable and, if it isn't an acceptable number, converts it into one of two possible error values. In the AreaOfCircle procedure, the IsError function returns True if its argument is an error value.

Public NoRadius, NotANumber

Sub AreaOfCircle()
    Const PI = 3.14
    NoRadius = CVErr(50000)
    NotANumber = CVErr(50001)
    Radius = CheckData(InputBox("Enter the radius"))
    If IsError(Radius) Then
        Select Case Radius
            Case NoRadius
                MsgBox "Error: No radius given."
            Case NotANumber
                MsgBox "Error: Radius isn't a number."
            Case Else
                MsgBox "Unknown error."
        End Select
    Else        ' there's no error
        MsgBox "The area of the circle is " & (PI * Radius ^ 2)
    End If
End Sub
Function CheckData(TheRadius)
    If Not IsNumeric(TheRadius) Then
        CheckData = NotANumber
    ElseIf TheRadius = 0 Then
        CheckData = NoRadius
    Else
        CheckData = TheRadius
    End If
End Function

It's important to remember that if Visual Basic attempts to compare an error value with a number or other value in an expression, a run-time error will occur.

If NoRadius = 50000 Then...    'Causes an error. Cannot compare error to a                             'number or other value.

The following code doesn't cause an error because you can compare an error value with another error value.

If NoRadius = CVErr(50000) Then...

For more information about IsError or CVErr, see the appropriate topic in Help.


Using Worksheet Error Values

Names and cell formulas in Microsoft Excel worksheets can contain one of seven error values: #DIV/0!, #N/A, #NAME?, #NULL!, #NUM!, #REF!, or #VALUE!. You can pass one of these error values from a worksheet to a procedure only if the passed argument is a Variant variable. To work with these error values, you can test the arguments using the IsError function and treat the error values as if they were user-defined error values (described in the preceding section).

You can also pass an error value from a user-defined function back to cells on a worksheet, as shown in the following example.

Function Commission(SharesSold, PricePerShare)
    If Not (IsNumeric(SharesSold) And IsNumeric(PricePerShare)) Then
        Commission = CVErr(xlErrNum)        ' xlErrNum corresponds to the                                             ' #NUM! error value.
        Exit Function
    Else
        TotalSalePrice = SharesSold * PricePerShare
        If TotalSalePrice <= 15000 Then
            Commission = 25 + 0.03 * SharesSold
        Else
            Commission = 25 + 0.03 * (0.9 * SharesSold)
        End If
    End If
End Function

You work with Microsoft Excel worksheet error values the same way you work with user-defined error values. However, as you can see in the following table, Visual Basic provides two ways to refer to worksheet error values: built-in constants that represent the error numbers, and literal error values (which must be enclosed in square brackets).

Error number (constant) | Literal error value | Converted error value
xlErrDiv0 | [#DIV/0!] | CVErr(xlErrDiv0)
xlErrNA | [#N/A] | CVErr(xlErrNA)
xlErrName | [#NAME?] | CVErr(xlErrName)
xlErrNull | [#NULL!] | CVErr(xlErrNull)
xlErrNum | [#NUM!] | CVErr(xlErrNum)
xlErrRef | [#REF!] | CVErr(xlErrRef)
xlErrValue | [#VALUE!] | CVErr(xlErrValue)

If you want to use the literal error value for #NUM! in the preceding example, just substitute [#NUM!] for CVErr(xlErrNum), as shown in the following code.

If Not (IsNumeric(SharesSold) And IsNumeric(PricePerShare)) Then
    Commission = [#NUM!]
    Exit Function
.
.
.


Advanced Error-Handling Techniques

This section describes several more error-handling techniques. It also explains how your code can control what happens when a user interrupts a procedure while it's running.


Simulating Run-Time Errors

Simulating run-time errors is useful when you're testing your applications or when you want to treat a particular condition as a run-time error. For example, you might write a module that calls routines in a dynamic-link library (DLL) and want the rest of your application to handle the DLL's return values as actual Visual Basic errors — that is, to generate run-time errors in Microsoft Excel.

You can simulate any Visual Basic run-time error by supplying the error code for that error in the Error statement, as in the following example.

Error 71        ' Simulate "Disk Not Ready" error.

You can also use the Error statement to generate your own, user-defined errors by supplying an error code that doesn't correspond to a Visual Basic run-time error. Of course, this is useful only if you also write code that handles the new errors you define. For a list of built-in errors, see "Trappable errors" in Help.

Note

As new errors are defined in future versions of Visual Basic, more error numbers will be assigned to built-in errors. If you want to generate and trap your own errors, begin your numbering scheme with 50,000 and work upward from there. This way, you'll avoid using the same number for your own error that a future version of Visual Basic might use for a built-in error.


Minimizing Code Size by Handling Errors in a Central Location

As you add error handlers to your applications, you'll soon discover that you're handling the same errors over and over again. You can reduce code size and save yourself time and effort by writing a few procedures that your error handlers can call to handle common error situations.

The following code is a function called FileErrors that can be called by an error handler. This function displays a message corresponding to the error that has occurred and, where possible, allows the user to choose a button to specify which action the function should take next. It then returns a code number to the procedure that called it (the calling procedure isn't shown in the example). The code number indicates which action — out of a set of actions — the program should take.

Public Const RESUME_STATEMENT = 0        'Resume
Public Const RESUME_NEXT = 1                'Resume Next
Public Const UNRECOVERABLE = 2            'Unrecoverable error
Public Const UNRECOGNIZED = 3            'Unrecognized error
Public Const Err_DeviceUnavailable = 68
Public Const Err_BadFilenameOrNumber = 52, Err_PathDoesNotExist = 76
Public Const ERR_BADFILEMODE = 54

Function FileErrors (errVal As Integer) As Integer
Dim MsgType As Integer, Msg As String, Response As Integer
    MsgType = vbExclamation
    Select Case errVal
        Case Err_DeviceUnavailable                      ' Error #68
            Msg = "That device appears unavailable."
            MsgType = MsgType + vbAbortRetryIgnore
        Case Err_BadFilenameOrNumber  ' Errors #52
            Msg = "That filename is not valid."
            MsgType = MsgType + vbOKCancel
        Case Err_PathDoesNotExist                      ' Error #76
            Msg = "That path doesn't exist."
            MsgType = MsgType + vbOKCancel
        Case Err_BadFileMode                              ' Error #54
            Msg = "Can't open your file for that type of access."
            MsgType = MsgType + vbOKCancel
        Case Else
            FileErrors = UNRECOGNIZED
            Exit Function
    End Select
    Response = MsgBox(Msg, MsgType, "Disk Error")
    Select Case response
        Case vbOK, vbRetry
            FileErrors = RESUME_STATEMENT
        Case vbIgnore
            FileErrors = RESUME_NEXT
        Case vbCancel, vbAbort
            FileErrors = UNRECOVERABLE
        Case Else
            FileErrors = UNRECOGNIZED
    End Select

End Function

What Happens to Errors That Your Error Handler Doesn't Handle?

The function in the preceding example handles a select group of file-related and disk-related errors. If an error you encounter doesn't belong to this set of errors, the function returns the value 3. The procedure that calls this function should then either handle the error itself, call another procedure to handle it, or just let the original run-time error occur again, as shown in the following example.

Function FileOperationsDemo(FileName As String)
'Demo of how you would call the FileErrors Function
On Error GoTo ConfirmFileError
.
.
.
'Code that attempts some file operation
.
.
.
ConfirmFileError:
Action = FileErrors(Err)            'Call the FileErrors function
    Select Case Action
        Case RESUME_STATEMENT    'User chose OK or Retry when FileErrors
                                'displayed its message, so try again.
            Resume
        Case RESUME_NEXT            'User chose Ignore when FileErrors
                                'displayed its message, so ignore error
                                'and continue.
            Resume Next
        Case UNRECOVERABLE         'User chose Cancel or Abort when
                                'FileErrors displayed its message,
                                'so abort procedure.
            Exit Function
        Case Else                'Cannot handle original run-time
                                'error, so repeat it and display
                                'the normal System error.
            Error Err
    End Select
End Function


Handling Errors with Inline Code

In previous sections of this chapter, you've used the On Error GoTo statement to jump to an error-handling subroutine and then resume running the rest of your code. You can also handle errors without branching to a subroutine.

If you anticipate that a particular statement might cause an error, include an On Error Resume Next statement before the potential error-causing statement to prevent the application from being interrupted. You can then test the value of the Err function and proceed accordingly.

The following procedure is a revision of the FileExists procedure shown earlier in this chapter. This revised version doesn't branch to a subroutine; instead, it handles errors in-line.

Function FileExists(filename)
Dim Msg

Const ERR_DISKNOTREADY = 71, ERR_DEVICEUNAVAILABLE = 68

' Resets the Err code to zero; handles errors inline
On Error Resume Next

CheckOnFile:
    FileExists = (Dir(filename) <> "")
    If Err = ERR_DISKNOTREADY Then
        Msg = "Put a floppy disk in the drive and close the drive door."
        If MsgBox (Msg, vbExclamation + vbOKCancel) = vbOK Then
            GoTo CheckOnFile
        End If
        FileExists = False
    ElseIf Err = ERR_DEVICEUNAVAILABLE Then
        Msg = "This drive or path doesn't exist: " & filename
        MsgBox Msg, vbExclamation
        FileExists = False
    ' If not successful, and if not one of the above errors, handle
    ElseIf Err <> 0 Then
        Msg = "Unexpected error #" & Str(Err) & ": " & Error(Err)
        MsgBox Msg, vbCritical
        FileExists = False
    End If

End Function


Handling User Interrupts

When a Visual Basic procedure is running, a user can interrupt it by pressing CTRL+BREAK or ESC. Although you may need to be able to interrupt procedures when you're debugging, you might want to prevent the user from interrupting procedures in the finished application. If you do allow user interrupts in a finished application, however, you can make sure that your procedures are notified of them so that the procedures can close files, disconnect from shared resources, or restore modified variables before returning control of the application to the user.

You can trap user interrupts in your procedures by setting the EnableCancelKey property to xlErrorHandler. With this property setting in effect, all interrupts generate run-time error 18, which you can trap using an On Error statement. You can handle this error to halt the procedure and exit the program. However, if you use the Resume statement to continue running the procedure after a run-time error has been trapped, the interrupt is ignored.

The following example illustrates a procedure that requires a long time to complete. If a user interrupts the procedure while it's running, an error is trapped — first to confirm that the procedure should be stopped, and then to exit the procedure in an orderly way. Note that you can use only one interrupt handler for each procedure, and that the same handler is used for all other run-time errors encountered in that procedure.

Sub ProcessData
    ' Set up user interrupt trapping as a run-time error
    On Error GoTo UserInterrupt
    Application.EnableCancelKey = xlErrorHandler
    'Start a long duration task
    OpenDataFile
    For x = 1 To 1000000
        ProcessRecord x
        WriteOutRecord x
    Next x
    CloseDataFile
    Exit Sub

UserInterrupt:
    If Err = 18 Then
        If MsgBox ("Stop processing records?" , vbYesNo) = vbNo Then
            ' Continue running at the point we were interrupted
            Resume
        Else
            ' Close open files before returning
            CloseDataFile
            Exit Sub
        End If
    Else
        ' Handle other errors that occur
        MsgBox Error(Err)
        Resume Next
    End If
End Sub

You can also ignore user interrupts completely by setting the EnableCancelKey property to xlIgnore. With this property setting in effect, Microsoft Excel ignores all attempts by the user to interrupt the procedure that's running.

Note

Use caution when disabling or ignoring user interrupts. It's possible to write code that never returns or ends. If you disable interrupts by setting the EnableCancelKey property to xlIgnore, or if you always use the Resume statement to return from a trapped error, your procedure won't return control to the user.

You can restore the default interrupt processing of Microsoft Excel by setting the EnableCancelKey property to xlInterrupt. To prevent a procedure from permanently turning off user interrupts, Microsoft Excel always restores the value of the EnableCancelKey property to xlInterrupt whenever code execution ends. To ensure that interrupts are handled properly, you must write your procedure so that it explicitly disables or traps interrupts each time it's run.


Chapter 8 Controls and Dialog Boxes

When you've gotten beyond writing simple macros for your own use and have started writing complete applications that several people use, you'll want to help your users accomplish tasks simply and conveniently. It's not enough to foresee the needs of the user and provide features that attend to those needs; you must also provide quick, convenient, and intuitive access to those features. Microsoft Excel offers several powerful user interface enhancements to help you effectively present features to the user: menus, toolbars, controls on worksheets or chart sheets, and controls in dialog boxes.

You use controls — such as buttons, check boxes, and list boxes — to create a custom user interface. This chapter discusses the use of controls and dialog boxes to manage the way the user interacts with your application, whereas Chapter 9, "Menus and Toolbars," discusses the use of menus and toolbars to achieve the same effect. Each of these enhancements has different advantages and disadvantages. As you design your user interface, you must decide which enhancement best suits the user's needs in a given situation.

In this chapter, you'll first get a brief overview of controls and dialog boxes and how they can enhance your application. Next, you'll learn to use simple, predefined dialog boxes and Microsoft Excel's built-in dialog boxes. Finally, you'll learn to create and use controls and custom dialog boxes.

Contents
  • Choosing the Best User Interface Enhancement
  • Using Built-In Dialog Boxes
  • Using Controls
  • Using Custom Dialog Boxes


Choosing the Best User Interface Enhancement

Controls (such as buttons and check boxes) can be placed on worksheets or chart sheets next to the data they access so that they're easy for the user to find and understand, and so that using them causes only minimal interruptions during a work session. In addition, because controls are always stored with the sheet they appear on, you never have to worry about losing them when you distribute the application. On the other hand, controls are tied to one sheet — and often to a particular object on that sheet — so they're not the best solution if you need a way to access commands in a variety of situations.

If you need to display a single message or ask the user for one string or number, you can use a message box or an input box. These predefined dialog boxes are easy to create and use, but they can be used only for simple input and output.

You can place controls on a dialog sheet to create a custom dialog box. Custom dialog boxes are useful when you want to manage a complex interaction between the user and the application. However, custom dialog boxes don't offer the quickest access to commands and can interrupt the flow of work.

Whereas dialog boxes are best suited to offering the user a set of complex options and returning information to the user, and controls offer the most visually obvious connection to the data they act on, menus and toolbars offer a quicker, more convenient way to expose simple options and commands to the user.

This chapter discusses using simple predefined dialog boxes and built-in dialog boxes; using controls on worksheets, chart sheets, and dialog sheets; and creating custom dialog boxes. Chapter 9, "Menus and Toolbars," describes in detail how to enhance the user interface of your application using customized menus and toolbars.


Using Built-in Dialog Boxes

Before you add custom controls to a sheet or design a custom dialog box, you should determine whether a built-in dialog box meets your needs.


Using Message and Input Dialog Boxes

The easiest way to add a dialog box to your application is to use a predefined built-in dialog box. Visual Basic provides two types of predefined dialog boxes: the message box and the input box. Both types are easy to use, but you have limited control over how they look and what type of information you can get from or display for the user.

The following table lists the functions and methods for adding predefined dialog boxes to your Visual Basic application.

Use this | To do this
MsgBox function | Display a message and return a value indicating the command button the user clicked.
InputBox function | Display a prompt and return the text the user typed.
InputBox method | Display a prompt and return the information the user entered. This method is similar to the InputBox function, but it provides additional functionality, such as requiring input to be of a specific data type.

Message Box

The MsgBox function creates a simple dialog box that can display a short message and a predefined set of buttons. The user can click one of the buttons to respond to the message or to cancel the message box. The simplest message box contains only a message string and an OK button, as in the following example.

MsgBox prompt:="Please close all files", title:="Files"

The MsgBox function performs any necessary string conversions before it displays the message string. You can use any data type for the prompt argument.

Tip

You can use a message box as a simple debugging tool. Use the message box text to display an interim value in a long calculation or to display a status message in a large procedure. For more information about debugging, see Chapter 6, "Debugging."

You can also create more complex message boxes that contain different icons and buttons. The following example uses the MsgBox function to display a message box containing the Warning Message icon and Yes and No buttons. The No button is the default response. The value that the MsgBox function returns depends on the button the user clicks; when you use the return value, you must enclose the MsgBox function arguments in parentheses (the preceding example ignores the return value, so the parentheses aren't required).

Sub CreateSampleBox()
    msg = "Do you want to continue?"
    dialogStyle = vbYesNo + vbExclamation + vbDefaultButton2
    title = "Error"
    response = MsgBox(msg, dialogStyle, title)    ' Get user response.
    If response = vbYes Then                        ' Evaluate response and
        msg = "You clicked Yes."                    ' act appropriately
    Else
        msg = "You clicked No or pressed ENTER."
    End If
    MsgBox msg                                    ' Display action taken.
End Sub

Note

The constants vbYesNo, vbExclamation, and so on are built into Visual Basic. For a list of these constants, see "MsgBox function" in Help.

Input Box

The InputBox function creates and displays a simple dialog box that contains a prompt, an edit box, and OK and Cancel buttons. You can use this input box to allow the user to enter data. You can change the text in the title bar, the prompt displayed to the user, and the position of the dialog box on the screen. To create a more elaborate dialog box, you must use a dialog sheet and create a custom dialog box. For more information about creating a custom dialog box, see "Using Custom Dialog Boxes" later in this chapter.

The return value from the InputBox function is a string containing the data in the edit box. If the edit box is empty or the user clicks Cancel, the return value is an empty string (""). The following code displays a simple input box.

radius = InputBox("Enter the circle's radius:", "Circle Radius")

For more information about the InputBox function, including the complete syntax, see "InputBox function" in Help.

The InputBox method of the Application object works like the InputBox function, but the method also allows you to specify the desired data type for the entered data (a range or a string, for example). If the user enters data with an incorrect type, Microsoft Excel displays a message box indicating that the entry isn't valid.

If you specify a desired data type, the return value from the InputBox method has that data type if the user clicked OK or pressed ENTER to dismiss the dialog box. If you don't specify a data type, the return value is a string (which can be an empty string if the user clicked OK with nothing in the edit box). Whether or not you specify a data type for the entered data, the return value is False if the user clicked Cancel or pressed ESC to cancel the dialog box. For more information about the InputBox method, including the complete syntax, see "InputBox method" in Help.

Note

Notice the difference between the terms dismiss and cancel. When the dialog box is dismissed, the Show method returns True, and Microsoft Excel processes the changes made to the dialog box. When the dialog box is canceled, the Show method returns False, and Microsoft Excel ignores changes made to the dialog box.

The following code uses the InputBox method to ask the user for a search range and a search value. The search range must be a valid Range reference (sheet1!a1:a20, for example), and the search value must be a number.

Sub CountValues()
    cellCount = 0
    Set rangeToSearch = Application.InputBox( _
        Prompt:="Enter the range to search", _
        Type:=8)        'type 8: must be a Range object
    searchValue = Application.InputBox( _
        Prompt:="Enter the search value", _
        Type:=1)        ' type 1: must be a number
    If searchValue = False Then Exit Sub        'user clicked Cancel
    For Each c In rangeToSearch
        If c.Value = searchValue Then
            cellCount = cellCount + 1
        End If
    Next c
    MsgBox cellCount
End Sub


Displaying Built-in Microsoft Excel Dialog Boxes

In addition to the message box and the input box, Microsoft Excel has approximately 200 built-in dialog boxes. Each dialog box allows the user to perform actions that change some feature of Microsoft Excel. For example, the built-in File Open dialog box allows the user to open a file, and the Clear dialog box allows the user to clear a range of cells.

The Dialogs method returns a built-in dialog box. This method takes as an argument a built-in constant that begins with "xlDialog" and that corresponds to a dialog box name. For example, the constant for the Find File dialog box is xlDialogFindFile.

The Show method displays the dialog box. You cannot replace the dialog box functionality (write your own file open code, for example) or trap the events that occur in the dialog box. The dialog box functions normally, and Microsoft Excel performs any actions the user requests.

The following example displays the built-in File Open dialog box, with the default folder set to Xlfiles.

Application.Dialogs(xlDialogOpen).Show("C:\XLFILES")

The Show method doesn't return to the calling procedure until the user has dismissed or canceled the dialog box and Microsoft Excel has completed any requested actions. The return value is True if the user clicked OK or pressed ENTER to dismiss the dialog box; the return value is False if the user clicked Cancel or pressed ESC to cancel the dialog box. The following example runs the ProcessWorkbook procedure if the user clicks a workbook in the File Open dialog box.

Sub NewWorkbook()
    If Application.Dialogs(xlDialogOpen).Show("c:\") And _
        ActiveWindow.Type = xlWorkbook Then ProcessWorkbook
End Sub

The Show method may fail if you try to show a dialog box in an incorrect context. For example, the method fails if you attempt to display the Format Data Labels dialog box (using the Visual Basic expression Application.Dialogs(xlDialogDataLabel).Show) when the active sheet isn't a chart.

You cannot copy a built-in dialog box, but you can create a custom dialog box that looks just like the built-in dialog box and write a series of procedures that duplicates the features of the built-in dialog box. You can then add and delete controls and change their behavior. For more information about creating and using custom dialog boxes, see "Using Custom Dialog Boxes" later in this chapter.

Note

Visual Basic does provide some methods that allow you to use duplicates of built-in dialog boxes. For example, the GetOpenFileName method displays the File Open dialog box and returns the filename the user selects. The GetSaveAsFileName method displays the File Save As dialog box.


Using Controls

You can place controls — such as buttons, check boxes, and list boxes — on worksheets, chart sheets, or dialog sheets (you cannot place controls on a module). Placing controls on a dialog sheet creates a custom dialog box.

One advantage of placing controls on a worksheet is that you can put them close to the data they're used with. Another advantage of placing controls on a worksheet is that you can create a document that looks like a dialog box but contains cells that recalculate automatically.

By using a dialog box to group controls together, on the other hand, you can reduce the degree of complexity that confronts a user who's working with a system of worksheets and procedures you've developed. You can keep the user interface for your application uncluttered so that the user isn't overwhelmed with infrequently used options. To minimize errors on a worksheet, you can isolate the process of entering data from that of transferring the data to the worksheet. You can also create dialog boxes that apply to many worksheets or charts or to the Microsoft Excel environment as a whole.

The following sections discuss placing and using controls on worksheets, chart sheets, and dialog sheets. Most of the techniques for using controls are the same, no matter what sheet type you use. In this section, the term "sheet" refers to a worksheet, chart sheet, or dialog sheet. This discussion is followed by the "Using Custom Dialog Boxes" section, which details the specific issues involved in working with custom dialog boxes.


Using Custom Controls in Your Application

You use the Forms toolbar to choose a control and place it on the sheet. After you've placed the control, you set its initial properties, such as whether a check box appears checked or whether a button should be resized when an underlying cell on a worksheet is resized.

Next, you can assign a Visual Basic procedure to the control. When the user clicks a button, check box, or option button, or when the user edits the text in an edit box, Visual Basic runs the associated procedure.

You can also link a control directly to a cell on a worksheet, without using procedures. This way, you can simplify the user interface for a worksheet so that the user can set options using the mouse rather than by typing data in a cell. For example, you can group a series of check boxes that represent options in a feasibility study and then link each check box to a cell used elsewhere on the worksheet. If the user selects a check box, the value linked to the worksheet cell becomes True, and the worksheet is recalculated. For more information about linking controls to cells, see "Linking Controls to Worksheet Cells" later in this chapter.


Choosing and Placing Controls

The first step in using a control on a worksheet, chart sheet, or dialog sheet is choosing the control from the Forms toolbar and placing it on the sheet.

To place a control on a sheet

1. On the Forms toolbar, click the button for the control you want to add.

2. Click on the sheet, and drag until the control's outline is the size and shape you want.

The following table describes the control created by each button on the Forms toolbar.

Button |  | Description of control
 | Label | Text you provide for the user, including names, instructions, and cautions.
 | Edit Box | A box where a user can enter text, numbers, or cell references.
 | Group Box | A border containing a group of option buttons or other controls.
 | Create Button | A command button such as the OK or Cancel button.
bshbruce hale | Check Box | A box that indicates whether an option is set, regardless of the state of other options in the dialog box.
 | Option Button | A button for selecting one of a group of mutually exclusive options. Place a series of option buttons in a group box to group them.
 | List Box | A list of text strings, one or more of which can be selected.
 | Drop-Down | An uneditable text box and an arrow, paired with a drop-down list box that appears when the user clicks the arrow.
 | Combination List-Edit | An editable text box combined with a list box.
 | Combination Drop-Down Edit | An empty edit box and an arrow, paired with a drop-down list box that appears when the user clicks the arrow.
 | Scroll Bar | A horizontal or vertical scroll bar for changing numeric values. To create a horizontal scroll bar, size the scroll bar so that it's wider than it is high.
 | Spinner | A pair of buttons for incrementing or decrementing a displayed value.

The Forms toolbar contains four additional buttons for working with controls on dialog boxes, as described in the following table.

Button |  | Description
 | Control Properties | Used to view or change the properties belonging to the selected object; equivalent to clicking Object on the Format menu.
 | Edit Code | Used to create or edit code assigned to the selected object.
 | Toggle Grid | Used to align controls on a grid.
 | Run Dialog | Used to display the dialog box as it appears when it's run.

You can also add a control using the Add method for the appropriate control collection. Arguments for the Add method specify the position of the upper-left corner of the control and its height and width. The following example places a new button on the worksheet named "sheet1."

Worksheets("sheet1").Buttons.Add 50, 25, 100, 20

On a worksheet or chart sheet, you specify the coordinates of the upper-left corner of the control relative to the upper-left corner of the sheet. On a dialog sheet, you specify the coordinates of the upper-left corner of the control relative to the upper-left corner of the dialog frame. For more information, see "Add method" in Help.


Selecting a Control

Selecting a control is different from clicking it. Typically, clicking a control on a sheet or in a dialog box has the same result as clicking a control in a built-in dialog box. For example, clicking a button on a worksheet causes the button to appear pushed down, or pressed, and clicking an empty check box causes a check to appear in the box.

Selecting a control causes a gray box to appear around it and allows you to change the control's properties, move it around on the sheet, or assign a procedure to one of the events it supports. (You select a control in Visual Basic using the Select method.)

To select a control on a sheet

While holding down Ctrl, click the control.

– Or –

Using the right mouse button, click the control. This selects the control and displays its shortcut menu. Press ESC to dismiss the shortcut menu and leave the control selected.

Drawing Selection

You can also click the Drawing Selection button on the Drawing toolbar and then drag a rectangle around the control you want to select. If you don't see the Drawing toolbar, click Toolbars on the View menu, and then select the Drawing check box in the Toolbars box.

Note

To select a group of controls on a dialog sheet, drag a rectangle that encloses the controls you want to select. You can also add controls to a group of controls that's already selected by holding down shift and selecting the additional controls.


Sizing, Moving, and Deleting a Control

To change the dimensions of a control, select it and drag one of its sizing handles. To change its position, drag one of its borders. A grid constrains the control's movement on a dialog sheet to specific increments, which vary with the type of display you're using; this behavior is called snap-to-grid.

To turn on or turn off snap-to-grid

Toggle Grid

On the Forms toolbar, click the Toggle Grid button.

You can temporarily override the snap-to-grid feature by holding down Alt while dragging a handle, border, or control. Holding down alt while dragging on a worksheet constrains vertical movement to multiples of a worksheet cell's height and constrains horizontal movement to multiples of a cell's width.

To delete a control

1. Select the control.

2. Press Del.

You can also click the control using the right mouse button and then click Clear on the shortcut menu, or you can point to Clear on the Edit menu and then click All.


Setting Control Properties

When you create a control, Microsoft Excel assigns it a set of default properties like those found in the built-in Microsoft Excel dialog boxes. The properties and their default values vary depending on the control. You can change these properties using the Object command on the Format menu.

To display or change a property of a control

1. Select the control.

2. On the Format menu, click Object.

3. Click a tab, and then review or change the property.

You can also click the control using the right mouse button and then click Format Object on the shortcut menu.


Assigning Code to Controls

After you place a control on a worksheet, chart sheet, or dialog sheet and establish its initial properties, you can assign a Visual Basic procedure to the control.

Whenever an action (also called an event) occurs on the control, Microsoft Excel runs the procedure assigned to the control. The following table describes the events that the various types of control respond to.

Controls | Event
Command buttons, group boxes, check boxes, option buttons | The user activates the control. This event is used for controls that have no value or that have only a simple value, such as True or False.
Edit boxes, list boxes, drop-down boxes, combination list-edit boxes, combination drop-down edit boxes, scroll bars, spinners | The user changes the control. This event is used for controls that support a complex value.
Dialog frames | The dialog box appears.

For example, if you assign a procedure to an edit box, the procedure is called whenever the user enters or changes data in the edit box. When you assign a procedure to a dialog frame, the procedure runs when the dialog box is first made visible.

Note

You can assign any Visual Basic procedure to a control. Functionally, there's nothing special about the procedure name; creating a procedure called "Button4_Click" doesn't automatically assign the procedure to Button4 — you must use the Assign Macro dialog box or the OnAction property to assign the procedure to the control.

You can also assign code to drawing objects (such as ovals and rectangles). For more information, see Chapter 11, "Automatic Procedures and OnEvent Procedures."

Using the Assign Macro Dialog Box

The Assign Macro dialog box allows you to specify the procedure that runs when an event occurs.

To associate an existing procedure with the event belonging to a control

1. Select the control.

2. On the Tools menu, click Assign Macro.

You can also click the control using the right mouse button (to display the shortcut menu) and then click Assign Macro.

3. In the Macro Name/Reference box, enter the name of the procedure you want to assign to the event.

To create a new procedure and associate it with the event belonging to a control

1. Select the control.

Edit Code

2. On the Forms toolbar, click the Edit Code button.

Microsoft Excel opens a Visual Basic module scrolled to display an empty procedure.

3. Between the Sub and End Sub statements, write the procedure you want to associate with the event.

To edit a procedure previously associated with the event belonging to a control

1. Select the control.

Edit Code

2. On the Forms toolbar, click the Edit Code button.

Microsoft Excel opens a Visual Basic module scrolled to display the associated procedure. If the associated code belongs to the Microsoft Excel 4.0 macro language, Microsoft Excel switches to the macro sheet containing the associated macro.

3. Edit the code.

Using Visual Basic

The OnAction property sets the name of the procedure that runs whenever an event occurs. The following example causes the StartDialog procedure to run whenever the dialog box first starts and causes the ButtonPressed procedure to run whenever the user clicks a button on the first dialog sheet.

With DialogSheets(1)
    .DialogFrame.OnAction = "StartDialog"
    .Buttons.OnAction = "ButtonPressed"
End With

Tip

The ButtonPressed procedure can use the Caller property to determine which button was clicked. For buttons, the Caller property returns the button name.


Linking Controls to Worksheet Cells

Some controls can be linked to one or more worksheet cells. If the cell value changes, the control value changes, and vice versa. For example, if you've linked an option button to a worksheet cell, the cell value is True as long as the option button is turned on. If you change the cell value to False, the option button is turned off. You can use linked cells to set initial conditions for controls and to create worksheets that respond immediately to user input.

Because changing the state of the control changes the value in the linked cell, any formulas referencing the linked cell are recalculated when you change the control. You might use this feature to implement a loan calculation worksheet for which the results depend on the interest rate. Linking a spinner to the interest rate cell would allow you to change the interest rate simply by clicking the spinner. This way, the loan payment would automatically recalculate when the interest rate changes.

Note

If you have the Automatic Calculation option set, changing a linked control will cause the entire worksheet to recalculate. To turn off Automatic Calculation, click Options on the Tools menu, click the Calculation tab, and then click Manual under Calculation.

Worksheet cells can be linked to check boxes, list boxes, drop-down list boxes, option buttons, scroll bars, and spinners. The link is a property of the control, not of the linked cell.

You can link the same cell to more than one control, but the control can be linked to only one cell. You can reference the linked cell in any other cell where you want to use the linked value.

You can link a control on a dialog sheet to a worksheet cell, but the link is always active, so changing the state of the control immediately changes the value appearing in the linked cell. This means that changes appear on the worksheet even if the user clicks Cancel to close the dialog box. This behavior is usually not desired. As a rule, you'd like to have the changes appear only when the user clicks OK or presses ENTER to dismiss the dialog box. For this reason, it's usually a better idea to use a procedure to transfer information from a dialog box to the cells on a worksheet and to run that procedure only when the user clicks OK. For more information, see "Getting Information from a Dialog Box" later in this chapter.

You can link a control to a cell and assign a procedure to the same control. In this case, the link is updated before the procedure runs. For more information, see the preceding section, "Assigning Code to Controls."

You can specify the cell link reference for a control on the Control tab in the Format Object dialog box.

To link a control to a worksheet cell

1. Select the control.

2. On the Format menu, click Object, and then click the Control tab.

3. In the Cell Link box, type the name or reference of the linked cell.

You can also click the cell to enter its reference in the box.

4. Enter any additional information that pertains to the linked control, as described in the following sections. For example, use the Input Range box to specify the cells you want to use to fill a list box.

Note

You can also establish a link by selecting the control on the worksheet or dialog sheet and then typing the cell reference in the formula bar.

The LinkedCell property, which corresponds to the Cell Link box in the Format Object dialog box, sets the cell link reference for a control. The following example links the check box named "Check Box 3" on the worksheet named "sheet1" to cell A5 on the same worksheet.

Worksheets("sheet1").CheckBoxes("Check Box 3").LinkedCell = "sheet1!a5"

List boxes and drop-down list boxes also use the ListFillRange property, which corresponds to the Input Range box in the Format Object dialog box. This property sets the worksheet range used to fill the list box. The following example fills the list box named "List Box 2" on the sheet named "sheet1" with the contents of cells A5:A10 on the same worksheet. Changes to the worksheet cells appear in the list box.

Worksheets("sheet1").ListBoxes("List Box 2"). _
    ListFillRange = "sheet1!a5:a10"

Check Boxes

For a check box, the value in the linked cell reflects the state of the check box. The check box can appear checked, unchecked, or grayed. These values correspond to the linked cell values True, False, and #N/A. Typing one of these values in the linked cell changes the state of the check box. Manually changing the check box changes the value in the linked cell.

Option Buttons

For grouped option buttons that are all linked to the same cell, the value in the linked cell shows the ordinal number of the option button that's turned on. For example, if an option button group contains four buttons and the third button is turned on, the value in the linked cell is 3. Changing the value in the linked cell to 1 turns on the first option button in the group. A linked cell value smaller than 1 or larger than the total number of buttons in the group (four, in this example) causes all buttons in the group to be turned off.

List Boxes

For a list box in which you can select only one item at a time (called a single-select list box), the value in the linked cell shows the ordinal number of the selected item in the list box (item one is at the top of the list box). For a multipleselection list box (a list box in which more than one item can be selected at a time), the value in the linked cell has no meaning.

You can also specify a range of cells on a worksheet that contains the list of items to appear in the list box, using the Input Range box on the Control tab in the Format Object dialog box, or using the ListFillRange property.

Formulas that depend on the linked cell are recalculated whenever the selected item changes ; this is useful for creating what-if models in which the user can watch results change while moving the selection up and down in the list box.

Scroll Bars

For a scroll bar, the value in the linked cell specifies the position of the scroll box in the scroll bar. The Format Object dialog box allows you to specify minimum and maximum values for the scoll bar and to specify the amount by which the position value changes when the user clicks the arrows or the scroll bar. You can also specify these values using the Min, Max, SmallChange, and LargeChange properties.

Changing the value in the linked cell changes the position of the scroll box. Changing the value in the linked cell to a number smaller than the minimum value moves the scroll box to the minimum position. Likewise, setting the value in the linked cell to a number larger than the maximum value moves the scroll box to the maximum position.

Spinners

For a spinner, the value in the linked cell represents the current "value" of the spinner. Unlike a scroll bar, a spinner has no visible position indicator (such as a scroll box). However, you set a minimum and maximum value for a spinner just as you do for a scroll bar, and the spinner value is incremented when you click the up arrow and decremented when you click the down arrow. Spinners support only the Max, Min, and SmallChange properties.


Using Custom Dialog Boxes

When you need to manage a complex interaction between the user and your application, it's usually best to create a custom dialog box. The custom dialog box can present all the options in one location, making it easier to read and use than controls placed directly on a worksheet or chart sheet. When the user is finished choosing options from the dialog box, the dialog box can be dismissed; this way, the controls take up screen space only as long as they're needed.

Creating and managing a custom dialog box is more complex than using controls directly on a sheet, however. You must carefully consider the trade-off between the convenience to the user and the amount of work involved for you to create and manage the dialog box.


Creating a Dialog Sheet

To create a custom dialog box, you must first insert a new dialog sheet.

To insert a new dialog sheet

1. On the Insert menu, point to Macro, and then click Dialog.

Microsoft Excel inserts a new dialog sheet on top of the current sheet in the active workbook and places within it a dialog box frame containing an OK button and a Cancel button.

2. To change the name that will appear at the top of the dialog box, select the text at the top of the dialog box frame, and then type a new name.

3. To change the size of the dialog box, drag a sizing handle until the dialog box frame is the size you want.

Note

Although you can change the location of a dialog box frame on its dialog sheet, you cannot set or change the position of the displayed dialog box using Visual Basic. Microsoft Excel displays the resulting dialog box with its upper-left corner in the same position as the last dialog box displayed, regardless of whether it was a built-in or custom dialog box. For more information, see "Displaying the Custom Dialog Box" later in this chapter.

After you've created a dialog sheet, you choose and place controls on the sheet using the same process you used to place controls on a worksheet or chart sheet. For more information, see "Choosing and Placing Controls" earlier in this chapter.


Testing the Custom Dialog Box

As you add controls to the dialog sheet, you'll want to test the dialog box. Unlike controls on a worksheet or chart sheet, controls on a dialog sheet aren't active — that is, they cannot be clicked. You can select, move, and resize them, and you can set their properties, but you cannot click them to activate the associated Visual Basic procedures. You must run the dialog sheet to see the working dialog box and test the controls.

Run Dialog

On the Forms toolbar, click the Run Dialog button to display the dialog box while you're creating and testing it. After you've finished creating the dialog box, you can use the Show method to display it from a Visual Basic procedure. For more information, see "Displaying the Custom Dialog Box" later in this chapter.


Setting Control Properties on a Dialog Sheet

You use the same process to set most properties for controls on worksheets, chart sheets, and dialog sheets. For more information, see "Setting Control Properties" and "Assigning Code to Controls" earlier in this chapter. For controls on a dialog sheet, you can also set the tab order and access key to control how the user accesses the controls. For buttons, you can set them to either dismiss or cancel the dialog box. For edit boxes, you can restrict the kind of data the user can enter.

Assigning Tab Order

There are several ways for a user to access a control in a dialog box (a process also called setting the focus to the control). One way is simply to click a control such as a button, edit box, or list box. Another way is to press Alt and then click the access key for the control (discussed in the next section).

You can also establish a tab order for the controls in a dialog box. When the user presses Tab, controls become active in the sequence, or tab order, you've established. Establishing a logical tab order is particularly useful for custom data-entry forms, because it minimizes the number of keystrokes it takes to get from one edit box to the next. You can set a tab order only for controls on a dialog sheet, not for controls on a worksheet or chart sheet.

To change the tab order of controls

1. Switch to the dialog sheet.

2. On the Tools menu, click Tab Order.

3. Click the item whose place in the tab order you want to change.

To select more than one control, hold down CTRL as you click the items.

4. Click one of the arrow buttons above or below Move.

Assigning an Access Key

An access key is the key you press in conjunction with the ALT key to access a control in Microsoft Excel. As with setting the tab order, defining access keys works only for controls on a dialog sheet. You can assign an access key to a label, command button, check box, option button, or group box. When you do this, a single character in the text associated with the control is underlined when the dialog box is displayed.

To set an access key for a control

1. Select the control.

2. On the Format menu, click Object.

3. Click the Control tab.

4. In the Accelerator box, type the key you want to use as the access key.

Note

If you want to create the effect of an access key for a control on a worksheet, you can develop a procedure associated with the OnKey event that runs when the user presses a certain key combination. Creating an OnKey procedure is discussed in Chapter 11, "Automatic Procedures and OnEvent Procedures."

Button Properties

When you create a new dialog sheet, Microsoft Excel adds an OK button and a Cancel button. When the user clicks the OK button, the default behavior is to dismiss the dialog box and cause the Show method to return True. For the Cancel button, the default behavior is to cancel the dialog box and return False. In addition, Visual Basic runs any procedures associated with the buttons. By default, only these two buttons dismiss and cancel the dialog box.

You can change this default behavior using either the Control tab in the Format Object dialog box or the DismissButton and CancelButton properties. You can set any number of buttons to dismiss the dialog box, but you can set only one button to cancel it. For more information, see "DismissButton property" and "CancelButton property" in Help.

Note

Notice the difference between the terms dismiss and cancel. When the dialog box is dismissed, the Show method returns True, and Microsoft Excel processes the changes made to the dialog box. When the dialog box is canceled, the Show method returns False, and Microsoft Excel ignores changes made to the dialog box.

Edit Box Data Validation

By default, an edit box allows the user to enter any data type. You may want to restrict each edit box to a single data type (for example, if you want the user to enter a filename, you can specify that the entry must be a string). You can set this either by using the Control tab in the Format Object dialog box or by using the InputType property for the edit box. When the user dismisses the dialog box, Microsoft Excel checks the entries in any edit boxes with data validation turned on. If the contents of an edit box are invalid, Microsoft Excel displays a message and switches the focus to the edit box so that the user can supply a value of the correct data type. This process continues until every edit box contains valid data.


Displaying the Custom Dialog Box

Run Dialog

The Run Dialog button on the Forms toolbar displays the dialog box. You will usually use this toolbar button while you're testing the dialog box. You can use the Show method to display the custom dialog box from a procedure. When the dialog box appears, the user is free to interact with its controls — entering text in an edit box, clicking an option button, clicking an item in a list box, and so on.

Note

Although you can change the position of a dialog frame on its dialog sheet, you cannot set or change the position of the displayed dialog box using Visual Basic. The dialog box appears with its upper-left corner in the same position as the last dialog box displayed.

When the user clicks a button that dismisses the dialog box (that is, a button for which the DismissButton property is True and the CancelButton property is False), the following actions occur:

  • Visual Basic runs any procedure assigned to the button.
  • Any edit boxes with data validation turned on are checked for valid data.

    If the contents of an edit box are invalid, Microsoft Excel displays a message and switches the focus to the edit box so that the user can supply a value of the correct data type. This process continues until every edit box contains valid data.

  • The dialog box is removed, and the Show method returns True.

When the user clicks a button that cancels the dialog box (that is, a button for which the CancelButton property is True), the following actions occur:

  • Visual Basic runs any procedure assigned to the button.
  • The dialog box is removed, and the Show method returns False.

For example, suppose that there's a button named "Object Color" on a worksheet. To change a drawing object's color, the user clicks this button to display a dialog box.

The following example shows the procedure assigned to the Object Color button.

Sub DoColorDialog()
    colors(1) = 5   'blue
    colors(2) = 10  'green
    colors(3) = 6   'yellow
    colors(4) = 22  'orange
    originalColor = Selection.Interior.ColorIndex
    saveInteriorColor = originalColor
    If DialogSheets("ChangeColorDialog").Show = False Then
        Selection.Interior.ColorIndex = originalColor
    End If
End Sub

The colors array must be declared at the module level so that it can be used by all procedures in the module. The colors in the array should be set in the same order as the tab order for the color option buttons.

When the user selects a graphic object and clicks the Object Color button, the procedure sets the color-index array values to the four color options, sets the saved color value and the original color value to the current selection color, and then displays the dialog box on the dialog sheet named "ChangeColorDialog."

The user can choose one of the four color options and then click Test, Undo, OK, or Cancel. The ChangeColor procedure is assigned to both the OK and Test buttons, so it runs whenever the user clicks either OK or Test. The UndoColor procedure is assigned to the Undo button. These procedures are discussed in the following sections. If the user clicks Cancel or presses ESC, the Show method returns False, and the procedure resets the object to its original color. For more information about using code with controls, see "Assigning Code to Controls" earlier in this chapter.


Getting Information from a Dialog Box

You can read and set the state of dialog box controls at any time. Typically, you set initial conditions before the dialog sheet runs or use a procedure assigned to the DialogFrame object to set controls when the dialog box starts. You will usually read controls when a specific event occurs in the dialog box or when the user dismisses the dialog box.

The ChangeColor procedure runs whenever the user clicks either Test or OK. This procedure saves the current color of the selected object and then reads the option buttons to determine the new color.

Sub ChangeColor()
    Dim selInterior As Interior
    With DialogSheets("ChangeColorDialog")
        Set selInterior = Selection.Interior
        saveInteriorColor = selInterior.ColorIndex
        selInterior.ColorIndex = colors(GetOptionIndex(.OptionButtons))
    End With
End Sub

The GetOptionIndex function scans the option buttons and returns the index value of the button that's turned on (the button's ordinal value in the button tab order). This index number is used to return the correct color value from the colors array, as in the following example.

Function GetOptionIndex(opBtns As OptionButtons)
    For Each ob In opBtns
        If ob.Value = xlOn Then
            GetOptionIndex = ob.Index
            Exit Function
        End If
    Next
End Function

The dialog box also has an Undo button that causes the UndoColor procedure to run. This procedure saves the current color and then resets the color to the saved value.

Sub UndoColor()
    With Selection.Interior
        temp = .ColorIndex
        .ColorIndex = saveInteriorColor
        saveInteriorColor = temp
    End With
End Sub


Modifying Controls While a Dialog Box Is Visible

You can make any dialog box you've created easier to use and understand by modifying controls while the dialog box is visible. For example, you can disable controls, change the focus, modify worksheet cell links, and change the dialog box size.

Enabling a Control

You can use the Enabled property of a control to prevent the user from making changes to an option unless a specified condition is met. This is often used to make a set of option buttons available only when the user selects a check box, as shown in the following code. This procedure is assigned to the check box, and it runs whenever the state of the check box changes.

Sub SetOptions()
    With ActiveDialog
        If .CheckBoxes(1).Value = xlOn Then
            .OptionButtons(Array(1, 2, 3, 4)).Enabled = True
        Else
            With .OptionButtons(Array(1, 2, 3, 4))
                .Enabled = False
                .Value = xlOff
            End With
        End If
    End With
End Sub

You could also use the Enabled property to create a procedure for an edit box that makes the OK button available only when the user has entered a part number that conforms to a standard pattern.

Setting the Focus to a Control

You can set the focus to a control in a dialog box by setting the Focus property of the dialog box (the control with the focus is acted on whenever the user presses ENTER). The following example sets the focus in the active dialog box to the button named "test."

Sub SetFocus()
    ActiveDialog.Focus = "test"
End Sub

Note

You can set the focus only while the dialog box is running. For more information, see "Focus property" in Help.

Modifying Links Between a Control and a Worksheet

You can establish links between a control and a cell on a worksheet when the control is created, but you can also create, modify, and delete links between a control and a cell while a procedure is running. You use the LinkedCell property of the control to do this. The LinkedCell property belongs to the linked control and not the linked cell. The ListFillRange property also specifies the input range for list boxes. For more information, see "Linking Controls to Worksheet Cells" earlier in this chapter.

Changing Dialog Box Properties

You can change some of the properties of the dialog box itself (such as its size) while it's running. A common use for this is to expand a dialog box to reveal additional options when the user clicks the Options button. You can place controls below what's usually the bottom border of the dialog box. When the user clicks Options, the procedure changes the vertical size of the dialog box to reveal the hidden options.

Sub DisplayOptions()
    ActiveDialog.DialogFrame.Height = 91
End Sub


Hiding a Custom Dialog Box

To remove a dialog box from the screen, either you can wait for the user to click a button whose DismissButton property is True, or you can create an event procedure for a control, as shown in the following example.

Sub HideDialog()
    If MsgBox("Remove dialog box?", vbYesNo) = vbYes Then
        ActiveDialog.Hide
    End If
End Sub

When the user clicks the control this procedure is attached to, a message is displayed asking whether the dialog box should be removed. If the user answers yes, the dialog box is removed. If the CancelButton property for the control is True, the Show method returns False. Otherwise, the Show method returns True.


Chapter 9 Menus and Toolbars

An essential part of creating a useful custom application is providing a simple and consistent way for the user to interact with your application. Chapter 8, "Controls and Dialog Boxes," describes two user interface enhancements that help you achieve this goal: dialog boxes and controls. Dialog boxes are well suited to presenting the user with a set of complex options or returning information to the user, whereas controls offer the most visually obvious connection to the data they act on. However, menus and toolbars often provide quicker, more convenient, and more widely accessible ways to expose simple commands and options to the user.

In this chapter, you'll first get an overview of menus and toolbars and how each can enhance your application. Next, you'll examine menus and their components in detail. You'll see how to make design-time changes to the menu system, such as adding a new menu to a menu bar, using either the Menu Editor or Visual Basic code. Then you'll learn how to make run-time changes to the menu system, such as adding a check mark to a menu item.

In the second part of the chapter, you'll examine toolbars and toolbar buttons. You'll learn how to modify toolbars and toolbar buttons while you're designing your user interface. For example, you can create a new toolbar or add a toolbar button to the toolbar. Then you'll see how to change the properties of toolbars and toolbar buttons in response to user input while your application is running. For example, you can hide a toolbar when the user no longer needs it, or you can change a button so that it will look "pushed" after a user has clicked it.

Contents

  • Choosing the Best User Interface Enhancement
  • The Menu System
  • Design-Time Modifications to the Menu System
  • Run-Time Modifications to the Menu System
  • Toolbars and Toolbar Buttons
  • Design-Time Modifications to Toolbars and Toolbar Buttons
  • Run-Time Modifications to Toolbars and Toolbar Buttons


Choosing the Best User Interface Enhancement

Menus are lists of commands from which the user can choose. Menus offer a convenient and consistent way to group commands and an easy way for users to access them. Commands for performing related tasks can be grouped on the same menu, and separator bars can be used to divide commands on a menu into logical groupings. Submenus offer additional levels of organization, and shortcut menus offer a way to group related commands that apply to the limited context of a specific task.

You can assign access keys to make commands accessible from the keyboard, and you can assign shortcut keys to provide the user even quicker access to the commands. In addition, menus take up less space than toolbars, as the items on a menu are displayed on demand and don't take up dedicated screen space. On the other hand, if you want quick, graphical access to a command, a toolbar may be a better choice.

Toolbars contain buttons that perform frequently used commands. Toolbars are ideal for presenting individual property settings (such as bold, italic, or font size), commands that are best represented visually, and commands you want to access with one click of the mouse. In addition, toolbars remain displayed while the user works, whereas menus are displayed only on demand; this makes scanning a toolbar for a particular button easier than scanning the menus on a menu bar for a particular command. However, if you need easy keyboard access to a command, if you want to display your commands hierarchically, or if you're short on screen space, a menu may be a better choice.

If you need to present a more complex set of options to the user, a dialog box may be a better choice than a toolbar or a menu. If you want to place a tool closer to the data the user is working with, the best solution may be to place a control directly on a worksheet or chart. Chapter 8, "Controls and Dialog Boxes," describes these user interface enhancements in detail.


The Menu System

The menu system in Microsoft Excel is composed of the entire set of available menus and the items on each menu. Each menu is either a drop-down menu, a submenu, or a shortcut menu. Each menu item is either a command, a separator bar, or a submenu caption. In this chapter, the term component refers generically to any menu or menu item.

A menu bar is a bar at the top of the active window that displays the captions of all the drop-down menus contained in the menu bar. Microsoft Excel changes the menu bar it displays in response to a change in the active sheet type or in response to a Visual Basic instruction. When you edit a chart, for example, Microsoft Excel automatically displays the menu bar containing a set of menus that apply to the charting environment.

A drop-down menu is a list of menu items that's displayed (drops down) when you select the appropriate menu caption on the menu bar.

A submenu (child menu) is a menu attached to the right side of a menu item (the submenu caption) on another menu (the parent menu). Each submenu caption is marked with an arrowhead pointing to the right. Submenus can be added to drop-down menus or shortcut menus. A submenu is displayed when you point to the appropriate submenu caption on the parent menu.

A shortcut menu is a floating menu that contains a group of commands pertinent to a specific task. A shortcut menu appears when the user clicks the right mouse button while the pointer is over an object. Unlike other menus, shortcut menus have no caption.

You've already worked with these components of the built-in menu system. For example, to insert a chart on a worksheet, you click the caption of the Insert drop-down menu on the worksheet menu bar, point to the Chart menu item (the caption for the Chart submenu), and then click the On This Sheet menu item. To change the chart type, you select the chart, click the right mouse button to display a shortcut menu containing commands that apply to charts, and then click the Chart Type menu item.


Guidelines for Customizing the Menu System

Microsoft Excel offers you a wide range of ways to modify the menu system: you can create new menu bars; add new drop-down menus to built-in or custom menu bars; create new shortcut menus; add new menu items (commands, submenus, or separator bars) to built-in or custom drop-down menus, shortcut menus, or submenus; and assign procedures to menu items. In addition, you can restore the built-in menu system to its default state at any time.

Adding Custom Components or Modifying Built-in Components

Microsoft Excel comes with a built-in menu system. You can modify components of this built-in system or create and modify custom menu components, using either the Menu Editor or Visual Basic.

Modifying a built-in menu bar, menu, or menu item is appropriate if you're adding or changing a small number of components. For example, if you just want to provide menu access to a macro, you can add a menu item to a built-in menu and then link the macro to that item.

If you need to make more extensive changes, it may be more appropriate to create a completely new component. For example, if you want to add several new drop-down menus, each containing several new menu items, it may be more appropriate to create an entirely new menu bar to contain the new menus.

Using Submenus

If your menus become crowded and difficult to scan, you can use submenus to organize them more effectively and add clarity to your application by reducing the amount of information presented to the user at any one time. For example, suppose you create a menu that presents a number of options, as shown in the following illustration.

Using submenus, you can present the same items in either of the following ways.

With submenus, the user can browse through commands that might otherwise be available only through a series of custom dialog boxes. However, if you need to create a complicated array of submenus to present a set of commands, a dialog box may in fact be a better solution.

Using Shortcut Menus

If you want to give the user access to a command that applies to the limited context of a selected object, you can add the command to the shortcut menu for that object.

Making Changes While the Application Is Running

In addition to making changes to the design of the menu system, you can also use Visual Basic to modify properties of menu components in response to conditions that change while the application is running. For example, you can display or hide a component, enable or disable a component, or add or remove a check mark next to a menu item.


Scope of the Changes

In Microsoft Excel, you can add, delete, and modify menu components using either the Menu Editor or Visual Basic. Although the two methods produce many of the same changes to the menu system, the scope of the changes they produce is different: Visual Basic produces changes that apply to all workbooks during a specific Microsoft Excel session, whereas the Menu Editor produces changes that apply to all Microsoft Excel sessions whenever a specific workbook is open. Defining the appropriate scope for the changes you want to make will help you decide which method to use.

Changes Made with Visual Basic

Changes you make to the menu system using Visual Basic methods and properties apply to all open workbooks until the end of the Microsoft Excel session during which the changes are made, even if you close the workbook where you've made the changes. If you want to limit the scope of changes made by Visual Basic to a specific sheet, set the sheet's OnSheetActivate property to the procedure that makes these changes, and set the sheet's OnSheetDeactivate property to the procedure that undoes these changes.

When you close Microsoft Excel, any changes you made to the menu system using Visual Basic are lost. If you want the menu changes to be available when you restart Microsoft Excel and reopen the workbook, you must use Visual Basic to reset the menus to the desired configuration when you reopen the workbook. An easy way to do this is to use an Auto_Open procedure. Because the changes you make to the menu system with Visual Basic are stored globally for the duration of a session, rather than in a particular workbook, these changes aren't shown in the Menu Editor.

Changes Made with the Menu Editor

Changes you make to the menu system using the Menu Editor — including adding or deleting menu items — are stored as a menu editing list in the active workbook. The changes aren't lost when you close Microsoft Excel, and they're automatically reapplied to the menu system when you reopen the workbook.

For example, suppose you've only one workbook open: You edit the menu system in the workbook using the Menu Editor, and you develop procedures that support the menus, worksheets, and other objects in your application. If you then save and close the workbook, the menu system reverts to its built-in state. When you reopen the workbook, the menu system is revised according to the menu editing list that was stored when the workbook was last saved.

Changes you make to the menu editing list for a workbook are reflected in the menu system whenever that workbook is open, but the Menu Editor shows only the changes made in the active workbook, no matter how many workbooks are open. If multiple workbooks containing menu editing lists are open, the menu system will combine and display the changes in all the workbooks, but the Menu Editor will still show only the changes made in the active workbook.

Note

Because the Menu Editor doesn't show changes made with Visual Basic or changes made by the Menu Editor in other workbooks, the menu components shown in Microsoft Excel may not agree with the menu components shown in the Menu Editor.

For example, suppose you make some changes to the built-in File menu on the worksheet menu bar, where the first three menu items are New, Open, and Close. First, you open a new workbook, name it Mybook1.xls, and add an Open Special menu item to the File menu, just above the Close item. Then you close Mybook1.xls, open a second workbook, name this new workbook Mybook2.xls, and add an Open Database menu item just above the Close item on the File menu. If you then reopen Mybook1.xls (with Mybook2.xls still open), the File menu contains all the menu items: New, Open, Open Database, Open, and Close. (Because the workbook whose menu editing list contains Open Special is the most recently opened workbook, Open Special appears below Open Database on the menu.)

However, if you start the Menu Editor while Mybook1.xls is the active workbook, select the worksheet menu bar, and then open the File menu, you see only the New, Open, Open Special, and Close menu items. If you bring up the Menu Editor while Mybook2.xls is active, you see New, Open, Open Database, and Close on the File menu. The Menu Editor displays the effects of only the active workbook's menu editing list.


Design-Time Modifications to the Menu System

Design-time changes to the menu system are any changes you make before the application runs. This includes adding, deleting, moving, and restoring menu components, as well as setting menu component properties that won't change in response to changing conditions at run time. Depending on the scope of the modifications you want to make, you can either use Visual Basic procedures or make changes in the Menu Editor dialog box. For more information about a Visual Basic procedure, see the specific property or method in Help. For more information about the Menu Editor, see "menu editor" in Help.

To display the Menu Editor dialog box

  • While a Visual Basic module is active, click Menu Editor on the Tools menu.

Menu Editor button

You can also click the Menu Editor button on the Visual Basic toolbar while any worksheet is active.


Adding a Custom Menu Bar

If you want to design a set of drop-down menus that differs significantly from what is available on the built-in menu bars, you may need to create a new menu bar. You can accomplish this using the Menu Editor or Visual Basic procedures.

Using the Menu Editor

The Menu Editor provides a convenient way to add a custom menu bar to the active workbook.

To add a menu bar to a workbook

1. While a Visual Basic module is active, click Menu Editor on the Tools menu.

2. In the Menu Bars box, click the arrow to display the drop-down list, and then click the name of any menu bar.

This step cancels the selection of items in the Menus, Menu Items, and Submenu Items boxes. If you omit this step, the text you type in the Caption box becomes the first menu item on the first menu that's selected in the Menus box.

3. Click Insert.

4. In the Caption box, either type a name for the new menu bar or accept the default name.

The new menu bar is added to the list in the Menu Bars box, below the final item. The default list of built-in menu bars is shown in the following table. The custom menu bars you create are listed in the order they're created. You can use up to 15 custom menu bars at one time.

Menu bar | Description
Worksheet | The menu bar that appears when a worksheet is active
Chart | The menu bar that appears when a chart is active
No Documents Open | The menu bar that appears when no workbooks are open
Visual Basic Module | The menu bar that appears when a Visual Basic module is active
Shortcut Menus 1 | A group of shortcut menus that appears when the user clicks a toolbar, toolbar button, cell, column or row selection, workbook tab, window title bar, or the desktop with the right mouse button
Shortcut Menus 2 | A group of shortcut menus that appears when the user clicks a drawing object, button graphic object, or text box graphic object with the right mouse button
Shortcut Menus 3 | A group of shortcut menus that appears when the user clicks a chart series, text, plot area, axis, gridline, floor or arrow, legend, or the entire chart with the right mouse button

Note

A shortcut menu is a type of menu, and each shortcut menu is represented by a Menu object in Visual Basic. Although shortcut menus are shown grouped into menu bars in the Menu Editor, a shortcut menu group isn't represented by a MenuBar object in Visual Basic.

Using Visual Basic

Use the Add method of the MenuBars collection to create a new menu bar; specifying the name of the new menu bar is optional.

MenuBars.Add "myWorksheetMenubar"

The MenuBars collection contains all the menu bars available in Microsoft Excel. The shortcut menu groups that appear in the Menu Editor cannot be accessed with the MenuBars method, as they aren't true menu bars. Use the ShortcutMenus method to access a shortcut menu, as described later in this chapter.


Activating a Menu Bar

Microsoft Excel automatically displays a built-in menu bar that's appropriate for the active sheet unless you explicitly activate a custom menu bar using a Visual Basic procedure. When you want Microsoft Excel to return to its normal menu bar behavior, you must deactivate the custom menu bar by activating the appropriate built-in menu bar.

Before you can activate a specific menu bar, you must access it using the MenuBars method, with the menu bar caption, index number, or built-in constant as an argument. You can use any of the constants in the following table as an argument to specify a built-in menu bar.

Constant | Associated menu bar
xlWorksheet |  | The menu bar displayed when a worksheet, macro sheet, or dialog sheet is active
xlChart |  | The menu bar displayed when a chart is active
xlModule |  | The menu bar displayed when when a Visual Basic module is active
xlNoDocuments |  | The menu bar displayed when no documents are open
xlInfo |  | The menu bar displayed when the Info Window is active
xlWorksheetShort |  | A short version of the worksheet menu bar (for compatibility with Microsoft Excel version 3.0)
xlChartShort |  | A short version of the chart menu bar (for compatibility with Microsoft Excel version 3.0)
xlWorksheet4 |  | An old version of the worksheet menu bar (for compatibility with Microsoft Excel version 4.0)
xlChart4 |  | An old version of the chart menu bar (for compatibility with Microsoft Excel version 4.0)

After you've accessed the custom or built-in menu bar you want to activate, use the Activate method to activate it. Microsoft Excel won't allow you to activate a built-in menu bar that isn't appropriate for the active sheet.

MenuBars(xlWorksheet4).Activate


Adding Menus

You can add a drop-down menu to any built-in or custom menu bar. Because Microsoft Excel displays different built-in menu bars when different sheet types are active (for instance, the Chart menu bar appears when you switch to a chart), you may have to add a command to more than one menu bar to make sure the user has access to the command regardless of what sheet type is active. For example, you might want to add a special Accounting menu to each menu bar so that employees in a company can run the corresponding macros from any sheet.

When you add a drop-down menu to a menu bar, you can specify an access key for the menu; the access key appears underlined when the menu is displayed. Although shortcut menus appear as "menu bar" groups in the Menu Editor, you can neither add custom shortcut menus to these menu bars nor delete built-in shortcut menus from them. You can, however, add items to or delete items from shortcut menus.

Using the Menu Editor

The Menu Editor provides a convenient way to add a drop-down menu to a built-in or custom menu bar.

To add a drop-down menu to a menu bar

1. While a Visual Basic module is active, click Menu Editor on the Tools menu.

2. In the Menu Bars box, click the name of the menu bar to which you want to add your new menu.

3. In the Menus box, click the name of the menu to the left of which you want to insert the new menu.

– Or –

To add a menu to the right of the rightmost menu on the menu bar, click End Of Menu Bar.

4. Click Insert to create the new menu.

5. In the Caption box, type the name of the new menu.

Type an ampersand (&) before the character you want to use as the access key for the menu.

Using Visual Basic

Use the Add method of the Menus collection to add a menu to the specified menu bar. The following example adds a new drop-down menu, myWorkMenu, to the left of the Help menu on the Chart menu bar.

Set newMenu = MenuBars(xlChart).Menus.Add( _
    Caption:="&MyWorkMenu", _
    before:="Help")

Note

You use an ampersand (&) in the menu name in front of the character that will be used as the access key for the menu. After the menu has been added, you can specify the menu name either with or without the ampersand when you reference the menu using the Menus method.


Adding Commands and Separator Bars

You can add commands and separator bars to any built-in or custom menu. This section deals with adding these items to drop-down menus and shortcut menus. The following section addresses the specific issues of adding submenus and then adding menu items to those submenus.

Using the Menu Editor

The Menu Editor offers an easy method for adding items to menus.

To add a menu item to a drop-down menu or shortcut menu

1. While a Visual Basic module is active, click Menu Editor on the Tools menu.

2. In the Menu Bars box, click the name of a menu bar or a group of shortcut menus.

3. In the Menus box, click the name of the menu to which you want to add the menu item or the object for which a shortcut menu is defined.

4. In the Menu Items box, click the name of the menu item above which you want to insert the new menu item.

– Or –

To add a menu item to the bottom of the menu, click End Of Menu.

5. Click Insert to create the new menu item.

6. In the Caption box, type a name for the new menu item.

Type an ampersand (&) before the character you want to use as the access key for the new menu item. To create a separator bar, type one hyphen (-).

7. To specify that a particular procedure run whenever the user clicks the new menu item, enter the name of the procedure in the Macro box.

Using Visual Basic

Use the Add method of the MenuItems collection to add a new menu item to the specified menu. You can specify the menu item caption, its position on the menu, and the name of the procedure to run when the user clicks the menu item.

The following example adds an Open Database menu item to the File menu on the Worksheet menu bar. Microsoft Excel runs the OpenDatabaseProc Visual Basic procedure whenever the user clicks the menu item. Open Database appears directly above the Close item on the File menu.

Set databaseItem = MenuBars(xlWorksheet).Menus("File") _
    .MenuItems.Add(Caption:="Open &Database", _
        OnAction:="OpenDatabaseProc", _
        before:="Close")

To place the menu item at the end of the specified menu, omit the before argument.

To create a separator bar, specify "-" for the new menu caption, as shown in the following example.

MenuBars(xlWorksheet).Menus("File").MenuItems.Add _
    Caption:="-", before:="Close"

You cannot create a new shortcut menu, but you can modify a built-in shortcut menu by adding or deleting menu items. The following example adds a Format Special menu item at the end of the Worksheet Cell shortcut menu. Notice that although shortcut menus are displayed as groups in the Menu Editor, those menu groups don't actually belong to the MenuBars collection. To access shortcut menus, you must use the ShortcutMenus method instead of the MenuBars method.

ShortcutMenus(xlWorksheetCell).MenuItems.Add _
    Caption:="Format &Special", OnAction:="FormatSpecialProc"


Adding Submenus and Submenu Items

A submenu (child menu) is a menu attached to the right side of a menu item (the submenu caption) on another menu (the parent menu). Submenus can be added to both drop-down menus and shortcut menus.

Note

A submenu caption is a menu item on the submenu's parent menu. Any commands, separator bars, or submenu captions on the submenu are also menu items; the submenu is their parent menu.

Just as you display the items on a drop-down menu by clicking the menu caption on the menu bar,you display items on a submenu by pointing to the submenu caption on the parent menu. Similarly, just as you first add an empty drop-down menu (containing a caption but no menu items) to a menu bar and then add individual menu items, you first add an empty submenu to a parent menu and then add menu items.

You can add submenu items to existing custom or built-in submenus, but you cannot add submenu items to built-in commands. For example, you can add a submenu item to the Record Macro submenu on the Tools menu, but not to the Macro command on the Tools menu. You can, however, delete a built-in command, add a custom submenu caption with the same name as the built-in command, and then add submenu items to the custom submenu.

Using the Menu Editor

To add a custom submenu using the Menu Editor, you start by adding the submenu caption as a new menu item on the parent menu. To do this, simply follow the instructions in the preceding section for adding a command to a menu, and add the submenu caption as a menu item. You don't need to specify a procedure in the Macro box. After you've added the submenu caption, you can add the submenu items. You can also add submenu items to an existing custom submenu or custom command (after you add a submenu item to a custom command, the command becomes a submenu caption).

To add a submenu item

1. While a Visual Basic module is active, click Menu Editor on the Tools menu.

2. In the Menu Bars box, click the name of a menu bar or a group of shortcut menus.

3. In the Menus box, click the name of the menu to which you want to add the submenu or the object for which a shortcut menu is defined.

4. In the Menu Items box, click the name of the menu item to which you want to add the submenu item.

5. In the Submenu Items box, click the name of the submenu item above which you want to insert the new submenu item.

– Or –

To insert a submenu item at the bottom of the submenu, click End Of Submenu.

6. Choose Insert to create the new submenu item.

7. In the Caption box, type the name of the new submenu item.

Type an ampersand (&) before the character you want to use as the access key for the new submenu item.

To create a separator bar, type one hyphen (-).

8. To specify that a particular procedure run whenever the user chooses the submenu item, enter the name of the procedure in the Macro box.

Using Visual Basic

Adding a submenu to a menu using Visual Basic entails two main steps. First, you add the submenu caption to the parent menu, and then you add submenu items to the submenu.

The AddMenu method of the MenuItems collection adds a submenu caption. You cannot add submenu items to a command or separator bar created with the Add method. (This is different from the Menu Editor, where you use the same technique to add commands, separator bars, and submenu captions.)

The following example creates a custom menu.

MenuBars(xlModule).Menus.Add "myMenu"

The following example adds a submenu caption to a menu.

MenuBars(xlModule).Menus("myMenu").MenuItems.AddMenu "mySM"

Adding items to a submenu can be confusing because you must apply the MenuItems method once to access the submenu caption (a menu item on the parent menu), and then you must apply the method again to access the collection of menu items on the submenu. The following example adds a menu item to the submenu created in the preceding example.

MenuBars(xlModule).Menus("myMenu").MenuItems("mySM") _
    .MenuItems.Add "mySMItem"

The following example places a check mark next to a menu item on a submenu.

MenuBars(xlModule).Menus("myMenu").MenuItems("mySM") _
    .MenuItems("mySMItem").Checked = True

Note

The MenuItems method returns a MenuItem object when the menu item is a command or a separator bar, and it returns a Menu object when the menu item is a submenu caption.

The following example combines the preceding four examples into one.

MenuBars(xlModule).Menus.Add("myMenu").MenuItems.AddMenu("mySM") _
    .MenuItems.Add("mySMItem").Checked = True

The following example adds a new menu to the Worksheet menu bar and then adds several new menu items and a submenu to the new menu.

Sub AddNewMenu()
    Set sortMenu = MenuBars(xlWorksheet).Menus.Add("&Sort By")
    With sortMenu.MenuItems
        .Add "Company Name", "SortByCompany"
        .Add "Category ID", "SortByCategory"
        .Add "Type", "SortByType"
        .Add ("-")
        .Add "Random", "SetRandomOrder"
        Set sortSubMenu = sortMenu.MenuItems _
                .AddMenu("Cost", before:="-")
            sortSubMenu.MenuItems.Add "Ascending", "SortByCostAscending"
            sortSubMenu.MenuItems.Add "Descending", _
                "SortByCostDescending"
    End With
End Sub


Deleting Menu Components

You can delete built-in or custom items from menus; you can delete built-in or custom menus from menu bars; and you can delete custom menu bars. Note, however, that although you can delete all the items on shortcut menus and built-in menu bars, you cannot delete the shortcut menus or built-in menu bars themselves.

Deleting built-in menu components can help you tailor your application to the needs of your user. For example, you might want to delete a built-in command from a menu and replace it with a custom version of the command that performs specialized tasks for the user. Or you might want to remove certain menu items to simplify the interface or reduce the possibility that inexperienced users will choose commands you didn't intend for them to use.

Note

You can restore built-in menu bars, menus, or menu items that you've deleted. However, you cannot restore custom menu bars, menus, or menu items that you've deleted; you must recreate them.

Using the Menu Editor

The Menu Editor provides a quick, simple way to delete menu components. Remember that changes you make in the Menu Editor will be in effect whenever the workbook where you made the changes is open. If you want to restore built-in components that you've deleted, you must open the Menu Editor from the workbook where you originally made the deletions. For more information, see the following section.

To delete a menu system component

1. While a Visual Basic module is active, click Menu Editor on the Tools menu.

2. In the appropriate box, click the name of the menu bar, menu, menu item, submenu item, or shortcut menu item that you want to delete.

3. Click Delete.

Using Visual Basic

Use the Delete method to delete a custom menu bar, a custom or built-in drop-down menu or submenu, or a custom or built-in menu item. You cannot delete a built-in menu bar or a shortcut menu.

The following example deletes the custom menu bar that has the caption myWorksheetMenubar.

MenuBars("myWorksheetMenubar").Delete

This example deletes the Edit menu from the Chart menu bar.

MenuBars(xlChart).Menus("Edit").Delete

This example deletes the Group menu item from the Drawing Object shortcut menu.

ShortcutMenus(xlDrawingObject).MenuItems("Group").Delete

You can restore built-in components that you've deleted. For more information, see the following section.


Restoring Built-in Menu Components

You can restore built-in menu bars, menus, or menu items that you've deleted. However, you cannot restore custom menu bars, menus, or menu items that you've deleted; you must recreate them.

Using the Menu Editor

If you want to restore built-in components that you've deleted using the Menu Editor, you must open the Menu Editor while the workbook where you originally made the deletions is active. You can restore menu components one at a time, or you can restore the entire default menu system for the active workbook at once. The Menu Editor cannot restore components deleted with Visual Basic code.

To restore a deleted menu item

1. While a Visual Basic module is active, click Menu Editor on the Tools menu.

2. Select the Show Deleted Items check box.

Deleted menu items appear dimmed.

3. In the appropriate box, select the deleted item that you want to restore.

4. Click Undelete.

To restore all the built-in menu bars, menus, menu items, and submenu items (that is, the entire default menu system) at once, click Restore All.

Caution

Clicking Restore All not only restores deleted built-in components, but it also deletes from the active workbook every custom menu bar, menu, menu item, and submenu item that was added with the Menu Editor. Unless you're absolutely sure that there are no custom menu components you want to save, you should restore any deleted components one by one, using the foregoing procedure.

Using Visual Basic

Use the Reset method of the MenuBars collection to restore a built-in menu bar and all the menu components it contains to their default configuration.

MenuBars(xlWorksheet).Reset

Caution

Be careful when you use this method; the Reset method not only restores any deleted built-in components of the menu bar, but it also deletes any custom components that have been added. Keep in mind that another macro may have added custom components to the menu bar in question, and resetting the menu bar will remove these as well. In addition, resetting the menu bar may cause conflicts with the menu editing lists of open workbooks. To avoid these problems, remove any menu components that your macro has added (and restore any menu components that you've deleted) one by one, without resetting the entire menu bar.

Set the restore argument of the Add method to True to restore a previously deleted built-in drop-down menu, shortcut menu, or menu item. To restore a previously deleted built-in submenu, set the restore argument of the AddMenu method to True. The following example restores the previously deleted Edit menu to the Chart menu bar.

MenuBars(xlChart).Menus.Add caption:="Edit", _
    before:="View", restore:=True

This example restores the previously deleted Open menu item to the File menu on the Worksheet menu bar.

MenuBars(xlWorksheet).Menus("File").MenuItems.Add _
    caption := "Open...", _
    restore := True, _
    before := "Close"

This example restores the previously deleted Protection submenu to the Tools menu on the Visual Basic Module menu bar.

MenuBars(xlModule).Menus("Tools").MenuItems.AddMenu _
    caption := "Protection", _
    restore := True, _
    before := "Add-Ins..."

Note

If you omit the restore argument, Visual Basic adds a custom command that has the same name as the deleted built-in command but lacks its built-in functionality. If you omit the before argument, Visual Basic places the restored command at the end of the menu, rather than in its original position.


Run-Time Modifications to the Menu System

The menu system that you create at design time can be programmed to respond dynamically to changing conditions at run time. If a particular menu item is an inappropriate choice in certain contexts, you can prevent the user from selecting it by removing it or disabling it (also called dimming the menu item, or making it gray). If a menu item represents an option with two possible states, you can place a check mark next to it to show that the option is turned on and remove the check mark to show that it's turned off. For example, the Microsoft Excel default menu system uses a check mark on the Record Macro submenu on the Tools menu to show that the Use Relative References option is turned on.

Finally, you might want to rename a menu item in response to current conditions. For example, clicking the Freeze Panes command on the Windows menu causes it to be renamed "Unfreeze Panes."

Note that although you can make design-time changes to the menu system using either the Menu Editor or Visual Basic, you must use Visual Basic to make any run-time changes.


Displaying Menu Components Dynamically

If a menu component applies only to a particular sheet or workbook, it's best if that menu component appears only when that sheet or workbook is active; this reduces needless clutter in the interface. However, unlike changes made to the menu system with the Menu Editor, changes made using Visual Basic are stored globally, and their effects cannot be limited to a given workbook or sheet. You can, however, limit their lifetime to the period between the opening and subsequent closing of a particular workbook or the period between the activation and subsequent deactivation of a given sheet.

If you want a menu or menu item to appear only on a specific sheet, Visual Basic must add the component to the menu system every time the user activates the sheet and delete it every time the user deactivates the sheet. If you want to associate a menu bar with a sheet, Visual Basic can activate the menu bar when the user activates the sheet and then deactivate the menu bar when the user deactivates the sheet, rather than add the entire menu bar and then delete it. To do this, set the sheet's OnSheetActivate property to a procedure that adds or activates the component, and set the sheet's OnSheetDeactivate property to a procedure that removes or deactivates the component.

The following example causes the procedure AddNewMenu to run whenever the worksheet named "data108" is activated. This procedure adds a new menu to the Worksheet menu bar. The procedure RemoveNewMenu removes the menu when the worksheet is deactivated.

With Worksheets("data108")
    .OnSheetActivate = "AddNewMenu"
    .OnSheetDeactivate = "RemoveNewMenu"
End With

Use the Auto_Open and Auto_Close procedures attached to a workbook to add and remove menu components or to activate and deactivate a menu bar whenever that workbook is opened and closed. If you close the workbook without removing any new menus that you created while it was open, these menus will remain on the menu bar until you quit Microsoft Excel.


Enabling or Disabling Menu Components

If you want to prevent the user from choosing a particular menu item under certain conditions, you can disable it. A disabled command still appears on the menu, but it appears dimmed and doesn't respond to user actions. Use the Enabled property to enable or disable a menu item. The Enabled property is True if the menu item is enabled, and it's False if the menu item is disabled (you cannot set the Enabled property for a built-in menu item). The following example adds the Open Database menu item to the File menu on the Worksheet menu bar and then disables Open Database.

MenuBars(xlWorksheet).Menus("File") _
    .MenuItems.Add("Open Database").Enabled = False

If you want to disable all the commands on a drop-down menu, you can disable the menu itself. This effectively disables all the commands on the menu, as the user cannot access them. The following example disables the entire File menu on the Worksheet menu bar.

MenuBars(xlWorksheet).Menus("File").Enabled = False

Note

You can disable all the menu items on a submenu, but you cannot disable the submenu itself.

The following example disables all the menu items on the Cost submenu that was created by the example in "Adding Submenus and Submenu Items" earlier in this chapter.

With MenuBars(xlWorksheet).Menus("sort by").MenuItems("cost")
    For Each mnItem In .MenuItems
        mnItem.Enabled = False
    Next
End With

You can enable or disable a shortcut menu by setting the Enabled property for menu item 0 (zero). The following example disables the Worksheet Cell shortcut menu.

ShortcutMenus(xlWorksheetCell).MenuItems(0).Enabled = False


Adding or Removing a Check Mark

If a menu item represents an option that has only two states, you can add or remove a check mark next to the menu item to indicate the current state of the option. The check mark should be alternately added or removed — and the option turned on or off, accordingly — each time the user clicks the menu item.

Use the Checked property to add or remove a check mark next to a menu item. The Checked property is True if the menu item is checked, and it's False if the menu item isn't checked. To see how this works, suppose the following procedure is assigned to the custom menu item Database on the View menu on the Worksheet menu bar. This menu item offers the user the option of viewing a worksheet either in database view or in worksheet view. Every time the user clicks the Database menu item, the procedure adds or removes a check mark next to the item and then switches views.

Sub DatabaseView()
    With MenuBars(xlWorksheet).Menus("View").MenuItems("Database")
    .Checked = Not .Checked
    If .Checked Then
            'Switch to database view
            .
            .
            .
        Else
            'Switch to worksheet view
            .
            .
            .
        End If
    End With
End Sub


Renaming a Menu Item

You can use the Caption property of a menu item to change the item's name in response to changing conditions in your Visual Basic code. Suppose, for example, that you've a menu command that opens a database. After the user has opened a database, you may want to replace the original command with a command that closes the database. The following example shows how you could accomplish this.

MenuBars("MyMenubar").Menus("File").MenuItems("Open Database") _
    .Caption = "Close &Database"

When you rename a menu item this way, make sure that the other procedures in your application reference the menu item by its new name (Close Database, in this example).

You can also use variables to refer to a menu item. An advantage of this technique is that variables continue to work even if the item's caption changes. For example, the following line of code sets a variable to the Open Database menu item.

Set myMenu = MenuBars("My Menubar").Menus _
    ("File").MenuItems("Open Database")

You can change the caption later using the following code.

myMenu.Caption = "Close &Database"


Toolbars and Toolbar Buttons

Microsoft Excel provides a system of toolbars containing toolbar buttons that the user can click to access frequently used commands. Each toolbar can appear as a bar docked at the top, at the bottom, or on either side of the application window, or as a floating window positioned anywhere on the workspace. Each toolbar button is a simple, graphical control that allows the user to exchange information with your application.

There are several types of controls that are classified as toolbar buttons.

The most common type of toolbar button is simply a button control containing a graphic. The graphic, called the button image, is a visual representation of the command or option accessed by the toolbar button. The user can click one of these toolbar buttons to execute a command (for example, clicking the New Workbook button on the Standard toolbar creates a new workbook) or to alternate between the two possible states of an option represented by a button (for example, clicking the Bold button on the Formatting toolbar alternately applies and removes bold formatting from selected text).

Another type of toolbar button is composed of a button control containing a graphic and an attached drop-down palette. The user clicks the drop-down arrow to display a palette and chooses an option from the palette. The user clicks the button control to apply the current option. For example, clicking the drop-down arrow of the Font Color button displays a palette of font colors. Clicking the button control of this toolbar button applies the color to the selected text.

A combination drop-down edit box can also be a toolbar button. The user either types text in the box or clicks the drop-down arrow and then clicks an item in the list. For example, you can set the font size of the selected text by either clicking an item in the drop-down list contained in the Font Size button or typing an entry in the edit box.

The last type of toolbar button is the TipWizard® box, which consists of a text box containing tips pertinent to the user's current task and a spinner that lets the user browse through tips.

To display any Microsoft Excel toolbar, click Toolbars on the View menu, and then click the name of the toolbar you want to display. To see additional available buttons, click Customize in the Toolbars dialog box, and browse through the items in the Categories box.

Now that you understand what toolbars and the various types of toolbar buttons are, you can study the specifics of modifying the toolbars and toolbar buttons described in the preceding paragraphs. In the following sections, you will learn how to customize toolbars, how to control the availability of the toolbar changes you've made, and how to make specific types of changes.


Guidelines for Customizing Toolbars

Microsoft Excel offers you a wide range of ways to modify the built-in toolbar system to better serve the needs of the user. You can create new toolbars; add new toolbar buttons to built-in or custom toolbars; modify the image on a toolbar button face; and assign macros, ToolTip text, and status bar text to toolbar buttons. If a toolbar button contains an edit box or a text box, you can adjust the width of the box.

Whether you modify a built-in toolbar or create a new one depends on the extent of the changes you want to make. Modifying a built-in toolbar makes sense if you're adding or changing only a few toolbar buttons; creating a new toolbar may be more convenient if you want to provide an entirely different assortment of commands than are found on any of the built-in toolbars or if you want to present a number of custom toolbar buttons as a distinct group. Regardless of how many changes you make, you can restore the built-in menu system to its default state whenever you want.

In addition to the above changes, which are usually made at design time, you can use Visual Basic procedures to change the properties of toolbars and toolbar buttons in response to user input while your application is running (at run time). For example, you can hide a toolbar when the user no longer needs it, move or resize a toolbar to keep it out of the user's way, disable a toolbar button to prevent the user from clicking it at an inappropriate time, or switch between the "pushed" appearance and the "not pushed" appearance of a toolbar button every time the user clicks it.


Scope of the Changes

Besides making changes to the system of toolbars, you can control the scope of the changes by choosing whether to store them with the workspace or with a workbook.

Storing Toolbars in a Workspace or a Workbook

Custom toolbars can be stored with the workspace or with the workbook. When you quit Microsoft Excel, the toolbars in the workspace are saved in the file Username.xlb (where Username is the Windows 95 logon name of the current user). If the user isn't logged on, the filename is Excel5.xlb. The toolbars saved in a workbook are stored in the workbook file.

Workbook-level toolbars make it easier to create a polished user interface for a custom application, such as an add-in, and to distribute custom toolbar buttons and their supporting procedures. If you're going to distribute a custom toolbar with a custom application, you should attach it to the workbook containing the application so that the toolbar is stored in the same file as the application.

To move a toolbar from the workspace to a workbook

1. While a Visual Basic module is active, click Attach Toolbars on the Tools menu.

2. In the Custom Toolbars box, click the name of the toolbar you want to copy to the active workbook.

3. Click Copy.

The name of the toolbar you copied appears in the Toolbars In Workbook box.

You can delete the original workspace-level toolbar by clicking Toolbars on the View menu, selecting the check box next to the name of the toolbar you want to delete, and then clicking Delete. If you don't delete the workspace version of the toolbar, you can change it without affecting the version stored in the workbook. If you make changes to the workspace version of the toolbar and would like to update the workbook version to match it, you can copy the current workspace version of the toolbar to the workbook again, replacing the previous workbook version.

After you've copied a toolbar to a workbook, the toolbar becomes available only after the user has opened that workbook. A workbook toolbar retains not only the name and contents of the toolbar, but also the assignment of code to toolbar buttons; the location, size, and shape of the toolbar; its on-screen position; and whether it's visible or hidden.

You can also delete a workbook toolbar.

To delete a workbook toolbar

1. While a Visual Basic module is active, click Attach Toolbars on the Tools menu.

2. In the Toolbars In Workbook box, click the name of the toolbar you want to delete.

3. Click Delete.

How Workbook and Workspace Toolbars Interact

When you open a workbook that contains one or more toolbars, Microsoft Excel first determines whether a workspace toolbar with that name already exists. If not, Microsoft Excel creates a new workspace toolbar and copies the workbook toolbar into it. This way, the you get a fresh copy of the toolbar that you can alter by hiding it or by copying toolbar buttons to or from the workspace-level copy of the toolbar. When you quit Microsoft Excel, changes made to this copy of the toolbar are stored with the workspace file.

There is no way to rename the toolbar, so when the workbook or add-in is reopened, the workspace already contains a toolbar with the same name as the workbook toolbar, and Microsoft Excel uses the workspace copy rather than reloading the workbook toolbar. However, the procedures that support the toolbar buttons in the open workbook still run when the user clicks the corresponding toolbar button.

As a developer, you can design a toolbar and then attach it to an add-in workbook, as shown in the preceding section. When the user opens the add-in workbook, the custom add-in toolbar appears. The user can then edit it and move toolbar buttons from it to personal toolbars, without affecting the copy stored in the add-in workbook. The user's changed toolbars are stored with the workspace file when he or she quits Microsoft Excel. When the user starts Microsoft Excel again, the edited toolbar appears; clicking one of the developer's toolbar buttons loads the add-in workbook containing the procedure attached to that toolbar button. To generate a fresh copy of the workbook toolbar, the user can delete the edited copy.


Design-Time Modifications to Toolbars and Toolbar Buttons

The simplest way to make design-time changes to toolbars or toolbar buttons is from the user interface. To display the Customize dialog box, click Toolbars on the View menu, and then click Customize.

With the Customize dialog box open, you can create a new toolbar, add new or built-in toolbar buttons to a toolbar, delete toolbar buttons from a toolbar, adjust spacing between toolbar buttons, and change the width of a toolbar button containing an edit box. You can use the Button Image Editor to customize the image associated with a particular toolbar button; and you can use the Assign Macro dialog box to assign a procedure that runs when the user clicks that toolbar button.

Although the user interface provides the most practical way to make design-time changes to the toolbars, you can also make these changes using Visual Basic. If you want to see how Visual Basic would make a particular change, turn on the macro recorder, make the change manually, stop the recorder, and then examine the code that the macro recorder has produced. If you want more information about a specific object, property, or method that you find in the code, click anywhere in the term in question, and press F1. For more information about using the macro recorder, see "Recording and Running Macros" in Help.


Run-Time Modifications to Toolbars and Toolbar Buttons

If you want to make changes to toolbars and toolbar buttons while your application is running, you must use Visual Basic procedures to access the Toolbar and ToolbarButton objects and apply the appropriate properties or methods. For more information about using these objects, see "Toolbar Object" and "ToolbarButton Object" in Help.

Note

Be careful when you use the toolbar button index number to access a member of the ToolbarButtons collection. The index number represents the position of the button on the toolbar, and this number can change when buttons are added to or deleted from the toolbar.


Displaying or Hiding Toolbars

A toolbar takes up screen space that could otherwise be used to display data; you can display a toolbar when necessary and hide it when the user no longer needs it. A toolbar is visible if its Visible property is True, and it isn't visible if this property is False. Setting this property to True corresponds to selecting the check box next to the name of the toolbar in the Toolbars dialog box and then clicking OK.

For example, the following procedure, assigned to the View MyToolbar menu item on the View menu, toggles the value of the Checked property of the menu item and the visible property of the toolbar every time the user clicks the menu item. When the toolbar is made visible, it reappears in the same position it occupied when it was made invisible.

Sub ViewMyAppToolbar()
    With MenuBars(xlWorksheet).Menus("View").MenuItems("View MyToolbar")
        .Checked = Not .Checked
        Toolbars("MyAppTools").Visible = .Checked
    End With
End Sub

When a toolbar is visible, the user can click any toolbar button on it to run that button's assigned procedure.


Moving and Resizing Toolbars

You may want to adjust the prominence of a toolbar on the screen in response to changing conditions while your application is running. To do this, you can change the size or position of the toolbar. Toolbars support several properties that you can use to resize them; to dock them at the top, bottom, left, or right edge of the workspace; or to position them elsewhere on the screen (if they're floating toolbars). For more information about the properties and methods you can use with Toolbar objects, see "Toolbar Object" in Help, and use the jumps at the top of the topic to display the lists of properties and methods.


Restoring a Built-in Toolbar

If one of the default toolbars has been modified — either by a user or by a Visual Basic procedure — you can return the toolbar to its default state by using the Reset method. Using this method corresponds to clicking the Toolbars command on the View menu, selecting the check box next to the name of the customized built-in toolbar in the Toolbars dialog box, and then clicking Reset.

For example, you can use the following code to reset all the toolbars to their default state and simultaneously delete all the custom toolbars.

For Each thisToolbar In Toolbars
    If thisToolbar.BuiltIn Then
        thisToolbar.Reset
    Else
        thisToolbar.Delete
    End If
Next

Caution

Be careful when you use the Reset method; it not only restores any built-in toolbar buttons that have been deleted, but it also deletes any custom toolbar buttons that have been added. Keep in mind that another macro may have added custom toolbar buttons to the toolbar, and resetting the toolbar will remove these buttons as well. To avoid these problems, remove any toolbar buttons added by your application one by one, without resetting the entire toolbar.


Adding and Deleting Toolbar Buttons

If you want a specific toolbar button to appear on a toolbar only under certain conditions, you can add and delete the button at run time. When you add a toolbar button, you can attach a macro to it or change the ToolTip text associated with it.

The Add method for the ToolbarButtons collection adds a new toolbar button to an existing built-in or custom toolbar. The onAction argument of the Add method specifies the procedure that will run when the user clicks the toolbar button.

Use the Name property for the new toolbar buttons to set the ToolTip text (the text that appears beneath a toolbar button when the mouse pointer is directly over that button). To set the status bar text (the text that appears appears in the status bar when the mouse pointer is directly over a button), use the statusBar argument of the Add method.

The following example adds two toolbar buttons, separated by a gap, to the toolbar "MyAppTools."

With Toolbars("MyAppTools").ToolbarButtons

    ' Add a button with the clock face
    Set newButton1 = .Add( _
        Button:=213, _
        before:=1, _
        OnAction:="Module1.MyScheduler", _
        Enabled:=True, _
        Pushed:=False, _
        StatusBar:="Run custom scheduler")    ' sets status bar text
    newButton1.Name = "Scheduler"            ' sets tool tip text

    ' Add a button with the scissors face
    Set newButton2 = .Add( _
        Button:=12, _
        before:=2, _
        OnAction:="Module1.MyCutProc", _
        Enabled:=True, _
        Pushed:=False, _
        StatusBar:="Custom cut command")        ' sets status bar text
    newButton2.Name = "Custom Cut"            ' sets tool tip text

    ' Add a space between the buttons
    .Add Button:=0, before:=2
End With

If you don't specify a position for a new toolbar button, the button is added at the end of the toolbar. If you don't specify a procedure to run when the toolbar button is clicked and it's a built-in button, the default action occurs. If you don't specify a procedure for a custom toolbar button, nothing happens when the button is clicked.

The Delete method deletes a toolbar button. The following example deletes toolbar button three from the Standard toolbar.

Toolbars("Standard").ToolbarButtons(3).Delete


Enabling or Disabling Toolbar Buttons

You may want to control the availability of a toolbar button while your application is running, to prevent the user from clicking the button at inappropriate times. To do this, you can dynamically enable and disable the toolbar button. When a toolbar button is disabled, it beeps when it's clicked and doesn't run the procedure associated with it. The Enabled property sets or returns the state (enabled or disabled) of a toolbar button.

The following example disables button three on the Standard toolbar.

Toolbars("Standard").ToolbarButtons(3).Enabled = False


Making Custom Toolbar Buttons Look Pressed

If a toolbar button represents an option with two possible states, you can change the appearance of the toolbar button to indicate the current state of the option: When the option is turned on, the associated button looks pressed; when the option is turned off, the button looks raised. This is analagous to placing or removing a check mark next to a menu item.

The Pushed property for a toolbar button is True if the button appears pressed, and it's False if the button doesn't appear pressed. For example, the following procedure, assigned to a new Database View toolbar button, changes the appearance of the toolbar button before switching between special views on the worksheet.

Sub DatabaseView()
    With Toolbars("MyAppToolbar").ToolbarButtons(3)
        .Pushed = Not .Pushed
        If .Pushed Then
            'Switch to database view
            .
            .
            .
        Else
            'Switch to worksheet view
            .
            .
            .
        End If
    End With
End Sub


Chapter 10 Communicating with Other Applications

In addition to working with Microsoft Excel data, you may want your application to exchange data with other applications, such as Microsoft Project, Word, or PowerPoint®. There are several ways to communicate with other applications, including OLE automation, dynamic data exchange (DDE), and dynamic-link libraries (DLLs). This chapter shows you how to use these methods to communicate with other applications.

Contents
  • Using OLE Automation from Microsoft Excel
  • Using Dynamic-Link Libraries
  • Using Dynamic Data Exchange
  • Sending Keystrokes


Using OLE Automation from Microsoft Excel

OLE Automation is a feature (introduced in Microsoft OLE version 2.0) that allows you to retrieve, edit, and export data by referencing another application's objects, properties, and methods. Objects that can be returned from outside the application are OLE Automation objects. An application that exposes its OLE Automation objects to other applications is called an OLE server application. An application that can access and manipulate OLE Automation objects is called an OLE controller application. Not all applications support OLE Automation; the applications that do support it are said to be OLE compatible.

To exchange data with another application by using OLE Automation while working in Microsoft Excel, you first create a reference to the application you want to communicate with (the OLE server application). Then, using the objects, properties, and methods of the other application, you add, change, or delete information. When you finish making changes, you close the OLE server application from inside the OLE controller application.


Referring to Another Application

When you refer to another application by using OLE Automation, you actually refer to one of the application's top-level objects. The task you want to accomplish determines the object you refer to. The following table shows the most common top-level objects for Microsoft Project and Word; for a more complete list of the top-level objects in Office applications, see the Microsoft Solutions Development Kit.

To return | From this application | Use this class name
A reference to the Microsoft Project Application object, which allows you to use all of Microsoft Project's objects, properties, and methods | Microsoft Project | MSProject.Application
A reference to a new Project object or a reference to the Project object specified in the GetObject method, which allows you to work with a specific project | Microsoft Project | MSProject.Project
A reference to the WordBasic object, which allows you to run WordBasic statements | Word | Word.Basic

There are two ways to refer to a top-level object using OLE Automation from Microsoft Excel. One way is to refer to the application's object library using the References dialog box.

To establish a reference to an application's object library

1. Switch to a Visual Basic module.

2. On the Tools menu, click References.

3. Click the object library you want to refer to.

If the object library you want doesn't appear in the Available References box, click Browse and then locate the file you want.

After you've established a reference to an object library, you can use commands from the library in your Microsoft Excel Visual Basic code. For example, after you've established a reference to the Word object library, you can use a command such as FileOpen. However, referring to objects this way can yield unpredictable results, because you cannot always be sure which object will be returned. The preferred way is either to use the CreateObject method to start the application and return a reference to a top-level object or to use the GetObject method to return a reference to a top-level object from an application that's already running. For more information about these methods, see the following sections.

Note

An object library is a catalog of an application's objects, properties, and methods. Any application that registers object libraries in the Windows system registry allow other applications to use its objects, properties, and methods as if they were native to that application.

Word exposes three top-level objects: the Application object, the CurValues object, and the WordBasic object. The WordBasic object is the most commonly used of the three because you execute all WordBasic commands by first referring to this object.

The CreateObject Method

The CreateObject method starts a new instance of an application invisibly and returns a reference to a new top-level object. The following code loads Microsoft Project into memory and returns the Microsoft Project Application object.

Dim projapp As Object

Set projapp = CreateObject("MSProject.Application")

The following example returns a Project object instead of the Application object, specifying the Project class name in the CreateObject argument.

Dim projapp As Object

Set projapp = CreateObject("MSProject.Project")

The GetObject Function

The GetObject function returns a top-level object reference from an application that's is already running. The pathName argument can be either the complete path to an existing file or an empty string, or it can be omitted altogether. If you omit this argument, you must supply the class argument; the function will then create a new instance of the application. An error will be returned if the path you specify doesn't exist. For more information about the syntax for the GetObject function, see "GetObject function" in Help.

The following code returns the Microsoft Project Application object from an instance of Microsoft Project that's already loaded into memory. You can return a Project object instead by specifying the Project class name in the GetObject argument.

Dim projapp As Object

Set projapp = GetObject("", "MSProject.Application")


Retrieving Data

After you set an object variable to the top-level object of an application, you can use the application's objects, properties, and methods to retrieve data. The following code searches a Microsoft Project file for information and returns the information to a range on Sheet1 in the active Microsoft Excel workbook.

Dim proj as Object
Dim nameoftask As String
Dim writetime As Integer, edittime As Integer, incorptime As Integer
Dim busytime As Integer, i As Integer, mecount As Integer
Dim othercount As Integer, timespent As Integer

Set proj = GetObject("c:\winproj\MyProject.mpp", "msproject.project")
mecount = 0
othercount = 0

For i = 1 To proj.tasks.Count
    If proj.tasks(i).Resources.Count > 0 Then
    With proj.tasks(i)
        If .Resources(1).Name = "Jane Smith" Then
            timespent = .Duration
            Select Case .Name
                Case "write"
                    writetime = writetime + timespent
                Case "incorp. tech review"
                    incorptime = incorptime + timespent
                Case "edit incorp.", "review/edit merged art"
                    edittime = edittime + timespent
                Case "art to designer", "hand-off to production"
                    busytime = busytime + timespent
                Case Else
                MsgBox "Error " & .Name
            End Select
        End If
    End With
    End If
Next i

With Worksheets("sheet1")
    .Range("B1") = writetime
    .Range("B2") = incorptime
    .Range("B3") = busytime
    .Range("B4") = edittime

    .Range("A1") = "Writing"
    .Range("A2") = "Adding Changes"
    .Range("A3") = "Other"
    .Range("A4") = "Editing"
End With

proj.Application.Quit


Changing Object Properties

After data is inserted into a worksheet, the data belongs to Microsoft Excel. You can then convert that data to a Microsoft Excel chart and customize the chart by changing its properties. The following code charts the data retrieved from Microsoft Project and customizes the chart by adding a legend and a blue title.

Dim newEmbeddedChart As ChartObject

Set newEmbeddedChart = Worksheets(1).ChartObjects.Add(50, 50, 250, 250)
With newEmbeddedChart.Chart
    .ChartWizard Source:=Worksheets(1).Range("A1:B4"), _
        Gallery:=xlPie, Format:=7, PlotBy:=xlColumns, _
        CategoryLabels:=1, SeriesLabels:=0, HasLegend:=2
    .HasTitle = True
    .ChartTitle.Text = "My Schedule"
    .ChartTitle.Font.Color = RGB(0, 0, 255)
    .HasLegend = True
End With


Exporting Data

In addition to importing data into Microsoft Excel from another application, you may also want to export data from Microsoft Excel to another application so that you can create a presentation with it or combine it with other data.

Exporting Data to PowerPoint

You may want to present your data in an application other than Microsoft Excel. The following example charts the data from Sheet1 in the active workbook (the imported data from Microsoft Project) and places it in a PowerPoint slide for presentation. The code starts the PowerPoint application, creates a presentation, and adds one slide to it. The slide is then prepared to accept a chart, and you can chart the data from Sheet1 by using the Microsoft Excel ChartWizard.

Set pptApp = CreateObject("PowerPoint.Application.7")
Set pptPres = pptApp.Presentations.Add
Set pptSlide = pptPres.Slides.Add(1, 1)
Set pptSlideObj = pptSlide.Objects _
    .AddOleObject("Excel.Chart", 1000, 1000, 5000, 5000)
Set pptChart = pptSlideObj.Object
With pptChart
    .ChartWizard Source:=Worksheets("sheet1").Range("A1:B4"), _
        Gallery:=xlPie, Format:=7, PlotBy:=xlColumns, _
        CategoryLabels:=1, SeriesLabels:=0, HasLegend:=2
    .HasTitle = True
    .ChartTitle.Text = "My Schedule"
    .ChartTitle.Font.Color = RGB(0, 0, 255)
    .HasLegend = True
End With
pptPres.SaveAs "MayWork.ppt"

Exporting Data to Word

The customized Chart object that the example in the preceding section creates can be placed in a Word document by means of OLE Automation. However, the approach is different because you use WordBasic statements and functions instead of objects, properties, and methods to refer to and work with the WordBasic object.

The following example takes the first Chart object from Sheet1 in the active workbook, copies it to the Clipboard, and pastes it into the Word document called "MyDoc.doc."

Dim wdbasic As Object

Worksheets("sheet1").ChartObjects(1).Copy
Set wdbasic = CreateObject("word.basic")
With wdbasic
    .FileOpen "C:\msoffice\winword\MyDoc.doc"
    .EditPaste
    .FileSave
End With

Note

The preceding example embeds the chart in the Word document. To link the chart into the Word document, use the EditPasteSpecial method. For more information about linking and embedding, see "Communicating with Embedded Word Objects" later in this chapter.

Using Conventional Arguments

When you use WordBasic commands as part of OLE Automation, you must use conventional arguments instead of named arguments — that is, you must specify arguments by position instead of by name. If you leave out a conventional argument, you must indicate the missing value with a comma; you can, however, omit trailing commas. The following line of WordBasic code uses named arguments to apply drop cap formatting.

FormatDropCap .Position = 1, .Font = "Arial", .DropHeight = "3", \
    .DistFromText = "6"

The following Visual Basic code does the same thing as the preceding example, but using conventional arguments. Your code must have already created the object variable wordobj and opened a file in Word before you run this line.

wordobj.FormatDropCap 1, "Arial", 3, 6

Note

The syntax for most statement and function entries in WordBasic Help describes the correct order for conventional arguments. There are some exceptions, however. For a complete list of these exceptions and the correct order of their arguments, see the Position.txt file included on the companion disk in the Microsoft Word Developer's Kit.

Running a Macro from Outside Word

In addition to calling individual WordBasic commands, you can use the ToolsMacro command to run existing Word macros from outside Word. The following code runs a Word macro called "CreateDocandFormat." For more information about the ToolsMacro command and its arguments, see "ToolsMacro" in Help.

Dim wordobj As Object

Set wordobj = CreateObject("Word.Basic")
wordobj.toolsmacro "CreateDocandFormat", True


Quitting Applications

Because OLE Automation objects can use a significant amount of memory, you should explicitly close an object when you no longer need it. Many OLE Automation objects support a Quit method that closes an object and quits the OLE server application from inside the OLE controller application. The following code explicitly closes Microsoft Project.

proj.Application.Quit

Setting an object variable to "nothing" both releases the object variable and closes the OLE server application. The following code opens a document in Word and then sets the variable to "nothing," thereby closing the OLE server application.

Dim wdBasic As Object

Set wdBasic = CreateObject("word.basic")
wdBasic.FileOpen "C:\msoffice\winword\Speedup.doc"
Set wdBasic = Nothing


Communicating with Embedded Word Objects

When you embed a Word document in a Microsoft Excel worksheet, Microsoft Excel controls the object, and Word controls everything inside the object.

A linked object is an object that contains a reference pointer to its application. Data associated with a linked object isn't stored within the application that contains the object. If you change data in a linked application, the data will change in the original application as well.

An embedded object is an object that contains a "snapshot" of data existing at the time you embedded the object. Data associated with an embedded object is stored in the file in which the object is embedded. If you change data in an embedded object, the data in the original application doesn't change.

An OLE container application is an OLE-based application that can store embedded or linked objects provided by OLE object applications. An OLE object application is an application that exposes the OLE object.

Editing an Embedded Word Object

To edit a Word document embedded as an OLE object, you must activate it before you can refer to one of the top-level objects. The following example activates and edits a Word document, which is the first OLE object on Sheet1.

Dim wordobj As Object

Worksheets("sheet1").OLEObjects(1).Verb
Set wordobj = Worksheets("sheet1").OLEObjects(1).Object _     .Application.WordBasic
With wordobj
    .Insert "This is the new first line."
    .InsertPara
    .LineUp 1
    .EndOfLine 1
    .Bold
    .LineDown 1
End With

Note

Using the Verb method with no arguments, as demonstrated in the preceding example, is equivalent to using the Activate method. For information about the arguments you can use with the Verb method, see "Verb method" in Help.

Printing an Embedded Word Object

To print a Word document that's embedded on a Microsoft Excel sheet, first activate the embedded document, and then use the WordBasic FilePrint command. The following example activates, edits, and prints a Word document, which is the first OLE object on Sheet1.

Dim wordobj As Object

Worksheets("sheet1").OLEObjects(1).Verb
Set wordobj = Worksheets("sheet1").OLEObjects(1).Object _     .Application.WordBasic
With wordobj
    .Insert "Dear Mrs. Jones:"
    .InsertPara
    .FilePrint
    .FileClose
End With


Using Dynamic-Link Libraries

A dynamic-link library (DLL) is a library of routines loaded into memory and linked to applications at run time. DLLs are usually created in a programming language such as C, MASM, Assembler, or FORTRAN, and they contain procedures you call in your application. You can call DLL functions from Visual Basic in Microsoft Excel. For more information about DLLs, see the Microsoft Excel Developer's Kit.


Using Dynamic Data Exchange

Dynamic data exchange (DDE) is a mechanism that permits two applications to communicate by automatically and continuously exchanging data. Many applications that don't yet support OLE Automation support DDE. To run a DDE conversation between applications, you establish a channel, select a topic, request and send data, and then close the channel when you finish exchanging data. The following table lists the tasks that Microsoft Excel performs with DDE and the method used for each task.

Task | Method
Starting DDE | DDEInitiate
Getting text from another application | DDERequest
Sending text to another application | DDEPoke
Carrying out a command in another application | DDEExecute
Ending DDE | DDETerminate

Note

Not all applications support DDE. To find out whether an application supports DDE, see the documentation for that application.

The following procedure uses most of the DDE calls explained in the preceding table. The DemoDDE() procedure places the text string "I'm here" in cell A1 on Sheet1 of the active workbook.

Sub DemoDDE()
    Set dataCell = ActiveWorkbook.Worksheets("Sheet1").Range("A1")
    dataCell.Value = "I'm here!"
    ChannelNumber = Application.DDEInitiate("DDE", "Form1")
    Application.DDEPoke ChannelNumber, "Text1", dataCell
    Application.DDETerminate ChannelNumber
End Sub


Sending Keystrokes

When you're operating in the Microsoft Windows operating system, the only way to communicate with applications that don't support OLE, OLE Automation, or DDE is by sending keystrokes using the SendKeys method.

Note

You can send keystrokes only to a Windows-based application that's running. MS-DOS–based applications and Macintosh applications don't accept keystrokes.

The SendKeys method is processed when your system is idle or when the DoEvents method is called. If the wait argument of the SendKeys method is True, Microsoft Excel waits for the keys to be processed before it returns control to the procedure; if the wait argument is False, the procedure continues to run without waiting for the keys to be processed. The following example sends keystrokes to the Calculator that add the numbers from 1 to 10 and then close the Calculator.

Sub DemoSendKeys()
    returnvalue = Shell("calc.exe", 1)
    AppActivate returnvalue
    For i = 1 To 10
        SendKeys i & "{+}", True
        Next i
        SendKeys "=", True
        SendKeys "%{F4}", True
End Sub

Note

Keystrokes are sent to the active application. If the active application isn't the one you want to send keystrokes to, you need to activate it using the AppActivate statement. If the application you want to send keystrokes to isn't already running, start it using the Shell function. If you don't specifically activate another application, your DDE procedure will send keystrokes to itself.

To specify characters that aren't displayed when you press the key (such as ENTER or TAB), enclose the key code in braces ({}), and enclose the braces in double straight quotation marks. To specify a key to be used in combination with SHIFT, CTRL, or ALT, precede the braces with "+", "^", or "%", respectively. The following example sends the key combination ALT+F4.

SendKeys "%{F4}", True

For a complete list of key codes, see "SendKeys method" in Help.

Note

You cannot send keystrokes that generate interrupts instead of character codes; for example, you cannot send ALT+CTRL+DEL or print scrEEn.


Chapter 11 Automatic Procedures and OnEvent Procedures

An event in Microsoft Excel is the occurrence of an action such as opening a workbook, switching to a sheet, using a particular key combination, or recalculating a worksheet. Some events are initiated by the user; others are initiated by Microsoft Excel or by other applications. By assigning procedures to events, you can enhance or alter the way users interact with your application.

There are three main classes of event-driven procedures, organized by the way you associate the procedure with the event:

  • You can associate a procedure with the action of clicking a button or other object; you do this by using the Assign Macro command on the Tools menu, as discussed in the preceding chapters.
  • You can associate a procedure with one of a specfic set of workbook-level and worksheet-level events by giving the procedure a special automatic procedure name that begins with "Auto_".
  • You can associate a procedure with a defined event for an object by setting an OnEvent property of the object (such as the OnWindow or OnCalculate property) to the procedure name.

Contents
  • Creating Automatic Procedures
  • Creating OnEvent Procedures


Creating Automatic Procedures

An automatic procedure runs automatically whenever one of a specific set of events occurs. You can associate automatic procedures with either workbook-level or worksheet-level events.


Using Workbook-Level Automatic Procedures

A workbook-level automatic procedure is stored in a workbook and runs automatically whenever an event such as opening or closing a workbook occurs. You can place automatic procedures in any Visual Basic module in the workbook.

Workbook-level automatic procedures are identified by their names as they appear in a module — Auto_Open or Auto_Close, for example. When you name the procedure in a module, the name isn't case sensitive; therefore, Auto_Open and auto_open are equivalent.

The following table lists the automatic procedure names available in Microsoft Excel and describes the event that causes each procedure to run.

Procedure name | Event that causes the procedure to run
Auto_Open | User opens the workbook that contains the procedure.
Auto_Close | User closes the workbook that contains the procedure.
Auto_Add | User installs the add-in that contains the procedure, or the Installed property of the add-in is set to True. For more information, see Chapter 12, "Creating Add-Ins."
Auto_Remove | User removes the add-in that contains the procedure, or the Installed property of the add-in is set to False. For more information, see Chapter 12, "Creating Add-Ins."

Note

To give you more programming flexibility, the Auto_Open and Auto_Close procedures don't run if you open or close a workbook under program control. For example, the statement Workbooks.Open filename:="book2.xls" opens the workbook but doesn't run the Auto_Open procedure. To run the Auto_Open procedure under program control, use the RunAutoMacros method. For more information, see "RunAutoMacros method" in Help.

To define an automatic procedure

1. Switch to the Visual Basic module where you want to store the automatic procedure.

2. Create a new procedure named "Auto_Open," "Auto_Close," "Auto_Add," or "Auto_Remove."

3. Write the code for the procedure.

To test an automatic procedure without having to explicitly open or close the workbook, click Macro on the Tools menu, click the name of the procedure, and then click Run.

You can use at most one Auto_Open and one Auto_Close procedure in each workbook. If more than one Auto_Open or Auto_Close procedure exists in a workbook, none of them will run when the user opens or closes the workbook.

If more than one Auto_Add or Auto_Remove procedure exists in an add-in, an error occurs when the user installs or removes the add-in.

Note

You can prevent an automatic procedure from running by holding down Shift while opening or closing a workbook or switching to or from a worksheet. For example, you can hold down Shift while opening an application that's under development to avoid running any of its Auto_Open procedures.


Auto_Open Procedures

An Auto_Open procedure runs when the user opens the workbook that contains the procedure. You can use an Auto_Open procedure to set up menu bars under program control, to customize the workbook for the operating system it's running with, to display a custom startup screen, or to initiate links to other files or other applications.

For example, the following procedure automatically adds a custom menu item to the worksheet Tools menu.

Sub Auto_Open()
    MenuBars(xlWorksheet).Menus("Tools").MenuItems.Add _
        caption := "My Analysis", _
        onAction := ThisWorkbook.Name & "!Module2.MyAnalysisProc", _
        before := 1
End Sub


Auto_Close Procedures

An Auto_Close procedure runs just before the workbook containing the procedure closes. You can use this feature to restore menu bars, toolbars, and other elements of the user interface to their previous condition and to save and close the files that support an application.

You can also use an Auto_Close procedure to ensure an orderly disconnection from another application. For example, if your application uses Windows Terminal to download stock quotations from a remote information service, you probably want Terminal to log off from the service before you close the workbook, as shown in the following procedure.

Sub Auto_Close()
    MenuBars(xlWorksheet).Menus("Tools"). _
        MenuItems("My Analysis").Delete
    CloseLogFile            'Procedure: close transaction file.
    DisconnectService    'Procedure: disconnect info service.
End Sub


Using Worksheet-Level Automatic Procedures

A worksheet-level automatic procedure is associated with a specific worksheet and runs automatically when an event such as activating or deactivating a worksheet occurs. In most cases, it's better to use workbook-level automatic procedures than worksheet-level procedures. This is because when you use worksheet-level procedures, you must explicitly define procedures for each worksheet you want to support, and because these worksheet-level procedures are then not available for chart sheets and Visual Basic modules.

Worksheet-level automatic procedures are associated with defined names that begin with Auto_Open_, Auto_Close_, Auto_Activate_, or Auto_Deactivate_. These defined names aren't case sensitive; therefore, Auto_Open_ and auto_open_ are equivalent. The following table lists the automatic procedure names available in Microsoft Excel, and it describes the event that causes each procedure to run.

Beginning of procedure name | Event that causes the procedure to run
Auto_Open_ | User opens the workbook that contains the worksheet.
Auto_Close_ | User closes the workbook that contains the worksheet.
Auto_Activate_ | User activates the worksheet.
Auto_Deactivate_ | User deactivates the worksheet.

To create a defined-name automatic procedure

1. Switch to the worksheet for which you want to define an automatic procedure.

2. On the Insert menu, point to Name, and then click Define.

3. In the Names In Workbook box, type a name that begins with Auto_Open_, Auto_Close_, Auto_Activate_, or Auto_Deactivate_. Precede the name with the worksheet name, followed by an exclamation point — for example, type Sheet1!Auto_Open_First

4. In the Refers To box, type an equal sign and the name of the procedure you want to associate with the defined name; for example, =CheckData would be a valid entry in the Refers To box.

The procedure named in the Refers To box runs when the workbook that contains the worksheet is opened or closed or when the worksheet is activated or deactivated. You can use the same name you typed in the Names In Workbook box, or you can type a different name.

5. Click Add.

Note

If the procedure you want to associate with the defined name is in a different workbook, you must specify the name of the workbook, followed by an exclamation point, along with the procedure name. For example, if the CheckData procedure were in another workbook named "DataBook," you would type =DataBook!CheckData in the Refers To box.

If the procedure you want to associate with the defined name has the same name as another procedure in the same workbook, you must specify the name of the module, followed by a period, along with the procedure name. For example, to specify the CheckData procedure in the module called "DataLib" in the workbook that contains the defined name, you would type =DataLib.CheckData in the Refers To box.

To specify one of several procedures with the same name in a workbook other than the one that contains the defined name, specify the workbook name and the module name in the Refers To box; for example, type =DataBook!DataLib.CheckData.

Defined-name automatic procedures differ from standard automatic procedures in that the name defined on the worksheet needs only to begin with the name of the type of the procedure you want to run for the event. For example, you can define the names Auto_Open_Public, Auto_Open_StartupScreen, and Auto_Open_Files on the same worksheet; when the user opens the workbook containing the worksheet, the procedures associated with all three names run.

Standard automatic procedures run before defined-name procedures. For example, suppose that you place an Auto_Open procedure in a module, and on a certain worksheet you define the name Auto_Open_ThisWorksheet as the text StartupWorksheet. When the user opens the workbook, the workbook-level Auto_Open procedure runs before the StartupWorksheet procedure. Note that you cannot set the order in which the Auto_Open procedures defined in a worksheet will run.

Note

You can prevent an automatic procedure from running by holding down Shift while opening or closing a workbook or switching to or from a worksheet. For example, you can hold down Shift while opening an application that's under development to avoid running any of its Auto_Open procedures.


Creating OnEvent Procedures

Certain objects in Visual Basic have properties and methods that are associated with specific events. For example, the Button object has an OnAction property, which is associated with clicking the button; and the Application object has an OnRepeat method, which is associated with clicking Repeat on the Edit menu. These events are generated by Microsoft Excel, sometimes as the result of user input. An example of an event that isn't the result of user input is the arrival of data from another application by means of OLE (see the OnData property).

If you associate a procedure with one of these properties or methods, that procedure — called an OnEvent procedure or an event handler — will run whenever the event associated with the property or method occurs.

The following table lists the properties and methods you can use to trap events.

Property or method | Event that causes the associated procedure to run
OnAction | Clicking a control or graphic object, clicking a menu command, or clicking a toolbar button
OnCalculate | Recalculating a worksheet
OnData | The arrival of data from another application by way of DDE or OLE
OnDoubleClick | Double-clicking anywhere on a chart sheet, dialog sheet, module, or worksheet
OnEntry | Entering data using the formula bar or editing data in a cell
OnKey | Pressing a particular key or key combination
OnRepeat | Clicking Repeat on the Edit menu
OnSheetActivate | Activating a chart sheet, dialog sheet, module, worksheet, workbook, or Microsoft Excel itself
OnSheetDeactivate | Deactivating a chart sheet, dialog sheet, module, worksheet, workbook, or Microsoft Excel itself
OnTime | Waiting until a specific time arrives, or waiting for a specified time delay
OnUndo | Clicking Undo on the Edit menu
OnWindow | Activating a window

There are several steps involved in creating and using any type of OnEvent procedure:

  • You must create the procedure (the event handler) you want to run when the specified event occurs.
  • Elsewhere in your Visual Basic code, you must associate the event handler with the event you want to respond to. After the statement that associates the event with its handler is executed, the handler runs whenever the event occurs; this is called trapping the event.
  • When you want to stop trapping this event, you must disassociate the event from the event handler.

To associate an event with an OnEvent procedure

Set the property associated with the event — or set the procedure argument of the method associated with the event — to the name of the OnEvent procedure, as shown in the following examples.

ActiveSheet.Buttons("MyButton").OnAction = "ButtonClickHandler"
Application.OnRepeat text:= "Paste Again", procedure:= "PasteAgain"

To disassociate an event from an OnEvent procedure

Set the property associated with the event — or set the procedure argument of the method associated with the event — to the empty string (""), as shown in the following examples.

ActiveSheet.Buttons("MyButton").OnAction = ""
Application.OnRepeat text:= "Paste Again", procedure:= ""

The following sections show how event trapping is done with specific types of events.


OnAction Property

An OnAction event handler runs when you act on a control or when you click a graphic object or a toolbar button. For example, if you create a custom dialog box, you can use the OnAction property of each control in the dialog box to associate the controls with their event handlers. Unlike other OnEvent properties and methods, the OnAction property of a control retains its value between sessions, so you don't have to run a procedure to set its value at the beginning of each session.

The following example causes the StartDialog procedure to run when the dialog box first starts, and it causes the ButtonPressed procedure to run whenever the user presses a button on the first dialog sheet.

With DialogSheets(1)
    .DialogFrame.OnAction = "StartDialog"
    .Buttons.OnAction = "ButtonPressed"
End With

Note that you can also set the OnAction property for a control by selecting the control, clicking Assign Macro on the Tools menu, and entering a procedure name in the Macro Name/Reference box.

For more information about using the OnAction property, see Chapter 8, "Controls and Dialog Boxes," and Chapter 9, "Menus and Toolbars," or see the appropriate topic in Help.


OnCalculate Property

An OnCalculate event handler runs immediately after a worksheet is recalculated. Use the OnCalculate property of the Worksheet object to associate a procedure with the recalculation of a single, specified worksheet. Use the OnCalculate property of the Application object to associate a procedure with the recalculation of any open worksheet.

For example, you might use an OnCalculate handler to update column widths when new data is recalculated, as shown in the following example.

Sub TrapCalculate()
    Application.OnCalculate = "FitColumns"
End Sub

Sub FitColumns()
    Columns("A:H").EntireColumn.AutoFit
End Sub

If you've assigned a procedure to the OnCalculate property of the Application object, the procedure runs for any recalculated worksheet that doesn't have its own OnCalculate handler.

Note

The OnCalculate event handler doesn't run if you recalculate under program control. For example, the statement Application.Calculate recalculates all open workbooks, but it doesn't cause the OnCalculate event handler to run.


OnData Property

An OnData event handler runs when data arrives from an application other than Microsoft Excel. You can use the OnData property of either the Worksheet or Application object to associate a procedure with the arrival of data linked to one of these objects through dynamic data exchange (DDE) or OLE.

For example, the following code associates the arrival of stock price data on a worksheet with a procedure that validates each item of information.

Sub TrapData()                        'Set up OnData trapping
    Worksheets("StockAnalysis").OnData = "ValidateData"
End Sub

Sub ValidateData()                    'OnData handler
    For Each Cell in InputRange        'InputRange is a public variable
        CheckData                    'Run my validation procedure
    Next
End Sub

For more information about using DDE and OLE, see Chapter 10, "Communicating with Other Applications."


OnDoubleClick Property

An OnDoubleClick event handler runs when you double-click anywhere on a sheet. You can use the OnDoubleClick property of a Chart, DialogSheet, or Worksheet object to associate a procedure with double-clicking anywhere on the sheet. You can use the OnDoubleClick property of the Application object to associate the event handler with double-clicking on any sheet in any open workbook.

This property overrides the normal behavior of a double-click in Microsoft Excel. For example, you can double-click a cell to edit its contents in the cell instead of in the formula bar. If you set an OnDoubleClick handler, your event handler can override the in-cell editing. This may confuse users, so be careful when you use the OnDoubleClick property.

The following code runs the DoubleClickEvent procedure whenever you double-click a cell on Sheet1.

Sub TrapDoubleClick()
    Worksheets("Sheet1").OnDoubleClick = "DoubleClickEvent"
End Sub

Sub DoubleClickEvent()
    MsgBox "Something was double-clicked on Sheet1"
End Sub

Note

The OnDoubleClick event handler doesn't run if you simulate double-clicking under program control. For example, the statement Application.DoubleClick simulates double-clicking the active cell, but the OnDoubleClick event handler doesn't run.


OnEntry Property

An OnEntry event handler runs when the user either enters data on a worksheet using the formula bar or edits data in a cell. You can use the OnEntry property of a Worksheet object to associate a procedure with the entry of data on any worksheet. You can use the OnEntry property of the Application object to associate the event handler with the entry of data on any worksheet in any open workbook. The event handler runs after the user enters data in a cell or in the formula bar and then either presses Enter, selects another cell, or clicks the enter box on the formula bar.

For example, the following code associates the OnEntry event with a procedure that validates the data entered in a cell in column B on the GeneCountDB worksheet.

Sub TrapEntry()
    ActiveWorkbook.Worksheets("GeneCountDB").OnEntry = _
        "ValidateColB"
End Sub

Sub ValidateColB()
    With ActiveCell
        If .Column = 2 Then                'Test for second column.
            If IsNumeric(.Value) Then
                If .Value < 0 Or .Value > 255 Then
                    MsgBox "Entry must be between 0 and 255."
                    .Value = ""
                End If
            Else
                'Handle non-numeric entry
                MsgBox "Entry must be a number between 0 and 255."
                .Value = ""
            End If
        End If
    End With
End Sub

Note

The OnEntry event handler doesn't run if you enter data in a cell by clicking either Cut, Copy, or Paste on the Edit menu, or if you change the contents of a cell under program control.


OnKey Method

An OnKey event handler runs when the user presses a specified key combination. To associate a procedure with a specified key combination, use the procedure argument to the OnKey method of the Application object. Unlike many of the other OnEvent handlers, the OnKey handler does run if you simulate sending keystrokes to Microsoft Excel under program control. You would use the SendKeys method to do this.

The following code runs the DoReports procedure when the user presses F12.

Sub TrapKeys()                            'Trap key combinations.
    Application.OnKey _
        key := "{F12}" , _
        procedure := "DoReports"
End Sub

Sub DoReports()                            'F12 OnKey handler.
    AssembleReports
    PrintReports
End Sub

For a complete list of special codes for key combinations, see "OnKey method" in Help.

Note

The OnKey event handler doesn't run if its associated key combination is pressed while another procedure is running. Therefore, you cannot use an OnKey handler if you want to run a special procedure when the user presses Esc to stop the currently running procedure. You can, however, use the EnableCancelKey property to modify the behavior of the Esc key. For more information, see "EnableCancelKey property" in Help.


OnRepeat and OnUndo Methods

An OnRepeat event handler runs when the user clicks Repeat on the Edit menu. A good use for an OnRepeat event handler is to allow the user to rerun a macro that performs a series of complicated operations on a worksheet. (Usually, clicking Repeat on the Edit menu after a macro has run will repeat only the last operation in the macro.)

You can use the procedure argument to the OnRepeat method of the Application object to customize the the Repeat menu item and to associate a procedure with the action of clicking this menu item.

For example, suppose that after pasting a date into a cell, you want to increment the date by one day in each successive paste from the cell above the active cell. To do this, you might use code such as that shown in the following procedure.

Sub TrapRepeat()
    Application.OnRepeat _
        text:= "Paste Next Day", _
        procedure := "PasteIncrement"
End Sub

Sub PasteIncrement()                            'OnRepeat handler.
    With ActiveCell
        .Value = .Offset(-1, 0) + 1            'Add a day.
    End With
End Sub

Similarly, an OnUndo event handler runs when the user clicks Undo on the Edit menu. You use the procedure argument to the OnUndo method of the Application object to customize the Undo menu item and to associate a procedure with the action of clicking this menu item.

For example, in a procedure that inserts a row containing data for a new record, the last action might be to enter data in a cell; when this happens, the Undo menu item changes to Undo Entry. However, choosing this command removes the information entered in the cell, when you'd probably want to delete the entire row with a command named Undo New Record instead.


OnSheetActivate and OnSheetDeactivate Properties

An OnSheetActivate event handler runs whenever the user switches to a sheet in an open workbook. Set the OnSheetActivate property for the Application object to run a procedure whenever the user switches to any sheet in the application. Set the OnSheetActivate property for a Workbook to run a procedure whenever the user switches to any sheet in a specific workbook. Set the OnSheetActivate property for a Chart, DialogSheet, Module, or Worksheet object to run a procedure whenever the user switches to a specific sheet in a workbook.

You can use OnSheetActivate to ensure that a toolbar that belongs to the workbook is displayed whenever the user switches to that workbook. For example, the following Auto_Open procedure in a workbook initiates trapping for the OnSheetActivate event for the workbook and runs a procedure that displays an Engineering Analysis toolbar whenever the user switches to the workbook.

Sub Auto_Open()
    ThisWorkbook.OnSheetActivate = "WBActivateHandler"
End Sub

Sub WBActivateHandler()
    If ActiveSheet.Name = "My_Data" Then
        Toolbars("EngAnalysisToolbar").Visible = True
    Else
        Toolbars("EngAnalysisToolbar").Visible = False
    End If
End Sub

Another use for an OnSheetActivate procedure is to display a custom menu bar whenever the user switches to a sheet of a certain type. For example, if the user switches to a chart sheet, the built-in chart menu bar is displayed automatically. If you create a custom chart menu bar, Microsoft Excel doesn't display it unless you create a procedure that runs whenever the user switches to a chart sheet.

Similarly, an OnSheetDeactivate procedure runs whenever the user switches away from a sheet or workbook. OnSheetDeactivate procedures are useful for resetting a customized user interface — for example returning menu bars, toolbars, and view settings to their original states.

Note

The OnSheetActivate and OnSheetDeactivate event handlers don't run when you activate a sheet under program control.

When you activate a workbook, the workbook becomes active before the OnSheetDeactivate procedure in the previous workbook runs. Therefore, using the ActiveSheet or ActiveWorkbook property in the OnSheetDeactivate handler may produce unpredictable results.


OnTime Method

An OnTime event handler runs at a specified time in the future — either at a specified time of day or after a specified period of time has passed. This event handler runs only if Microsoft Excel is running and the workbook containing the OnTime event handler is loaded. You can use the arguments to the OnTime method of the Application object to specify the time you want the handler to run and the name of the handler. For example, to accumulate and print a series of reports every day at noon, you might use the following code.

'Initialize trapping using OnTime method
Sub TrapTime()
    'Set OnTime arguments
    Application.OnTime _
        earliestTime := TimeValue("12:00:00"), _
        procedure := "DoReports"
End Sub

Sub DoReports()                'OnTime handler
    AssembleReports
    PrintReports
End Sub

The TrapTime procedure initializes trapping of the OnTime event; at the first noon after TrapTime runs, Microsoft Excel runs the DoReports handler. To run the procedure only once, set the earliestTime argument to a date and a time rather than using the time alone.

If another procedure is running when the event occurs, Microsoft Excel waits for an additional interval specified by the latestTime argument of the OnTime method. For example, the following version of the TrapTime procedure waits for half an hour for Microsoft Excel to become free, and then it stops the event.

Sub TrapTime()                    'Initialize OnTime trapping.
    Application.OnTime _
        earliestTime := TimeValue("12:00:00"), _
        procedure := "MyOnTimeHandler", _
        latestTime := TimeValue("12:30:00")
End Sub

If you don't supply the latestTime argument, the procedure runs when Microsoft Excel next becomes available. You can schedule multiple OnTime handlers to run at different times; if you schedule more than one OnTime handler for the same time, the last-scheduled procedure runs first.

Tip

The initialization of an OnTime event isn't stored from session to session. To achieve the effect of its being stored, you can place in the startup folder a workbook that contains both an Auto_Open procedure and the OnTime handler itself. The Auto_Open procedure must initialize OnTime trapping for a specific time. Then, whenever Microsoft Excel is started, trapping of that event is reinitialized.

To remove a pending OnTime event, you must specify the exact time of the event and the name of its handler, and you must set the schedule argument to False. For example, if there are two OnTime events scheduled for noon — one handled by DoReports and the other one handled by a procedure called CleanUp — you can stop the CleanUp handler request with the following code.

Application.OnTime _
    earliestTime := TimeValue("12:00:00"), _
    procedure := "CleanUp", _
    schedule := False

Note

With the OnTime method, the user can work until an OnTime event occurs; with the Wait method, the user cannot interact with Microsoft Excel until the wait is over. To suspend all activity except for printing and recalculation, use the Wait method as shown in the following statement.

'Wait 15 seconds
Application.Wait Now + TimeValue("00:00:15")

For more information about the Wait method, see "Wait method" in Help.


OnWindow Property

An OnWindow event handler runs whenever the user switches to a window. To associate a procedure with switching to any window in the Microsoft Excel application, use the OnWindow property of the Application object, as shown in the following example.

Application.OnWindow = "AllWindowHandler"

To associate a procedure with switching to any window in the Microsoft Excel application, use the OnWindow property of a Window object. To associate a procedure with switching to a specific sheet in a workbook, use an Auto_Activate procedure, as described earlier in this chapter.

For example, the following code contains a procedure that traps each instance of switching to the second window called BikeDB.xls and then forces the window to appear at a specific location on-screen.

Sub TrapBicycle2()
    Windows("BikeDB.XLS:2").OnWindow = "PositionWindow"
End Sub

Sub PositionWindow()
    With Windows("BikeDB.XLS:2")
        .Left = 0
        .Top = 100
        .Width = 300
        .Height = 50
    End With
End Sub

If a workbook, worksheet, or other sheet has an associated OnSheetActivate procedure, it runs after the procedure specified in the OnWindow property.

Note

The OnWindow event handler doesn't run if you switch to a window under program control.


Chapter 12 Creating Add-Ins

This chapter shows you how to package Microsoft Excel worksheets, controls, menus, toolbars, and supporting Visual Basic modules in the form of an add-in application. You can use add-ins to assemble and distribute custom features that, from the user's point of view, act as if they're built into Microsoft Excel itself.

An add-in is a hidden, read-only workbook in which the Visual Basic code has been fully compiled from a source workbook. Because the code is already fully compiled, there is no compiler-induced delay when you run a procedure from an add-in. The add-in is hidden so that users can run procedures without having to see your code in a workbook. This also saves the system resources that would otherwise be required to display a workbook. Finally, the add-in is read-only so that users cannot make inadvertent changes to your code.

Contents
  • Improving Performance with Add-Ins
  • Preparing a Workbook to Compile to an Add-In
  • Compiling the Add-In
  • Using an Add-In's Procedures


Improving Performance with Add-Ins

You can improve your code's performance by compiling a workbook to an add-in. In a workbook that isn't an add-in, Visual Basic uses incremental compilation to reduce the amount of time it takes to compile changes to code. However, when you compile an add-in, Visual Basic fully compiles the code, which may slightly improve performance.

You can further improve performance by compiling the add-in on the platform in which you want to run it. For example, you can write an add-in that runs in both the Windows and Macintosh operating systems. Although you can successfully move the compiled add-in from one platform to another, performance suffers. Instead, move the source workbook and recompile it in the other platform.


Preparing a Workbook to Compile to an Add-In

You create a source workbook for an add-in the same way you create any other workbook. However, before you compile the source workbook to an add-in, there are several unique issues associated with add-ins that you need to be aware of.

Note

Because add-in applications cannot be edited, it's extremely important that you keep a copy of your original workbook so that you can update its procedures or add new procedures.


Tips for Debugging Add-ins

Before compiling a workbook to an add-in, you can hide the workbook and then run its procedures from another workbook. This will help you find reference errors and errors that occur because the workbook is hidden. If your code uses error handling, you can turn on the Break On All Errors option to disable the error handler and display error messages. The Break On All Errors option is located on the Module General tab in the Options dialog box (Tools menu).

Note

After you compile the add-in, Microsoft Excel ignores the state of the Break On All Errors option. Therefore, your add-in's error handler will run, regardless of whether this option was on or off when you compiled the add-in.

After an add-in is compiled, it can be difficult to debug. The add-in's procedures don't appear in the Run dialog box, so you cannot use the debugging features such as Step Into and Step Over, nor can you see the add-in code in the Debug window. This behavior is intentional — you usually don't want users to be able to single-step through your code or to see your code in the Debug window.

You can use an error handler, line numbers, and the Debug.Print statement to continue debugging after you compile the add-in. Although line numbering may sound archaic, it does give you a way to indicate where an error occurred. You can number all the lines in your code, or just the lines in certain critical sections, as shown in the following example.

Sub AddinSub()
    Dim x, y As Integer
    On Error GoTo ErrHandler
    ' Notice the line number in the following statement
10  For x = 1 To 10
        For y = 1 To 10
            If x = 7 And y = 7 Then
                ThisWorkbook.Worksheets("Sheet" & x * y).Cells(1, 1) = 5
            End If
        Next y
    Next x
    ' Here's another line number . . .
50  ' Do some more stuff
    ' Exit sub before running error handler
Exit Sub
ErrHandler:
    ' This statement prints the error information
    Debug.Print "Error " & Err & " " & Error(Err) & _
        " in line no. " & Erl
    ' This line prints the values of two variables of interest
    Debug.Print "x ="; x; Chr(13); "y ="; y
End Sub

To use code in the following example, compile it to an add-in; create a new workbook, add a module to it; and then create a reference to the add-in using the References dialog box (Tools menu). In the new workbook, create a small sub that calls the AddinSub procedure:

Sub dbg()
    AddinSub
End Sub

The AddinSub procedure should fail on the line that contains the Worksheets method call (unless the add-in contains more than 48 worksheets), although you'll see no indication of this error. Press CTRL+G to display the Debug window; notice that the Debug.Print statements in AddinSub wrote error information to the Immediate pane. Notice also that the error occurred on a line that didn't have a line number. In this case, the Erl function returns line number 10, which is the previous line number closest to the line in which the error occurred.

Before you compile a copy of a workbook in the add-in format (assuming that you've already thoroughly tested and debugged your code), remember to remove all debugging code, such as Stop statements and Debug.Print calls.


Using the ThisWorkbook Property

The most important thing to remember when writing an add-in is the definition of the active workbook. The active workbook is the one that's on top in the Microsoft Excel window. The active workbook isn't necessarily the one that contains the running Visual Basic code. In fact, an add-in can never be the active workbook, because it's invisible.

When you're writing and debugging an add-in, the workbook that contains the code is often the active workbook. Therefore, statements that contain an implicit ActiveWorkbook property call — such as DialogSheets("MyDialog").Show — work properly. When you compile the add-in and run the same code, the implicit ActiveWorkbook property call returns the workbook that's on top, not the workbook that contains the dialog sheet named "MyDialog." This causes the code to fail.

Using the ThisWorkbook property eliminates the workbook referencing problem. In addition to using ThisWorkbook, you should always use complete references to objects, meaning that you should start with ThisWorkbook and then navigate down the object hierarchy, as shown in the following code.

Don't forget that objects are often used in arguments to methods; it's very easy to overlook the workbook reference issue in such cases, as shown in the following code.


Updating References to Procedures in Add-Ins

When you write and debug your add-in code, the workbook that contains the code probably has the filename extension .xls. When you compile the workbook, the add-in you create has the filename extension .xla.

Note

If your system isn't set up to display filename extensions, you won't be able to tell the difference between your source workbook and your add-in in the Open dialog box (File menu). To display filename extensions, open the Windows Explorer, and then click Options on the View menu. Next, clear the Hide MS-DOS File Extensions For File Types That Are Registered check box on the View tab.

Suppose you create a custom button that refers to a procedure in a workbook before it's compiled to an add-in. The button's OnAction property contains a reference to the original workbook filename — the one with the .xls extension. When you create an add-in from the workbook, the add-in has a different filename extension. Unless you update the button's OnAction property to refer to the procedure in the add-in, clicking the button will cause Microsoft Excel to open the original workbook and run the version of the procedure stored there, instead of calling the procedure in the add-in.

In most cases, you can update OnAction references using code similar to that shown in the following example. Remember to run this code in the workbook that contains custom buttons.

Sub ConvertRefs()
    For Each sh In ActiveWorkbook.Sheets
        If TypeName(sh) <> "Module" Then
            For Each b In sh.Buttons
                mystr = b.OnAction
                strpos = InStr(mystr, ".xls")
                If strpos <> 0 Then
                    l = Len(mystr)
                    b.OnAction = Left$(mystr, strpos - 1) & _
                        ".xla" & Right$(mystr, l - strpos - 3)
                End If
            Next b
        End If
    Next sh
End Sub


Maintaining References to Other Add-Ins

If an add-in's source workbook contains a reference to another add-in — for instance, a reference to Xlodbc.xla — make sure that when you distribute the add-ins, the referenced add-in is stored somewhere on the user's machine where the calling add-in can find it. When you compile a source workbook to an add-in, Microsoft Excel stores a hard-coded path to the referenced add-in in the calling add-in. If you move the calling add-in to another computer (when you distribute the add-in to your users, for example), and if Microsoft Excel cannot find the file in the hard-coded location, it searches in the following locations (in this order):

  • The folder that contains the calling add-in
  • The System folder in the Windows folder
  • The Windows folder
  • The path defined by the Path environment setting (to see the path, type set in an MS-DOS prompt window)

If you experiment with the resolution algorithm, you'll also notice that after Microsoft Excel has reestablished the reference, it will keep it even if you move the referenced add-in somewhere outside the locations described in the preceding list. When you restart Microsoft Excel, however, the reference will be unresolved again.

To be safe, always store a referenced add-in in the folder that contains the calling add-in. A less advisable but still relatively safe method is to store the referenced add-in in a folder in the path.


Writing Code That Modifies the Add-In

Although an add-in is a hidden, read-only workbook, you can programmatically modify it. For example, you can add a worksheet on which you can perform calculations and store values. However, changes to an add-in are temporary — when you close the add-in, or when the add-in is unloaded from memory when you quit Microsoft Excel, the changes are lost. If you require more persistent storage, you can use your add-in to create a new workbook, transfer data into it, and then save it.


Compiling the Add-In

After you've debugged your source workbook and addressed the referencing issues discussed in the preceding section, you're ready to compile your add-in.

To compile an add-in

1. Switch to a Visual Basic module in the workbook you want to compile.

2. On the Tools menu, click Make Add-In.

3. Click the icon for the folder in which you want to save the file.

4. In the File Name box, enter the name you want for the compiled add-in file.

5. Click Save.


Making an Add-In's Source Code Secure

The Visual Basic source code stored in the modules of a compiled add-in isn't completely protected from being read and copied. If you need complete security for your code, you can protect the structure of the source workbook using the Protection command on the Tools menu. Be sure to use a password when protecting the workbook structure. After protecting the workbook structure, compile the add-in.

When you use this protection technique, you can no longer add the add-in to the list box in the Add-Ins dialog box (Tools menu). If you attempt to add a protected add-in, you'll see an error message telling you that the add-in isn't valid. You can still use the procedures in the add-in by opening the add-in using the Open command (File menu) or by creating a reference to it from a Visual Basic module in another workbook. For more information about these techniques, see "Using an Add-In's Procedures" later in this chapter.

If you must create a secure add-in and it must appear in the Add-Ins dialog box, create two add-ins. The first add-in is the secure one; the second add-in is unprotected and contains a reference to the first add-in — a reference you create using the References dialog box (Tools menu). You can now use the functions in the second add-in, which call the protected code in the first add-in.

Creating completely secure add-in code is a complicated process, and it may add overhead to your add-in, which could reduce performance. Also, you may forget the protection password, in which case you would be unable to add, delete, move, rename, hide, or unhide sheets in the source workbook. For these reasons, you should secure add-ins only when it's absolutely necessary.


Reducing the Size of an Add-In

While developing an add-in, you can create and delete many variables and procedures. For example, you could create many temporary variables during debugging and then later delete them, or you could create procedures that you eventually delete as your code evolves. Visual Basic might not delete the variable and procedure names from its symbol table; this could cause the add-in to use more memory than it would if the symbol table were clean.

If you suspect that a heavily edited workbook is using an unusually large amount of memory, you can reduce its size by cleaning its symbol table.

Note

The following technique does more than just clean the symbol table; it also removes all the information in the Macro Options dialog box, such as the shortcut key, function category, status bar text, and so on. The information is removed for every procedure in every module. If you've used the Macro Options dialog box to add any information to the procedures, you'll have to restore it after cleaning the symbol table.

To clean an add-in's symbol table

1. Open the original source workbook.

2. Save each module in the workbook to a separate text file.

3. Delete every module from the workbook.

4. Save the workbook.

5. Create new modules, giving them the same names as the ones you deleted.

6. On the Insert menu, click File to add the code back into the new modules. Be sure to copy the code to the correct modules.

Although cleaning the symbol table may be tedious, it can reduce the memory requirements of an extensively edited add-in. You can compare the values returned by the MemoryUsed property (which returns the amount of memory that's currently being used by Microsoft Excel) before and after cleaning to measure the saved memory.


Using an Add-In's Procedures

There are several ways to use the procedures in an add-in. By understanding the advantages and disadvantages of each technique, you can choose the method that's best suited to your work.

Technique | Advantages | Disadvantages
Use the Open command (File menu) or the Open method in Visual Basic to open the add-in. | This is the simplest way to load an add-in. Custom worksheet functions in the add-in can be typed into a worksheet, and the add-in can modify the user interface by using the Auto_Open procedure. | Visual Basic procedures in the add-in aren't available to other workbooks, even though functions in the add-in are available to worksheets in other workbooks. In addition, all add-in resources are loaded into memory, whether or not they're required.
Use the References dialog box (Tools menu) to create a reference to the add-in. | Visual Basic procedures in the add-in are available to other workbooks. Custom worksheet functions in the add-in are available to worksheets in other workbooks. | No auto procedure (for example, auto_open) runs when the reference is created. In addition, there is no reliable way to create a reference using Visual Basic code.
Use the Add-Ins dialog box (Tools menu) to install the add-in. | Microsoft Excel stores the location of the add-in in the system registry and can automatically load the add-in on startup. | Visual Basic procedures in the add-in aren't available to other workbooks, even though functions in the add-in are available to worksheets in other workbooks.

Placing the add-in the Xlstart folder (so that Microsoft Excel opens the add-in when it starts) results in the same behavior as opening the add-in any other way. Remember that Visual Basic procedures in the add-in aren't available to any other workbook unless you create a reference to the add-in using the References dialog box (Tools menu).


Demand Loading Add-Ins

To increase the speed with which Microsoft Excel starts, you can have an add-in be demand loaded. This means that when Microsoft Excel starts, it reads only enough information from the add-in workbook file to establish references to the custom worksheet functions in the add-in. These functions are added to the list in the Function Wizard and can be entered on a worksheet. However, the add-in isn't fully loaded until Microsoft Excel recalculates one of the custom worksheet functions.

Demand loading can significantly decrease the amount of time required to start Microsoft Excel, especially when you're working with large add-ins that contain numerous custom functions. Nothing is free of course, and the time delay eventually occurs when the add-in is fully loaded at the time of the initial function recalculation. In most cases, this is an acceptable tradeoff because the user encounters individual time delays one by one instead of encountering one long time delay at startup time.

To use demand loading for custom worksheet functions that are written in Visual Basic, you must wrap the Visual Basic function procedure in a Microsoft Excel 4.0 macro function. You must also define the name __DemandLoad (the string "DemandLoad" preceded by two underscores) in the workbook. Use the following steps to create an add-in that contains demand-loaded custom functions written in Visual Basic.

To create a demand-loaded add-in

1. Create a source workbook.

2. Insert a Visual Basic module, and then write the custom worksheet function.

3. Insert a Microsoft Excel 4.0 macro sheet. For each argument to the Visual Basic function, create an ARGUMENT function on the macro sheet.

4. The last function on the macro sheet is the RETURN function. In the argument list for this function, type the name of the Visual Basic function, including the argument strings you defined in step 3.

5. On the Insert menu, point to Name, and then click Define to define a name for the first ARGUMENT function. This will be the name that you'll use to call the custom function (the Visual Basic function name is known only to the RETURN function on the macro sheet). Be sure to click Function under Macro.

6. On the Insert menu, point to Name, and then click Define to define the name __DemandLoad (the string "DemandLoad" preceded by two underscores) on the macro sheet. In the Refers To box, type =TRUE

7. Save the source workbook.

8. On the Tools menu, click Make Add-In to compile the workbook to an add-in.

9. Close the add-in.

To use the add-in, install it by using the Add-Ins dialog box (Tools menu). Click Browse to locate an add-in that's not listed in the Add-Ins Available box. After the add-in is installed, the custom function name should appear in the User Defined category in the Function Wizard. The following illustration shows an example of a demand-loaded custom function called "vb_hyp," which calculates the length of the hypotenuse of a right triangle, given the lengths of the other two sides.

When you install an add-in that contains demand-loaded custom functions, there will be an OPEN value in the Microsoft Excel key in the system registry that points to the add-in workbook, and the OPEN value will contain the /F switch to indicate demand loading. Add-ins that aren't demand loaded don't have the /F switch in the OPEN value. For more information about the system registry, see "Removing an Add-In from the List" in the following section.


Managing the Add-Ins Dialog Box

The Add-Ins dialog box provides a way for users to customize the loading of add-ins. If an add-in appears in the Add-Ins Available box, Microsoft Excel knows the location of the add-in. If the check box to the left of the add-in name is selected, the add-in is loaded when Microsoft Excel starts. Users can clear the check boxes to load fewer add-ins at startup, thus speeding up the startup process.

Adding an Add-In to the List

You can add a custom add-in to the list by clicking Browse in the Add-Ins dialog box or by using the Add method of the AddIns collections object. After the add-in appears in the list, you can use the Installed property to select or clear the check box. Note that whereas the Add method specifies an add-in by using its path and filename, the Installed property takes an AddIn object returned by the AddIns method, and the AddIns method specifies an add-in by using its name.

You should give the add-in a descriptive name before you compile it. This is the name you use as the argument to the AddIns method (it's also the name that appears in the list).

To name an add-in

1. Open the source workbook for the add-in.

2. On the File menu, click Properties.

3. In the Title box on the Summary tab, type the name you want for the add-in.

You can also add other information at this point, such as comments and keywords.

4. Click OK.

5. Save the source workbook, and then compile it to an add-in.

Removing an Add-In from the List

When you add an add-in to the Add-Ins Available box in the Add-Ins dialog box, Microsoft Excel stores the location of the add-in in the system registry. If you want to remove the name from the list, you use the Windows 95 Registry Editor to delete the registry value associated with the add-in. You can run the Registry Editor by typing regedit in the Run dialog box (Windows 95 Start menu).

If the add-in appears in the Add-Ins Available box and the check box next to it is selected (meaning that the add-in is installed), you delete the corresponding OPEN value in the Microsoft Excel key, as shown in the following illustration.

If the add-in appears in the Add-Ins Available box and the check box next to it is cleared (meaning that the add-in isn't installed), you delete the corresponding value in the Add-In Manager key instead of the OPEN value in the Microsoft Excel key.

Note

Microsoft Excel updates the registry when you quit the application. Before editing the registry, be sure to quit Microsoft Excel. If the Registry Editor is already running, quit Microsoft Excel, switch to the Registry Editor, and then press F5 to refresh the display.

After you find the location of the value you want to delete, select the value name in the right-hand pane of the Registry Editor window, and then press DEL to delete the value. The add-in no longer appears in the Add-Ins dialog box list when you restart Microsoft Excel.

For more information about the Windows 95 system registry, see the Microsoft Windows 95 Resource Kit, which is available from Microsoft Press.


Chapter 13 Accessing External Data

In addition to working with Microsoft Excel data, you may want your application to access data from other sources, such as text files or databases. Microsoft Excel provides several powerful ways to access external data.

The first part of this chapter explores how to import external data as a text file. The next section discusses how to use data access objects to access the data and change the structure of a database. The final section describes how to connect to external database servers or files by using open database connectivity (ODBC).

Contents
  • Accessing Text Files
  • Working with Data Access Objects
  • Using ODBC


Accessing Text Files

Microsoft Excel provides two ways to access external data that's in the form of a text file: the Text Import Wizard and the OpenText method.

You can import delimited or fixed-width text files into a worksheet by using the Text Import Wizard. This wizard allows you to tell Microsoft Excel what form your data is in, specify how you want to distribute the text across columns, and choose the data format for each column.

To open the Text Import Wizard

1. On the File menu, click Open.

2. Click the name of the text file you want to import.

3. Click Open.

You can also use the OpenText method to load and parse a text file. This method creates a new workbook with a single worksheet containing the parsed text file data. For more information about the OpenText method, see "OpenText method" in Help.


Working with Data Access Objects

DAO (data access objects) is a library of objects, properties, and methods that you use to retrieve, edit, or delete data stored in a database or to change the structure of a database. Using DAO, you can insert cell values from a Microsoft Excel worksheet into records in a database; you can query a data set and bring the result set into Microsoft Excel for charting or presentation; and you can change relationships between tables.

Note that anything that you do using DAO is subject to the object permissions granted by the login user name and the login password — DAO isn't designed as a way around database security.

Important

Any changes you make to the database using DAO are permanent. If you delete a record from a base table, for example, using a DAO method in your function, the record will be physically deleted from the table and cannot be recovered.


Understanding the DAO Object Model

You use data access objects the same way you use objects in the Microsoft Excel object model. For example, to change a field attribute in a specific table in your application, you first need to establish a reference to the field. Beginning at the application level (using the DBEngine object), you define a workspace and then enter the database. From there, you navigate through the object and collection levels until you reach the object you want to change.

The DBEngine Object

The DBEngine object represents the Microsoft Jet database "engine," which is what powers Microsoft Access; this is the engine that Visual Basic uses to program database objects. This engine is actually a set of dynamic-link libraries (DLLs) that are linked to your application at run time. This engine is commonly referred to as "Jet," and it's the top-level object in the DAO model. It's this set of DLL files that translates the DAO code you write in your application into physical operations involving the Access .mdb file (or other database files). Also built into the DBEngine is a query processor that compiles and runs the Structured Query Language (SQL) queries you write to the database.

Note

The data file is the file that contains the database tables. Microsoft Access data files have the extension .mdb. Microsoft FoxPro® and dBASE® databases have the .dbf extension. Other database applications have different filename extensions.

The Workspace Object

The Workspace object represents a workspace, which is an area in memory where you can perform a set of DAO operations. It's similar to a Microsoft Excel worksheet in that more than one workspace can be open at a time, but only one workspace can be active at a time. Depending on your system configuration, you may be able to open as many as 255 workspaces at once. Because Workspace objects are zero-based, the first workspace you open is Workspace(0).

You can define a workspace variable and open any workspace you specify. Most applications use only one workspace; therefore, it's faster to use the default workspace that's automatically assigned when you open a database.

Note

It's possible to open a database without defining a workspace variable or using a Workspace object. To do this, define a database variable only; the variable will be assigned a default workspace when it's opened.

The Database Object

The Database object represents a Jet database, which is a collection of tables, indexes, fields, and links to outside sources. Whereas in Microsoft Excel you can define and set a range of cells as a database, in a Jet database the range you defined would be a single table. A Jet database is composed of a collection of tables (among other things).

The TableDef Object

The TableDefs collection object represents the collection of all the tables in a database. Each TableDef object represents a separate base table or attached table in the database.

The QueryDef Object

The QueryDefs collection object represents all the compiled SQL code in the database. Each QueryDef object represents one compiled SQL command string.

The Recordset Object

A Recordset object represents a set of records drawn from the database. The records can be drawn from a base table, or they can be the result of a single SQL query or a series of queries. The records that make up a Recordset object don't have to be stored in the same table. The Recordset object has three subtypes: the Table object, the Dynaset object, and the Snapshot object.

The Table Object

The Table object represents a base table, which is a logical set of records that are physically stored together. For example, a set of employee records can be stored in the same table because all the employees work for same company. The records can then be subdivided, or grouped with other records from other tables; in the base table, however, they're still a logical, physical set of records.

The Dynaset Object

The Dynaset object represents an updatable group of records. The group can be either a base table or a virtual table. A Dynaset object is updatable because the table indexes are loaded into memory, and the other fields in the record are retrieved from a buffer when they're needed.

The Snapshot Object

Like a Dynaset object, a Snapshot object can represent either a base table or a virtual table. Unlike a Dynaset object, a Snapshot object isn't updatable; all fields in a Snapshot object record are loaded into memory so that the set can be searched faster for matching records. The result of a SQL pass-through query is always a Snapshot object.


Using DAO from Microsoft Excel

You can use DAO properties, objects, and methods the same way you reference and use Microsoft Excel properties, objects, and methods. After you establish a reference to the DAO object library, you're free to open or create databases, run queries to create result sets, and bring the result sets back to Microsoft Excel.

Referencing DAO

Before you can use DAO, you must establish a reference to the DAO object library using the Microsoft Excel References dialog box.

To establish a reference to the DAO object library

1. Switch to a Visual Basic module.

2. On the Tools menu, click References.

3. In the Available References box, click Microsoft DAO 3.0 Object Library.

If you don't see Microsoft DAO 3.0 Object Library in the Available References box, rerun Setup to install it.

To install the Microsoft DAO 3.0 Object Library

1. Run Setup in maintenance mode, and click Custom Setup.

2. Click Add/Remove.

3. Clear the Data Access check box, and then click Change Option.

4. Under Options, select the check boxes for the data access drivers you want to install, and then click OK.

5. Click Continue, and proceed with the installation.

Opening a Database

To open an existing database using DAO, create a database variable. Then, in an open workspace, use the OpenDatabase method and specify the path to the existing database. The following example opens the Microsoft Access sample database Nwind.mdb.

Dim db As Database

Set db = OpenDatabase("e:\access\sampapps\nwind.mdb")

db.Close
End Sub

Running a Query and Returning a Recordset object

There are two ways to query a database using DAO: you can run a query that already exists, or you can create a new query. If you run a query that already exists, you simply refer to the name of the existing query in the OpenRecordset method. If you create a new query, you can choose to write it back to the database when you're finished, or you can choose to load it into memory.

To run any type of query, define a database variable and then set it to the database you want to work in.

Dim db As Database
Set db = OpenDatabase("e:\access\sampapps\nwind.mdb")

Opening an Existing Query

To open an existing query, use the OpenRecordset method to open the specified query and return the Recordset object. The first argument contains the name of the stored query you want to open, and the second argument describes the type of Recordset object that's returned.

Dim myset as Recordset
Set myset = db.OpenRecordset("Country", dbOpenDynaset)

If you omit the Recordset object type, DAO will try to return the fastest Recordset object type that allows you to modify the data. If you need only to read the data or append new data, see "OpenRecordset method" in Help for information about Option arguments that may make your application run faster.

To store a query in the database, use the CreateQueryDef method. The result of a CreateQueryDef method is compiled SQL code written back to the database as a query definition. You can store the SQL code in the database this way and then run it later using the OpenRecordset method to return a result set. The string you specify in the first argument is the query name that will be stored in the database, and the second argument is the SQL command string.

Dim qd As QueryDef

Set qd = db.CreateQueryDef("Country", "select distinctrow orders. _
    [ship country],sum(orders.[freight])as SumofFreight from  _
    orders group by orders.[ship country] order by orders.[ship _
    country];")

Note

If you're not familiar with writing SQL code, you can examine the examples that go with a specific object, property, or method in Help, or you can construct a query in Access and view the resulting SQL code. If necessary, you can copy and paste most SQL code from the SQL view in Microsoft Access into a CreateQueryDef method.

Creating a New Query from a SQL Statement

To run SQL code and return a Recordset object that exists entirely in memory, use the OpenRecordset method, and specify a SQL string (instead of a stored query definition) as the first argument.

Dim myset As Recordset
Dim SQLString As String

After you set the database variable to the database you want to work in, load the SQL string into a string variable. Then use the OpenRecordset method, using as arguments the name of the SQL string and the Recordset object type.

SQLString = "select distinctrow orders.[ship
    country],sum(orders.[freight])as SumofFreight from orders  _
    group by orders.[ship country] order by orders.[ship country];"
Set myset = db.OpenRecordset(SQLString, dbOpenSnapshot)

For information about optimizing your SQL statement, see "SQL" in Help. For information about optimizing your application, see "Optimizing DAO Code" later in this chapter. If you want to run multiple queries that differ only in the records selected, you may want to use a parameter query and provide new parameters each time you open the query. For more information about parameter queries, see "Parameter object" in Help.

Filling a Range with a Result Set

You can import the contents of a result set into a Microsoft Excel worksheet either by placing the records into rows one by one or by importing the entire set at once using the CopyFromRecordset method. After you copy the result set to the worksheet, the record values become part of the worksheet.

Copying a Result Set Range Row by Row

If you copy the records one by one, you'll need to keep track of index variables because these dictate where the record will be placed on the worksheet. Although keeping track of index variables can be confusing if you have many fields, copying records this way gives you complete control over where your information is placed.

Copying an Entire Result Set as a Unit

You can copy an entire result set to a range on a worksheet at once by using the CopyFromRecordset method. This method begins to copy at the current row of the result set; when the transfer is completed, the Recordset object pointer is positioned just past the last row, or at EOF. Other than moving the Recordset object pointer, this method doesn't alter the Recordset object.

Dim db As Database
Dim rs As Recordset

Set db = OpenDatabase("e:\access\sampapps\nwind.mdb")
Set rs = db.OpenRecordset("Orders")

Worksheets("Sheet1").Range("A2").CopyFromRecordset rs

rs.Close
db.Close

Note

In some circumstances, if you're copying either a result set containing OLE objects or pictures (such as the Categories table in Nwind.mdb), the copy operation will fail, and an exception error will be returned.

For more information about the CopyFromRecordset method, see "Optimizing DAO Code" later in this chapter.

Filling a List Box with a Result Set

There are two ways to fill a list box with a result set. You can specify a range of cells on a worksheet that contains a list of items you want to appear in the list box, or you can use the Additem method to directly fill the list box.

Filling a List Box with a Range of Cells

To fill a list box with a range of cells, use the ListFillRange property. The following example assumes that there's at least one dialog sheet in the active workbook, that there's at least one ListBox object on the first dialog sheet, and that there are values in cells A1:A10 on the worksheet named "Sheet1." The following example fills the list box with the values in cells A1:A10.

ActiveWorkbook.DialogSheets(1).ListBoxes(1).ListFillRange _
     = "Sheet1!A1:A10"

Note

A cell can contain up to 255 characters; a list box can contain more than 255 characters. Therefore, if you use the ListFillRange property to fill a list box, be careful that the text you insert from a cell into a list box isn't truncated.

Filling a List Box with a Single Item

To fill a list box with a single item or to add selected items to a list box, use the AddItem method. The following example adds the second field value in the result set to the contents of the list box. The example assumes that there's at least one dialog sheet in the active workbook and that there's at least one ListBox object on the first dialog sheet.

Dim db As Database
Dim rs As Recordset
Dim x as Integer, I as Integer

Set db = OpenDatabase("d:\access\sampapps\nwind.mdb")
Set rs = db.OpenRecordset("shippers")
rs.MoveLast
x = rs.RecordCount
rs.MoveFirst

For i = 0 To x - 1
DialogSheets(1).ListBoxes(1).AddItem Text:=rs.Fields(1).Value
rs.MoveNext
Next I

rs.Close
db.Close

End Sub

Note

Using the AddItem method will delete all list box entries made with the ListFillRange method.


Managing a Multiuser Environment

If you develop an application that allows two or more users (or applications) to refer to the same data set, you want to ensure that your application shares data effectively. This section explores strategies for managing multiuser access to data with different locking techniques, and it then discusses how to resolve locking conflicts in a multiuser environment.

Sharing Data

When one user is adding or changing data in a multiuser database, you need a way to prevent other users from changing the data until the first user is finished with it. To accomplish this, Jet provides three locking mechanisms. When a data set is locked, other users can read the records inside the data set, but only the user who initiated the lock can edit them.

By default, Jet locks an entire page of data when a record within the page is edited. A page is a block of record data that takes up approximately 2048 bytes (2 kilobytes) of memory. Depending on the size of each record, a page can contain one record or many records.

Note

When Jet locks a record from an external database in Microsoft FoxPro, dBASE, Paradox®, or Btrieve® format, it locks the smallest unit of memory (that is, record, page, or file) that's lockable in the external database.

Pessimistic Locking

Pessimistic locking is the default locking scheme and is in effect when the LockEdits property is True. Jet locks the entire page containing the record you're editing as soon as you use the Edit method, and it releases the locked page when you either terminate a transaction or explicitly release the lock by using the CancelEdit method. The locked page isn't static — it moves up when you move up in the set of records, and it moves down when you move down, so it's possible to unintentionally lock a set of records.

Optimistic Locking

Optimistic locking is a locking scheme that allows you to edit a record in memory and to lock the record only when you're ready to write the changes to the database. This method attempts to lock the record when you call the Update method. The advantage of optimistic locking is that pages are locked only briefly. To use optimistic locking, set the LockEdits property to False.

Recordset Operations

A common practice in most applications are Recordset object operations: adding and editing records, or moving within a Recordset object. This section describes these operations.

Navigating a Recordset

One way to navigate inside a Recordset object is to move up or down one record at a time using the Move method. You can also use one of the Find methods (which one you use depends on your position in the Recordset object) and a specified criterion to locate a record in a dynaset or a snapshot. If your Recordset object is opened as a table, use the Seek method for optimal performance. For information about the syntax of the four Find methods and the Seek method, see the appropriate topic in Help.

Adding New Records

To add a new record, use the AddNew method to prepare the record for editing, and use the Update method to save the record. The AddNew method prepares a new, blank record and makes it the current record. The Update method saves the record and repositions the record pointer back to the record that was active before you used the AddNew method. The following code segment adds a new record to the Shippers table in Nwind.mdb.

Dim db As Database
Dim rs As Recordset
Set db = OpenDatabase("Nwind.mdb")
Set rs = db.OpenRecordset("Shippers", dbOpenTable)
rs.MoveFirst
rs.AddNew
    rs.Fields(0).value = "4"
    rs.Fields(2).value = "Global Parcel Service"
    rs.Fields(3).value = "(503)545-3190"
rs.Update
End If

Editing Records

When you edit records, you use the Edit method to mark the start of an editing session, and you use the Update method to signal the completion of the session. The Edit method tells Jet to buffer the changes to the specified record and write the changes to the data set when the editing tasks are completed. The Update method saves the record. The following code changes the job title for each sales representative in the Employees table.

Dim db As Database
Dim rs As Recordset
Set db = OpenDatabase("Nwind.mdb")
Set rs = db.OpenRecordset("Employees", dbOpenTable)
rs.MoveFirst
Do Until rs.EOF
If rs.Fields(3).value = "Sales Representative" Then
    rs.Edit
    rs.Fields(3).value = "Account Executive"
    rs.Update
End If
rs.MoveNext
Loop

Note

You must use the Edit method before you use the Update method to write changes back to a record; otherwise, an error will occur.

Advanced Note

If you're changing large groups of records regularly, it's faster and easier to create a SQL statement than it is to write code. For examples that could replace the code preceding these notes, see "Update method" in Help.

Managing Transactions

If your application depends on successfully adding or deleting records in one data set before proceeding to another one, you'll probably want some assurance that the first set of tasks has been completed successfully before you begin the second set. For example, if you update accounting records, you'll want records to be posted to Receivables before you delete records from Payables — otherwise, the books won't balance. When you wrap these actions into transactions, you ensure that each transaction is performed successfully before your application continues.

BeginTrans, CommitTrans, and RollBack

The BeginTrans method marks the beginning of a transaction. When you've completed your tasks, use the CommitTrans method to make the changes permanent, or use the RollBack method to delete the changes from memory. The most common way to implement transaction processing is within an error routine that traps errors during your procedure. If an error occurs, the routine flags the error and ignores any changes to the file; otherwise, the routine makes these changes permanent.

The following example demonstrates how transaction processing works.

Sub ChoiceToCommit()
On Error GoTo MyErrorHandler
Dim db As Database
Dim rs As Recordset

Set db = OpenDatabase("d:\access\sampapps\nwind.mdb")
Set rs = db.OpenRecordset("Customers")
rs.MoveFirst

BeginTrans
    MsgBox "The original record value is " & rs.Fields(0).Value
    rs.Edit
    rs.Fields(0).Value = 5000
    rs.Update
    action = MsgBox("We are changing the value to " & rs.Fields(0).Value
    & " ." & Chr(13) & " Do you want to continue? ", vbYesNo)
        If action = vbYes Then
            CommitTrans
        Else
            Rollback
        End If

rs.Close
db.Close
Exit Sub
MyErrorHandler:
MsgBox DBEngine.Errors(0)
End Sub

In the BeginTrans segment of code, rs.Edit marks the beginning of an editing session within the transaction; rs.Update marks the end of the editing session and updates the record set in memory only. The first message box displays the original value of the first field in the first record of the Customers table in Nwind.mdb. The second message box tells you that the original value is about to be changed to 5000 and asks you whether you want to continue. If you click Yes, the CommitTrans method is triggered, and the change becomes permanent. If you click No, the RollBack method is triggered, and the changes are deleted from memory, leaving the record unchanged.


Using DAO to Alter a Database

One of the more powerful features of DAO is its ability to change the structure of a database. During the development of your application, you may find that you could organize your information better by adding temporary tables to the database or adding fields to a table. You can add tables while working in an application by appending a TableDef object to the TableDefs collection; you can add fields to a table by appending a Field object to the Fields collection and then appending the Fields collection to the TableDefs collection. You can also change relationships or indexes between tables.

Mapping the Database

Before you begin modifying the objects in a database, it's helpful to get a summary of the object names and structures in the database. Getting this summary is called "mapping the database." The following example maps the Nwind.mdb database by looping through the elements in the TableDefs collection and transferring the structure to Sheet1 in the active workbook. This process is similar to scanning the headings of a worksheet in Microsoft Excel.

Dim db as Database
Dim i As Integer, j As Integer, col As Integer, rw as Integer
Dim system_Prefix as String, Current_TableName as String
Dim hidden_prefix as String
Set db = OpenDatabase("d:\access\sampapps\nwind.mdb")
With Worksheets("Sheet1")
    col = 1
    For i = 0 To db.TableDefs.Count - 1
        Current_TableName = db.TableDefs(i).Name
        ' Omit jet system tables from the list
        system_Prefix = Left(Current_TableName, 4)
        hidden_prefix = Left(Current_TableName, 1)
        If system_Prefix <> "MSys" And system_Prefix <> "USys" And
        hidden_prefix <> "~" Then
            .Cells(1, col) = db.TableDefs(i).Name
            'Display the fields inside each table
            rw = 2
            For j = 0 To db.TableDefs(i).Fields.Count - 1
                .Cells(rw, col) = db.TableDefs(i).Fields(j).Name
                .Cells(rw, col + 1) = db.TableDefs(i).Fields(j).Type
                rw = rw + 1
            Next j
        col = col + 2
        End If
    Next i
End With

You can set up a similar procedure to loop through the query names in the database by specifying the QueryDefs collection instead of the TableDefs collection and adjusting the index and looping variables.

Modifying the Database Structure

You can use DAO to change the structure of your database programatically. Modifying the database is similar to creating it initially. In most cases, you use the same Create and Append methods to add objects. You can add new TableDef objects to a database or add new Field and Indexes objects to existing tables. In addition, you can delete a TableDef object from a database or delete an Index object from a TableDef object.

There are some restrictions that apply to deleting field objects, however. For example, you cannot change an individual field after it's been appended to a TableDef object. You can delete a Field object only if it's not part of any Index or Relation objects. To delete an individual Field object, use the Delete method of the TableDef object. To change a Field object, you must first add a new TableDef object that reflects the desired changes in the structure, and then you must move the data to the new table and delete the old table. For more information about modifying the database structure, see "TableDef object" in Help.

Note

To delete an indexed field, you must first delete the index. You must also delete any affected Relation objects before you can delete a Field object or a TableDef object that's part of a relationship.

Attaching Tables

In addition to defining your own tables, you can attach tables from any supported database to the database you're working in. When you attach an external table, the connection information is stored in your database, and the connection to the outside table is activated when you open the table. The data itself remains in the external database.

You can use attached tables the same way you use any other table in your database. You can create Recordset objects that include fields from attached and local tables, giving you the flexibility to perform queries with multiple databases. When you attach an external table, you must specify a SourceTableName string and a Connect string as you create the TableDef object.

Note

Because an attached table isn't controlled by Jet, you cannot change the fields inside the table, add new fields to its structure, or delete its indexes.

Use the CreateTableDef method to create a new table object in your database. The name of the table in the argument is the name of the table as it will appear in your database; the table may have a different name in its native database.

Dim tb as TableDef

Set tb = db.CreateTableDef("Attached Customers Table")

Set the SourceTableName property to the name of the table in the source database that you want to connect to. You must specify the table name as it appears in its native database.

tb.SourceTableName = "Customers"

Set the Connect property by first specifying the path and filename of the source database and then appending the new table to the Tabledefs collection.

tb.Connect = ";database=e:\access\sampapps\nwind.mdb"
db.TableDefs.Append tb


Optimizing DAO Code

After you've gotten your application working, you can begin optimizing. There are several ways to optimize your application, many of which are described in the following paragraphs. However, the optimization you choose will depend on your computer configuration and the application you're using.

Optimizing All Queries

If your application updates data frequently or performs calculations on sections of large data sets, optimizing the queries that perform these actions will significantly improve the speed of your application. Small adjustments in the body of the query or in the SQL statement may be all you need to improve your application. For information about optimizing queries, see "Queries" in Help.

Opening Tables Directly

This method cannot be used with ODBC data sources because they cannot, by design, be opened directly as tables.

When using remote data sources, Jet provides two types of Recordset objects: Dynaset objects and Snapshot objects. If you don't need to update data in your result set, and if the result set contains fewer than 500 records, you can optimize your application by returning a Snapshot object. Snapshot objects are read-only optionally forward-only scrolling result sets; a Snapshot object is generated faster than a Dynaset object because it represents a picture of your data set.

Replacing the Find Method with the Seek Method

If you directly open a table that contains an index on the field you want to search, using the Seek method will always be the fastest way to locate a record. However, the Seek method can be used only on directly opened tables.

The Find method isn't as fast as the Seek method because of the overhead associated with dynasets or snapshots — specifically,copying matching records from a table and maintaining the indexes.

Using Stored Queries Instead of SQL Text

Using stored queries greatly increases processing speed — especially low-memory computers — because Jet's query compiler isn't needed. If you call a SQL text string, the query compiler is called; Jet then binds references, builds a query tree, chooses an optimization method, and then runs the query.

Using Parameter Queries Instead of SQL Text

If the values of a query aren't known before compile time, or if the application depends on user-supplied values for the query, it may not be possible to use stored static queries. In this case, using a parameter query is still faster than using a SQL text string because a parameter query is also a stored compiled query. For information about building a parameter query, see "parameter queries" in Help.

Using Transaction Processing

The BeginTrans method tells Jet to buffer all changes to the Recordset object. The changes will be written to the data set when the EndTrans method is applied. Without transaction processing, Jet writes changes directly to the Recordset object each time a change occurs, which may dramatically increase disk access. However, if the activity within the transaction is too large, changes to the Recordset object will be stored both in memory and in a swapfile, which increases disk access. The optimal number of records to store in a transaction depends on the computer configuration; you may need to experiment with the record numbers.

Using Bookmarks Instead of the Find Method

Using a bookmark instead of the Find method dramatically increases performance because a bookmark is essentially a stored primary key that Jet uses to return to the previous record location. In contrast, the Find method searches the entire data set for the previous record.

Using the CopyFromRecordset Method

The CopyFromRecordset method optimizes your application by copying large chunks of records as a unit instead of copying individual records. Variables for indexing and looping aren't needed in the result set or on the worksheet.

Using the GetRows Method

Whereas the CopyFromRecordset method copies and pastes an entire result set into a Microsoft Excel range, the GetRows method returns only a specified number of records from the result set (starting with the first record).

The following example pastes the first six records from the result set created by the OpenRecordset method into cells A1:B6 on Sheet1.

Dim db As Database, rs As Recordset
Dim data As Variant
Set db = OpenDatabase("c:\access\sampapps\Nwind.mdb")
Set rs = db.OpenRecordset("Select Customer.[City] from Customer;")
Do While Not rs.EOF
    data = rs.GetRows(6)
Loop
Sheets("Sheet1").Activate
For Each i In ActiveSheet.Range("A1:B6") _
    i.Value = data(i.Column - 1, i.Row - 1)
Next
rs.Close
db.Close

End Sub


Using ODBC

Open Database Connectivity (ODBC) is a standard protocol that permits applications to connect to a variety of external database servers or files. The ODBC drivers that Jet uses permit access to Microsoft SQL Server and other external databases, such as ORACLE®. An ODBC driver is a dynamic-link library (DLL) used to connect a specific ODBC data source with another (client) application. You can use the ODBC driver supplied with the application you program in, you can use a third-party driver, or you can write your own driver.


Connecting to ODBC Data

Establishing a connection to a server requires time and memory from both the client and the server. If you can limit your ODBC connection time or the number of connections to the server, you will reduce the resources your application uses and thereby optimize performance. When you connect to an ODBC data source, you supply file locations, server and user passwords, and sometimes locking information. You supply this information with the connection string, which must be verified and executed each time you access the data file. However, Jet has a built-in connection management capability that caches this information and reuses it as needed. In addition, Jet shares connections whenever possible.

You may therefore want to consider storing your ODBC tables as attached tables in an .mdb file. The only drawback to storing ODBC data this way is that if the ODBC file locations change, you must reestablish a connection to the new data file by dropping and reattaching the tables in the .mdb file.


Optimizing ODBC Performance

The fastest way to access ODBC data is first to use Microsoft Access to create linked tables in an .mdb file and then to use those linked tables in your DAO code. Although older versions of DAO permitted you to do it, one of the slowest and most inefficient ways to process server data is to open a dynaset on an attached ODBC table directly and then proceed to move through the dynaset.

Many of the same techniques used to optimize DAO code — excluding the ones previously noted — can be used to optimize ODBC performance as well. In addition to the techniques suggested in "Optimizing DAO Code" earlier in this chapter, there are several techniques that apply specifically to improving ODBC data performance.

If you don't have Microsoft Access, you can create your own linked tables in an .mdb file by using code such as that shown in the following example. You only have to do this once, after which you can reuse the .mdb file in multiple applications.

Dim db As Database
Dim td as Tabledef
Set db = CreateDatabase("d:\attached\CorpSQL.mdb", dbLangGeneral)
Set td = db.CreateTableDef("OrderDetail")
td.Connect = "ODBC;DSN=SSRVR1;UID=Fred;PWD=RHS;DATABASE=SQLDB;"
td.SourceTableName = "OrderDetails"
db.Tabledefs.Append td

For more information, see "Accessing External Databases with DAO" in Help.

Using Remote Data Caching

You can improve your application's performance by caching remote data. A cache is a space in local memory that holds the data most recently retrieved from the server. When data is requested from an ODBC source, Jet first checks the cache for the requested data, which takes less time than retrieving it from the server. If you anticipate working extensively in a small range of records (fewer than 200), you should use remote data caching. Use the CacheStart and CacheSize properties to specify the range and size you want within the result set. Use the FillCache method to quickly fill all or part of this range with data from the server.

Dim rs As Recordset
Dim db As Database

Set db = OpenDatabase("e:\attached\CorpSQL.mdb")
Set rs = db.OpenRecordset("OrderDetail", dbOpenDynaset)
rs.FindFirst "CustID = 1001"
rs.CacheStart = rs.Bookmark
rs.CacheSize = 50
rs.FillCache

Note

This code assumes that you have an .mdb file with an OrderDetail table attached to an ODBC data source.

Using SQL Pass-Through Queries

A SQL pass-through query is a specialized type of SQL query that's designed to bypass the Jet engine and communicate directly with a SQL server. In a regular query, Jet resolves references to fields, tables, and functions when the SQL statement is compiled. In a pass-through query, Jet hands the entire query over to the server to compile and resolve references. There are several advantages to running a SQL pass-through query:

  • You can take advantage of server-specific functionality that doesn't exist at the local level (such as SQL stored procedures) when you write your statement. For more information about stored procedures, see your server software manual.
  • SQL pass-through queries are faster than local queries because they communicate directly with the SQL server, which can process data, compile SQL code, and return a result set faster that the Jet engine can.
  • Because the entire query is processed on the server and only the Recordset object is returned, you have less network traffic while data is being requested and returned.

The following example creates a temporary pass-through query.

Dim db as Database
Dim tempqry as QueryDef

Set db = OpenDatabase("Mydb.mdb")
Set tempqry = db.CreateQueryDef("")
db.Connect = "ODBC; DSN=MySQLDBD; UIS=Guest;PWD=''
PassThrough.ReturnsRecords = True
tempqry.SQL = "UPDATE Orders Set ShipCity = 'LondonTown' WHERE _
    ShipCity = 'London'"
tmpqry.Execute
tmpqry.SQL = "UPDATE Orders Set ShipCity = 'New York City' WHERE _
    ShipCity = 'New York'"
tempqry.Execute


Appendix A Writing Code for International Use

Using Visual Basic, it's possible to distribute Microsoft Excel applications to users in countries whose native language isn't the one you wrote your code in. This appendix offers guidelines for choosing a language to write your code in and provides tips for writing and distributing applications for international use. You'll also learn techniques to ensure that your code runs as you expect it to run — and more important, as your users expect it to run — no matter where you transport it.

In this appendix, an application is assumed to be a workbook or collection of workbooks that performs a specific task and that runs within Microsoft Excel. A locale is the country or locale selected on the Regional Settings tab in the Regional Settings Properties dialog box (Control Panel). A language is the country or language selected in the Language/Country box on the Module General Tab in the Options dialog box (Tools menu). Finally, an object library is a file that determines what words and symbols Visual Basic can understand — that is, the names of objects, properties, methods, Visual Basic statements, and so on that you type in a Visual Basic module. These words and symbols vary from language to language.


General Guidelines

Use the following guidelines to write Visual Basic code that runs effectively in other locales. These guidelines are presented as three scenarios, beginning with the scenario that provides the safest and most predictable results. If you understand these three scenarios, you can better predict how your distributed code will perform.

  • Write your code in English (with English/United States selected in the Language/Country box on the Module General Tab in the Options dialog box (Tools menu)). The code will run on any computer running Microsoft Excel because Microsoft Excel registers the English object libraries as the default libraries during installation.
  • Write your code in any localized language, and distribute the code with the corresponding object library files. The code will run correctly on the localized machine if the accompanying object is installed. For a complete list of languages and their corresponding object libraries, see "Names of the Object Library Files" later in this appendix.
  • Write your code in any localized language, and distribute the code without object library files. The code will only run on computers that already have the proper object library files installed. For a complete list of languages and their corresponding object libraries, see "Names of the Object Library Files" later in this appendix.

Important

Don't write Visual Basic code for distribution to other computers with English/(Custom) selected in the Language/Country box on the Module General Tab in the Options dialog box (Tools menu). Code you write with that option in effect won't run properly on other computers.


Writing Transportable Visual Basic Code

The following guidelines will help you write your Visual Basic code so that it runs more effectively in other locales. Understanding these guidelines is important in predicting how your code will perform. The guidelines fall into the following areas:

  • Working with formulas
  • Using conversion functions
  • Displaying information with locale-aware functions and statements
  • Working with local language text in your code
  • Other considerations when writing transportable Visual Basic code


Working with Formulas

Microsoft Excel provides formulas to help you analyze data on a worksheet or to perform operations on sets of data on multiple worksheets. When you write code, you can choose to use a formula in the language of your user, or you can choose to use a formula in a language that's familiar to you and have Visual Basic convert the formula to the language of your user.

Using the Formula and FormulaLocal Properties

You can use the Formula property to enter a formula in a cell. If the formula you enter contains worksheet functions, Microsoft Excel converts the functions to the appropriate language. For example, suppose you use the Formula property to enter a formula in cell A1 on Sheet1, as shown in the following code.

ThisWorkBook.Worksheets("Sheet1").Range("A1"). _
    Formula = "=SUM(A2:A3)"

When Microsoft Excel enters the formula on the worksheet, it automatically converts it to the equivalent formula in the language that's been set for the workbook.

If, instead, you write your code so that the user enters formulas in input boxes, Visual Basic still converts worksheet functions in the provided formulas, but you must use the FormulaLocal property instead of the Formula property. The FormulaLocal property converts the worksheet function the user types in the input box to the equivalent formula in the language that's been set for the workbook. The following example displays an input box and then inserts the formula the user supplies into cell A1 on Sheet1.

FormulaText = InputBox(EnterFormulaMessage)
ThisWorkbook.Worksheets("Sheet1").Range("A1") _
    .FormulaLocal = "=" & FormulaText

If you subsequently open the workbook on a computer that's running the German version of Microsoft Excel, run the preceding example, and type sum(a2:a3) in the input box, the following formula appears in the formula bar.

= SUMME(A2:A3)

Using the NumberFormat and NumberFormatLocal Properties

The NumberFormat property is used to set the format code for a range on a worksheet. The format code is the string that appears in the Category box on the Number tab in the Format Cells dialog box. The following example sets the format code for cell A17 on Sheet1 to "General."

Worksheets("Sheet1").Range("A17").NumberFormat = "General"

The NumberFormatLocal property sets the format code for the object in the language that's been set for the workbook. The following example displays a message box showing the number format for cell A17 on Sheet1 in the language that's been set for workbook.

Msgbox "The number format for cell A17 is " & _
    Worksheets("Sheet1").Range("A17").NumberFormatLocal


Using Conversion Functions

Visual Basic provides several functions that convert data from one type to another using locale settings. However, some functions aren't locale-aware. Whenever possible, use the locale-aware functions to make your code transportable. This is especially important when you're converting strings to numbers or dates.

For example, the Str and Val functions always assume that a period is the decimal separator, but CStr, CDbl, CSng, CInt, and CLng use the current operating system settings to determine the decimal separator.

Special Considerations for Dates

Never type dates as strings in your code, because date formats aren't the same in every country. Even locale-aware conversion functions can process strings in ways you might not expect. For example, the following code behaves differently in different locales.

StartDate = "2/3/95"
NewDate = CDate(StartDate)

When run in an English/United States locale, NewDate contains a value equivalent to February 3, 1995; in an English/Australia locale, NewDate contains a value equivalent to March 2, 1995. This behavior is a potential source of error when you're programming, but it's very useful for processing user input from a dialog box. CDate converts the user's text into the date that the user intends.

However, as the programmer, you should always code dates as literals — such as #2/3/95# — so that Visual Basic recognizes the exact date you intend. For example, in the following code, NewDate contains a value equivalent to either February 3, 1995, or March 2, 1995, depending on the locale of the programmer, but not the locale of the user. The date is the same for all users wherever the code is run.

StartDate = #2/3/95#
NewDate = CDate(StartDate)

The date literal is interpreted in the context of the programmer's locale.

Special Considerations for Currencies

Similarly, never store a currency value as a string that includes a currency symbol, because the currency symbol varies according to locale. For example, the following code doesn't run in any locale except those where the dollar sign ($) is the currency symbol.

Money = "$1.22"
NewMoney = CCur(Money)

Instead, store a currency value as a decimal number, as shown in the following example. (This example assumes that the period is the decimal separator in the programmer's locale, but the code runs correctly no matter what the decimal separator is in the user's locale.)

Money = 1.22
NewMoney = CCur(Money)


Displaying Information with Locale-Aware Functions and Statements

As explained previously, different locales have different conventions for displaying dates, times, numbers, currency, and other information. As a programmer, you cannot know the conventions for all your users' locales, and you don't have to know them. Many Visual Basic statements use the locale settings to determine the conventions automatically at run time, but some statements are more locale-aware than others. In general, Help tells you whether a statement or function is locale-aware, and if so, in what ways.

For example, the Print statement provides little flexibility for different output formats; it does, however, use the operating system locale settings. Dates are printed using the correct short date format, numbers are printed with the correct decimal separator, and currencies are printed with the correct symbol.

The Format function can accept format codes, but format codes always produce the same type of output without regard to the user's locale. For example, the format code "mm-dd-yy" isn't appropriate for locales in which the day precedes the month.

For more flexibility, the Format function also provides named formats that are locale-aware, including Short Date, Long Date, Long Time, and General Number. Using named formats produces output that's based on the user's operating system locale settings.

MyDate = #January 27, 1994#
MyStr = Format(MyDate, "dd-mm-yy")        'Returns 01-27-94
MyStr = Format(MyDate, "Short Date")        'Returns a short date based on
                                        'the locale where the code is                                             'running


Working with Local Language Text in Your Code

Visual Basic includes many features to help your code run properly in other locales, but it cannot automatically translate text from one language to another. For example, you might want your application to include menu text, dialog text, alert messages, and so on. At first, it might seem that you must type this text directly into your code, which prevents the code from becoming a truly transportable application. However, you can create a string table to replace specific quoted text with variables and references to worksheet names. The cells your worksheet names refer to can vary depending on the locale in which your code is running. In this way, you can display words and phrases that change depending on your user's locale.

For example, the following worksheet includes a string table for three languages.

To use the string table, define names for cells in the Localized Strings column. You can use the Offset method to get the text in the other language columns. To work in English, use 0 (zero) for the columnOffset argument; to work in French, use 1 for the columnOffset argument; and to work in German, use 2 for the columnOffset argument. You can obtain the column offset value in any of the following ways:

  • Use the International property of the Application object to determine the locale version of Microsoft Excel (xlCountryCode) or the current country setting of the operating system (xlCountrySetting). Make a mathematical adjustment to convert the setting to a column offset value, and then define a Public variable accordingly. (For more information about public scope, see Chapter 2, "Variables, Constants, and Data Types.")
  • Display a dialog box asking the user for a language or country name. Then define a public variable, and assign it an offset value according to the user's input.
  • Define a public constant that the user sets.

The following code determines an offset code based on the language version of Microsoft Excel you're using.

Public GlobalOffsetCode

Sub GetGlobalOffsetCode()
Select Case Application.International(xlCountryCode)
    Case 1:                            'US English
        GlobalOffsetCode = 1
    Case 33:                            'French
        GlobalOffsetCode = 2
    Case 49:                            'German
        GlobalOffsetCode = 3
    Case Else:                        'US English as the default language
        GlobalOffsetCode = 1
End Select
End Sub

The following code uses this offset code to display an appropriate message box to welcome the user.

WelcomeMsg = ThisWorkbook.Worksheets("LocalizationTable").Range _
    ("Welcome").Offset(0, GlobalOffsetCode).Value
MsgBox WelcomeMsg

You can use a similar technique to change the text, positions, and sizes of items in dialog boxes, making your code truly transportable.


Other Considerations When Writing Transportable Visual Basic Code

There are other things you need to consider when you're writing code that can vary by locale. The following are the most common of these considerations:

  • Comparing strings

    The rules for comparing strings vary by locale when you're using the less-than (<), greater-than (>), equal-to (=), and Like operators, and the StrComp function. For more information, see "Option Compare," "Like," and "StrComp" in Help.

  • Working with file input and output

    Locale is also a consideration for file input and output. The Print # statement writes to data into a file as the data is displayed on-screen in a locale-aware format. The Input # statement cannot read this information from the file. By comparison, the Write # statement puts data into a file in a fixed format, which ensures that the Input # statement can read it later in any user locale.

  • Using the macro recorder

    The macro recorder records your actions in a module in the language specified on the Module General Tab, not in the language of the worksheet. If, for example, your language setting is English/United States and your locale setting (the setting for the worksheet) is French/France, the macro is recorded in English.

    You can use the FormulaLocal property to return a formula, as a string, in the same format in which it would be displayed in the formula bar (including the equal sign). For more information about the FormulaLocal property, see "Working with Formulas" earlier in this appendix.


Using Object Libraries to Make Your Code Transportable

During installation, Microsoft Excel registers the English object libraries as the default libraries, regardless of the language version of Microsoft Excel. However, if you install the appropriate Visual Basic object library in your Windows system folder and the corresponding Microsoft Excel object library in your Microsoft Excel program folder, you can write your Visual Basic code in a language other than English. Your code language can be different from the language of the Microsoft Excel application because the object library translates your code into statements that can run in any language version of Microsoft Excel.

Important

You cannot transport code written on a system that's set up for a Far Eastern double-byte character system (DBCS) language to a system that's not similarly set up, unless the code is written in English.

Object libraries provide lexical information that Microsoft Excel uses to determine how to work with dates, times; and number separators.

With object libraries, you can write your code in a way that's familiar to you, and users in other countries can run your code in a way that's familiar to them. For example, if the decimal separator in your locale is the period, you'll want to use it when you type numbers in code. If another symbol, such as the comma, is the decimal separator in your user's locale, you'll want it to appear when your code displays numbers. And you want your code to interpret the comma correctly when a user enters a number in a cell or dialog box. Object libraries make this possible.


Choosing a Locale for your Visual Basic Code

If the appropriate object libraries are installed on your disk and registered with Visual Basic, you can choose to write your Visual Basic module code in a language other than English. You can also specify a corresponding country, thus specifying how you type dates and times and what symbols you use for the list separator, the decimal separator, and so on. The language/country combination sets the locale of your Visual Basic environment — the language in your module code can be different from the language of the Microsoft Excel application. The object library registered when you select a language translates your module code into statements that Microsoft Excel understands.

To choose a language in which to write or edit Visual Basic code

1. On the Tools menu, click Options, and then click the Module General tab.

2. In the Language/Country box, click the language and country you want to use.

If the locale setting you want isn't listed in the Language/Country box, you must install the appropriate object libraries, as explained in "Installing and Registering Object Libraries" later in this appendix.


Current Settings and Default Settings

Under International on the Module General tab in the Options dialog box (Tools menu), you'll see the Current Settings and Default Settings option buttons. If you click Current Settings, the Language/Country and associated settings for the active workbook will be displayed. If you click Default Settings, the default settings for each new workbook you create will be displayed. For example, if you usually work in the English/United States locale and you receive a French/France application, clicking Current Settings displays locale information about the application, but the default settings for the rest of your work are still the English/United States settings.


Working in Multiple Locales

There's one locale setting stored with each workbook, so different workbooks can have different settings, even if all the workbooks are open at the same time. With this feature, you can write and call procedures written in several languages.

Visual Basic doesn't automatically translate existing code from one language into another. You must edit the code using the same locale setting that was used when the code was originally written. Using multiple locales requires using multiple workbooks and multiple object libraries. However, you can edit the code with any language version of Microsoft Excel; for example, you can edit Dutch code using Norwegian Microsoft Excel, but the code will be displayed in Dutch.


Installing and Registering Object Libraries

If you cannot find the locale you want to use listed in the Language/Country box on the Module General tab in the Options dialog box (Tools menu), you must install and register the corresponding object libraries. Visual Basic in Microsoft Excel requires two object library files for each language: the Microsoft Excel object library and the Visual Basic for applications object library.

For specific information about the names of the object library files and how you acquire the files, see the appropriate Help topics.

To install object libraries

  • For each language you want to work with, copy the Microsoft Excel object library files to your Microsoft Excel program folder, and copy the Visual Basic object library files to your Windows system folder (or your System32 folder if you're using the Windows NT™ operating system). For a complete list of object library names, see "Names of the Object Library Files" later in this appendix.

If someone gives you an application written in another language and includes the object library files, those files are registered automatically when you try to run any of the procedures in the application. However, if you write code and use the object libraries for the first time, you must register them with Microsoft Excel yourself. Registering files means making Microsoft Excel aware that they exist. You only have to register an object library once, unless you move or rename one or both files.

To register a new language version of the object library files

1. Switch to a Visual Basic module.

2. On the Tools menu, click References.

3. Click Browse.

4. In the Look In box, click the name of the folder that contains the new Microsoft Excel object library file.

5. Double-click the object library filename.

(Repeat steps 3 through 5 for the Visual Basic object library file.)

6. Click OK to close the References dialog box.

You can now click Options on the Tools menu, click the Module General tab, and select the locale you want.

If the language you want still isn't available, Microsoft Excel has already assigned a language to your workbook. You should open a new workbook and repeat the preceding steps. Remember, you can assign a language to a workbook only once, as explained in "Working in Multiple Locales" earlier in this appendix.


Distributing Object Libraries

If your Visual Basic code isn't written in English (with the English/United States option selected on the Module General tab), you must either include the appropriate language object libraries when you distribute your application or make sure that the recipients already have the appropriate object libraries installed on their computers. If your code calls procedures written in multiple languages, you should include the object libraries for each of those languages. You should also include all workbooks and other object libraries that are referenced by the application you're distributing.

Note

Microsoft allows all registered owners of Microsoft Excel to distribute object libraries with their applications to other registered owners as necessary.

Object libraries are platform-specific, so if you plan to distribute your workbooks both to users of Microsoft Excel for Windows and users of Microsoft Excel for the Macintosh, you must include both the Windows and Macintosh versions of the object libraries.


Names of the Object Library Files

For Microsoft Excel for Windows, some of the object library filenames are listed in the following table.

Language | Microsoft Excel object library filename | Visual Basic for applications object library filename
English | Xl5en32.olb | Vbaen32.olb
French | Xl5fr32.olb | Vbafr32.olb
German | Xl5de32.olb | Vbade32.olb
Spanish | Xl5es32.olb | Vbaes32.olb
Italian | Xl5it32.olb | Vbait32.olb
Portuguese | Xl5ptg32.olb (Portugal) | Vbaptg32.olb
Portuguese | Xl5ptb32.olb (Brazil) | Vbaptb32.olb
Swedish | Xl5sv32.olb | Vbasv32.olb
Norwegian | Xl5mp32.olb | Vbamp32.olb
Finnish | Xl5fo32.olb | Vbafo32.olb
Dutch | Xl5nl32.olb | Vbanl32.olb
Danish | Xl5da32.olb | Vbada32.olb

Many other object libraries might become available later.


Running Your Code in Other Language Environments

The preceding sections explain how a locale setting determines how you, as a programmer, should enter Visual Basic code. However, the way you enter items such as dates, formats, and so on isn't always the same as what the user should see, depending on his or her locale.

At run time, Visual Basic functions usually behave as they should for the user. Visual Basic typically uses the locale settings of the operating system — not the locale settings of your Visual Basic editing environment — to determine how to interpret user-supplied numbers and dates, such as information the user enters in dialog boxes, values the user enters in cells, and so on. Visual Basic also uses these settings to determine how to display numbers and dates — such as the results of the Format function — to the user.

For example, the following two procedures are written in different languages (one in English and one in French), but they display the results in the same language when they're run on the same system. The language of the display is determined by the locale settings of the operating system. The following illustration assumes that the user has a German system with German, English, and French object libraries installed.

As a user, you might occasionally need to change your operating system locale settings to suit your needs. Or, as a programmer, you might want to change the settings to test applications you plan to distribute to others. Changing operating system locale settings will change the output of locale-aware functions and statements.

To change the locale (region) settings in Microsoft Windows

1. Click Start on the taskbar, point to Settings, and then click Control Panel.

2. Double-click the Regional Settings icon.

3. On the Regional Settings tab, click a country on the map, or click the name of a language in the list box.

The settings on the Number, Currency, Time, and Date tabs automatically change according to the language you select; however, you can also change the settings on these tabs manually.


Writing International Code That Controls Multiple Desktop Applications

If you plan to run Microsoft Excel with another desktop application that supports Visual Basic, you need the appropriate language version of the object libraries for that desktop application. For example, suppose you want to write Italian code that uses features of both Microsoft Excel and Microsoft Project. To do this, you need the following files:

  • The Microsoft Excel Italian object library
  • The Visual Basic for applications Italian object library
  • The Microsoft Project Italian object library

For the purposes of this example, the language versions of Microsoft Excel and Microsoft Project are unimportant. Your Italian code will work with any version of Microsoft Excel and any version of Microsoft Project, provided that you include the appropriate object libraries (see the preceding list).

For more information about writing code that works with other applications, see Chapter 10, "Communicating with Other Applications."


Appendix B Switching from the Microsoft Excel 4.0 Macro Language

This appendix introduces users of the Microsoft Excel 4.0 Macro Language to programming with Visual Basic. In this appendix, you'll learn how Visual Basic differs from the Microsoft Excel 4.0 Macro Language, how you can continue using your existing Microsoft Excel 4.0 macros, and where to find more information about Visual Basic.

Visual Basic is a true programming language that features variables with scoping, an integrated editor, and enhanced dialog box tools and debugging tools. Learning Visual Basic with Microsoft Excel version 7.0 makes it easier for you to learn programming with Microsoft Access, Microsoft Project, and other Microsoft applications that use Visual Basic. You can also control these other applications easily in your Visual Basic code. You can use Microsoft Excel with Visual Basic to easily learn Visual Basic programming at your own pace, without losing any of your existing investment in Microsoft Excel 4.0 macros.

Important

Most features of Microsoft Excel version 7.0 can be recorded in the Microsoft Excel Macro Language. For more information, refer to the Microsoft Answer Wizard.


Information for Users of Microsoft Excel 4.0 Macros

This section guides experienced users of Microsoft Excel 4.0 macros to information about learning and using Visual Basic. For more detailed information, see the chapters and Help topics that are cross-referenced in this section.


Recording Macros in Visual Basic

In Microsoft Excel version 7.0, you can choose the language in which to record a macro.

To choose the programming language in which to record a macro

1. On the Tools menu, point to Record Macro, and then click Record New Macro.

2. Click Options.

3. Under Language, click an option.

In Microsoft Excel version 7.0, you can still record your macros in a workbook that opens each time you start Microsoft Excel. In Microsoft Excel version 4.0, this workbook is called Global.xlm (in Microsoft Excel for Windows) or Global Macro Sheet (in Microsoft Excel for the Macintosh). In Microsoft Excel version 7.0, this workbook is now called Personal.xls or Personal Macro Workbook, depending on the platform (Windows or the Macintosh). Your existing macros still run; new macros are simply recorded in the new workbook. Microsoft Excel version 7.0 creates your new Personal Macro Workbook when you record your first macro.

For more information about recording macros, see "Record a macro" in Help.


Acting Directly on Objects in Visual Basic

In Microsoft Excel version 4.0, macros follow the "select, then do" order of actions that pertains to all of Microsoft Excel. With Visual Basic, you don't need to select an object you want your procedure to change. You can change the object directly.

For example, to make a range of text bold in Microsoft Excel version 4.0, you have to first select the range with the SELECT function before changing the format of the text with the FORMAT.FONT function. In Visual Basic, you make a range of text bold just by setting the Bold property of the range to True. For example, type the following function in a module:

Sub MakeSectionBold()
    Worksheets("Sheet1").Range("C1:G5").Font.Bold = True
End sub

Note that you can use Visual Basic to directly change an object (in this case, the range C1:G5) without selecting it or canceling the current selection. For more information about how to change cells, sheets, charts, shapes, and other objects in Visual Basic, see Chapter 4, "Objects and Collections."


Variables: More Powerful Than Names

To store a value as a variable in Microsoft Excel version 4.0, you'd typically store the value in a name. In Visual Basic, you'd assign the value to a variable instead.

Variables are much more flexible than names. You can make variables available to all procedures, to only the procedures in a given module, or to only a single procedure. You can control the type of data that can be stored in a variable and even create variables that store a combination of your choice of data types.

In Visual Basic, you can also define constants to hold static (constant) values that you can refer to repeatedly. For more information about variables and constants in Visual Basic, see Chapter 2, "Variables, Constants, and Data Types."


Using Worksheet Functions in a Procedure

Many worksheet functions can be used directly in Visual Basic procedures; the IF function is one exception, though, as If is also a keyword in Visual Basic. You can use the Application qualifier to run a Microsoft Excel worksheet function rather than a Visual Basic function. For example, the following procedure causes a "Sub or Function not defined" error because it doesn't identify ACOS as a worksheet function.

Sub MissingObject()
    x = Acos(-1)
End Sub

The following procedure successfully uses the Microsoft Excel worksheet function ACOS because the code first refers to the Application object.

Sub ReturnArccosine()
    x = Application.Acos(-1)
End Sub

The only worksheet function that requires you to explicitly specify that you're referring to either the function's Microsoft Excel version or its Visual Basic version is the LOG function, because both function names are spelled the same way. The Microsoft Excel LOG function returns the logarithm of a number to the base you specify. The Visual Basic Log function returns the natural logarithm of a specified number.


Using Your Existing Macros in a Procedure

You can include your existing macros in new Visual Basic procedures by using the Run method. When you debug Microsoft Excel 4.0 macros as part of your Visual Basic procedures, the Visual Basic debugger steps into your macros as if they were written in Visual Basic. Your macros can return information to a procedure using the RETURN macro function.

For more information and an example of the Run method, see "Run Method" in Help.


New Tools to Make Debugging Easy

There are numerous tools in Visual Basic to help you debug your code.

  • Breakpoints. A breakpoint defines a statement or set of conditions at which Visual Basic automatically stops your program and puts the code in break mode without running the statement containing the breakpoint. You can use breakpoints to examine your code and variables at places in your procedures where you think errors are occurring.
  • Debugging buttons. The debugging buttons are included on the Visual Basic toolbar, which is displayed whenever a Visual Basic module is active. You can use these buttons to run your code one statement or procedure at a time, to control breakpoints, and to examine values of variables and expressions.
  • The Debug window. You can use the Step Into command on the Run menu to display the Debug window. Using the Debug window, you can monitor the values of expressions and variables while running your code one statement at a time. You can also use this window while running your code to change the value of variables and properties to see how different values affect your code.

The Debug window contains three areas:

  • The Immediate pane, which displays results from debugging statements in your code. You can also request debugging information by typing commands directly in the Immediate pane.
  • The Watch pane, which displays expressions whose values you've decided to monitor as your code runs.
  • The Code pane, which displays the most recently executed statement and allows you to browse surrounding pieces of code.

For more information about these tools and other aspects of debugging in Microsoft Excel, see Chapter 6, "Debugging."


Visual Basic Equivalents for Common Macro Functions

The easiest way to see the Visual Basic equivalents for common macro functions and Microsoft Excel commands is to use the macro recorder to record macros in Visual Basic. You can open two windows in your workbook: one window shows your Visual Basic module, and the other one shows the worksheet or chart you're working on while you're recording a macro. As you work, Microsoft Excel adds Visual Basic statements to your module.

No matter how you write your programs in Microsoft Excel, there are common tasks you'll want to accomplish, such as referring to ranges, controlling how macros run, accessing data in other applications, getting information about workbooks and objects, and creating procedures that run in response to certain events. The following table shows you where to look in this book for information about how to accomplish these tasks with Visual Basic.

For information about | See this chapter
Referring to cells and ranges on worksheets | Chapter 4, "Objects and Collections"
Controlling the flow of a macro | Chapter 3, "Controlling Program Flow"
Accessing data in other applications | Chapter 13, "Accessing External Data"
Getting information about objects in Microsoft Excel | Chapter 4, "Objects and Collections"
Running procedures in response to events | Chapter 11, "Automatic Procedures and OnEvent Procedures"

Microsoft Excel version 7.0 also includes example code written in both Visual Basic and the Microsoft Excel 4.0 Macro Language. To see this code, open the workbooks in the Examples folder in the folder where you installed Microsoft Excel.


Creating Custom Commands and Dialog Boxes Using Visual Basic

Microsoft Excel version 7.0 includes tools for creating custom menus, commands, and dialog boxes. For more information about creating custom commands and dialog boxes using Visual Basic, see Chapter 8, "Controls and Dialog Boxes," and Chapter 9, "Menus and Toolbars."


Creating Custom Commands

To create a custom menu or command in Microsoft Excel version 4.0, you first create a menu or command table. You then use the macro function ADD.MENU or ADD.COMMAND to place your custom menu or command on a menu bar or a menu.

To create a custom menu or command in Microsoft Excel version 7.0, you use the Menu Editor to assign custom commands and menus to menu bars. For more information about using the Menu Editor, see Chapter 9, "Menus and Toolbars."


Displaying Built-in Dialog Boxes

In Microsoft Excel version 4.0, to display built-in dialog boxes while running a macro, you use the question-mark form of the macro function corresponding to the dialog box. For example, the DEFINE.STYLE? macro function displays the dialog box used to define worksheet styles.

In Microsoft Excel version 7.0, to display built-in dialog boxes while running a procedure, you use the Dialogs method with the identifier of the dialog box you want displayed. For example, the following procedure displays the dialog box for the Open command ( File menu).

Sub OpenFile()
    Application.Dialogs(xlDialogOpen).Show
End Sub


Creating and Displaying Custom Dialog Boxes

To create a custom dialog box in Microsoft Excel version 4.0, you use the Dialog Editor to generate a dialog box definition you place on a macro sheet. You then use the DIALOG.BOX macro function to display your dialog box.

In Microsoft Excel version 7.0, custom dialog boxes are stored on dialog sheets in your workbook. To create a custom dialog box, you use the buttons on the Forms toolbar to design and run a dialog box on a dialog sheet in a workbook. You use the Show method in a Visual Basic procedure to display your custom dialog box.

You can use the DialogBox method in your Visual Basic procedures to run a Microsoft Excel 4.0 custom dialog box. The following example uses the DialogBox method to display such a dialog box and then tests the result. The variable DialogRange refers to the range on a Microsoft Excel 4.0 macro sheet that contains the dialog-box definition table.

Result = DialogRange.DialogBox
If Not Result Then
    ' User canceled the dialog box
Else
    ' Result is position number of chosen control
End If

For more information about using dialog boxes in programming Microsoft Excel version 7.0, see Chapter 8, "Controls and Dialog Boxes."


Creating Add-in Applications

In Microsoft Excel version 4.0, all you need to do to convert a macro to an add-in macro is save the macro sheet in the add-in file format; after you do this, the macro sheet will be hidden from view. Microsoft Excel 4.0 add-in macros still run in Microsoft Excel version 7.0. (Add-in macros are called add-in applications in Microsoft Excel version 7.0.)

To create an add-in application in Microsoft Excel version 7.0, you use the Make Add-In command (Tools menu) while a Visual Basic module, Microsoft Excel 4.0 macro sheet, or dialog sheet is active. However, before you convert a workbook containing Visual Basic code to an add-in application, you must save your code in a workbook with a different filename if you want to continue working with the code. After you've converted a workbook to an add-in application, you cannot edit code in that workbook again. You can distribute your add-in application to other users of Microsoft Excel version 7.0, who can run your add-in application but cannot see or change your code.

For more information about add-in applications in Microsoft Excel version 7.0, see Chapter 11, "Automatic Procedures and OnEvent Procedures."


Appendix C Toolbar Buttons in Microsoft Excel

Microsoft Excel provides more than 200 toolbar buttons and boxes that you can display on your toolbars. By default, most of these buttons appear on the built-in toolbars. You can add any built-in button to a built-in or custom toolbar. You can also assign a macro to a built-in or custom button on any toolbar.


Built-in Buttons

The following table lists the built-in buttons alphabetically. The face of each button is shown along with its default action, the category from which the button is selected, and its identifying number for use with Visual Basic. For more information about a built-in button, display the toolbar on which it appears, click the Help button on the Standard toolbar, and then click the toolbar button.

Button | Action |  | Category |  | Number
3-D Area Chart AutoFormat |  | Creates a 3-D area chart with 3-D markers. |  | Charting |  | 109
3-D Bar Chart AutoFormat |  | Creates a bar chart with 3-D markers. |  | Charting |  | 110
3-D Column Chart AutoFormat |  | Creates a column chart with 3-D markers. |  | Charting |  | 111
3-D Line Chart AutoFormat |  | Creates a 3-D line or ribbon chart. |  | Charting |  | 113
3-D Perspective Column Chart AutoFormat |  | Creates a 3-D column chart with a 3-D plot area. |  | Charting |  | 112
3-D Pie Chart AutoFormat |  | Creates a 3-D pie chart with value labels expressed as percentages. |  | Charting |  | 114
3-D Surface Chart AutoFormat |  | Creates a 3-D surface chart. |  | Charting |  | 116
Align Left |  | Aligns the cell, text box, button contents, or selected text in a chart to the left. |  | Text Formatting |  | 63
Align Right |  | Aligns the cell, text box, button contents, or selected text in a chart to the right. |  | Text Formatting |  | 65
Arc |  | Displays a cross-hair pointer you use to draw an arc, or a segment of a circle. |  | Drawing |  | 85
Area Chart AutoFormat |  | Creates a simple area chart. |  | Charting |  | 103
Arrow |  | Displays a cross-hair pointer you use to draw an arrow on the active worksheet or adds an arrow to the active chart document. |  | Drawing |  | 77
Attach Note |  | Adds a note to the current selection. |  | Auditing |  | 154
AutoFilter |  | Displays only those rows that match the value contained in the active cell and inserts drop-down arrows next to each column label in your list. |  | Data |  | 168
AutoFormat |  | Applies the last table format you set. |  | Formatting |  | 52
AutoSum |  | Inserts the SUM function and a proposed sum range based on the data above or to the left of the active cell. |  | Utility |  | 39
Bar Chart AutoFormat |  | Creates a simple bar chart. |  | Charting |  | 104
Bold |  | Applies bold formatting to the selected cells or objects. |  | Text Formatting |  | 58
Borders |  | Displays the Borders palette so that you can apply borders to the selection. |  | Formatting |  | 198
Bottom Border |  | Adds or removes a border along the lower edge of cells. |  | Formatting |  | 47
Bottom Double Border |  | Adds or removes a double border below cells. |  | Formatting |  | 48
Bring To Front |  | Places the selected objects in front of all other objects. |  | Drawing |  | 95
Calculate Now |  | Calculates the formulas in all the open documents or the formula in the formula bar. |  | Utility |  | 126
Camera |  | Copies a picture of the selected range of cells. Click on the worksheet to paste the picture and link the picture to the source cells. |  | Utility |  | 125
Center |  | Centers the cell, text box, button contents, or selected text in a chart. |  | Text Formatting |  | 64
Center Across Columns |  | Centers the text from one cell horizontally across the selected columns. |  | Text Formatting |  | 67
Chart Type |  | Displays the Chart Type palette so that you can change a chart's type. |  | Charting |  | 234
ChartWizard |  | Starts the ChartWizard so that you can edit the selected chart or create an embedded chart. |  | Charting |  | 121
Check Box |  | Creates a check box control. |  | Forms |  | 140
Clear Contents |  | Removes only the formulas or values from the selected cells or deletes the selected objects. |  | Edit |  | 15
Clear Formats |  | Removes only the formats from the selected cells or objects. |  | Edit |  | 16
Colon |  | Inserts a colon in the formula bar. |  | Formula |  | 35
Color |  | Displays the color palette you use to assign a color to the selected object. |  | Drawing |  | 233
Column Chart AutoFormat |  | Creates a simple column chart. |  | Charting |  | 105
Combination Drop-Down Edit |  | Creates a combination drop-down edit control. |  | Forms |  | 197
Combination List-Edit |  | Creates a list box control linked to an edit control. |  | Forms |  | 188
Comma |  | Inserts a comma in the formula bar. |  | Formula |  | 36
Comma Style |  | Applies a comma style to the selected cells. |  | Formatting |  | 55
Constrain Numeric |  | Constrains pen recognition to digits and punctuation. |  | Formula |  | 42
Control Properties |  | Changes control properties. |  | Forms |  | 238
Copy |  | Copies the selection to the Clipboard. |  | Edit |  | 13
Create Button |  | Displays a cross-hair pointer you use to draw a button to which you assign a procedure or a Microsoft Excel 4.0 macro. |  | Drawing, Utility |  | 80
Currency Style |  | Applies a currency style to the selected cells. |  | Formatting |  | 53
Cut |  | Cuts the selection and places it on the Clipboard. |  | Edit |  | 12
Cycle Font Color |  | Changes the color of fonts in selected objects. |  | Text Formatting |  | 62
Dark Shading |  | Applies dark shading to selected cells or objects. |  | Drawing |  | 49
Decrease Decimal |  | Removes one decimal place from a number format. |  | Formatting |  | 57
Decrease Font Size |  | Decreases the font size of the selected text to the next smaller size in the Font Size box. |  | Text Formatting |  | 72
Default Chart |  | Creates a chart using the default chart type set on the Chart tab in the Options dialog box. |  | Charting |  | 120
Delete |  | Removes the selected cells or objects. If you delete cells, using the Delete button shifts the surrounding cells to fill in the space. |  | Edit |  | 19
Delete Column |  | Deletes the selected column. |  | Edit |  | 21
Delete Row |  | Deletes the selected row. |  | Edit |  | 20
Division Sign |  | Inserts a slash in the formula bar. |  | Formula |  | 31
Dollar Sign |  | Inserts a dollar sign in the formula bar. |  | Formula |  | 38
Double Underline |  | Applies double underlining to the selected cells or objects. |  | Text Formatting |  | 176
Doughnut Chart AutoFormat |  | Creates a doughnut chart. |  | Charting |  | 145
Drawing |  | Displays or hides the Drawing toolbar. |  | Drawing |  | 240
Drawing Selection |  | Displays a cross-hair pointer you use to select drawing objects. |  | Drawing |  | 184
Drop Shadow |  | Adds a shadowed rectangle around the selected cells or adds a shadow to the border of the selected objects. |  | Drawing |  | 51
Drop-Down |  | Creates a drop-down control. |  | Forms |  | 182
Edit Box |  | Creates an edit control. |  | Forms |  | 142
Edit Code |  | Goes to an object macro, or creates a new macro if none exists. |  | Forms |  | 244
Ellipse |  | Displays a cross-hair pointer you use to draw an ellipse or a circle. |  | Drawing |  | 84
Equal Sign |  | Inserts an equal sign in the formula bar. |  | Formula |  | 27
Exponentiation Sign |  | Inserts an exponent sign in the formula bar. |  | Formula |  | 32
Fill Down |  | Copies the values, formulas, and formats of the cells in the top row of the selection into the cells below. To copy from the bottom row upward, hold down SHIFT and click this button. |  | Edit |  | 26
Fill Right |  | Copies the values, formulas, and formats of the cells in the left column of the selection into the cells to the right. To copy from the right column to the left, hold down SHIFT and click this button. |  | Edit |  | 25
Filled Arc |  | Displays a cross-hair pointer you use to draw an arc or a circle segment filled with the window background pattern and color. |  | Drawing |  | 90
Filled Ellipse |  | Displays a cross-hair pointer you use to draw an ellipse or a circle filled with the window background pattern and color. |  | Drawing |  | 89
Filled Freeform |  | Displays a cross-hair pointer you use to draw a polygon that's a combination of freehand and straight lines filled with the window background pattern and color. |  | Drawing |  | 92
Filled Polygon |  | Displays a cross-hair pointer you use to draw a polygon filled with the window background pattern and color. |  | Drawing |  | 91
Filled Rectangle |  | Displays a cross-hair pointer you use to draw a rectangle or square filled with the window background pattern and color. |  | Drawing |  | 88
Find File |  | Displays the Find File dialog box so that you can search for files by attribute. |  | File |  | 177
Font |  | Lists the available fonts. Select the font you want to apply to the current selection. |  | Text Formatting |  | 68
Font Color |  | Displays a palette of colors you can use to change the font color in selected cells or the font color of selected text. |  | Text Formatting |  | 236
Font Size |  | Lists the available sizes for the font shown in the Font box. Select the size you want to apply to the current selection. |  | Text Formatting |  | 69
Format Painter |  | Copies formats from one selection to another. |  | Edit |  | 185
Freeform |  | Displays a cross-hair pointer you use to draw a shape that's a combination of freehand and straight lines. |  | Drawing |  | 87
Freehand |  | Displays a cross-hair pointer you use to draw a continuous freehand line. |  | Drawing |  | 78
Freeze Panes |  | Freezes or unfreezes the split in the active window; if no split exists, splits the window above and to the left of the active cell and freezes the panes. |  | Utility |  | 137
Full Screen |  | Toggles full-screen display. |  | Utility |  | 241
Function Wizard |  | Displays the Function Wizard so that you can insert a function into the selected cells. |  | Macro, Utility |  | 40
Group |  | Defines the selected detail rows or columns as a group. In a PivotTable, groups items by category to create a single item from multiple items. |  | Data |  | 130
Group Box |  | Creates a group box control. |  | Forms |  | 181
Group Objects |  | Joins the selected graphic objects together as a single graphic object. |  | Drawing |  | 93
Help |  | Adds a question mark to the mouse pointer. When you choose a command or click a screen region, a Help topic on that item is displayed. Click this button again to cancel the question mark. Double-click this button to display Help Topics dialog box. |  | Utility |  | 128
Hide Detail |  | Hides details of the selection. |  | Data |  | 175
Horizontal Gridlines |  | Adds or deletes major gridlines for the value axis. |  | Charting |  | 122
Increase Decimal |  | Adds one decimal place to a number format. |  | Formatting |  | 56
Increase Font Size |  | Increases the font size of the selected text to the next larger size in the Font Size box. |  | Text Formatting |  | 71
Insert |  | Inserts blank cells in place of the current selection. |  | Edit |  | 22
Insert Chart Sheet |  | Inserts a new chart sheet into the active workbook. |  | File |  | 8
Insert Column |  | Inserts entire columns in the location of the current selection. |  | Edit |  | 24
Insert Dialog |  | Inserts a new dialog sheet to the left of the selected sheet. |  | File |  | 245
Insert Module |  | Inserts a new module into the active workbook. |  | File, Macro |  | 190
Insert MS Excel 4.0 Macro |  | Inserts a new Microsoft Excel 4.0 macro sheet into the active workbook. |  | File |  | 6
Insert Row |  | Inserts entire rows in the location of the current selection. |  | Edit |  | 23
Insert Worksheet |  | Inserts a new worksheet into the active workbook. |  | File |  | 7
Instant Watch |  | Displays the value of the selected expression. |  | Macro |  | 194
Italic |  | Applies italic formatting to the selected cells or objects. |  | Text Formatting |  | 59
Justify Align |  | Increases word spacing in a text box, button, or cell with wrapped text to fill each line. |  | Text Formatting |  | 66
Label |  | Creates a dialog label. |  | Forms |  | 199
Left Border |  | Adds or removes a border along the left edge of the selection. |  | Formatting |  | 44
Left Parenthesis |  | Inserts an opening parenthesis in the formula bar. |  | Formula |  | 33
Legend |  | Adds or deletes a chart legend. |  | Charting |  | 124
Light Shading |  | Applies light shading to selected cells or objects. |  | Drawing |  | 50
Line |  | Displays a cross-hair pointer you use to draw a straight line. |  | Drawing |  | 76
Line Chart AutoFormat |  | Creates a line chart with markers. |  | Charting |  | 107
Line/Column Chart AutoFormat |  | Creates a combination chart with a column chart overlaid by a line chart. |  | Charting |  | 118
List Box |  | Creates a list box control. |  | Forms |  | 144
Lock Cell |  | Formats the selected cells or objects as locked so that no changes can be made to them when the document is protected. |  | Utility |  | 136
Menu Editor |  | Displays the Menu Editor dialog box so that you can change menu bars and commands. |  | Macro |  | 192
Microsoft Access |  | Starts Microsoft Access, or switches to it if it's already running. |  | Utility |  | 216
Microsoft FoxPro |  | Starts Microsoft FoxPro, or switches to it if it's already running. |  | Utility |  | 160
Microsoft Mail |  | Starts Microsoft Mail, or switches to it if it's already running. |  | Utility |  | 203
Microsoft PowerPoint |  | Starts Microsoft PowerPoint, or switches to it if it's already running. |  | Utility |  | 204
Microsoft Project |  | Starts Microsoft Project, or switches to it if it's already running. |  | Utility |  | 205
Microsoft Schedule+ |  | Starts Microsoft Schedule+, or switches to it if it's already running. |  | Utility |  | 227
Microsoft Word |  | Starts Microsoft Word, or switches to it if it's already running. |  | Utility |  | 202
Minus Sign |  | Inserts a minus sign in the formula bar. |  | Formula |  | 29
Multiplication Sign |  | Insers an asterisk in the formula bar. |  | Formula |  | 30
New Workbook |  | Creates a new workbook. |  | File |  | 9
Object Browser |  | Displays procedures, objects, methods, and properties. |  | Macro |  | 191
Open |  | Displays the Open dialog box so that you can open an existing document. |  | File |  | 1
Option Button |  | Creates an option button control. |  | Forms |  | 141
Outline Border |  | Adds a border around the outer edge of the selected cells. |  | Formatting |  | 43
Paste |  | Pastes the contents of the Clipboard. |  | Edit |  | 14
Paste Formats |  | Pastes only the formats from the copied cells into the selected cells. |  | Edit |  | 17
Paste Names |  | Displays the Paste Names dialog box so that you can paste worksheet names into the selected cells. |  | Macro, Utility |  | 41
Paste Values |  | Pastes only the values from the copied cells into the selected cells. |  | Edit |  | 18
Pattern |  | Displays a palette of patterns and pattern colors you can apply to filled objects. |  | Drawing |  | 232
Percent Sign |  | Inserts a percent sign in the formula bar. |  | Formula |  | 37
Percent Syle |  | Applies a percent style to the selected cells. |  | Formatting |  | 54
Pie Chart AutoFormat |  | Creates a pie chart with value labels expressed as percentages. |  | Charting |  | 108
PivotTable Field |  | Inserts a subtotal for a row field or column field in an existing PivotTable. If you select a cell in the data area, clicking this button defines the summary functions used in the selected data field. |  | Data |  | 171
PivotTable Wizard |  | Starts the PivotTable Wizard, which guides you through all the steps needed to create or modify a PivotTable. |  | Data |  | 167
Plus Sign |  | Inserts a plus sign in the formula bar. |  | Formula |  | 28
Polygon |  | Displays a cross-hair pointer you use to draw a polygon. |  | Drawing |  | 86
Print |  | Prints the active sheet according to the current page setup and print settings. |  | File |  | 3
Print Preview |  | Displays the active sheet in print preview. |  | File |  | 4
Radar Chart AutoFormat |  | Creates a radar chart with markers. |  | Charting |  | 117
Record Macro |  | Records actions to create a procedure. |  | Macro |  | 98
Rectangle |  | Displays a cross-hair pointer you use to draw a rectangle or square. |  | Drawing |  | 83
Refresh Data |  | Updates the data in a PivotTable after the source data is changed. |  | Data |  | 170
Remove All Arrows |  | Removes all arrows used in auditing. |  | Auditing |  | 153
Remove Dependent Arrows |  | Removes one level of arrows tracing dependent cells. |  | Auditing |  | 147
Remove Precedent Arrows |  | Removes one level of arrows tracing precedent cells. |  | Auditing |  | 149
Repeat |  | Repeats the last action or command. |  | Edit |  | 11
Reshape |  | Changes the shape of a polygon. |  | Drawing |  | 82
Resume Macro |  | Resumes running a paused procedure. |  | Macro |  | 102
Right Border |  | Adds or removes a border along the right edge of the selection. |  | Formatting |  | 45
Right Parenthesis |  | Inserts a closing parenthesis in the formula bar. |  | Formula |  | 34
Rotate Text Down |  | Rotates text sideways so that it reads from top to bottom. |  | Text Formatting |  | 75
Rotate Text Up |  | Rotates text sideways so that it reads from bottom to top. |  | Text Formatting |  | 74
Routing Slip |  | Adds a routing slip to the current workbook. |  | Workgroup |  | 162
Run Dialog |  | Runs the current dialog box. |  | Forms |  | 187
Run Macro |  | Runs the procedure you're editing, starting at the insertion point. |  | Macro |  | 100
Save |  | Saves changes made to the active workbook. |  | File |  | 2
Scenarios |  | Adds, displays, or edits scenarios. |  | Utility |  | 166
Scroll Bar |  | Creates a scroll bar control. |  | Forms |  | 143
Select Current Region |  | Selects a rectangular range of cells around the active cell that's bounded by blank rows and columns. |  | Utility |  | 133
Select Visible Cells |  | Selects only the visible cells in a selection and none of the hidden rows or columns. |  | Utility |  | 132
Selection |  | Selects graphic objects by drawing a selection rectangle around them. |  | Drawing |  | 81
Send Mail |  | Sends mail using the mail system you're connected to. |  | Workgroup |  | 163
Send To Back |  | Places the selected objects behind all other objects. |  | Drawing |  | 96
Set Print Area |  | Sets the selected cells as the area to print. |  | File |  | 5
Shape |  | Displays a palette of drawing shapes. |  | Drawing |  | 235
Show Detail |  | Shows details of the selection. |  | Data |  | 173
Show Info Window |  | Displays the Info window. |  | Auditing |  | 243
Show Outline Symbols |  | Displays or hides the outlining symbols on a worksheet containing an outline; if no outline exists, displays a message asking whetheryou want to create one. |  | Utility |  | 131
Show Pages |  | Copies each page of a page field to a new worksheet in the current workbook. |  | Data |  | 172
Sort Ascending |  | Sorts the current list in order from the lowest value to the highest value, using the column that contains the active cell. |  | Data, Utility |  | 134
Sort Descending |  | Sorts the current list in order from the highest value to the lowest value, using the column that contains the active cell. |  | Data, Utility |  | 135
Spelling |  | Starts checking the spelling of the active document or the text in the formula bar. |  | Utility |  | 127
Spinner |  | Creates a spinner control. |  | Forms |  | 183
Stacked Column Chart AutoFormat |  | Creates a stacked column chart. |  | Charting |  | 106
Step Into |  | Executes the next statement by stepping into the procedure. |  | Macro |  | 195
Step Macro |  | Runs the procedure you're editing one statement at a time, starting at the insertion point. |  | Macro |  | 101
Step Over |  | Runs the next statement by stepping over the procedure. |  | Macro |  | 196
Stop Macro |  | Stops the currently running procedure. If the macro recorder is running, clicking this button stops the macro recorder. |  | Macro |  | 99
Strikethrough |  | Applies strikethrough formatting to the selected cells or objects. |  | Text Formatting |  | 61
Style |  | Lists the defined cell styles. Select the style you want to apply to the current selection. |  | Text Formatting |  | 70
Tab Order |  | Changes the tab order of controls. |  | Forms |  | 186
Text Box |  | Displays a cross-hair pointer you use to draw a text box, in which you can type text. |  | Drawing, Utility |  | 79
TipWizard |  | Indicates when a tip is available and displays the TipWizard toolbar. |  | TipWizard |  | 179
TipWizard box |  | Displays the current tip. Using this box, you can scroll through a list of tips. |  | TipWizard |  | 178
Toggle Breakpoint |  | Sets or clears breakpoints. |  | Macro |  | 193
Toggle Grid |  | Toggles gridlines on and off. |  | Forms |  | 239
Toggle Read Only |  | Switches between read-only and read-write status. |  | Workgroup |  | 165
Top Border |  | Adds or removes a border along the upper edge of cells. |  | Formatting |  | 46
Trace Dependents |  | Shows the cells that depend on the current cell. |  | Auditing |  | 148
Trace Error |  | Shows the cell or cells that are causing the error in the current cell. |  | Auditing |  | 174
Trace Precedents |  | Shows the cells that the current cell depends on. |  | Auditing |  | 242
Underline |  | Applies underlining to the selected cells or objects. |  | Text Formatting |  | 60
Undo |  | Undoes the last action or command. |  | Edit |  | 10
Ungroup |  | Removes selected rows or columns from their group. In a PivotTable, separates a combined group of items, replacing each instance of the group with all the items it contained. |  | Data |  | 129
Ungroup Objects |  | Separates grouped objects into individual objects. |  | Drawing |  | 94
Update File |  | Updates a read-only file to the last saved version. |  | Workgroup |  | 164
Vertical Gridlines |  | Adds or deletes major gridlines for the category axis. |  | Charting |  | 123
Vertical Text |  | Places text characters upright, one below another, so that the text reads vertically. |  | Text Formatting |  | 73
Volume/High-Low-Close Chart AutoFormat |  | Creates a combination chart with a column chart overlaid by a line chart containing three data series for high, low, and closing stock prices. |  | Charting |  | 119
XY (Scatter) Chart AutoFormat |  | Creates an xy (scatter) chart with markers but no lines. |  | Charting |  | 115
Zoom Control |  | Changes the magnification of the active worksheet. |  | Utility |  | 189
Zoom In |  | Displays the worksheet at the next higher magnification. |  | Utility |  | 138
Zoom Out |  | Displays the worksheet at the next lower magnification. |  | Utility |  | 139


Custom Buttons

The following table describes and gives identifying numbers for the buttons available in the Custom category. None of these buttons has a built-in action. You can use these buttons with your own procedures.

Button picture | Button | Button number
 | Balloon | 219
 | Bell | 226
 | Blank | 231
 | Calculator | 237
 | Camcorder | 228
 | Clock | 213
 | Club | 224
 | Diamond | 222
 | Envelope | 230
 | Fish | 214
 | Frown | 212
 | Hand | 229
 | Heart | 221
 | Integral | 200
 | Mug | 218
 | Note | 210
 | Notebook | 217
 | Open | 206
 | Palette | 97
 | Save | 207
 | Smile | 211
 | Solitaire | 201
 | Spade | 223
 | Speaker | 209
 | Tack | 215
 | Telephone | 220
 | Trash | 225
 | Undo | 208


Appendix D Microsoft Excel Object Model Graphics

Whenever you want to work with an object in Microsoft Excel, you must first build an expression that returns the object. To build the expression, you must understand where the object fits into the object hierarchy, or object model. This appendix contains graphical representations of the Microsoft Excel object model and the DAO (Data Access Objects) object model.

Microsoft Excel Objects

Data Access Objects


Introduction

This manual is an alphabetic reference for Visual Basic for Microsoft Excel. The reference contains topics for all functions, methods, objects, properties, and statements in the language, and is essentially identical to the information contained in Microsoft Excel Visual Basic Help.

Unless otherwise noted, each topic in this manual is applicable to both Microsoft Excel 5 and Microsoft Excel for Windows 95. At the beginning of the reference, there is a section with lists of methods, objects, and properties that are new or changed in Microsoft Excel for Windows 95. References to other online and printed material refer to documentation for Microsoft Excel for Windows 95.


Where to Find Information About Visual Basic for Microsoft Excel

For general information about Microsoft Excel, see Getting Results with Microsoft Excel for Windows 95 or Getting Results with Microsoft Office for Windows 95.

For in-depth information about using Visual Basic in Microsoft Excel, read the Microsoft Excel/Visual Basic for Windows 95 Programmer's Guide, available from Microsoft Press. If you're new to Visual Basic in Microsoft Excel, or if you prefer a task-oriented approach to learning, you might want to start by reading Microsoft Excel Visual Basic Step by Step, a self-paced tutorial also available from Microsoft Press. Another Microsoft Press book, Developing Microsoft Excel Solutions, contains expert development strategies, tips, tricks, and sample Microsoft Excel/Visual Basic macros and applications.

Note

You can order the Microsoft Excel/Visual Basic for Windows 95 Programmer's Guide, Microsoft Excel Visual Basic Step by Step, and Developing Microsoft Excel Solutions directly from Microsoft Press. To place a credit card order, call 615-793-5090, or call 1-800-MS-PRESS toll-free. Please be sure to have your reference code FXL ready for faster order processing. CompuServe subscribers can also order through the Microsoft Press Electronic Book Store by typing GO MSP.


Using Online Help

Microsoft Excel provides an extensive Help system for the Visual Basic language, the objects that Microsoft Excel supports, and the properties and methods of those objects.

If you clicked Typical when you installed Microsoft Excel, you'll need to run Setup again to install Help for Visual Basic for Microsoft Excel.

You can access Visual Basic Help in any of the following four ways:

In a Visual Basic module, place the insertion point anywhere in an object, property, method, function, or other keyword, and then press F1 to get context-sensitive Help.

On the Help menu, click Microsoft Excel Help Topics. You can then either click "Getting Started with Visual Basic" on the Contents tab, look up a specific topic or Visual Basic term on the Index tab, or perform a full-text search from the Find tab.

On the Help menu, click Microsoft Excel Help Topics. You can then ask a question on the Answer Wizard tab and read the topics displayed in the Programming and Language Reference section of the dialog box.

With a Visual Basic module active, click Object Browser on the View menu, and then click the Element Help button (appears as a question mark below the Objects/Modules box) for information about an object, method, property, or function.


Document Conventions

This book uses the typographic conventions shown in the following table. You might not recognize all the terms or Visual Basic keywords, but you'll learn more about them later.

Example of convention | Description
setup | Words or characters you're instructed to type appear in bold.
Sub, If, ChDir, MsgBox, True, Add, Height, Application, Range, Row | Words in bold with the initial letter capitalized indicate a language-specific term: a property, method, or object name; or another Visual Basic keyword.
propertyname | In syntax, italic type indicates placeholders for information you supply.
index | In syntax, bold italic type indicates placeholders for arguments when you can use either positional or named-argument syntax.
[expressionlist] | In syntax, items inside square brackets are optional.
{While|Until} | In syntax, braces and a vertical bar indicate a mandatory choice between two or more items.
ENTER | Small capital letters are used for the names of keys and key combinations, such as ENTER and CTRL+R.
CTRL+V | A plus sign (+) between key names indicates a combination of keys. For example, CTRL+V means to hold down the CTRL key while pressing the V key.
myVar | This font is used for example code.


Programming Style

This book uses the following programming style guidelines for code examples.

The following font is used for code.

Sub HelloWorld

Cells(1,1).Value = "Hello, world!"

End Sub

An apostrophe (') introduces comments in code.

' This is a comment; these two lines

' are ignored when the program is running.

Names of macros and user-defined functions appear with initial letters capitalized throughout this book. Note that macro and function names cannot include spaces, so if a name consists of more than one word, the other words in the name also have their initial letters capitalized.

' The AuditResult user-defined function is in the Finance module.

Function AuditResult(latestIncome, expenses, taxes, commissions)

Argument and variable names appear with initial letters lowercase (to distinguish them from macro, function, property, method, and object names).

Keywords appear with initial letters capitalized, whereas built-in constants appear with an initial lowercase "xl" or "vb."

' Sub is a keyword.

Sub Title(titleText)

' xlManual is a built-in constant.

Application.Calculation = xlManual

Control-flow blocks and statements in Sub and Function procedures are indented within the code that surrounds them.

Sub CheckRecordSound

SoundRecordCapable = Application.CanRecordSounds

If SoundRecordCapable Then

Cells(1,1).SoundNote.Record

End If

End Sub

The line-continuation character — an underscore ( _ ) — indicates that code continued from one line to the next is part of the same logical line. You can type these statements all on one line in the Visual Basic module. You can also divide lines of code and add the line-continuation character yourself.

ActiveSheet.Rectangles.Add _

width:=200, _

height:=200, _

left:=50, _

top:=50


Changes to Visual Basic in Microsoft Excel for Windows 95

Existing properties and methods have been changed, and several new properties, methods, and objects have been added to Visual Basic in Microsoft Excel for Windows 95.

Changed Properties and Methods

The following properties and methods have been changed to support new Microsoft Excel features or to enhance existing features.

Topic | Description
GetOpenFileName Method | The new multiSelect argument allows you to select more than one filename in the Open dialog box.
HelpContextID Property | Added to the ToolbarButton object.
HelpFile Property | Added to the ToolbarButton object.
Names Method | Added to the Worksheet object to handle sheet-scoped names.
PasteSpecial Method | For the Range object, a new constant for the paste argument allows you to paste range content and formatting but not border formatting.
Protect Method | The new userInterfaceOnly argument allows you to specify protection from user changes while still allowing changes from Visual Basic code.
SaveAs Method | New arguments allow you to specify shared-mode access and how change conflicts are resolved.
StatusBar Property | Added to the ToolbarButton object.

AutoCorrect Support

The following new object, properties, methods have been added to support automatic corrections.

Topic | Description
AddReplacement Method | Adds a row to the array of AutoCorrect replacements returned by the ReplacementList property.
AutoCorrect Object | Contains AutoCorrect attributes (capitalization of names of days, correction of two initial capital letters, automatic correction list, and so on).
AutoCorrect Property | Returns an AutoCorrect object that represents the AutoCorrect attributes.
CapitalizeNamesOfDays Property | True if the first letters of names (and abbreviations) of days are capitalized automatically.
DeleteReplacement Method | Deletes a row from the array of AutoCorrect replacements returned by the ReplacementList property.
ReplacementList Property | Returns or sets the entire array or one row of the array of AutoCorrect replacements.
ReplaceText Property | True if text from column one of the array of AutoCorrect replacements is automatically replaced with the text from column two.
TwoInitialCapitals Property | True if occurrences of two initial capital letters in a word are corrected automatically.

OLE Document Properties Support

The following new properties, methods, and objects have been added to support OLE document properties. Document properties allow Microsoft Excel to expose a standard set of built-in document properties and additional custom document properties added by the user.

Topic | Description
BuiltinDocumentProperties Property | Returns a DocumentProperties collection object that contains the built-in document properties for the object.
CustomDocumentProperties Property | Returns a DocumentProperties collection object that contains the custom document properties for the object.
DocumentProperties Object | Represents the collection of document properties (either built-in or custom).
DocumentProperty Object | Represents a single document property.
LinkedToContent Property | True if the value of a custom property is linked to the contents of the document it's contained in; False if the property is a static value.
LinkSource Property | Specifies the source of a custom document property that's linked to document contents.

AutoComplete Support

The following method and property have been added to support the AutoComplete feature.

Topic | Description
AutoComplete Method | Returns a completed string from the list, or returns an empty string if there was no completion or if more than one entry in the list matches.
EnableAutoComplete Property | True if the AutoComplete feature is enabled.

Protection Control

The following properties have been added to allow you to control the user's ability to change toolbars, filtered lists, PivotTables, and outlining.

Topic | Description
EnableAutoFilter Property | True if AutoFilter arrows are enabled when user-interface-only protection is turned on.
EnableOutlining Property | True if outlining symbols (show detail or hide detail) are enabled when user-interface-only protection is turned on.
EnablePivotTable Property | True if PivotTable controls and actions are enabled when user-interface-only protection is turned on
Protection Property | Controls what kinds of changes the user can make to a toolbar.

Appearance Control

The following properties and methods have been added to control the appearance of the mouse pointer, turn animated insertion and deletion on and off, create a password-entry edit box, and set the background graphic for a worksheet or chart.

Topic | Description
Cursor Property | Sets the appearance of the mouse pointer in Microsoft Excel.
EnableAnimations Property | True if animated insertion and deletion is enabled.
PasswordEdit Property | Causes an edit box to display its contents as a series of asterisks.
SetBackgroundPicture Method | Sets the background graphic for a worksheet or chart.

Miscellaneous

Topic | Description
AutoLoad Property | True if the OLE object is automatically loaded when the workbook that contains the object is opened.
CopyFromRecordset Method | Copies the contents of a DAO Recordset object into cells on a worksheet, beginning at the first cell of the specified range.
ListHeaderRows Property | Returns the number of header rows for the specified range.
MoveAfterReturnDirection Property | Controls the direction in which the active cell is moved after the user presses ENTER.
NetworkTemplatesPath Property | Returns the network path where templates are stored. If the network path doesn't exist, the property returns an empty string.
OnSave Property | Returns or sets the name of a Visual Basic procedure to run whenever the user invokes the Save or Save As command.
Post Method | Posts the specified workbook to a Microsoft Exchange public folder or a Lotus Notes database.
ProtectionMode Property | True if user-interface-only protection is turned on.
RangeSelection Property | Returns a Range object that represents the selected cells on the worksheet in the specified window even if a graphic object is active or selected on the worksheet.
RefersToRange Property | Returns the Range object referred to by a Name object.
TemplatesPath Property | Returns the local path where templates are stored.


A-Z Reference


& Operator

Description

Used to force string concatenation of two expressions.

Syntax

result = expression1 & expression2

The & operator syntax has these parts:

Part | Description
result | Any numeric variable.
expression1 | Any expression.
expression2 | Any expression.

Remarks

Whenever an expression is not a string, it is converted to a String variant. The data type of result is String if both expressions are String expressions; otherwise, result is a String variant. If both expressions are Null, result is also Null. However, if only one expression is a Null, that expression is treated as a zero-length string when concatenated with the other expression. Any expression that is Empty is also treated as a zero-length string.

See Also

Operator Precedence.

Example

This example uses the & operator to force string concatenation.

MyStr = "Hello" & " World"    ' Returns "Hello World".
MyStr = "Check " & 123 & " Check"    ' Returns "Check 123 Check".


* Operator

Description

Used to multiply two numbers.

Syntax

result = number1*number2

The * operator syntax has these parts:

Part | Description
result | Any numeric variable.
number1 | Any numeric expression.
number2 | Any numeric expression.

Remarks

The data type of result is usually the same as that of the most precise expression. The order of precision, from least to most precise, is Integer, Long, Single, Double, Currency. The following are exceptions to this order:

  • When multiplication involves a Single and a Long, the data type of result is converted to a Double.
  • When the data type of result is a Long, Single, or Date variant that overflows its legal range, result is converted to a Variant containing a Double.
  • When the data type of result is an Integer variant that overflows its legal range, result is converted to a Long variant.

If one or both expressions are Null expressions, result is a Null. If an expression is Empty, it is treated as if it were 0.

See Also

Operator Precedence.

Example

This example uses the * operator to multiply two numbers.

MyValue = 2 * 2    ' Returns 4.
MyValue = 459.35 * 334.90     ' Returns 153836.315.


+ Operator

Description

Used to sum two numbers.

Syntax

result = expression1+expression2

The + operator syntax has these parts:

Part | Description
result | Any numeric variable.
expression1 | Any expression.
expression2 | Any expression.

Remarks

Although you can also use the + operator to concatenate two character strings, you should use the & operator for concatenation to eliminate ambiguity and provide self-documenting code.

When you use the + operator, you may not be able to determine whether addition or string concatenation will occur. If at least one expression is not a Variant, the following rules apply:

If | Then
Both expressions are numeric data types (Boolean, Integer, Long, Single, Double, Date or Currency) | Add.
Both expressions are String | Concatenate.
One expression is a numeric data type and the other is any Variant (except a Null) | Add.
One expression is a String and the other is any Variant (except a Null) | Concatenate.
One expression is an Empty Variant | Return the remaining expression unchanged as result.
One expression is a numeric data type and the other is a String | A Type mismatch error occurs.
Either expression is a Null | result is a Null.

If both expressions are Variant expressions, the underlying type of the expressions determines the behavior of the + operator in the following way:

If | Then
Both Variant expressions are numeric | Add.
Both Variant expressions are strings | Concatenate.
One Variant expression is numeric and the other is a string | Add.

For simple arithmetic addition involving only expressions of numeric data types, the data type of result is usually the same as that of the most precise expression. The order of precision, from least to most precise, is Integer, Long, Single, Double, and Currency. The following are exceptions to this order:

  • When a Single and a Long are added together, the data type of result is converted to a Double.
  • When the data type of result is a Long, Single, or Date variant that overflows its legal range, result is converted to a Double variant.
  • When the data type of result is an Integer variant that overflows its legal range, result is converted to a Long variant.
  • When a Date is added to any other data type, the data type of result is always a Date.

If one or both expressions are Null expressions, result is a Null. If both expressions are Empty, result is an Integer. However, if only one expression is Empty, the other expression is returned unchanged as result.

See Also

Operator Precedence.

Example

This example uses the + operator to sum numbers. The + operator can also be used to concatenate strings but to eliminate ambiguity, you should use the & operator instead.

MyNumber = 2 + 2    ' Returns 4.
MyNumber = 4257.04 + 98112    ' Returns 102369.04.
Var1 = "34" : Var2 = 6    ' Initialize variables.
MyNumber = Var1 + Var2    ' Returns 40.
Var1 = "34" : Var2 = "6"    ' Initialize variables.
MyNumber = Var1 + Var2    ' Returns "346" (string concatenation).


- Operator

Description

Used to find the difference between two numbers or to indicate the negative value of a numeric expression.

Syntax 1

result = number1-number2

Syntax 2

-number

The - operator syntax has these parts:

Part | Description
result | Any numeric variable.
number | Any numeric expression.
number1 | Any numeric expression.
number2 | Any numeric expression.

Remarks

In Syntax 1, the - operator is the arithmetic subtraction operator used to find the difference between two numbers. In Syntax 2, the - operator is used as the unary negation operator to indicate the negative value of an expression.

The data type of result is usually the same as that of the most precise expression. The order of precision, from least to most precise, is Integer, Long, Single, Double, Currency. The following are exceptions to this order:

  • When subtraction involves a Single and a Long, the data type of result is converted to a Double.
  • When the data type of result is a Long, Single, or Date variant that overflows its legal range, result is converted to a Variant containing a Double.
  • When the data type of result is an Integer variant that overflows its legal range, result is converted to a Long variant.
  • When subtraction involves a Date and any other data type, the data type of result is a Date.
  • When subtraction involves two Date expressions, the data type of result is Double.

If one or both expressions are Null expressions, result is a Null. If an expression is Empty, it is treated as if it were 0.

See Also

Operator Precedence.

Example

This example uses the - operator to calculate the difference between two numbers.

MyResult = 4 - 2    ' Returns 2.
MyResult = 459.35 - 334.90    ' Returns 124.45.


/ Operator

Description

Used to divide two numbers and return a floating-point result.

Syntax

result = number1/number2

The / operator syntax has these parts:

Part | Description
result | Any numeric variable.
number1 | Any numeric expression.
number2 | Any numeric expression.

Remarks

The data type of result is usually a Double or a Double variant. The following are exceptions to this rule:

  • When both expressions are Integer or Single expressions, result is a Single unless it overflows its legal range; in which case, an error occurs.
  • When both expressions are Integer or Single variants, result is a Single variant unless it overflows its legal range; in which case, result is a Variant containing a Double.

If one or both expressions are Null expressions, result is a Null. Any expression that is Empty is treated as 0.

See Also

Operator Precedence.

Example

This example uses the / operator to perform floating-point division.

MyValue = 10 / 4    ' Returns 2.5.
MyValue = 10 / 3    ' Returns 3.333333.


\ Operator

Description

Used to divide two numbers and return an integer result.

Syntax

result = number1\number2

The \ operator syntax has these parts:

Part | Description
result | Any numeric variable.
number1 | Any numeric expression.
number2 | Any numeric expression.

Remarks

Before division is performed, the numeric expressions are rounded to Integer or Long expressions.

Usually, the data type of result is an Integer, Integer variant, Long, or Long variant, regardless of whether or not result is a whole number. Any fractional portion is truncated. However, if any expression is a Null, result is also a Null. Any expression that is Empty is treated as 0.

See Also

Operator Precedence.

Example

This example uses the \ operator to perform integer division.

MyValue = 11 \ 4    ' Returns 2.
MyValue = 9 \ 3    ' Returns 3.
MyValue = 100 \ 3    ' Returns 33.


^ Operator

Description

Used to raise a number to the power of an exponent.

Syntax

result = number^exponent

The ^ operator syntax has these parts:

Part | Description
result | Any numeric variable.
number | Any numeric expression.
exponent | Any numeric expression.

Remarks

Number can be negative only if exponent is an integer value. When more than one exponentiation is performed in a single expression, the ^ operator is evaluated as it is encountered from left to right.

Usually, the data type of result is a Double or a Variant containing a Double. However, if either number or exponent is a Null expression, result is also a Null.

See Also

Operator Precedence.

Example

This example uses the ^ operator to raise a number to the power of an exponent.

MyValue = 2 ^ 2    ' Returns 4.
MyValue = 3 ^ 3 ^ 3    ' Returns 19683.
MyValue = (-5) ^ 3    ' Returns -125.


Abs Function

Description

Returns the absolute value of a number.

Syntax

Abs(number)

The number argument can be any valid numeric expression. If number contains no valid data, Null is returned; if it is an uninitialized variable, Empty is returned.

Remarks

The absolute value of a number is its unsigned magnitude. For example, ABS(-1) and ABS(1) both return 1.

See Also

Sgn Function.

Example

This example uses the Abs function to compute the absolute value of a number.

MyNumber = Abs(50.3)    ' Returns 50.3.
MyNumber = Abs(-50.3)    ' Returns 50.3.


Accelerator Property

Applies To

Button Object, Buttons Collection, CheckBox Object, DrawingObjects Collection, GroupBox Object, GroupBoxes Collection, Label Object, Labels Collection, OptionButton Object, OptionButtons Collection.

Description

Returns or sets the keyboard accelerator character for the control. Read-write.

Remarks

Each control has one accelerator character which the user can press in combination with the ALT key to activate a control while a dialog is running.

The first text character of the control that matches the first accelerator text character will be underlined. The comparison for underlining is case-sensitive, but case is not considered when a key is pressed.

On the Apple Macintosh, the accelerator character is only underlined when the CommandUnderlines property is True. If this property is False, the accelerator character is preserved, but it is not underlined.

If the accelerator key doesn't match any text in the control, the accelerator is nonfunctional.

Example

This example sets the button text and accelerator key for button two on Dialog1.

With DialogSheets("Dialog1").Buttons(2)
.Text = "Press Me"
.Accelerator = "P"
End With


Activate Method

Applies To

Chart Object, ChartObject Object, DialogSheet Object, MenuBar Object, Module Object, OLEObject Object, Pane Object, Range Object, Window Object, Workbook Object, Worksheet Object.

Description

Activates the object, as shown in the following table.

Object | Description
Chart, ChartObject | Makes this chart the active chart.
DialogSheet, Module, Worksheet | Makes this sheet the active sheet. Equivalent to clicking the tab.
MenuBar | Activates the menu bar. There are certain restrictions on which menu bars you can activate at certain times. See the Remarks section for details.
OLEObject | Activates the object.
Pane | Activates the pane. If the pane is not in the active window, the window that the pane belongs to will also be activated. You cannot activate a frozen pane.
Range | Activates a single cell, which must be inside the current selection. To select a range of cells, use the Select method.
Window | Brings the window to the front of the z-order. This will not run any Auto_Activate or Auto_Deactivate macros that might be attached to the workbook (use the RunAutoMacros method to run those macros).
Workbook | Activates the first window associated with the workbook. This will not run any Auto_Activate or Auto_Deactivate macros that might be attached to the workbook (use the RunAutoMacros method to run those macros).

Syntax

object.Activate object

Required. The object to activate.

Remarks

When you activate a built-in menu bar, you can display only a menu bar appropriate for the object. For example, if you try to display a chart menu bar for a worksheet or macro sheet, this method returns an error and interrupts the current macro.

Activating a custom menu bar disables automatic menu bar switching when different types of documents are selected. For example, if a custom menu bar is displayed and you switch to a chart, the two chart menus are not displayed (they would be if you were using the built-in menu bars). Automatic menu bar switching is reenabled when a built-in menu bar is displayed.

See Also

Select Method.

Example

This example activates Sheet1 in the workbook BOOK1.XLS.

Workbooks("BOOK1.XLS").Worksheets("Sheet1").Activate

This example selects cells A1:C3 on Sheet1 and then makes cell B2 the active cell.

Worksheets("Sheet1").Activate
Range("A1:C3").Select
Range("B2").Activate

This example activates the workbook BOOK4.XLS. If BOOK4.XLS has multiple windows, the example activates the first window, BOOK4.XLS:1.

Workbooks("BOOK4.XLS").Activate


ActivateMicrosoftApp Method

Applies To

Application Object.

Description

Activates a Microsoft application. If the application is already running, this method activates the running application. If the application is not running, this method starts a new instance of the application.

Syntax

object.ActivateMicrosoftApp(index)

object

Required. The Application object.

index

Required. Specifies the Microsoft application to activate (one of xlMicrosoftWord, xlMicrosoftPowerPoint, xlMicrosoftMail, xlMicrosoftAccess, xlMicrosoftFoxPro, xlMicrosoftProject, or xlMicrosoftSchedulePlus).

Example

This example starts and activates Word.

Application.ActivateMicrosoftApp xlMicrosoftWord


ActivateNext Method

Applies To

Window Object.

Description

Activates the specified window and then sends it to the back of the window z-order.

Syntax

object.ActivateNext

object

Required. The Window object.

See Also

ActivatePrevious Method, Next Property.

Example

This example sends the active window to the back of the z-order.

ActiveWindow.ActivateNext


ActivatePrevious Method

Applies To

Window Object.

Description

Activates the specified window and then activates the window at the back of the window z-order.

Syntax

object.ActivatePrevious

object

Required. The Window object.

See Also

ActivateNext Method, Previous Property.

Example

This example activates the window at the back of the z-order.

ActiveWindow.ActivatePrevious


ActiveCell Property

Applies To

Application Object, Window Object.

Description

Accessor. Returns a Range object that represents the active cell in the active window (the window on top) or in the specified window. If the window is not displaying a worksheet, this property fails. Read-only.

Remarks

If you do not specify an object qualifier, this property returns the active cell in the active window.

Be careful to distinguish between the active cell and the selection. The active cell is a single cell inside the current selection. The selection may contain more than one cell, but only one is the active cell.

The following expressions all return the active cell, and are all equivalent.

ActiveCell
Application.ActiveCell
ActiveWindow.ActiveCell
Application.ActiveWindow.ActiveCell

Example

This example uses a message box to display the value in the active cell. Because the ActiveCell property will fail if the active sheet is not a worksheet, the example activates Sheet1 before using the ActiveCell property.

Worksheets("Sheet1").Activate
MsgBox ActiveCell.Value

This example changes font formatting for the active cell.

Worksheets("Sheet1").Activate
With ActiveCell.Font
.Bold = True
.Italic = True
End With


ActiveChart Property

Applies To

Application Object, Window Object, Workbook Object.

Description

Accessor. Returns a Chart object that represents the active chart (either an embedded chart or a chart sheet). An embedded chart is considered active when it is either selected or activated. When no chart is active, this property returns Nothing. Read-only.

Remarks

If you do not specify an object qualifier, this property returns the active chart in the active workbook.

Example

This example turns on the legend for the active chart.

ActiveChart.HasLegend = True


ActiveDialog Property

Applies To

Application Object.

Description

Accessor. Returns a DialogSheet object that represents the topmost running dialog sheet. If there is no running dialog sheet, this property returns Nothing. Note that the active dialog sheet is not necessarily the active sheet. Read-only.

Example

This example sets the height of the active dialog box.

ActiveDialog.DialogFrame.Height = 91


ActiveMenuBar Property

Applies To

Application Object.

Description

Accessor. Returns a MenuBar object that represents the active menu bar. Read-only.

Example

This example displays the name (Caption property) of the active menu bar.

MsgBox "The active menu bar is called " & ActiveMenuBar.Caption


ActivePane Property

Applies To

Window Object.

Description

Accessor. Returns a Pane object that represents the active pane in the window. Read-only.

Remarks

This property can be used only on worksheets and macro sheets.

This property returns a Pane object. You must use the Index property to obtain the index of the active pane.

See Also

ActiveWindow Property.

Example

This example activates the next pane for the active window in BOOK1.XLS. You cannot activate the next pane if the panes are frozen. The example must be run from a workbook other than BOOK1.XLS. Before running the example, make sure that BOOK1.XLS has either two or four panes in the active worksheet.

Workbooks("BOOK1.XLS").Activate
If not ActiveWindow.FreezePanes Then
    With ActiveWindow
        i = .ActivePane.Index
        If i = .Panes.Count Then
            .Panes(1).Activate
        Else
            .Panes(i+1).Activate
        End If
    End With
End If


ActivePrinter Property

Applies To

Application Object.

Description

Returns or sets the name of the active printer. Read-write. The name is a string.

Remarks

This property cannot be set on the Apple Macintosh.

Example

This example displays the name of the active printer.

MsgBox "The name of the active printer is " & Application.ActivePrinter


ActiveSheet Property

Applies To

Application Object, Window Object, Workbook Object.

Description

Accessor. Returns an object that represents the active sheet (the sheet on top) in the active workbook or in the specified window or workbook. Returns Nothing if no sheet is active. Read-only.

The object type returned by the ActiveSheet property depends on the active sheet, as shown in the following table.

Active sheet | Object type returned
Worksheet | Worksheet
Visual Basic module | Module
Chart | Chart
Dialog sheet | DialogSheet

Remarks

If you do not specify an object qualifier, this property returns the active sheet in the active workbook.

If a workbook appears in more than one window, the ActiveSheet property may be different in different windows.

See Also

Activate Method, Select Method.

Example

This example displays the name (Name property) of the active sheet.

MsgBox "The name of the active sheet is " & ActiveSheet.Name


ActiveWindow Property

Applies To

Application Object.

Description

Accessor. Returns a Window object that represents the active window (the window on top). Read-only. Returns Nothing if no windows are open.

See Also

Activate Method, Select Method.

Example

This example displays the name (Caption property) of the active window.

MsgBox "The name of the active window is " & ActiveWindow.Caption


ActiveWorkbook Property

Applies To

Application Object.

Description

Accessor. Returns a Workbook object that represents the workbook in the active window (the window on top). Read-only. Returns Nothing if no windows are open or if the active window is the Info window or the Clipboard window.

Example

This example displays the name (Name property) of the active workbook.

MsgBox "The name of the active workbook is " & ActiveWorkbook.Name


Add Method (AddIns Collection)

Applies To

AddIns Collection.

Description

Adds a new add-in file to the list of add-ins. Returns an AddIn object.

Syntax

object.Add(fileName, copyFile)

object

Required. The AddIns object.

fileName

Required. The name of the file containing the add-in you wish to add to the list in the add-in manager.

copyFile

Optional. Ignored if the add-in file is on a hard disk. If True and the add-in is on removable media (a floppy disk or CD-ROM), the add-in will be copied to your hard disk. If False, the add-in will remain on the removable media. If this argument is omitted, Microsoft Excel displays a dialog box and asks you to choose.

Remarks

This method does not install the new add-in. You must set the Installed property to install the add-in.

See Also

Installed Property.

Example

This example inserts the add-in MYADDIN.XLA from drive A. When you run this example, Microsoft Excel copies the file A:\MYADDIN.XLA to the LIBRARY folder on your hard disk and adds the add-in title to the list in the Add-Ins dialog box.

Set myAddIn = AddIns.Add(filename:="A:\MYADDIN.XLA", _
        copyfile:=True)
MsgBox myAddIn.Title & " has been added to the list"

In Microsoft Excel for the Macintosh, this example copies the add-in from the disk labeled Add-In Disk to the Macro Library folder.

Set myAddIn = AddIns.Add(filename:="Add-In Disk:My Add-In", _
        copyfile:=True)
MsgBox myAddIn.Title & " has been added to the list"


Add Method (Arcs and Lines)

Applies To

Arcs Collection, Lines Collection.

Description

Creates a new arc or line.

Syntax

object.Add(x1, y1, x2, y2)

object

Required. The Arc or Line object.

x1, y1

Required. Specifies the position of the first coordinate of the object, in points (1/72 inch) relative to the top left corner of cell A1 or the upper left corner of the chart.

x2, y2

Required. Specifies the position of the second coordinate of the object, in points relative to the top left corner of cell A1 or the upper left corner of the chart.

See Also

Add Method (Drawings Collection), Add Method (DropDowns Collection), Add Method (Graphic Objects and Controls), Duplicate Method.

Example

This example creates a new line on Sheet1, with the arrowhead pointing to the upper left. Note the order of the points: the arrowhead points to the second coordinate.

With Worksheets("Sheet1").Lines.Add(80, 80, 10, 10)
    .ArrowHeadStyle = xlOpen
    .Border.LineStyle = xlDot
End With


Add Method (Charts Collection)

Applies To

Charts Collection.

Description

Creates a new chart. Returns a Chart object.

Syntax

object.Add(before, after, count)

object

Required. The Charts object.

before

Optional. Specifies the sheet before which the new sheet is added.

after

Optional. Specifies the sheet after which the new sheet is added.

count

Optional. The number of sheets to add. If omitted, the default is one.

Remarks

If before and after are omitted, the new chart is inserted before the active sheet.

Example

This example creates an empty chart sheet and inserts it before the active sheet.

ActiveWorkbook.Charts.Add


Add Method (DialogSheets Collection)

Applies To

DialogSheets Collection.

Description

Creates a new dialog sheet. Returns a DialogSheet object.

Syntax

object.Add(before, after, count)

object

Required. The DialogSheets object.

before

Optional. Specifies the sheet before which the new sheet is added.

after

Optional. Specifies the sheet after which the new sheet is added.

count

Optional. The number of sheets to add. If omitted, the default is one.

Remarks

If before and after are omitted, the new sheet is inserted before the active sheet.

Example

This example creates a new dialog sheet containing a default dialog frame and buttons. The new sheet is inserted before the active sheet.

ActiveWorkbook.DialogSheets.Add


Add Method (DocumentProperties Collection)

Applies To

DocumentProperties Collection.

Description

Creates a new custom document property. Returns a DocumentProperty object.

To use this method, you should establish a reference to the Microsoft Office 95 Object Library by using the References command (Tools menu).

Syntax

object.Add(name, linkToContent, type, value, linkSource)

object

Required. The custom DocumentProperties collection object.

name

Required. The name of the property.

linkToContent

Required. Specifies whether the property is linked to the content of the container document. If True, the linkSource argument is required. If False, the value argument is required.

type

Required. The data type of the property (can be one of offPropertyTypeBoolean, offPropertyTypeDate, offPropertyTypeFloat, offPropertyTypeString, or offPropertyTypeNumber).

value

Optional. The value of the property if it's not linked to the content of the container document. The value is converted to match the data type specified by the type argument, if possible; otherwise, an error occurs. If linkToContent is True, this argument is ignored and the new document property has a default value until linked property values are updated by the container application (usually when the document is saved).

linkSource

Optional. Ignored if linkToContent is False. The source of the linked property. The container application determines what types of source linking are allowed.

Remarks

This method cannot be used with the collection of built-in document properties.

Example

This example adds a new custom document property. You must pass the custom DocumentProperties collection to the procedure.

Sub AddCustomProperty(dp As DocumentProperties)
    dp.Add name:="Complete", linkToContent:=False, _
        type:=offPropertyTypeBoolean, value:=False
End Sub

This example adds a static custom property named "Complete."

With ActiveWorkbook.CustomDocumentProperties
    .Add name := "Complete", linkToContent := False, _
        type := offPropertyTypeBoolean, value := False
End With

This example adds a property linked to the name "Grand_Total."

With ActiveWorkbook.CustomDocumentProperties
    .Add name := "Total Sales", linkToContent := True, _
        linkSource := "Grand_Total"
End With


Add Method (Drawings Collection)

Applies To

Drawings Collection.

Description

Creates a new drawing using the first two vertices of the polygon as coordinates relative to cell A1 or the upper left corner of the chart. Additional vertices can be added to the first two vertices using the AddVertex method.

Syntax

object.Add(x1, y1, x2, y2, closed)

object

Required. The Drawings object.

x1, y1

Required. Specifies the position of the first coordinate of the polygon, in points (1/72 inch) relative to the top left corner of cell A1 or the upper left corner of the chart.

x2, y2

Required. Specifies the position of the second coordinate of the polygon, in points relative to the top left corner of cell A1 or the upper left corner of the chart.

closed

Required. If True, the new drawing is closed and the last vertex is always connected to the first vertex. If False, the drawing is open and the last vertex is not connected to the first vertex.

See Also

Add Method (Arcs and Lines), Add Method (DropDowns Collection), Add Method (Graphic Objects and Controls), AddVertex Method, Reshape Method, Vertices Property.

Example

This example creates a new open trapezoid on Sheet1.

With Worksheets("Sheet1").Drawings.Add(100, 100, 200, 100, False)
    .AddVertex 180, 200
    .AddVertex 80, 200
    .AddVertex 100, 100
    .Border.Weight = xlMedium
End With


Add Method (DropDowns Collection)

Applies To

DropDowns Collection.

Description

Creates a new drop-down list box using rectangular coordinates specified in points (1/72 inch).

Syntax

object.Add(left, top, width, height, editable)

object

Required. The DropDowns object.

left, top, width, height

Required. Specifies the width, height, and initial coordinates of the upper left corner of the object, in points relative to the top left corner of cell A1 or the upper left corner of the chart.

editable

Optional. True if the drop-down list box can be edited. If this argument is False or omitted, the contents of the list-box editing region can be changed only by selecting from the list.

See Also

Add Method (Arcs and Lines), Add Method (Drawings Collection), Add Method (Graphic Objects and Controls), Duplicate Method.

Example

This example creates a drop-down list box on Sheet1.

With Worksheets("Sheet1").DropDowns.Add(10, 10, 120, 18)
    .DropDownLines = 10
End With


Add Method (Graphic Objects and Controls)

Applies To

Buttons Collection, ChartObjects Collection, EditBoxes Collection, GroupBoxes Collection, Labels Collection, ListBoxes Collection, OptionButtons Collection, Ovals Collection, Pictures Collection, Rectangles Collection, ScrollBars Collection, Spinners Collection, TextBoxes Collection.

Description

Creates a new graphic object or control using coordinates specified in points (1/72 inch).

The type of the object depends on the collection on which you call Add. For example, Rectangles.Add creates a new rectangle; Ovals.Add creates a new oval.

Syntax

object.Add(left, top, width, height)

object

Required. The object to which this method applies.

left, top

Required. Specifies the initial coordinates of the new object, in points (1/72 inch), relative to the top left corner of cell A1 on a worksheet, or to the upper left corner of a chart.

width, height

Required. Specifies the initial size of the new object, in points (1/72 inch).

Remarks

The specified coordinates describe the new object's bounding rectangle. The object fills the bounding rectangle.

See Also

Add Method (Arcs and Lines), Add Method (Drawings Collection), Add Method (DropDowns Collection), Duplicate Method.

Example

This example creates a new oval on Sheet1. The oval is aligned with and the same size as cell D3.

Set myCell = ActiveWorkbook.Worksheets("Sheet1").Range("D3")
ActiveWorkbook.Worksheets("Sheet1").Ovals.Add _
    Top:=myCell.Top, Left:=myCell.Left, _
    Height:=myCell.Height, Width:=myCell.Width


Add Method (MenuBars Collection)

Applies To

MenuBars Collection.

Description

Creates a new menu bar. Returns a MenuBar object.

Syntax

object.Add(name)

object

Required. The MenuBars object.

name

Optional. The name for the new menu bar.

Remarks

The name of the menu bar is the same as its caption.

Example

The following example adds a new menu bar and then activates it. After running the example, you can use MenuBars(xlModule).Activate to restore the Visual Basic Module menu.

With MenuBars.Add("Stock Chart")
    With .Menus.Add("File")
        .MenuItems.Add "Update", "UpdateProc"
        .MenuItems.Add "Print", "PrintProc"
    End With
End With
MenuBars("Stock Chart").Activate


Add Method (MenuItems Collection)

Applies To

MenuItems Collection.

Description

Adds a new menu item to the specified menu. Can also be used to restore a built-in menu item in Microsoft Excel that has been deleted. Returns a MenuItem object. Use the AddMenu method to add a submenu caption.

Syntax

object.Add(caption, onAction, shortcutKey, before, restore, statusBar, helpContextID, helpFile)

object

Required. The MenuItems object.

caption

Required. The text of the menu item (sets the initial value of the Caption property for the new menu item). Use an ampersand (&) before the command underline. Use a single hyphen ("-") for the caption to create a separator bar.

onAction

Optional. Specifies the name of the macro that runs when the new menu item is selected.

shortcutKey

Optional. Used only on the Apple Macintosh. Specifies the shortcut key for the menu item as text.

before

Optional. Specifies the menu item before which the new item will be added. Can be either a number (1 to insert at the top of the menu, for example) or a caption of another, existing menu item (in the language of the macro, without the ampersand), or a reference to the menu item.

restore

Optional. If True, Microsoft Excel will restore the previously deleted built-in menu item named caption. If False or omitted, Microsoft Excel will add a new menu item. The restored menu item is placed at the end of the menu unless you use the before argument to specify the location.

statusBar

Optional. Specifies help text to display in the status bar when the menu item is selected or browsed by the user. If omitted the default status bar text assigned to the macro is used.

helpContextID

Optional. Specifies the context ID for the custom help topic of the menu item. If omitted the default help context ID assigned to the macro is used.

helpFile

Optional. Specifies the help file name containing the custom help topic of the menu item. If omitted the default help file name assigned to the macro is used.

Remarks

The settings specified for the statusBar, helpContextID, and helpFile arguments override any per-macro options set by the macro specified by the onAction argument.

However, changing the macro options after the menu item has been added overrides the custom help arguments used with the Add method.

See Also

AddMenu Method, Checked Property, Enabled Property, MacroOptions Method, OnAction Property.

Example

This example adds a new menu item at the top of the Help menu on each menu bar.

For Each mb in MenuBars
    mb.Menus("Help").MenuItems.Add _
        caption:="Read Me First", _
        onAction:="Read_Me_First", _
        before:=1
Next mb


Add Method (Menus Collection)

Applies To

Menus Collection.

Description

Adds a new menu. Can also be used to restore a built-in menu in Microsoft Excel that has been deleted. Returns a Menu object.

Syntax

object.Add(caption, before, restore)

object

Required. The Menus object.

caption

Required. The text of the menu (sets the initial value of the Caption property for the new menu). Use an ampersand (&) before the command underline.

before

Optional. Specifies the menu before which the new menu will be added. Can be either a number (one to insert at the beginning of the menu bar, for example) or a caption of another, existing menu (in the language of the macro, without the ampersand), or a reference to the menu. If this argument is omitted, the new menu is added to the left of the Window menu.

restore

Optional. If True, Microsoft Excel will restore the previously deleted built-in menu named caption. If False or omitted, Microsoft Excel will add a new menu. The restored menu is placed at the end of the menu bar unless you use the before argument to specify the location.

Remarks

On the Apple Macintosh, this method returns an error if there is not enough room to create the new menu. You should always check the return value to ensure that the new menu was added successfully.

In Windows, the menu bar will wrap if necessary to fit the new menu.

You cannot create a new shortcut menu; you can only modify a built-in shortcut menu.

Example

This example adds a new menu to the worksheet menu bar.

MenuBars(xlWorksheet).Menus.Add caption:="More Help"


Add Method (Modules Collection)

Applies To

Modules Collection.

Description

Creates a new Visual Basic module. Returns a Module object.

Syntax

object.Add(before, after, count)

object

Required. The Modules object.

before

Optional. Specifies the sheet before which the new module is added.

after

Optional. Specifies the sheet after which the new module is added.

count

Optional. The number of sheets to add. If omitted, the default is one.

Remarks

If before and after are omitted, the module is inserted before the active sheet.

Example

This example inserts a new Visual Basic module before the active sheet.

ActiveWorkbook.Modules.Add


Add Method (Names Collection)

Applies To

Names Collection.

Description

Defines a new name. Returns a Name object.

Syntax

object.Add(name, refersTo, visible, macroType, shortcutKey, category, nameLocal, refersToLocal, categoryLocal, refersToR1C1, refersToR1C1Local)

object

Required. The Names object.

name

Required (unless nameLocal is specified). The text to use as the name (in the language of the macro). Names cannot include spaces and cannot look like cell references.

refersTo

Required (unless one of the other refersTo arguments is specified). Describes what the name refers to (in the language of the macro, using A1-style notation).

visible

Optional. If True or omitted, Microsoft Excel defines the name normally. If False, the name is defined as a hidden name (it does not appear in the Define Name, Paste Name, or Goto dialog boxes).

macroType

Optional. Specifies the macro type, as shown in the following table.

Value | Meaning
1 | User-defined function (Function procedure)
2 | Macro (also known as Sub procedure)
3 or omitted | None (that is, the name does not refer to a user-defined function or macro)

shortcutKey

Optional. Specifies the macro shortcut key. Must be a single letter, such as "z" or "Z". Applies only for command macros.

category

Specifies the category of the macro or function if macroType is 1 or 2. The category is used in the Function Wizard. Existing categories can be referred to by number (starting at one), or by name (in the language of the macro). Microsoft Excel creates a new category if the specified category does not already exist.

nameLocal

Required if name is not specified. The text to use as the name (in the language of the user). Names cannot include spaces, and cannot look like cell references.

refersToLocal

Required (unless one of the other refersTo arguments is specified). Describes what the name refers to (in the language of the user, using A1-style notation).

categoryLocal

Required if category is not specified. Text identifying the category of a custom function in the language of the user.

refersToR1C1

Required (unless one of the other refersTo arguments is specified). Describes what the name refers to (in the language of the macro, using R1C1-style notation).

refersToR1C1Local

Required (unless one of the other refersTo arguments is specified). Describes what the name refers to (in the language of the user, using R1C1-style notation).

Example

This example defines a new name for the range A1:D3 on Sheet1.

ActiveWorkbook.Names.Add _
    name:="tempRange", _
    refersTo:="=Sheet1!$A$1:$D$3"


Add Method (OLEObjects Collection)

Applies To

OLEObjects Collection.

Description

Adds a new OLE object to the current sheet. Returns an OLEObject object.

Syntax

object.Add(classType, fileName, link, displayAsIcon, iconFileName, iconIndex, iconLabel)

object

Required. The OLEObjects collection.

classType

Optional (you must specify either classType or fileName). A string containing the OLE long class name for the object that is to be created. If classType is specified, fileName and link are ignored.

fileName

Optional (you must specify either classType or fileName). A string specifying the file from which the OLE object is to be created.

link

Optional. True if the new OLE object based on fileName should be linked to that file. If it is not linked, the file is created as a copy of the file. False if omitted.

displayAsIcon

Optional. True if the new OLE object is displayed as an icon, or as its regular picture. If True, the iconFileName and iconIndex can be used to specify an icon.

iconFileName

Optional. A string that specifies the file that contains the icon to be displayed. This is used only if displayAsIcon is True. If not specified or the file contains no icons, the default icon for the OLE Class is used.

iconIndex

Optional. The number of the icon within the iconFileName. This is used only if displayAsIcon is True and iconFileName refers to a valid file containing icons. If an icon with the given index does not exist in the file specified in iconFileName, the first one in the file is used.

iconLabel

Optional. A string specifying a label to display beneath the icon. This is used only if displayAsIcon is True. If this argument is omitted or the string is empty (""), then no caption is displayed.

Example

This example creates a new Microsoft Word OLE object on Sheet1.

ActiveWorkbook.Worksheets("Sheet1").OLEObjects.Add _
    classType:="Word.Document.6"


Add Method (Scenarios Collection)

Applies To

Scenarios Collection.

Description

Creates a new scenario and adds it to the list of scenarios available for the current worksheet. Returns a Scenario object.

Syntax

object.Add(name, changingCells, values, comment, locked, hidden)

object

Required. The Scenarios object.

name

Required. A string specifying the name for the new scenario.

changingCells

Required. A range giving the changing cells for the scenario.

values

Optional. An array containing the scenario values for the cells in changingCells. If omitted, the scenario values are assumed to be the current values in the cells of changingCells.

comment

Optional. A string specifying comment text for the scenario. When a new scenario is added, author name and date are automatically added at the beginning of the comment text.

locked

Optional. True if the scenario is locked to prevent changes. If this argument is omitted, the scenario is locked.

hidden

Optional. True if the scenario is hidden. If this argument is omitted, the scenario is not hidden.

Remarks

A scenario name must be unique; Microsoft Excel generates an error if you try to create a scenario with a name already in use.

Example

This example adds a new scenario to Sheet1.

Worksheets("Sheet1").Scenarios.Add Name:="Best Case", _
    ChangingCells:=Worksheets("Sheet1").Range("A1:A4"), _
    Values:=Array(23, 5, 6, 21), _
    Comment:="Most favorable outcome."


Add Method (SeriesCollection Collection)

Applies To

SeriesCollection Collection.

Description

Adds one or more new series to the SeriesCollection collection.

Syntax

object.Add(source, rowcol, seriesLabels, categoryLabels, replace)

object

Required. The SeriesCollection object.

source

Required. Specifies the new data, either as a Range or an array of data points.

rowcol

Optional. Specifies whether the new values are in the rows (xlRows) or columns (xlColumns) of the specified range. The default value is xlColumns.

seriesLabels

Optional. Ignored if source is an array. True if the first row or column contains the name of the data series. False if the first row or column contains the first data point of the series. If this argument is omitted, Microsoft Excel attempts to determine the series name location from the contents of the first row or column.

categoryLabels

Optional. Ignored if source is an array. True if the first row or column contains the name of the category labels. False if the first row or column contains the first data point of the series. If this argument is omitted, Microsoft Excel attempts to determine the category label location from the contents of the first row or column.

replace

Optional. If categoryLabels is True and replace is True, the specified categories replace the categories that currently exist for the series. If this argument is False or omitted, the existing categories will not be replaced.

See Also

Extend Method.

Example

This example creates a new series in Chart1. The data source for the new series is range B1:B10 on Sheet1.

Charts("Chart1").SeriesCollection.Add _
    source:=ActiveWorkbook.Worksheets("Sheet1").Range("B1:B10")

This is the same as the preceding example, except that the chart is an embedded chart on Sheet1.

Worksheets("Sheet1").ChartObjects(1).Activate
ActiveChart.SeriesCollection.Add _
    source:=Worksheets("Sheet1").Range("B1:B10")


Add Method (Sheets Collection)

Applies To

Sheets Collection.

Description

Creates a new worksheet, chart, module, dialog sheet or macro sheet.

Syntax

object.Add(before, after, count, type)

object

Required. The Sheets object.

before

Optional. Specifies the sheet before which the new sheet is added. Must be an object, for example ActiveWorkbook.Worksheets("Sheet1").

after

Optional. Specifies the sheet after which the new sheet is added. Must be an object, for example ActiveWorkbook.ActiveSheet.

count

Optional. The number of sheets to add. If omitted, the default is one.

type

Optional. The type of sheet to add. Must be one of xlWorksheet, xlChart, xlModule, xlDialogSheet, xlExcel4MacroSheet, or xlExcel4IntlMacroSheet. If omitted, the default is xlWorksheet.

Remarks

If before and after are omitted, the new sheet is inserted before the active sheet.

Example

This example inserts a new worksheet before the active sheet.

ActiveWorkbook.Sheets.Add before:=ActiveWorkbook.ActiveSheet

This example adds two new dialog sheets after Module1.

ActiveWorkbook.Sheets.Add after:=ActiveWorkbook.Sheets("Module1"), _
    type:=xlDialogSheet, count:=2


Add Method (Styles Collection)

Applies To

Styles Collection.

Description

Creates a new style and adds it to the list of styles available for the current workbook. Returns a Style object.

Syntax

object.Add(name, basedOn)

object

Required. The Styles object.

name

Required. A string specifying the name for the new style.

basedOn

Optional. A reference to a cell that will be used as the basis for the new style. If specified, the newly created style will be given a style based on that cell. If omitted, the newly created style will be based on the Normal style.

Remarks

If a style with the specified name already exists, this method redefines the style based on the cell specified in basedOn. The following example redefines the Normal style based on the active cell:

ActiveWorkbook.Styles.Add name:="Normal", _
    basedOn:=ActiveCell

Example

This example defines a new style based on cell A1 on Sheet1.

Worksheets("Sheet1").Activate
ActiveWorkbook.Styles.Add name:="myNewStyle", _
    basedOn:=ActiveSheet.Range("A1")

This example defines a new style that includes only the Font property.

With ActiveWorkbook.Styles.Add(name:="theNewStyle")
    .IncludeNumber = False
    .IncludeFont = True
    .IncludeAlignment = False
    .IncludeBorder = False
    .IncludePatterns = False
    .IncludeProtection = False
    .Font.Name = "Arial"
    .Font.Size = 18
End With


Add Method (ToolbarButtons Collection)

Applies To

ToolbarButtons Collection.

Description

Adds a new button to an existing toolbar. Returns a ToolbarButton object.

Syntax

object.Add(button, before, onAction, pushed, enabled, statusBar, helpContextID, helpFile)

object

Required. The ToolbarButtons object.

button

Optional. The button ID number, as an integer. If this argument is omitted, a gap is inserted in the toolbar. You can only insert a gap between two toolbar buttons (you cannot insert a gap at the beginning or at the end of the toolbar). To insert a button followed by a gap at the beginning of the toolbar, insert the new button first, and then insert the gap after the new button. For a complete list of button IDs available to Visual Basic, see Toolbar Button ID Values.

before

Optional. Specifies the new button position. The new button will be inserted before the button at this position. If this argument is omitted, the button is inserted at the end of the toolbar. Remember that gaps count as toolbar buttons; you cannot simply count buttons to get the button position. For example, if there is a gap between the first and second buttons on the toolbar, you must specify 3 for the before argument to insert a new button after the gap.

onAction

Optional. Specifies an initial value for the OnAction property, which is the name of the macro that runs when the button is clicked. If omitted with a built-in button, the button will have its built-in behavior. If omitted with a custom button, the Assign Macro dialog box is displayed when the button is first clicked.

pushed

Optional. Specifies an initial value for the Pushed property (True if the button appears pressed).

enabled

Optional. Specifies an initial value for the Enabled property (True if the button is enabled).

statusBar

Optional. Specifies help text to display in the status bar when the mouse cursor is positioned over the toolbar button. If omitted the default status bar text assigned to the macro is used.

helpContextID

Optional. Specifies the context ID for the custom help topic of the toolbar button. If omitted the default help context ID assigned to the macro is used.

helpFile

Optional. Specifies the help file name containing the custom help topic of the toolbar button. If omitted the default help file name assigned to the macro is used.

Remarks

The settings specified for the statusBar, helpContextID, and helpFile arguments override any per-macro options set by the macro specified by the onAction argument.

However, changing the macro options after the toolbar button has been added overrides the custom help arguments used with the Add method.

See Also

Enabled Property, MacroOptions Method, OnAction Property, Pushed Property.

Example

This example creates a new toolbar, adds the Camera button (button index number 228) to it, and then displays the new toolbar.

Set myNewToolbar = Toolbars.Add(Name:="My New Toolbar")
myNewToolbar.ToolbarButtons.Add Button:=228
myNewToolbar.Visible = True


Add Method (Toolbars Collection)

Applies To

Toolbars Collection.

Description

Creates a new toolbar. Returns a Toolbar object.

Syntax

object.Add(name)

object

Required. The Toolbars object.

name

Optional. A string that specifies a name for the new toolbar. If omitted, Microsoft Excel uses a default name (such as "Toolbar 1").

Example

This example creates a new toolbar, adds the Camera button (button index number 228) to it, and then displays the new toolbar.

Set myNewToolbar = Toolbars.Add(Name:="My New Toolbar")
myNewToolbar.ToolbarButtons.Add Button:=228
myNewToolbar.Visible = True


Add Method (Trendlines Collection)

Applies To

Trendlines Collection.

Description

Creates a new Trendline.

Syntax

object.Add(type, order, period, forward, backward, intercept, displayEquation, displayRSquared, name)

object

Required. The Trendlines object.

type

Optional. Specifies the trendline type (one of xlLinear, xlLogarithmic, xlExponential, xlPolynomial, xlMovingAvg, or xlPower). If omitted, the default is xlLinear.

order

Required if type is xlPolynomial. Specifies the trendline order. Must be an integer from two to six, inclusive.

period

Required if type is xlMovingAvg. Specifies the trendline period. Must be an integer greater than one and less than the number of data points in the series you are adding a trendline to.

forward

Optional. Sets the number of periods (or units on a scatter chart) that the trendline extends forward.

backward

Optional. Sets the number of periods (or units on a scatter chart) that the trendline extends backward.

intercept

Optional. Sets the trendline intercept. If omitted, the intercept is automatically set by the regression.

displayEquation

Optional. True if the equation of the trendline is displayed on the chart (in the same data label as the R-squared value).

displayRSquared

Optional. True if the R-squared value of the trendline is displayed on the chart (in the same data label as the equation).

name

Optional. Specifies the name of the trendline as text. If this argument is omitted, an automatically generated name is used.

See Also

Backward Property, DisplayEquation Property, DisplayRSquared Property, Forward Property, Intercept Property, Order Property, Period Property.

Example

This example creates a new linear trendline in Chart1.

ActiveWorkbook.Charts("Chart1").SeriesCollection(1).Trendlines.Add


Add Method (Workbooks Collection)

Applies To

Workbooks Collection.

Description

Creates a new workbook. The new workbook becomes the active workbook. Returns a Workbook object.

Syntax

object.Add(template)

object

Required. The Workbooks object.

template

Optional. Determines how the new workbook is created. If this argument is a string specifying the name of an existing Microsoft Excel file, the new workbook is created using the specified file as a template. If this argument is a constant (one of xlWorksheet, xlChart, xlExcel4MacroSheet, or xlExcel4IntlMacroSheet), the new workbook contains a single sheet of the specified type. If this argument is omitted, Microsoft Excel creates a new workbook with a number of blank sheets (the number of sheets is set by the SheetsInNewWorkbook property).

Remarks

If the template argument specifies a file, the filename may include a path.

See Also

ActiveWorkbook Property, SheetsInNewWorkbook Property.

Example

This example creates a new workbook.

Workbooks.Add


Add Method (Worksheets Collection)

Applies To

Worksheets Collection.

Description

Creates a new worksheet. The new worksheet becomes the active sheet. Returns a Worksheet object.

Syntax

object.Add(before, after, count, type)

object

Required. The Worksheets object.

before

Optional. Specifies the sheet before which the new sheet is added.

after

Optional. Specifies the sheet after which the new sheet is added.

count

Optional. The number of sheets to add. One if omitted.

type

Optional. Specifies the worksheet type (one of xlWorksheet, xlExcel4MacroSheet, or xlExcel4IntlMacroSheet). If omitted, the default is xlWorksheet.

Remarks

If before and after are omitted, the new sheet is inserted before the active sheet.

Example

This example creates a new worksheet and inserts it before the active sheet.

ActiveWorkbook.Worksheets.Add

This example adds a new worksheet after the last worksheet in the active workbook.

Worksheets.Add.Move after:=Worksheets(Worksheets.Count)


AddChartAutoFormat Method

Applies To

Application Object.

Description

Adds a custom chart autoformat to the list of available chart autoformats.

Syntax

object.AddChartAutoFormat(chart, name, description)

object

Required. The Application object.

chart

Required. A Chart object that contains the format that will be applied when the new chart autoformat is applied.

name

Required. A string that represents the name of the autoformat.

description

Optional. A string that describes the custom autoformat.

See Also

DeleteChartAutoFormat Method, SetDefaultChart Method.

Example

This example adds a new autoformat based on Chart1.

Application.AddChartAutoFormat _
    chart:=Charts("Chart1"), name:="Presentation Chart"


AddCustomList Method

Applies To

Application Object.

Description

Adds a custom list for custom autofill and/or custom sort.

Syntax

object.AddCustomList(listArray, byRow)

object

Required. The Application object.

listArray

Required. An array of strings, or a Range.

byRow

Optional. Only used if listArray is a Range. If True, Microsoft Excel creates a custom list from each row in the range. If False, Microsoft Excel creates a custom list from each column in the range. If this argument is omitted and there are more rows than columns (or an equal number of rows and columns) in the range, then Microsoft Excel creates a custom list from each column in the range. If this argument is omitted and there are more columns than rows in the range, then Microsoft Excel creates a custom list from each row in the range.

Remarks

If the list you are trying to add already exists, this method does nothing.

See Also

CustomListCount Property, DeleteCustomList Method, GetCustomListContents Method, GetCustomListNum Method.

Example

This example adds an array of strings as a custom list.

Application.AddCustomList Array("cogs", "sprockets", _
    "widgets", "gizmos")


AddFields Method

Applies To

PivotTable Object.

Description

Adds row, column and page fields to the PivotTable.

Syntax

object.AddFields(rowFields, columnFields, pageFields, addToTable)

object

Required. The PivotTable object.

rowFields

Optional. Specifies a pivot field name (or an array of pivot field names) to be added as rows.

columnFields

Optional. Specifies a pivot field name (or an array of pivot field names) to be added as columns.

pageFields

Optional. Specifies a pivot field name (or an array of pivot field names) to be added as pages.

addToTable

Optional. If True, the fields are added to the PivotTable (none of the existing fields are replaced). If False, the new fields replace existing fields. The default is False if this argument is not specified.

Remarks

You must specify one of the field arguments.

See Also

ColumnFields Method, DataFields Method, HiddenFields Method, PageFields Method, RowFields Method, VisibleFields Method.

Example

This example replaces the existing column fields in PivotTable one on Sheet1 with the Status and Closed_By fields.

Worksheets("Sheet1").PivotTables(1).AddFields _
    ColumnFields:=Array("Status", "Closed_By")


AddIn Object

Description

Represents a single add-in, either installed or not installed.

Accessors

The AddIn object is a member of the AddIns collection. The AddIns collection contains a list of all the add-ins available to Microsoft Excel, regardless of whether they are installed. This list corresponds to the list of add-ins displayed in the Add-Ins dialog box (Tools menu). To access a single member of the collection, use the AddIns method with the add-in title or index number as an argument. Do not confuse the add-in title, which appears in the Add-Ins dialog box, with the add-in name, which is the filename of the add-in.

Use the Title property to return the title of the add-in (this property is read-only for add-ins). You must exactly match the spelling, but not the capitalization, of the title as it is shown in the Add-Ins dialog box. The following example installs the Analysis Toolpak add-in.

AddIns("analysis toolpak").Installed = True

The index number represents the position of the add-in in the list of add-ins shown in the Add-Ins dialog box. The following example creates a list on the worksheet named "Sheet1." The list contains specified properties of the available add-ins.

Sub EnumerateAddIns()
    Worksheets("sheet1").Rows(1).Font.Bold = True
    Worksheets("sheet1").Range("a1:d1").Value = _
        Array("Name", "Full Name", "Title", "Installed")
    For i = 1 To AddIns.Count
        Worksheets("sheet1").Cells(i + 1, 1) = AddIns(i).Name
        Worksheets("sheet1").Cells(i + 1, 2) = AddIns(i).FullName
        Worksheets("sheet1").Cells(i + 1, 3) = AddIns(i).Title
        Worksheets("sheet1").Cells(i + 1, 4) = AddIns(i).Installed
    Next
    Worksheets("sheet1").Range("a1").CurrentRegion.Columns.AutoFit
End Sub

Remarks

The Add method adds an add-in to the list of available add-ins but does not install the add-in. Set the Installed property of the add-in to True to install it. To install an add-in not shown in the list of available add-ins, you must first use the Add method and then set the Installed property. This can be done in a single step, as shown in the following example (note that you use the name of the add-in, not the title, with the Add method):

AddIns.Add("generic.xll").Installed = True

Use the Workbooks method with the add-in filename (not title) to return a reference to the workbook corresponding to a loaded add-in. You must use the filename because loaded add-ins do not normally appear in the Workbooks collection. The following example sets the wb variable to the workbook for MYADDIN.XLA.

Set wb = Workbooks("myaddin.xla")

The following example sets the wb variable to the workbook for the Analysis Toolpak add-in.

Set wb = Workbooks(AddIns("analysis toolpak").Name)

If the Installed property returns True, but calls to functions in the add-in still fail, the add-in may not actually be loaded. This is because the Addin object represents the existence and installed state of the add-in but doesn't represent the actual contents of the add-in workbook (the add-in dialog sheets, worksheets, and so on).To guarantee that an installed add-in is loaded, you should open the add-in workbook. The following example opens the workbook for the add-in named "My Addin" if the add-in is not already present in the Workbooks collection.

On Error Resume Next    ' turn off error checking
Set wbMyAddin = Workbooks(Addins("My Addin").Name)
lastError = Err
On Error Goto 0        ' restore error checking
If lastError <> 0 Then
    ' the add-in workbook isn't currently open. Manually open it.
    Set wbMyAddin = Workbooks.Open(Addins("My Addin").FullName)
End If

While in a Visual Basic module, you create an add-in by clicking the Make Add-In command on the Tools menu. The AddIn object provides a programming interface to the Add-In Manager; it doesn't actually create an add-in.

Properties

Application Property, Author Property, Comments Property, Creator Property, FullName Property, Installed Property, Keywords Property, Name Property, Parent Property, Path Property, Subject Property, Title Property.


AddIndent Property

Applies To

Button Object, Buttons Collection, DrawingObjects Collection, GroupObject Object, GroupObjects Collection, Range Object, Style Object, TextBox Object, TextBoxes Collection.

Description

True if text with the distributed text alignment style has extra space added at the beginning and end of each line. Read-write.

Remarks

This property is available only in Far East versions of Microsoft Excel, and only works for text with the xlDistributed alignment style in the direction of the text (indent is added if the text Orientation is xlVertical and the VerticalAlignment is xlDistributed, or if the text Orientation is xlHorizontal and the HorizontalAlignment is xlDistributed).

See Also

HorizontalAlignment Property, Orientation Property, VerticalAlignment Property.

Example

This example sets cell A1 on Sheet1 to use distributed horizontal alignment with extra space at the beginning and the end.

With Worksheets("Sheet1").Range("A1")
    .HorizontalAlignment = xlDistributed
    .AddIndent = True
End With


AddIns Collection Object

Description

A collection of AddIn objects representing all the add-ins available to Microsoft Excel, regardless of whether they are installed. This list corresponds to the list of add-ins displayed in the Add-Ins dialog box (Tools menu).

Accessors

Use the Add method to add an add-in to the list of available add-ins.

Use the AddIns method with an argument to access a single member of the collection or without an argument to access the entire collection at once.

The following example creates a list on the worksheet named "Sheet1" of the names and installed states of all the available add-ins.

Sub DisplayAddIns()
    Worksheets("Sheet1").Activate
    rw = 1
    For Each ad In Application.AddIns
        Worksheets("Sheet1").Cells(rw, 1) = ad.Name
        Worksheets("Sheet1").Cells(rw, 2) = ad.Installed
        rw = rw + 1
    Next
End Sub

Properties

Application Property, Count Property, Creator Property, Parent Property.

Methods

Add Method (AddIns Collection), Item Method.


AddIns Method

Applies To

Application Object.

Description

Accessor. Returns an object that represents a single add-in (an AddIn object, Syntax 1) or the collection of add-ins (an AddIns object, Syntax 2) listed in the Add-Ins dialog box. Read-only.

Syntax 1

object.AddIns(index)

Syntax 2

object.AddIns

object

Optional. The Application object.

index

Required for Syntax 1. The number of the add-in, or the title of the add-in, as a string.

Example

This example displays the status of the Analysis ToolPak add-in. Note that the string used as the index to the AddIns method is the Title property of the AddIn object.

If AddIns("Analysis ToolPak").Installed = True Then
    MsgBox "Analysis ToolPak add-in is installed"
Else
    MsgBox "Analysis ToolPak add-in is not installed"
End If


AddItem Method

Applies To

DrawingObjects Collection, DropDown Object, DropDowns Collection, ListBox Object, ListBoxes Collection.

Description

Adds an item to a list box or drop-down list box.

Syntax

object.AddItem(text, index)

object

Required. The object to which this method applies.

text

Required. Specifies the text string to add.

index

Optional. Specifies the position at which to add the new entry. If the list has fewer entries than the specified index, blank items are added from the end of the list to the specified position. If this argument is omitted, the item is appended to the existing list.

Remarks

Using this method clears any range specified by the ListFillRange property.

See Also

List Property, RemoveItem Method.

Example

This example replaces the existing contents of list box one on Dialog1 with the letters A through M.

DialogSheets("Dialog1").ListBoxes(1).RemoveAllItems
For i = 65 To 77
    DialogSheets("Dialog1").ListBoxes(1).AddItem Text:=Chr(i)
Next i


AddMenu Method

Applies To

MenuItems Collection.

Description

Adds a new submenu to the menu. This method can also be used to restore a built-in submenu that was previously deleted, by setting the restore argument to True.

Syntax

object.AddMenu(caption, before, restore)

object

Required. The MenuItems object.

caption

Required. The caption to use for the new submenu. To create an access key, put an ampersand (&) before the access-key letter.

before

Optional. If this argument is present, specifies the menu item before which this submenu should be inserted. May be a string containing the caption of the menu item (without the ampersand), a number indicating the position of the menu item, or a reference to the menu item.

restore

Optional. If this argument is True, Microsoft Excel will restore the previously deleted built-in submenu named by the caption argument. If False or omitted, Microsoft Excel will add a new submenu. The restored submenu is placed at the end of the menu unless you use the before argument to specify the location.

See Also

Add Method (MenuItems Collection).

Example

This example adds a new submenu to the Help menu on the Worksheet menu bar and then adds a submenu item to it.

Set newSubMenu = MenuBars(xlWorksheet).Menus("Help"). _
        MenuItems.AddMenu(Caption:="More")
newSubMenu.MenuItems.Add Caption:="More Help"


AddReplacement Method

Applies To

AutoCorrect Object.

Description

Adds an entry to the array of AutoCorrect replacements. This method is available only in Microsoft Excel for Windows 95.

Syntax

object.AddReplacement(what, replacement)

object

Required. The AutoCorrect object.

what

Required. A string specifying the text to be replaced. If this string already exists in the array of AutoCorrect replacements, the existing substitute text is replaced by the new text.

replacement

Required. A string specifying the text to be substituted.

See Also

DeleteReplacement Method, ReplacementList Property.

Example

This example substitutes the word "Temp." for the word "Temperature" in the array of AutoCorrect replacements.

With Application.AutoCorrect
    .AddReplacement "Temperature", "Temp."
End With


Address Method

Applies To

Range Object.

Description

Returns the range reference, as a string in the language of the macro.

Syntax

object.Address(rowAbsolute, columnAbsolute, referenceStyle, external, relativeTo)

object

Required. Returns a reference to this range.

rowAbsolute

Optional. If True or omitted, the row part of the reference is returned as an absolute reference.

columnAbsolute

Optional. If True or omitted, the column part of the reference is returned as an absolute reference.

referenceStyle

Optional. If xlA1 or omitted, the method returns an A1-style reference. If xlR1C1, the method returns an R1C1-style reference.

external

Optional. If True, the method returns an external reference. If False, the method returns a local reference. The default is False.

relativeTo

Optional. If rowAbsolute and columnAbsolute are False, and referenceStyle is xlR1C1, you must include a starting point for the relative reference. This argument is a Range object that defines the starting point.

Remarks

If the reference contains more than one cell, rowAbsolute and columnAbsolute apply to all rows and columns.

See Also

AddressLocal Method, Offset Method.

Example

The following example displays four different address representations of the same cell address. The comments in the example are the addresses displayed in the message boxes.

Set mc = Worksheets("Sheet1").Cells(1, 1)
MsgBox mc.Address()                              ' $A$1
MsgBox mc.Address(rowAbsolute:=False)            ' $A1
MsgBox mc.Address(referenceStyle:=xlR1C1)        ' R1C1
MsgBox mc.Address(referenceStyle:=xlR1C1, _
    rowAbsolute:=False,     _
    columnAbsolute:=False,  _
    relativeTo:=Worksheets(1).Cells(3, 3))       ' R[-2]C[-2]


AddressLocal Method

Applies To

Range Object.

Description

Returns the range reference, as a string in the language of the user.

Syntax

object.AddressLocal(rowAbsolute, columnAbsolute, referenceStyle, external, relativeTo)

object

Required. Returns a reference to this range.

rowAbsolute

Optional. If True or omitted, the row part of the reference is returned as an absolute reference.

columnAbsolute

Optional. If True or omitted, the column part of the reference is returned as an absolute reference.

referenceStyle

Optional. If xlA1 or omitted, the method returns an A1-style reference. If xlR1C1, the method returns an R1C1-style reference.

external

Optional. If True, the method returns an external reference. If False, the method returns a local reference.

relativeTo

Optional. If rowAbsolute and columnAbsolute are False, and referenceStyle is xlR1C1, then you must include a starting point for the relative reference. This argument is a Range object type that defines the starting point.

Remarks

If the reference contains more than one cell, rowAbsolute and columnAbsolute apply to all rows and columns.

See Also

Address Method, Offset Method.

Example

Assume that the following example was created in the American English version of Microsoft Excel and was then run in the German version. The example displays the text shown in the comments.

Set mc = Worksheets(1).Cells(1, 1)
MsgBox mc.AddressLocal()                         ' $A$1
MsgBox mc.AddressLocal(rowAbsolute:=False)       ' $A1
MsgBox mc.AddressLocal(ReferenceStyle:=xlR1C1)   ' Z1S1
MsgBox mc.AddressLocal(ReferenceStyle:=xlR1C1, _
    rowAbsolute:=False, _
    columnAbsolute:=False, _
    relativeTo:=Worksheets(1).Cells(3, 3))       ' Z(-2)S(-2)


AddVertex Method

Applies To

Drawing Object.

Description

Adds a vertex to the end of the drawing.

Syntax

object.AddVertex(left, top)

object

Required. The Drawing object.

left

Required. The left position of the new vertex in points (1/72 inch), relative to the upper left corner of the sheet.

top

Required. The top position of the new vertex in points, relative to the upper left corner of the sheet.

See Also

Add Method (Drawings Collection), Reshape Method.

Example

This example creates a new open trapezoid on Sheet1.

With Worksheets("Sheet1").Drawings.Add(100, 100, 200, 100, False)
    .AddVertex 180, 200
    .AddVertex 80, 200
    .AddVertex 100, 100
    .Border.Weight = xlMedium
End With


AdvancedFilter Method

Applies To

Range Object.

Description

Filters or copies from a list based on a criteria range. If the initial selection is a single cell, its current region is used.

Syntax

object.AdvancedFilter(action, criteriaRange, copyToRange, unique)

object

Required. The Range object.

action

Required. Specifies the operation (either xlFilterInPlace or xlFilterCopy).

criteriaRange

Optional. The criteria range. If omitted, there are no criteria.

copyToRange

Required if action is xlFilterCopy, ignored otherwise. The destination range for the copied rows.

unique

Optional. True means unique records only, False means all records that meet the criteria. If omitted, assumed False.

See Also

AutoFilter Method, FilterMode Property, ShowAllData Method.

Example

This example filters a database (named "Database") based on a criteria range named "Criteria."

Range("Database").AdvancedFilter _
    action:=xlFilterInPlace, _
    criteriaRange:=Range("Criteria")


AlertBeforeOverwriting Property

Applies To

Application Object.

Description

True if Microsoft Excel displays a message before overwriting non-blank cells during a drag and drop editing operation. Read-write.

Example

This example causes an alert to be displayed before nonblank cells are overwritten during drag-and-drop editing.

Application.AlertBeforeOverwriting = True


AltStartupPath Property

Applies To

Application Object.

Description

Returns or sets a string that names the alternate startup folder. Read-write.

Example

This example sets the alternate startup folder.

Application.AltStartupPath = "C:\EXCEL\MACROS"

This is the same example in Microsoft Excel for the Macintosh.

Application.AltStartupPath = "HD:Excel:My Macros"


And Operator

Description

Used to perform a logical conjunction on two expressions.

Syntax

result = expression1 And expression2

The And operator syntax has these parts:

Part | Description
result | Any numeric variable.
expression1 | Any expression.
expression2 | Any expression.

Remarks

If, and only if, both expressions evaluate True, result is True. If either expression evaluates False, result is False. The following table illustrates how result is determined:

If expression1 is | And expression2 is | The result is
True | True | True
True | False | False
True | Null | Null
False | True | False
False | False | False
False | Null | False
Null | True | Null
Null | False | False
Null | Null | Null

The And operator also performs a bit-wise comparison of identically positioned bits in two numeric expressions and sets the corresponding bit in result according to the following truth table:

If bit in expression1 is | And bit in expression2 is | The result is
0 | 0 | 0
0 | 1 | 0
1 | 0 | 0
1 | 1 | 1

See Also

Operator Precedence.

Example

This example uses the And operator to perform a logical conjunction on two expressions.

A = 10: B = 8: C = 6 : D = Null    ' Initialize variables.
MyCheck = A > B And B > C    ' Returns True.
MyCheck = B > A And B > C    ' Returns False.
MyCheck = A > B And B > D    ' Returns Null.
MyCheck = A And B            ' Returns 8 (bit-wise comparison).


AppActivate Statement

Description

Activates an application window.

Syntax

AppActivate title [,wait]

The AppActivate statement syntax has these named-argument parts:

Part | Description
title | In Microsoft Windows, the title argument is the string in the title bar of the application window you want to activate.
 | On the Macintosh (System 7.0 or later), the title argument is the application name. You can use the MacID function to specify an application's signature instead of the application name. For example,
 | AppActivate MacID("MSWD")
 | In addition, the task ID returned by the Shell function can be used, in place of title, to activate an application.
wait | Boolean value specifying whether the calling application has the focus before activating another. If False (default), the specified application is immediately activated, even if the calling application does not have the focus. If True, the calling application waits until it has the focus, then activates the specified application.

Remarks

The AppActivate statement changes the focus to the named application or window but does not affect whether it is maximized or minimized. Focus moves from the activated application window when the user takes some action to change the focus or close the window. Use the Shell function to start an application and set the window style.

In trying to find the application to activate, a comparison is made to try to find an application whose title string is an exact match with title. If unsuccessful, any application's title string that begins with title is activated. In Microsoft Windows, if there is more than one instance of the application named by title, one is arbitrarily activated.

If you use the MacID function with AppActivate in Microsoft Windows, an error occurs.

See Also

MacID Function, SendKeys Statement, Shell Function.

Example

This example illustrates various uses of the AppActivate statement to activate an application window. On the Macintosh, you can use the MacID function to specify the application's signature instead of the application's name. The AppActivate statement is available with Macintosh System 7.0 or later.

' In Microsoft Windows.
AppActivate "Microsoft Word"    ' Activate Word.
' AppActivate can also use the return value of the Shell function.
MyAppID = Shell("C:\WORD\WINWORD.EXE", 1)    ' Run Microsoft Word.
AppActivate MyAppID    ' Activate Microsoft
    ' Word.

' On the Macintosh.
AppActivate "Microsoft Word"    ' Activate Microsoft
    ' Word.
' MacID("MSWD") returns signature for Microsoft Word.
AppActivate MacID("MSWD")    ' Activate Microsoft
    ' Word.
' You can also use the return value of the Shell function.
ReturnValue = Shell("Microsoft Excel")    ' Run Microsoft Excel.
AppActivate ReturnValue    ' Activate Microsoft
    ' Excel.


Application Object

Description

Represents the entire Microsoft Excel application. The Application object contains:

  • Application-wide settings and options (many of the options in the Tools Options dialog box, for example).
  • Built-in worksheet functions such as SUM, AVERAGE, and COUNTA.
  • Methods that return top-level objects such as ActiveCell, ActiveSheet, and so on.

Accessors

In Microsoft Excel, you can always access the Application object using the word "Application." The following example applies the Windows method to the Application object.

Application.Windows("book1.xls").Activate

For all Microsoft Excel objects, the Application property returns the Microsoft Excel Application object. This can be useful when you are using OLE Automation to access Microsoft Excel objects in another application. The following example creates a Microsoft Excel worksheet object in another application and then opens a workbook in Microsoft Excel.

Set xl = CreateObject("Excel.Sheet")
xl.Application.Workbooks.Open "newbook.xls"

Remarks

Many of the properties and methods that return the most common user-interface objects, such as the active cell (ActiveCell property) can be used without the Application object qualifier. For example, instead of writing Application.ActiveCell.Font.Bold = True, you can write ActiveCell.Font.Bold = True.

Properties

ActiveCell Property, ActiveChart Property, ActiveDialog Property, ActiveMenuBar Property, ActivePrinter Property, ActiveSheet Property, ActiveWindow Property, ActiveWorkbook Property, AlertBeforeOverwriting Property, AltStartupPath Property, Application Property, AskToUpdateLinks Property, AutoCorrect Property, CalculateBeforeSave Property, Calculation Property, Caller Property, CanPlaySounds Property, CanRecordSounds Property, Caption Property, CellDragAndDrop Property, ClipboardFormats Property, ColorButtons Property, CommandUnderlines Property, ConstrainNumeric Property, CopyObjectsWithCells Property, Creator Property, Cursor Property, CustomListCount Property, CutCopyMode Property, DataEntryMode Property, DDEAppReturnCode Property, DefaultFilePath Property, DisplayAlerts Property, DisplayClipboardWindow Property, DisplayExcel4Menus Property, DisplayFormulaBar Property, DisplayFullScreen Property, DisplayInfoWindow Property, DisplayNoteIndicator Property, DisplayRecentFiles Property, DisplayScrollBars Property, DisplayStatusBar Property, EditDirectlyInCell Property, EnableAnimations Property, EnableAutoComplete Property, EnableCancelKey Property, EnableTipWizard Property, FileConverters Property, FixedDecimal Property, FixedDecimalPlaces Property, Height Property, IgnoreRemoteRequests Property, Interactive Property, International Property, Iteration Property, LargeButtons Property, Left Property, LibraryPath Property, MailSession Property, MailSystem Property, MathCoprocessorAvailable Property, MaxChange Property, MaxIterations Property, MemoryFree Property, MemoryTotal Property, MemoryUsed Property, MouseAvailable Property, MoveAfterReturn Property, MoveAfterReturnDirection Property, Name Property, NetworkTemplatesPath Property, OnCalculate Property, OnData Property, OnDoubleClick Property, OnEntry Property, OnSheetActivate Property, OnSheetDeactivate Property, OnWindow Property, OperatingSystem Property, OrganizationName Property, Parent Property, Path Property, PathSeparator Property, PreviousSelections Property, PromptForSummaryInfo Property, RecordRelative Property,

ReferenceStyle Property, RegisteredFunctions Property, ScreenUpdating Property, Selection Property, SheetsInNewWorkbook Property, ShowToolTips Property, StandardFont Property, StandardFontSize Property, StartupPath Property, StatusBar Property, TemplatesPath Property, ThisWorkbook Property, Top Property, TransitionMenuKey Property, TransitionMenuKeyAction Property, TransitionNavigKeys Property, UsableHeight Property, UsableWidth Property, UserName Property, Value Property, Version Property, Visible Property, Width Property, WindowsForPens Property, WindowState Property.

Methods

ActivateMicrosoftApp Method, AddChartAutoFormat Method, AddCustomList Method, AddIns Method, Calculate Method, Cells Method, CentimetersToPoints Method, Charts Method, CheckSpelling Method, Columns Method, ConvertFormula Method, DDEExecute Method, DDEInitiate Method, DDEPoke Method, DDERequest Method, DDETerminate Method, DeleteChartAutoFormat Method, DeleteCustomList Method, Dialogs Method, DialogSheets Method, DoubleClick Method, Evaluate Method, Excel4IntlMacroSheets Method, Excel4MacroSheets Method, ExecuteExcel4Macro Method, FindFile Method, GetCustomListContents Method, GetCustomListNum Method, GetOpenFilename Method, GetSaveAsFilename Method, Goto Method, Help Method, InchesToPoints Method, InputBox Method, Intersect Method, MacroOptions Method, MailLogoff Method, MailLogon Method, MenuBars Method, Modules Method, Names Method, NextLetter Method, OnKey Method, OnRepeat Method, OnTime Method, OnUndo Method, Quit Method, Range Method, RecordMacro Method, RegisterXLL Method, Repeat Method, ResetTipWizard Method, Rows Method, Run Method, Save Method, SendKeys Method, SetDefaultChart Method, Sheets Method, ShortcutMenus Method, Toolbars Method, Undo Method, Union Method, Volatile Method, Wait Method, Windows Method, Workbooks Method, Worksheets Method.


Application Property

Applies To

All objects.

Description

Accessor. Used without an object qualifier, this property returns an Application object that represents the Microsoft Excel application. Used with an object qualifier, this property returns an Application object that represents the creator of the specified object (you can use this property with an OLE Automation object to return the automation object's application). Read-only.

See Also

Creator Property.

Example

This example displays a message about the application that created myObject.

Set myObject = ActiveWorkbook
If myObject.Application.Value = "Microsoft Excel" Then
    MsgBox "This is a Microsoft Excel object"
Else
    MsgBox "This is not a Microsoft Excel object"
End If


ApplyDataLabels Method

Applies To

Chart Object, Point Object, Series Object.

Description

Applies data labels to the point, the series, or to all series on the chart.

Syntax

object.ApplyDataLabels(type, legendKey)

object

Required. The Chart, Point, or Series object.

type

Optional. The type of data label, as shown in the following table.

Value

Meaning

xlNone

No data labels.

xlShowValue

Value for the point (assumed if this argument is not specified).

xlShowPercent

Percentage of the total. Only available for pie and doughnut charts.

xlShowLabel

Category for the point.

xlShowLabelAndPercent

Percentage of the total and category for the point. Only available for pie and doughnut charts.

legendKey

Optional. If True, Microsoft Excel shows the legend key next to the point.

See Also

DataLabel Property, HasDataLabel Property, HasDataLabels Property.

Example

This example applies category labels to series one in Chart1.

Charts("Chart1").SeriesCollection(1).ApplyDataLabels type:=xlShowLabel


ApplyNames Method

Applies To

Range Object.

Description

Applies names to the cells in the range.

Syntax

object.ApplyNames(names, ignoreRelativeAbsolute, useRowColumnNames, omitColumn, omitRow, order, appendLast)

object

Required. The range where names will be applied.

names

Optional. Contains an array of the names to apply. If omitted, all names on the sheet are applied to the range.

ignoreRelativeAbsolute

Optional. If True or omitted, replaces references with names regardless of the reference types of either the names or references. If False, replaces absolute references only with absolute names, relative references only with relative names, and mixed references only with mixed names.

useRowColumnNames

Optional. If True or omitted, Microsoft Excel uses the names of row and column ranges containing the specified range if names for the range cannot be found. If False, the omitColumn and omitRow arguments are ignored.

omitColumn

Optional. If True or omitted, Microsoft Excel replaces the reference with the row-oriented name without including a column-oriented name if the referenced cell is in the same column as the formula and within a row-oriented named range.

omitRow

Optional. If True or omitted, Microsoft Excel replaces the reference with the column-oriented name without including a row-oriented name if the referenced cell is in the same row as the formula within a column-oriented named range.

order

Optional. Determines which range name is listed first when a cell reference is replaced by a row-oriented and column-oriented range name (either xlRowThenColumn or xlColumnThenRow).

appendLast

Optional. If True, Microsoft Excel replaces the definitions of the names in names and also replaces the definitions of the last names defined. If appendLast is False or omitted, Microsoft Excel replaces the definitions of the names in names only.

Remarks

You can use the Array function to create the list of names for the names argument.

If you want to apply names to the entire sheet, use Cells.ApplyNames.

You cannot "unapply" names; to delete names, use the Delete method.

See Also

Add Method (Names Collection), Delete Method.

Example

This example applies names to the entire sheet.

Cells.ApplyNames names:=Array("Sales", "Profits")


ApplyOutlineStyles Method

Applies To

Range Object.

Description

Applies outlining styles to the range.

Syntax

object.ApplyOutlineStyles

object

Required. The range where outlining styles will be applied.

Example

The following example applies automatic outlining styles to the selection. The selection must include the entire outline range on a worksheet.

Selection.ApplyOutlineStyles


Arc Object

Description

Represents an arc graphic object on a chart sheet, dialog sheet, or worksheet. An arc always describes a quarter of a circle or oval.

Accessors

The Arc object is a member of the Arcs collection. Use the Add method to create a new arc and add it to the collection. To access a single member of the collection, use the Arcs method with the index number or name of the arc as an argument.

The following example sets the interior color for arc one.

Worksheets("sheet1").Activate
ActiveSheet.Arcs(1).Interior.Color = RGB(0, 255, 255)

The arc name is shown in the Name Box when the arc is selected. Use the Name property to set and return the arc name.

The following example selects the arc named "Arc 1" on the active sheet and then sets the arc border color.

Worksheets("sheet1").Activate
ActiveSheet.Arcs("arc 1").Select
Selection.Border.Color = RGB(255, 0, 0)

Properties

Application Property, Border Property, BottomRightCell Property, Creator Property, Enabled Property, Height Property, Index Property, Interior Property, Left Property, Locked Property, Name Property, OnAction Property, Parent Property, Placement Property, PrintObject Property, Top Property, TopLeftCell Property, Visible Property, Width Property, ZOrder Property.

Methods

BringToFront Method, Copy Method, CopyPicture Method, Cut Method, Delete Method, Duplicate Method, Select Method, SendToBack Method.


Arcs Collection Object

Description

A collection of all the Arc objects on the specified chart sheet, dialog sheet or worksheet

Accessors

Use the Add method to create a new arc and add it to the collection. The following example draws an arc starting at the upper-left corner of cell C3 and ending at the upper-left corner of cell D9.

Worksheets("sheet1").Activate
Set r1 = Range("c3")
Set r2 = Range("d9")
ActiveSheet.Arcs.Add r1.Left, r1.Top, r2.Left, r2.Top

Use the Arcs method with an argument to access a single member of the collection or without an argument to access the entire collection at once. The following example deletes all of the arcs on the worksheet named "Sheet1."

Worksheets("sheet1").Arcs.Delete

Properties

Application Property, Border Property, Count Property, Creator Property, Enabled Property, Height Property, Interior Property, Left Property, Locked Property, OnAction Property, Parent Property, Placement Property, PrintObject Property, Top Property, Visible Property, Width Property, ZOrder Property.

Methods

Add Method (Arcs and Lines), BringToFront Method, Copy Method, CopyPicture Method, Cut Method, Delete Method, Duplicate Method, Group Method, Item Method, Select Method, SendToBack Method.


Arcs Method

Applies To

Chart Object, DialogSheet Object, Worksheet Object.

Description

Accessor. Returns an object that represents a single arc (an Arc object, Syntax 1) or a collection of arcs (an Arcs object, Syntax 2) on the sheet. Read-only.

Syntax 1

object.Arcs(index)

Syntax 2

object.Arcs

object

Required. The object to which this method applies.

index

Required for Syntax 1. The name or number of the arc.

Example

This example deletes every arc on Sheet1.

Worksheets("Sheet1").Arcs.Delete

This example changes the color of arc one on Sheet1 to red.

Worksheets("Sheet1").Arcs(1).Border.ColorIndex = 3


Area3DGroup Property

Applies To

Chart Object.

Description

Accessor. Returns a ChartGroup object that represents the area chart group on a 3-D chart. Read-only.

See Also

AreaGroups Method.

Example

This example sets the subtype for the 3-D area chart group in Chart1. The example should be run on a 3-D area chart that has more than one series.

Charts("Chart1").Area3DGroup.SubType = 1


AreaGroups Method

Applies To

Chart Object.

Description

Accessor. On a 2-D chart, returns an object that represents a single area chart group (a ChartGroup object, Syntax 1), or a collection of the area chart groups (a ChartGroups collection, Syntax 2).

Syntax 1

object.AreaGroups(index)

Syntax 2

object.AreaGroups

object

Required. The Chart object.

index

Required for Syntax 1. Specifies the chart group.

See Also

Area3DGroup Property.

Example

This example sets the subtype for area chart group one. The example should be run on a 2-D chart that has an area group and a line group.

Charts("Chart1").AreaGroups(1).SubType = 1


Areas Collection Object

Description

A collection of the areas, or contiguous blocks of cells, within a selection. There is no singular Area object; individual members of the Areas collection are Range objects. The Areas collection contains one Range object for each discrete, contiguous range of cells within the selection. If the selection contains only one area, the Areas collection contains a single Range object that corresponds to that selection.

Accessors

Use the Areas method without an argument to return the entire collection. The following example clears the current selection if the selection contains more than one area.

If Selection.Areas.Count <> 1 Then Selection.Clear

Use the Areas method with an area index number as an argument to return a single area in the collection. The index numbers correspond to the order in which the areas were selected. The following example clears the first area in the current selection if the selection contains more than one area.

If Selection.Areas.Count <> 1 Then
        Selection.Areas(1).Clear
End If

Some operations cannot be performed on more than one area in a selection at once; you must loop through the individual areas in the selection and perform the operations on each area separately. The following example performs the operation named "myOperation" on the selected range if the selection contains only one area; if the selection contains multiple areas, the example performs myOperation on each individual area in the selection.

Set rangeToUse = Selection
If rangeToUse.Areas.Count = 1 Then
    myOperation rangeToUse
Else
    For Each singleArea in rangeToUse.Areas
        myOperation singleArea
    Next
End If

Properties

Application Property, Creator Property, Count Property, Parent Property.

Methods

Item Method.


Areas Method

Applies To

Range Object.

Description

Accessor. Returns an object that represents a single range (a Range object, Syntax 1), or a collection of all ranges (an Areas object, Syntax 2) in a multiple selection.

Syntax 1

object.Areas(index)

Syntax 2

object.Areas

object

Required. The multiple-selection range.

index

Required for Syntax 1. The number of the range within the multiple selection.

Remarks

For a single selection, the Areas method returns a collection of one object, the original Range object itself. For a multiple selection, the Areas method returns a collection that contains one object for each selection.

See Also

Union Method.

Example

This example displays a message if the user tries to carry out a command when more than one area is selected. This example must be run from a worksheet.

If Selection.Areas.Count > 1 Then
    MsgBox "Cannot do this to a multi-area selection."
End If


Arrange Method

Description

Arranges the windows on the screen.

Syntax

object.Arrange(arrangeStyle, activeWorkbook, syncHorizontal, syncVertical)

object

Required. The Windows object.

arrangeStyle

Optional. Arrange windows in this style. Can have one of the following values:

Value

Meaning

xlTiled

Windows are tiled (the default value, used if arrangeStyle is omitted).

xlCascade

Windows are cascaded.

xlHorizontal

Windows are arranged horizontally.

xlVertical

Windows are arranged vertically.

xlIcons

Arranges the icons (not available on the Apple Macintosh).

activeWorkbook

Optional. If True, arranges only the visible windows of the active workbook, instead of all the windows in Microsoft Excel. If False or omitted, arranges all the windows.

syncHorizontal

Optional. Ignored if activeWorkbook is False or omitted. If True, the windows of the active workbook are synchronized when scrolling horizontally. If False or omitted, the windows are not synchronized.

syncVertical

Optional. Ignored if activeWorkbook is False or omitted. If True, the windows of the active workbook are synchronized when scrolling vertically. If False or omitted, the windows are not synchronized.

Example

This example tiles all the windows in the application.

Application.Windows.Arrange arrangeStyle:=xlTiled


Array Function

Description

Returns a Variant containing an array.

Syntax

Array(arglist)

The arglist consists of a comma-delimited list of an arbitrary number of values that are assigned to the elements of the array contained within the Variant. If no arguments are specified, an array of zero-length is created.

Remarks

Although a Variant containing an array is conceptually different from an array whose elements are of type Variant, the way the array elements are accessed is the same. The notation used to refer to any element of an array consists of the variable name followed by parentheses containing an index number to the desired element. In the following example, the first statement creates a variable A as a Variant. The second statement assigns an array to the variable A. The final statement illustrates how to assign the value contained in the second array element to another variable.

Dim A As Variant
A = Array(10,20,30)
B = A(2)

The lower bound of an array created using the Array function is determined by the lower bound specified with the Option Base statement.

See Also

Deftype Statements, Dim Statement, Let Statement, Option Base Statement.

Example

This example uses the Array function to return a Variant containing an array.

MyWeek = Array("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun")
' Return values assume lower bound equals 1 (using Option Base).
MyDay = MyWeek(2)    ' Returns "Tue".
MyDay = MyWeek(4)    ' Returns "Thu".

This example fills the range A1:C5 on Sheet1, Sheet5, and Sheet7 with the contents of the same range on Sheet1.

x = Array("Sheet1", "Sheet5", "Sheet7")
Sheets(x).FillAcrossSheets _
    Worksheets("Sheet1").Range("A1:C5")

This example consolidates data from Sheet2 and Sheet3 onto Sheet1, using the SUM function.

Worksheets("Sheet1").Range("A1").Consolidate _
    sources:=Array("Sheet2!R1C1:R37C6", "Sheet3!R1C1:R37C6"), _
    Function:=xlSum

This example adds an array of strings as a custom list.

Application.AddCustomList Array("cogs", "sprockets", _
    "widgets", "gizmos")

This example hides Chart1, Chart3, and Chart5. Note that in this example, the Charts method returns a Sheets object instead of a Charts object.

Charts(Array("Chart1", "Chart3", "Chart5")).Visible = False

This example sets the entries in list box one on Dialog1.

DialogSheets("Dialog1").ListBoxes(1).List = _
    Array("cogs", "widgets", "sprockets", "gizmos")

This example creates a group from drawing objects one, three, and five on Sheet1.

Set myGroup = Worksheets("Sheet1").DrawingObjects(Array(1, 3, 5)).Group
Worksheets("Sheet1").Activate
myGroup.Select


ArrowHeadLength Property

Applies To

DrawingObjects Collection, GroupObject Object, GroupObjects Collection, Line Object, Lines Collection.

Description

Returns or sets the length of the arrow head (one of xlShort, xlMedium, or xlLong). Read-write.

See Also

ArrowHeadStyle Property, ArrowHeadWidth Property.

Example

This example creates a new line on Sheet1 and then sets the arrowhead length, width, and style.

Set newLine = Worksheets("Sheet1").Lines.Add(72, 72, 144, 144)
With newLine
    .ArrowHeadLength = xlShort
    .ArrowHeadWidth = xlNarrow
    .ArrowHeadStyle = xlOpen
End With


ArrowHeadStyle Property

Applies To

DrawingObjects Collection, GroupObject Object, GroupObjects Collection, Line Object, Lines Collection.

Description

Returns or sets the arrow head type (one of xlNone, xlOpen, xlClosed, xlDoubleOpen, or xlDoubleClosed). Read-write.

See Also

ArrowHeadLength Property, ArrowHeadWidth Property.

Example

This example creates a new line on Sheet1 and then sets the arrowhead length, width, and style.

Set newLine = Worksheets("Sheet1").Lines.Add(72, 72, 144, 144)
With newLine
    .ArrowHeadLength = xlShort
    .ArrowHeadWidth = xlNarrow
    .ArrowHeadStyle = xlOpen
End With


ArrowHeadWidth Property

Applies To

DrawingObjects Collection, GroupObject Object, GroupObjects Collection, Line Object, Lines Collection.

Description

Returns or sets the arrow head width (one of xlNarrow, xlMedium, xlWide). Read-write.

See Also

ArrowHeadLength Property, ArrowHeadStyle Property.

Example

This example creates a new line on Sheet1 and then sets the arrowhead length, width, and style.

Set newLine = Worksheets("Sheet1").Lines.Add(72, 72, 144, 144)
With newLine
    .ArrowHeadLength = xlShort
    .ArrowHeadWidth = xlNarrow
    .ArrowHeadStyle = xlOpen
End With


Asc Function

Description

Returns the character code corresponding to the first letter in a string.

Syntax

Asc(string)

The string named argument is any valid string expression. If the string contains no characters, and run-time error occurs.

See Also

Chr Function.

Example

This example uses the Asc function to return and character code corresponding to the first letter in the string.

MyNumber = Asc ("A")    ' Returns 65.
MyNumber = Asc ("a")    ' Returns 97.
MyNumber = Asc ("Apple")    ' Returns 65.


AskToUpdateLinks Property

Applies To

Application Object.

Description

True if Microsoft Excel asks the user to update links when opening files with links, or False if links are automatically updated with no dialog. Read-write.

Example

This example causes Microsoft Excel to ask the user to update links when a file that contains links is opened.

Application.AskToUpdateLinks = True


Atn Function

Description

Returns the arctangent of a number.

Syntax

Atn(number)

The number named argument can be any valid numeric expression.

Remarks

The Atn function takes the ratio of two sides of a right triangle (number) and returns the corresponding angle in radians. The ratio is the length of the side opposite the angle divided by the length of the side adjacent to the angle.

The range of the result is -pi/2 to pi/2 radians.

To convert degrees to radians, multiply degrees by pi/180. To convert radians to degrees, multiply radians by 180/pi.

Note

Atn is the inverse trigonometric function of Tan, which takes an angle as its argument and returns the ratio of two sides of a right triangle. Do not confuse Atn with the cotangent, which is the simple inverse of a tangent (1/tangent).

See Also

Cos Function, Derived Math Functions, Sin Function, Tan Function.

Example

This example uses the Atn function to return the arctangent of a number.

Pi = 4 * Atn(1)    ' Calculate the value of pi.


Author Property

Applies To

AddIn Object, Workbook Object.

Description

Returns or sets the author of the object, as a string. Read-only for AddIn, read-write for Workbook.

Remarks

In Microsoft Excel for Windows 95, this property has been replaced by a built-in OLE document property. For more information about OLE document properties, see BuiltinDocumentProperties.

You cannot use this property with an AddIn object that represents an XLL file or an add-in that was created with the Microsoft Excel 4.0 macro language.

See Also

Comments Property, Keywords Property, Subject Property, Title Property.

Example

This example displays the author and name of the Solver add-in.

Set a = AddIns("Solver Add-In")
MsgBox a.Author & " authored the add-in " & a.Name

This example sets the author of the active workbook.

ActiveWorkbook.Author = "Anonymous"


AutoComplete Method

Applies To

Range Object.

Description

Returns an AutoComplete match from the list. If there's no AutoComplete match or if more than one entry in the list matches the string to complete, the method returns an empty string. This method is available only in Microsoft Excel for Windows 95.

Syntax

object.AutoComplete(string)

object

Required. The Range object (must be a single cell).

string

Required. The string to complete.

Remarks

This method works whether or not the AutoComplete feature is disabled.

Example

This example returns the AutoComplete match for the string segment "Ap." An AutoComplete match is made if the column immediately above or below cell A5 (or the column containing cell A5) contains a contiguous list and one of the entries in the list contains a match for the string.

s = Worksheets(1).Range("A5").AutoComplete("Ap")
If Len(s) > 0 Then
    MsgBox "Completes to " & s
Else
    MsgBox "Has no completion"
End If

This example returns the AutoComplete match for the string segment "Ap." An AutoComplete match is made if the column immediately above or below cell A5 (or the column containing cell A5) contains a contiguous list and one of the entries in the list contains a match for the string.

s = Worksheets(1).Range("A5").AutoComplete("Ap")
If Len(s) > 0 Then
    MsgBox "Completes to " & s
Else
    MsgBox "Has no completion"
End If


AutoCorrect Object

Description

Contains Microsoft Excel AutoCorrect attributes (capitalization of names of days, correction of two initial capital letters, automatic correction list, and so on) This object is available only in Microsoft Excel for Windows 95.

Accessors

The AutoCorrect property returns the AutoCorrect object. The AutoCorrect attributes are properties of the AutoCorrect object. The following example sets Microsoft Excel to correct words that begin with two initial capital letters.

With Application.AutoCorrect
    .TwoInitialCapitals = True
    .ReplaceText = True
End With

Properties

Application Property, Parent Property, TwoInitialCapitals Property, CapitalizeNamesOfDays Property, ReplacementList Property, Creator Property, ReplaceText Property.

Methods

AddReplacement Method, DeleteReplacement Method.


AutoCorrect Property

Applies To

Application Object.

Description

Accessor. Returns an AutoCorrect object that represents the Microsoft Excel AutoCorrect attributes. This property is available only in Microsoft Excel for Windows 95. Read-only.

See Also

AddReplacement Method, CapitalizeNamesOfDays Property, DeleteReplacement Method, ReplacementList Property, ReplaceText Property, TwoInitialCapitals Property.

Example

This example substitutes the word "Temp." for the word "Temperature" in the array of AutoCorrect replacements.

With Application.AutoCorrect
    .AddReplacement "Temperature", "Temp."
End With


AutoFill Method

Applies To

Range Object.

Description

Performs an autofill on the cells in the range.

Syntax

object.AutoFill(destination, type)

object

Required. The source range.

destination

Required. A Range object that represents the cells to fill. The object must include the source range.

type

Optional. Can be one of xlFillDefault, xlFillSeries, xlFillCopy, xlFillFormats, xlFillValues, xlFillDays, xlFillWeekdays, xlFillMonths, xlFillYears, xlLinearTrend, xlGrowthTrend. If xlFillDefault or omitted, the method selects the most appropriate type based on the source range.

Example

This example performs an autofill on cells A1:A20 on Sheet1, based on the source range of A1:A2 on Sheet1. Before running this example, type 1 in cell A1 and type 2 in cell A2.

Set sourceRange = Worksheets("Sheet1").Range("A1:A2")
Set fillRange = Worksheets("Sheet1").Range("A1:A20")
sourceRange.AutoFill destination:=fillRange


AutoFilter Method

Applies To

Range Object.

Description

Syntax 1: Displays or hides the AutoFilter drop-down arrows.

Syntax 2: Filters a list using the AutoFilter.

Syntax 1

object.AutoFilter

Syntax 2

object.AutoFilter(field, criteria1, operator, criteria2)

object

Required. The Range object.

field

Required. The integer offset of the field on which to base the filter (from the left of the list-the leftmost field is field one).

criteria1

Optional. The criteria (a string; for example "101"). Use "=" to find blank fields, "<>" to find non-blank fields. If this argument is omitted, the criteria is All. If operator is xlTop10Items, criteria1 specifies the number of items (for example "10").

operator

Optional. Used with criteria1 and criteria2 to construct compound criteria. Can be either xlAnd or xlOr. If omitted, xlAnd is used. Specify xlTop10Items to use the Top 10 AutoFilter.

criteria2

Optional. The second criteria (a string). Used with criteria1 and operator to construct compound criteria.

See Also

AdvancedFilter Method, AutoFilterMode Property, FilterMode Property, ShowAllData Method.

Example

This example filters a list starting in cell A1 on Sheet1 to show only the entries in which field one is equal to the string "Otis".

Worksheets("Sheet1").Range("A1").AutoFilter _
    field:=1, _
    criteria1:="Otis"


AutoFilterMode Property

Applies To

Worksheet Object.

Description

True if the drop-down arrows for AutoFilter are currently displayed on the sheet. This property is independent of the FilterMode property. Read-write.

Remarks

This property will be True if the drop-down arrows are currently displayed. You can set this property to False to remove the arrows, but you cannot set it to True. Use the AutoFilter method to filter a list and display the drop-down arrows.

See Also

AutoFilter Method, FilterMode Property.

Example

This example displays the current state of the AutoFilterMode property on Sheet1.

If Worksheets("Sheet1").AutoFilterMode Then
    isOn = "On"
Else
    isOn = "Off"
End If
MsgBox "AutoFilterMode is " & isOn


AutoFit Method

Applies To

Range Object.

Description

Changes the width of the columns in the range or the height of the rows in the range for the best fit.

Syntax

object.AutoFit

object

Required. The range to apply the best fit to. Must be a row or a range of rows, or a column or a range of columns. Otherwise, this method generates an error.

Remarks

One unit of column width is equal to the width of one character of the Normal style.

See Also

ColumnWidth Property, RowHeight Property.

Example

This example changes the width of columns A through I on Sheet1 for the best fit.

Worksheets("Sheet1").Columns("A:I").AutoFit

This example changes the width of columns A through E on Sheet1 for the best fit, based only on the contents of cells A1:E1.

Worksheets("Sheet1").Range("A1:E1").Columns.AutoFit


AutoFormat Method (Chart object)

Applies To

Chart Object.

Description

Applies a built-in or custom autoformat to the specified chart.

Syntax

object.AutoFormat(gallery, format)

object

Required. The Chart object.

gallery

Required. Specifies the built-in gallery. Can be one of xl3DArea, xl3DBar, xl3DColumn, xl3DLine, xl3DPie, xl3DSurface, xlArea, xlBar, xlColumn, xlCombination, xlCustom, xlDefaultAutoFormat, xlDoughnut, xlLine, xlPie, xlRadar, or xlXYScatter.

format

Optional. Specifies the option number for the built-in autoformats or a string containing the name of the custom autoformat if gallery is xlCustom.

See Also

AutoFormat Method (Range object).

Example

This example applies the third radar autoformat to Chart1.

Charts("Chart1").AutoFormat xlRadar, 3

This example applies the "Monthly Sales" custom autoformat to Chart1.

Charts("Chart1").AutoFormat xlCustom, "Monthly Sales"


AutoFormat Method (Range object)

Applies To

Range Object.

Description

Automatically formats a range of cells using a predefined format.

Syntax

object.AutoFormat(format, number, font, alignment, border, pattern, width)

object

Required. The range to format.

format

Optional. The name or number of the format to apply (one of xlClassic1, xlClassic2, xlClassic3, xlAccounting1, xlAccounting2, xlAccounting3, xlAccounting4, xlColor1, xlColor2, xlColor3, xlList1, xlList2, xlList3, xl3DEffects1, xl3DEffects2, xlSimple, or xlNone). If this argument is omitted, the default value is xlClassic1.

number

Optional. Corresponds to the Number check box in the AutoFormat dialog box. Can be True or False (True if omitted).

font

Optional. Corresponds to the Font check box in the AutoFormat dialog box. Can be True or False (True if omitted).

alignment

Optional. Corresponds to the Alignment check box in the AutoFormat dialog box. Can be True or False (True if omitted).

border

Optional. Corresponds to the Border check box in the AutoFormat dialog box. Can be True or False (True if omitted).

pattern

Optional. Corresponds to the Pattern check box in the AutoFormat dialog box. Can be True or False (True if omitted).

width

Optional. Corresponds to the Column Width/Row Height check box in the AutoFormat dialog box. Can be True or False (True if omitted).

Remarks

If the range is a single cell, this method also formats the current region around the cell. In other words, the AutoFormat method performs CurrentRegion.AutoFormat on the single cell.

In Japanese Microsoft Excel, the following additional formats are available: xlLocalFormat1 and xlLocalFormat2.

See Also

AutoFormat Method (Chart object), CurrentRegion Property, Style Property.

Example

This example formats cells A1:D8 on Sheet1, using a predefined format.

Worksheets("Sheet1").Range("A1:D8").AutoFormat format:=xlClassic1


AutoLoad Property

Applies To

OLEObject Object.

Description

True if the OLE object is automatically loaded when the workbook that contains the object is opened. This property is available only in Microsoft Excel for Windows 95. Read-write.

Remarks

For most OLE object types, this property should not be set to True. By default, the AutoLoad property is set to False for new OLE objects; this saves time and memory when Microsoft Excel is loading workbooks. The benefit of automatically loading OLE objects is that, for objects that represent volatile data, links to source data can be reestablished immediately and the objects can be rendered again, if necessary.

Example

This example sets the AutoLoad property for OLE object one.

ActiveSheet.OLEObjects(1).AutoLoad = True


AutomaticStyles Property

Applies To

Outline Object.

Description

True if the outline uses automatic styles. Read-write.

Example

This example sets the outline on Sheet1 to use automatic styles.

Worksheets("Sheet1").Outline.AutomaticStyles = True


AutoOutline Method

Applies To

Range Object.

Description

Automatically creates an outline for the specified range. If the range is a single cell, Microsoft Excel creates an outline for the entire sheet. The new outline replaces any existing outline.

Syntax

object.AutoOutline

object

Required. The Range object.

See Also

ApplyOutlineStyles Method, ClearOutline Method.

Example

This example creates an outline for the range A1:G37 on Sheet1. The range must contain either a summary row or a summary column.

Worksheets("Sheet1").Range("A1:G37").AutoOutline


AutoScaling Property

Applies To

Chart Object.

Description

If True, Microsoft Excel scales a 3-D chart so that it is closer in size to the equivalent 2-D chart. The RightAngleAxes property must be True. Read-write.

Example

This example automatically scales Chart1. The example should be run on a 3-D chart.

With Charts("Chart1")
    .RightAngleAxes = True
    .AutoScaling = True
End With


AutoSize Property

Applies To

Button Object, Buttons Collection, DrawingObjects Collection, GroupObject Object, GroupObjects Collection, TextBox Object, TextBoxes Collection.

Description

True if the object will be automatically resized to fit the text it contains. Read-write.

Remarks

This property is set to False if the object is resized manually (by the user or by the Height or Width properties).

Example

This example sets button one on Sheet1 to automatically size to fit the text it contains.

Worksheets("Sheet1").Buttons(1).AutoSize = True


AutoText Property

Applies To

DataLabel Object, DataLabels Collection.

Description

True if the object automatically generates appropriate text based on context. Read-write.

Example

This example sets the data labels for series one in Chart1 to automatically generate appropriate text.

Charts("Chart1").SeriesCollection(1).DataLabels.AutoText = True


AutoUpdate Property

Applies To

OLEObject Object.

Description

True if the OLE object updates automatically when the source changes. Valid only if the object is linked (its OLEType property must be xlOLELink). Read-only.

Example

This example displays the status of automatic updating for all OLE objects on Sheet1.

Worksheets("Sheet1").Activate
Range("A1").Value = "Name"
Range("B1").Value = "Link Status"
Range("C1").Value = "AutoUpdate Status"
i = 2
For Each obj In ActiveSheet.OLEObjects
    Cells(i, 1) = obj.Name
    If obj.OLEType = xlOLELink Then
        Cells(i, 2) = "Linked"
        Cells(i, 3) = obj.AutoUpdate
    Else
        Cells(i, 2) = "Embedded"
    End If
    i = i + 1
Next


Axes Collection Object

Description

A collection of all the Axis objects in the specified chart.

Accessors

Use the Axes method with an argument to access a single member of the collection or without an argument to access the entire collection at once. Unlike most collections, the Axes collection is indexed using constants. Secondary axes, if present, are accessed using an additional argument. For more information, see the Axes method.

The following example uses the Axes method with an argument to set the category axis title text on the chart sheet named "Chart1."

With Charts("chart1").Axes(xlCategory)
    .HasTitle = True
    .AxisTitle.Caption = "1994"
End With

Properties

Application Property, Count Property, Creator Property, Parent Property.

Methods

Item Method.


Axes Method

Applies To

Chart Object.

Description

Accessor. Returns an object that represents a single axis (an Axis object, Syntax 1) or a collection of the axes on the chart (an Axes object, Syntax 2).

Syntax 1

object.Axes(type, axisGroup)

Syntax 2

object.Axes

object

Required. The Chart object.

type

Required for Syntax 1. Specifies the axis to return. Can be one of xlValue, xlCategory, or xlSeries (xlSeries is only valid for 3-D charts).

axisGroup

Optional. Specifies the axis group (either xlPrimary or xlSecondary). If this argument is omitted, the primary group is used. 3-D charts have only one axis group.

Example

This example adds an axis label to the category axis in Chart1.

With Charts("Chart1").Axes(xlCategory)
    .HasTitle = True
    .AxisTitle.Text = "July Sales"
End With

This example turns off major gridlines for the category axis in Chart1.

Charts("Chart1").Axes(xlCategory).HasMajorGridlines = False

This example turns off all gridlines for all axes in Chart1.

For Each a In Charts("Chart1").Axes
    a.HasMajorGridlines = False
    a.HasMinorGridlines = False
Next a


Axis Object

Description

Represents a single axis in a chart.

Accessors

The Axis object is a member of the Axes collection. An individual member of the collection can be accessed with the Axes method by specifying the axis type (xlCategory, xlValue, or xlSeries) and optionally the axis group (xlPrimary or xlSecondary). Only 3-D charts have a series axis, and only 2-D charts can have a secondary axis group.

The following example sets the category axis title text on the chart sheet named "Chart1."

With Charts("chart1").Axes(xlCategory)
    .HasTitle = True
    .AxisTitle.Caption = "1995"
End With

Properties

Application Property, AxisBetweenCategories Property, AxisGroup Property, AxisTitle Property, Border Property, CategoryNames Property, Creator Property, Crosses Property, CrossesAt Property, HasMajorGridlines Property, HasMinorGridlines Property, HasTitle Property, MajorGridlines Property, MajorTickMark Property, MajorUnit Property, MajorUnitIsAuto Property, MaximumScale Property, MaximumScaleIsAuto Property, MinimumScale Property, MinimumScaleIsAuto Property, MinorGridlines Property, MinorTickMark Property, MinorUnit Property, MinorUnitIsAuto Property, Parent Property, ReversePlotOrder Property, ScaleType Property, TickLabelPosition Property, TickLabels Property, TickLabelSpacing Property, TickMarkSpacing Property, Type Property.

Methods

Delete Method, Select Method.


AxisBetweenCategories Property

Applies To

Axis Object.

Description

True if the value axis crosses the category axis between categories.

Remarks

This property only applies to category axes, and does not apply to 3-D charts.

Example

This example causes the value axis in Chart1 to cross the category axis between categories.

Charts("Chart1").Axes(xlCategory).AxisBetweenCategories = True


AxisGroup Property

Applies To

Axis Object, ChartGroup Object, Series Object.

Description

Returns the group (either xlPrimary or xlSecondary) for the specified axis, chart group, or series. Read-write for Series; read-only for Axis and ChartGroup.

Remarks

For 3-D charts, only xlPrimary is valid.

Example

This example deletes the value axis in Chart1 if it is in the secondary group.

With Charts("Chart1").Axes(xlValue)
    If .AxisGroup = xlSecondary Then .Delete
End With


AxisTitle Object

Description

Represents an axis title in a chart.

Accessors

The AxisTitle property returns the axis title for the specified axis. The following example activates embedded chart one on the worksheet named "Sheet1," sets the value axis title text, sets the font to Bookman 10 point, and sets the word "millions" to italics.

Worksheets("sheet1").ChartObjects(1).Activate
With ActiveChart.Axes(xlValue)
    .HasTitle = True
    With .AxisTitle
        .Caption = "Revenue (millions)"
        .Font.Name = "bookman"
        .Font.Size = 10
        .Characters(10, 8).Font.Italic = True
    End With
End With

Remarks

The AxisTitle object does not exist and cannot be accessed unless the HasTitle property for the axis is True.

Properties

Application Property, Border Property, Caption Property, Creator Property, Font Property, HorizontalAlignment Property, Interior Property, Left Property, Name Property, Orientation Property, Parent Property, Shadow Property, Text Property, Top Property, VerticalAlignment Property.

Methods

Characters Method, Delete Method, Select Method.


AxisTitle Property

Applies To

Axis Object.

Description

Accessor. Returns an AxisTitle object that represents the title of the specified axis. Read-only.

See Also

ChartTitle Property, HasTitle Property, Title Property.

Example

This example adds an axis label to the category axis in Chart1.

With Charts("Chart1").Axes(xlCategory)
    .HasTitle = True
    .AxisTitle.Text = "July Sales"
End With


Background Property

Applies To

Font Object.

Description

Returns or sets the text background type (can be one of xlAutomatic, xlOpaque, or xlTransparent). This property is only used for text on charts. Read-write.

Example

This example adds a chart title to embedded chart one on Sheet1 and then sets the font size and background type of the title.

With Worksheets("Sheet1").ChartObjects(1).Chart
    .HasTitle = True
    .ChartTitle.Text = "1995 Rainfall Totals by Month"
    With .ChartTitle.Font
        .Size = 10
        .Background = xlTransparent
    End With
End With


Backward Property

Applies To

Trendline Object.

Description

Returns or sets the number of periods (or units on a scatter chart) that the trendline extends backward. Read-write.

See Also

Forward Property.

Example

This example sets the number of units the trendline on Chart1 extends forward and backward. The example should be run on a 2-D column chart that contains a single series with a trendline.

With Charts("Chart1").SeriesCollection(1).Trendlines(1)
    .Forward = 5
    .Backward = .5
End With


Bar3DGroup Property

Applies To

Chart Object.

Description

Accessor. Returns a ChartGroup object that represents the bar chart group on a 3-D chart. Read-only.

See Also

BarGroups Method.

Example

This example sets the subtype for the 3-D bar chart group in Chart1. The example should be run on a 3-D bar chart that has more than one series.

Charts("Chart1").Bar3DGroup.SubType = 1


BarGroups Method

Applies To

Chart Object.

Description

Accessor. On a 2-D chart, returns an object that represents a single bar chart group (a ChartGroup object, Syntax 1), or a collection of the bar chart groups (a ChartGroups collection, Syntax 2).

Syntax 1

object.BarGroups(index)

Syntax 2

object.BarGroups

object

Required. The Chart object.

index

Required for Syntax 1. Specifies the chart group.

See Also

Bar3DGroup Property.

Example

This example sets the subtype for bar chart group one. The example should be run on a 2-D chart that has a bar group and a line group.

Charts("Chart1").BarGroups(1).SubType = 1


BaseField Property

Applies To

PivotField Object.

Description

Returns or sets the base field for the custom calculation. Valid only for data fields. Read-write.

Example

This example sets the data field in the PivotTable on Sheet1 to calculate the difference from the base field, sets the base field to the field named "ORDER_DATE," and sets the base item to the item named "5/16/89."

Worksheets("Sheet1").Range("A3").PivotField.Calculation = _
    xlDifferenceFrom
Worksheets("Sheet1").Range("A3").PivotField.BaseField = "ORDER_DATE"
Worksheets("Sheet1").Range("A3").PivotField.BaseItem = "5/16/89"


BaseItem Property

Applies To

PivotField Object.

Description

Returns or sets the item in the base field for the custom calculation. Valid only for data fields. Read-write.

Example

This example sets the data field in the PivotTable on Sheet1 to calculate the difference from the base field, sets the base field to the field named "ORDER_DATE," and sets the base item to the item named "5/16/89."

Worksheets("Sheet1").Range("A3").PivotField.Calculation = _
    xlDifferenceFrom
Worksheets("Sheet1").Range("A3").PivotField.BaseField = "ORDER_DATE"
Worksheets("Sheet1").Range("A3").PivotField.BaseItem = "5/16/89"


BCCRecipients Property

Applies To

Mailer Object.

Description

Returns or sets the blind carbon copy recipients of the mailer. Available only in Microsoft Excel for the Apple Macintosh with the PowerTalk mail system extension installed. Read-write.

Remarks

This property is an array of strings specifying the address, in one of the following formats:

  • A record in the Preferred Personal Catalog. These names are one level deep ("Fred" or "June").
  • A full path specifying either a record in a personal catalog ("HD:Excel Folder:My Catalog:Barney") or a plain record ("HD:Folder:Martin").
  • A relative path from the current working folder specifying either a personal catalog record ("My Catalog:Barney") or a plain record ("Martin").
  • A path in a PowerShare catalog tree of the form "CATALOG_NAME:<node>:RECORD_NAME" where <node> is a path to a PowerShare catalog. An example of a complete path is "AppleTalk:North Building Zone:George's Mac".

See Also

CCRecipients Property, Enclosures Property, Mailer Property, Received Property, SendDateTime Property, Sender Property, SendMailer Method, Subject Property, ToRecipients Property.

Example

This example sets up the Mailer object for workbook one and then sends the workbook.

With Workbooks(1)
    .HasMailer = True
    With .Mailer
        .Subject = "Here is the workbook"
        .ToRecipients = Array("Jean")
        .CCRecipients = Array("Adam", "Bernard")
        .BCCRecipients = Array("Chris")
        .Enclosures = Array("TestFile")
    End With
    .SendMailer
End With


Beep Statement

Description

Sounds a tone through the computer's speaker.

Syntax

Beep

Remarks

The frequency and duration of the beep depends on hardware, which may vary among computers.

Example

This example uses the Beep statement to sound three consecutive tones through the computer's speaker.

For I = 1 to 3    ' Loop 3 times.
    Beep    ' Sound a tone.
Next I


BlackAndWhite Property

Applies To

PageSetup Object.

Description

True if elements of the document will be printed in black and white. Read-write.

Remarks

This property applies only to worksheet pages.

Example

This example causes Sheet1 to print in black and white.

Worksheets("Sheet1").PageSetup.BlackAndWhite = True


Bold Property

Applies To

Font Object.

Description

True if the font is bold. Read-write.

Example

This example sets the font to bold for the range A1:A5 on Sheet1.

Worksheets("Sheet1").Range("A1:A5").Font.Bold = True


Border Object

Description

Represents the border of an object.

Accessors

Most bordered objects (all except the Range and Style objects) have a border that is treated as a single entity, regardless of how many sides it has. The entire border must be accessed at once. Use the Border property to return the border of this kind of object. The following example activates the chart sheet named "Chart1," places a dashed border around the chart area for the active chart and a dotted border around the plot area.

Charts("chart1").Activate
With ActiveChart
    .ChartArea.Border.LineStyle = xlDash
    .PlotArea.Border.LineStyle = xlDot
End With

The appearance of line-like objects (such as lines, error bars, and arcs) is controlled by setting properties of the Border object for the line-like object. Setting the Border property for a line, for example, changes the way the line itself is drawn. The following example activates the worksheet named "Sheet1" and then sets the line style and color for a line on the active sheet.

Worksheets("sheet1").Activate
With ActiveSheet.Lines(1).Border
    .LineStyle = xlDashDot
    .Color = RGB(255, 0, 0)
End With

Range and Style objects have four discrete borders—left, right, top, and bottom—which can be accessed individually or as a group. Use the Borders method with an argument to return a single Border object. The following example sets the bottom border of cells A1:G1 to a double line.

Worksheets("Sheet1").Range("a1:g1"). _
    Borders(xlBottom).LineStyle = xlDouble

To change all four borders of a Range or Style object, use the Borders method with no arguments to access the entire Borders collection at once.

Properties

Application Property, Color Property, ColorIndex Property, Creator Property, LineStyle Property, Parent Property, Weight Property.


Border Property

Applies To

Arc Object, Arcs Collection, Axis Object, AxisTitle Object, ChartArea Object, ChartObject Object, ChartObjects Collection, ChartTitle Object, CheckBox Object, DataLabel Object, DataLabels Collection, DownBars Object, Drawing Object, DrawingObjects Collection, Drawings Collection, DropLines Object, ErrorBars Object, Floor Object, Gridlines Object, GroupObject Object, GroupObjects Collection, HiLoLines Object, Legend Object, LegendKey Object, Line Object, Lines Collection, OLEObject Object, OLEObjects Collection, OptionButton Object, OptionButtons Collection, Oval Object, Ovals Collection, Picture Object, Pictures Collection, PlotArea Object, Point Object, Rectangle Object, Rectangles Collection, Series Object, SeriesLines Object, TextBox Object, TextBoxes Collection, Trendline Object, UpBars Object, Walls Object.

Description

Accessor. Returns a Border object that represents the border of the object. Read-only.

Example

This example sets the color of the chart area border of Chart1 to red.

Charts("Chart1").ChartArea.Border.ColorIndex = 3

This example creates a new rectangle on Sheet1 and then sets the border color to red.

Set newRect = Worksheets("Sheet1").Rectangles.Add(72, 72, 72, 144)
newRect.Border.ColorIndex = 3


BorderAround Method

Applies To

Range Object.

Description

Adds a border to a range and sets the Color, LineStyle, and Weight properties for the new border.

Syntax

object.BorderAround(lineStyle, weight, colorIndex, color)

object

Required. The Range object.

lineStyle

Optional. Specifies the border line style. Can be one of xlContinuous, xlDash, xlDot, or xlDouble.

weight

Optional. Specifies the border weight. Can be one of xlHairline, xlThin, xlMedium, or xlThick. If omitted, xlThin is assumed.

colorIndex

Optional. Specifies the border color as a color index into the current color palette. Can be a number from 1 to 56, or the special constant xlAutomatic to use the window text color.

color

Optional. Specifies the border color as an RGB value.

Remarks

You can specify either colorIndex or color, but not both. If you do not specify either argument, Microsoft Excel uses the xlAutomatic color index.

Similarly, you can specify either lineStyle or weight, but not both. If you do not specify either argument, Microsoft Excel creates a default border.

This method outlines the entire range without filling it in. To set the borders of all the cells, you must set the Color, LineStyle, and Weight properties for the Borders collection. To clear the border, you must set the LineStyle property to xlNone for all the cells in the range.

Example

This example adds a thick red border around the range A1:D4 on Sheet1.

Worksheets("Sheet1").Range("A1:D4").BorderAround _
        ColorIndex:=3, Weight:=xlThick


Borders Collection Object

Description

A collection of four Border objects representing the four borders of a Range or Style object.

Accessors

Use the Borders method with an argument to access a single member of the collection. The following example sets the bottom border of cells A1:G1 to a double line.

Worksheets("Sheet1").Range("a1:g1"). _
    Borders(xlBottom).LineStyle = xlDouble

Use the Borders method with no arguments to access all four borders at once. The following example puts a double blue border around cell C5:

With Worksheets("sheet1").Range("c5").Borders
    .LineStyle = xlDouble
    .Color = RGB(0, 0, 255)
End With

Remarks

You can set border properties for an individual border only with Range and Style objects. Other bordered objects, such as check boxes or chart areas, have a border that is treated as a single entity, regardless of how many sides it has. For these objects, you must access and set properties for the entire border at once. See the Border object for more information.

Properties

Application Property, Color Property, ColorIndex Property, Count Property, Creator Property, LineStyle Property, Parent Property, Value Property, Weight Property.

Methods

Item Method.


Borders Method

Applies To

Range Object, Style Object.

Description

Accessor. Returns an object that represents a single border (a Border object, Syntax 1) or a collection of borders (a Borders object, Syntax 2). Read-write.

Syntax 1

object.Borders(index)

Syntax 2

object.Borders

object

Required. The Range or Style object.

index

Required for Syntax 1. Specifies the border (one of xlTop, xlBottom, xlLeft, or xlRight).

Example

This example sets the color of the bottom border of cell B2 on Sheet1 to red.

With Worksheets("Sheet1").Range("B2").Borders(xlBottom)
    .LineStyle = xlContinuous
    .ColorIndex = 3
End With

This example sets the color of all four borders of cell B2 on Sheet1 to red.

With Worksheets("Sheet1").Range("B2").Borders
    .LineStyle = xlContinuous
    .ColorIndex = 3
End With


BottomMargin Property

Applies To

PageSetup Object.

Description

Returns or sets the size of the bottom margin, in points (1/72 inch). Read-write.

Remarks

Margins are set or returned in points. Use the InchesToPoints or CentimetersToPoints function to convert.

See Also

LeftMargin Property, RightMargin Property, TopMargin Property.

Example

These two examples set the bottom margin of Sheet1 to 0.5 inch (36 points).

Worksheets("Sheet1").PageSetup.BottomMargin = _
        Application.InchesToPoints(0.5)

Worksheets("Sheet1").PageSetup.BottomMargin = 36

This example displays the current bottom margin setting for Sheet1.

marginInches = Worksheets("Sheet1").PageSetup.BottomMargin / _
    Application.InchesToPoints(1)
MsgBox "The current bottom margin is " & marginInches & " inches"


BottomRightCell Property

Applies To

Arc Object, Button Object, ChartObject Object, CheckBox Object, Drawing Object, DropDown Object, EditBox Object, GroupBox Object, GroupObject Object, Label Object, Line Object, ListBox Object, OLEObject Object, OptionButton Object, Oval Object, Picture Object, Rectangle Object, ScrollBar Object, Spinner Object, TextBox Object.

Description

Accessor. Returns a Range object that represents the cell that lies under the bottom right corner of the object. For drawing objects, this property applies only when the drawing object is on a worksheet. Read-only.

See Also

TopLeftCell Property.

Example

This example displays the address of the cell beneath the lower-right corner of rectangle one on Sheet1.

MsgBox "The bottom right corner is over cell " & _
    Worksheets("Sheet1").Rectangles(1).BottomRightCell.Address


BringToFront Method

Applies To

Arc Object, Arcs Collection, Button Object, Buttons Collection, ChartObject Object, ChartObjects Collection, CheckBox Object, Drawing Object, DrawingObjects Collection, Drawings Collection, DropDown Object, DropDowns Collection, EditBox Object, EditBoxes Collection, GroupBox Object, GroupBoxes Collection, GroupObject Object, GroupObjects Collection, Label Object, Labels Collection, Line Object, Lines Collection, ListBox Object, ListBoxes Collection, OLEObject Object, OLEObjects Collection, OptionButton Object, OptionButtons Collection, Oval Object, Ovals Collection, Picture Object, Pictures Collection, Rectangle Object, Rectangles Collection, ScrollBar Object, ScrollBars Collection, Spinner Object, Spinners Collection, TextBox Object, TextBoxes Collection.

Description

Brings the object to the front of the z-order.

Syntax

object.BringToFront

object

Required. The object to which this method applies.

See Also

SendToBack Method, ZOrder Property.

Example

This example brings rectangle one on Sheet1 to the front of the z-order.

Worksheets("Sheet1").Rectangles(1).BringToFront


BuiltIn Property

Applies To

MenuBar Object, Toolbar Object, ToolbarButton Object.

Description

True if the object is built-in (part of Microsoft Excel, as opposed to a custom object). Read-only.

See Also

BuiltInFace Property.

Example

This example lists the names of all built-in buttons on the Formatting toolbar. The names are placed in the first column on Sheet1.

rowNumber = 1
For Each btn In Application.Toolbars("Formatting").ToolbarButtons
    If btn.BuiltIn Then
        Worksheets("Sheet1").Cells(rowNumber, 1).Value = btn.Name
        rowNumber = rowNumber + 1
    End If
Next btn

This example resets the face of each built-in button on the Standard toolbar that has a custom face.

For Each btn In Application.Toolbars("Standard").ToolbarButtons
    If btn.BuiltIn And Not btn.BuiltInFace Then
        If Not(btn.IsGap) Then  ' don't try to reset the separator gap!
            btn.BuiltInFace = True
        End If
    End If
Next btn


BuiltinDocumentProperties Property

Applies To

Workbook Object.

Description

Returns a DocumentProperties collection object that represents all the built-in document properties for the specified workbook. Read-only.

To use this property, you should establish a reference to the Microsoft Office 95 Object Library by using the References command (Tools menu).

Remarks

This property returns the entire collection of built-in document properties. Use the Item method to return a single member of the collection (a DocumentProperty object) by specifying either the name of the property or the collection index (as a number). For a list of valid built-in document property names, see the Item method.

Because the Item method is the default method for the DocumentProperties collection object, the following statements are identical:

BuiltinDocumentProperties.Item(1)
BuiltinDocumentProperties(1)

Use the CustomDocumentProperties property to return the collection of custom document properties.

Example

This example displays the names of the built-in document properties as a list on worksheet one.

rw = 1
Worksheets(1).Activate
For Each p In ActiveWorkbook.BuiltinDocumentProperties
    Cells(rw, 1).Value = p.Name
    rw = rw + 1
Next


BuiltInFace Property

Applies To

ToolbarButton Object.

Description

True if the button is using its built-in face. False if the button has a custom face. Read-write.

Remarks

This property can only be set to True, which forces the button to use its built-in face. You cannot set this property to False; to use a custom face, use the CopyFace and PasteFace methods (this sets the BuiltInFace property to False).

See Also

BuiltIn Property, CopyFace Method, PasteFace Method.

Example

This example resets the face of each built-in button on the Standard toolbar that has a custom face.

For Each btn In Application.Toolbars("Standard").ToolbarButtons
    If btn.BuiltIn And Not btn.BuiltInFace Then
        If Not(btn.IsGap) Then  ' don't try to reset the separator gap!
            btn.BuiltInFace = True
        End If
    End If
Next btn


Button Object

Description

Represents a custom button graphic object on a chart sheet, dialog sheet, or worksheet. Do not confuse the Button object with the ToolbarButton object, which is a button on a toolbar.

Accessors

The Button object is a member of the Buttons collection. The Buttons collection contains all the Button objects on a single sheet. Use the Add method to create a new button and add it to the collection.

To access a single member of the collection, use the Buttons method with the index number or name or of the button as an argument.

The following example sets the text for button one on the worksheet named "Sheet1."

Worksheets("sheet1").Buttons(1).Text = "Repeat"

The button name is shown in the Name Box when the button is selected. Use the Name property to set or return the name of the button. The following example positions the button named "go_button" so that it completely cover cell C10. When the button is pressed, the GoButtonTest macro runs.

Worksheets("sheet1").Activate
Set r = ActiveSheet.Range("c10")
With ActiveSheet.Buttons("go_button")
    .Caption = "Go"
    .Left = r.Left
    .Top = r.Top
    .Width = r.Width
    .Height = r.Height
    .OnAction = "GoButtonTest"
End With

Properties

Accelerator Property, AddIndent Property, Application Property, AutoSize Property, BottomRightCell Property, CancelButton Property, Caption Property, Creator Property, DefaultButton Property, DismissButton Property, Enabled Property, Font Property, Formula Property, Height Property, HelpButton Property, HorizontalAlignment Property, Index Property, Left Property, Locked Property, LockedText Property, Name Property, OnAction Property, Orientation Property, Parent Property, PhoneticAccelerator Property, Placement Property, PrintObject Property, Text Property, Top Property, TopLeftCell Property, VerticalAlignment Property, Visible Property, Width Property, ZOrder Property.

Methods

BringToFront Method, Characters Method, CheckSpelling Method, Copy Method, CopyPicture Method, Cut Method, Delete Method, Duplicate Method, Select Method, SendToBack Method.


Buttons Collection Object

Description

A collection of all the Button objects on the specified chart sheet, dialog sheet, or worksheet.

Accessors

Use the Add method to create a new button and add it to the collection. The following example activates worksheet one and then adds a new button to the active sheet. The new button is positioned over cells C5 and D5.

Worksheets(1).Activate
Set r = ActiveSheet.Range("c5:d5")
Set newButton = ActiveSheet.Buttons.Add(r.Left, r.Top, _
    r.Width, r.Height)

Use the Buttons method with an argument to access a single member of the collection or without an argument to access the entire collection at once.

Properties

Accelerator Property, AddIndent Property, Application Property, AutoSize Property, CancelButton Property, Caption Property, Count Property, Creator Property, DefaultButton Property, DismissButton Property, Enabled Property, Font Property, Formula Property, Height Property, HelpButton Property, HorizontalAlignment Property, Left Property, Locked Property, LockedText Property, OnAction Property, Orientation Property, Parent Property, PhoneticAccelerator Property, Placement Property, PrintObject Property, Text Property, Top Property, VerticalAlignment Property, Visible Property, Width Property, ZOrder Property.

Methods

Add Method (Graphic Objects and Controls), BringToFront Method, Characters Method, CheckSpelling Method, Copy Method, CopyPicture Method, Cut Method, Delete Method, Duplicate Method, Group Method, Item Method, Select Method, SendToBack Method.


Buttons Method

Applies To

Chart Object, DialogSheet Object, Worksheet Object.

Description

Accessor. Returns an object that represents a single button (a Button object, Syntax 1) or a collection of buttons (a Buttons object, Syntax 2) on the sheet. Read-only.

Syntax 1

object.Buttons(index)

Syntax 2

object.Buttons

object

Required. The object to which this method applies.

index

Required for Syntax 1. The name or number of the button.

Example

This example deletes every button on Sheet1.

Worksheets("Sheet1").Buttons.Delete

This example changes the text on button one on Sheet1.

Worksheets("Sheet1").Buttons(1).Text = "New Button Name"


Calculate Method

Applies To

Application Object, Range Object, Worksheet Object.

Description

Calculates all open workbooks, a specific worksheet in a workbook, or a specified range of cells in a sheet, as shown in the following table.

To calculate | Example
All open workbooks | Application.Calculate (or just Calculate)
A specific worksheet | Worksheets(1).Calculate
A specified range | Worksheets(1).Rows(2).Calculate

Syntax

object.Calculate

object

Optional for Application, required for Worksheet and Range. Specifies where the calculation will occur.

Example

This example calculates the formulas in columns A, B, and C in the used range on Sheet1.

Worksheets("Sheet1").UsedRange.Columns("A:C").Calculate


CalculateBeforeSave Property

Applies To

Application Object.

Description

True if workbooks are calculated before they are saved to disk (if the Calculation property is set to xlManual). This property is preserved even if you change the Calculation property. Read-write.

Example

This example causes workbooks to be calculated before they are saved to disk.

Application.Calculation = xlManual
Application.CalculateBeforeSave = True


Calculation Property

Applies To

Application Object, PivotField Object.

Description

For the Application object, returns or sets the calculation mode, as shown in the following table. Read-write.

Value | Meaning
xlAutomatic | Recalculate automatically.
xlManual | Recalculate only at user's request.
xlSemiautomatic | Recalculate automatically, except for data tables.

For the PivotField object, returns or sets the type of calculation done by the specified pivot field (one of xlDifferenceFrom, xlIndex, xlNormal, xlPercentDifferenceFrom, xlPercentOf, xlPercentOfColumn, xlPercentOfRow, xlPercentOfTotal, or xlRunningTotal). Valid only for data fields. Read-write.

See Also

CalculateBeforeSave Property.

Example

This example causes Microsoft Excel to calculate workbooks before they are saved to disk.

Application.Calculation = xlManual
Application.CalculateBeforeSave = True

This example sets the data field in the PivotTable on Sheet1 to calculate the difference from the base field, sets the base field to the field named "ORDER_DATE," and sets the base item to the item named "5/16/89."

Worksheets("Sheet1").Range("A3").PivotField.Calculation = _
    xlDifferenceFrom
Worksheets("Sheet1").Range("A3").PivotField.BaseField = "ORDER_DATE"
Worksheets("Sheet1").Range("A3").PivotField.BaseItem = "5/16/89"


Call Statement

Description

Transfers control to a Sub procedure, Function procedure, dynamic-link library (DLL) procedure, or a Macintosh code resource procedure.

Syntax

[Call] name [argumentlist]

The Call statement syntax has these parts:

Part | Description
Call | Optional keyword; if specified, you must enclose argumentlist in parentheses. For example:
 | Call MyProc(0)
name | Name of the procedure to call.
argumentlist | Comma-delimited list of variables, arrays, or expressions to pass to the procedure. Components of argumentlist may include the keywords ByVal or ByRef to describe how the arguments are to be treated by the called procedure. However, ByVal and ByRef can be used with Call only when making a call to a DLL procedure or a Macintosh code resource.

Remarks

You are never required to use the Call keyword when calling a procedure. However, if you use the Call keyword to call a procedure that requires arguments, argumentlist must be enclosed in parentheses. If you omit the Call keyword, you also must omit the parentheses around argumentlist. If you use either Call syntax to call any intrinsic or user-defined function, the function's return value is discarded.

To pass a whole array to a procedure, use the array name followed by empty parentheses.

See Also

Declare Statement.

Example

This example illustrates how the Call statement is used to transfer control to a Sub procedure, an intrinsic function, a dynamic-link library (DLL) procedure and a procedure in a Macintosh code resource.

' Call a Sub procedure.
Call PrintToDebugWindow("Hello World")
' The above statement causes control to be passed to the following
' Sub procedure.
Sub PrintToDebugWindow(AnyString)
    Debug.Print AnyString    ' Print to Debug window.
End Sub

' Call an intrinsic function. The return value of the function is
' discarded.
Call Shell(AppName, 1)    ' AppName contains the path of the
    ' executable.
' Call a Microsoft Windows DLL procedure.
Declare Sub MessageBeep Lib "User" (ByVal N As Integer)
Sub CallMyDll()
    Call MessageBeep(0)    ' Call Windows DLL procedure.
    MessageBeep 0    ' Call again without Call keyword.
End Sub

' Call a Macintosh Code Resource.
Declare Sub MessageAlert Lib "MyHd:MyAlert" Alias "MyAlert" (ByVal N _
As Integer)
Sub CallMyCodeResource()
    Call MessageAlert(0)    ' Call Macintosh code resource.
    MessageAlert 0    ' Call again without Call keyword.
End Sub


Caller Property

Applies To

Application Object.

Description

Returns information about how Visual Basic was called (see the Remarks section for details). Read-only.

Remarks

This property returns information about how Visual Basic was called, as shown in the following table.

Caller | Return
A custom function entered in a single cell | A Range specifying that cell
A custom function, part of an array formula in a range of cells | A Range specifying that range of cells
An Auto_Open, Auto_Close, Auto_Activate, or Auto_Deactivate macro | The name of the document as text
A command on a menu | An array of three elements specifying the command's position number, the menu number, and the menu bar number
A drawing object | The specifier of that object as a string
A button on a toolbar | An array of two elements specifying the tool position number and the toolbar name as text
A macro set by the OnDoubleClick or OnEntry properties. | The name of the chart object identifier or cell reference, if applicable, to which the macro applies
The Macro dialog box (Tools menu), or any caller not described above | The #REF! error value


CancelButton Property

Applies To

Button Object, Buttons Collection, DrawingObjects Collection.

Description

Applies only to buttons in a user-defined dialog box. True if the button is automatically selected when the ESCAPE key is pressed or when the system menu close box or menu item is selected. When the user presses the ESCAPE key, the Cancel button is selected, and Microsoft Excel runs the macro identified by the button's OnAction property.

Remarks

Set this property for a button if you want some code to always run when the dialog box is canceled, even if it is canceled by the ESCAPE key or the system menu.

Only one button in the dialog box can have the CancelButton property set to True at any given time. Setting one will reset this property for all other buttons on the dialog sheet.

See Also

DismissButton Property.

Example

This example sets the CancelButton property for button one on Dialog1.

DialogSheets("Dialog1").Buttons(1).CancelButton = True


CanPlaySounds Property

Applies To

Application Object.

Description

True if the computer can play sound notes. Read-only.

See Also

CanRecordSounds Property.

Example

This example determines whether the computer can play sound notes. If it can, it plays the sound note in cell A1 on Sheet1.

If Application.CanPlaySounds = True Then
    Worksheets("Sheet1").Range("A1").SoundNote.Play
End If


CanRecordSounds Property

Applies To

Application Object.

Description

True if the computer can record sound notes. Read-only.

See Also

CanPlaySounds Property.

Example

This example determines whether the computer can record sound notes. If it can, it records a sound note into cell A1 on Sheet1.

If Application.CanRecordSounds = True Then
    With Worksheets("Sheet1").Range("A1").SoundNote
        .Delete
        .Record
    End With
End If


CapitalizeNamesOfDays Property

Applies To

AutoCorrect Object.

Description

True if the first letters of the names of days are capitalized automatically. This property is available only in Microsoft Excel for Windows 95. Read-write.

Example

This example sets Microsoft Excel to capitalize the first letters of the names of days.

With Application.AutoCorrect
    .CapitalizeNamesOfDays = True
    .ReplaceText = True
End With


Caption Property

Applies To

Application Object, AxisTitle Object, Button Object, Buttons Collection, Characters Object, ChartTitle Object, CheckBox Object, DataLabel Object, DialogFrame Object, DrawingObjects Collection, DropDown Object, DropDowns Collection, EditBox Object, EditBoxes Collection, GroupBox Object, GroupBoxes Collection, Label Object, Labels Collection, Menu Object, MenuBar Object, MenuItem Object, OptionButton Object, OptionButtons Collection, TextBox Object, TextBoxes Collection, Window Object.

Description

The Caption property has several different meanings, depending on the object type to which it is applied. The Caption property is read-write, except as noted in the following table.

Object type | Meaning
Application | The name that appears in the title bar of the main Microsoft Excel window. If you don't set a name, or if you set the name to Empty, then this property returns "Microsoft Excel". Read-only on the Apple Macintosh.
AxisTitle | The axis title text.
Button | The button text.
Characters | The text of this range of characters.
ChartTitle | The chart title text.
Controls | The control text (check box, dialog frame, drop down, edit box, group box, label, and option button).
DataLabel | The data label text.
Menu | The name of the menu. Use an ampersand (&) before the letter that you want to be the command underline (for example, "&File").
MenuBar | The menu bar text. Read-only.
MenuItem | The name of the menu item (command). Use an ampersand (&) before the letter that you want to be the command underline (for example, "E&xit").
TextBox | The text in the text box.
Window | The name that appears in the title bar of the document window. When you set the name, you can use that name as the index to the Windows property; see the second example.

See Also

Text Property.

Example

This example sets the name that appears in the title bar of the main Microsoft Excel window to be a custom name (this can be done only in Windows; Application.Caption is read-only on the Macintosh).

Application.Caption = "Blue Sky Airlines Reservation System"

This example sets the name of the first window in the workbook to be Consolidated Balance Sheet. This name is then used as the index to the Windows method.

ActiveWorkbook.Windows(1).Caption = "Consolidated Balance Sheet"
ActiveWorkbook.Windows("Consolidated Balance Sheet") _
    .ActiveSheet.Calculate

This example changes the Open command on the File menu to Open Workbook. The example changes every menu bar in the product.

For Each mb In MenuBars
    mb.Menus("File").MenuItems(2).Caption = "&Open Workbook"
Next mb


Category Property

Applies To

Name Object.

Description

If the name refers to a custom function or command, this property returns or sets the category for this name as a string translated to the language of the macro. Read-write.

See Also

MacroType Property.

Example

This example assumes that you created a custom function or command on a Microsoft Excel version 4.0 macro sheet. The example displays the function category, in the language of the macro. It assumes that the name of the custom function or command is the only name in the workbook.

With ActiveWorkbook.Names(1)
    If .MacroType <> xlNone Then
        MsgBox "The category for this name is " & .Category
    Else
        MsgBox "This name does not refer to" & _
            " a custom function or command."
    End If
End With


CategoryLocal Property

Applies To

Name Object.

Description

If the name refers to a custom function or command, this property returns or sets the category for this name as a string in the language of the user. Read-write.

See Also

Category Property, MacroType Property.

Example

This example displays, in the language of the user, the function category of a custom function or command created on a Microsoft Excel version 4.0 macro sheet. The example assumes that the custom function name or command name is the only name in the workbook.

With ActiveWorkbook.Names(1)
    If .MacroType <> xlNone Then
        MsgBox "The category for this name is " & .CategoryLocal
    Else
        MsgBox "This name does not refer to" & _
            " a custom function or command."
    End If
End With


CategoryNames Property

Applies To

Axis Object.

Description

Returns or sets all the category names for the specified axis, as a text array. When you set this property, you can set it to an array or a Range object containing the category names. Read-write.

Remarks

Category names are really a property of the "special" series in an axis grouping. Deleting or modifying that special series will change the category names for all series using the axis.

See Also

Formula Property, Values Property, XValues Property.

Example

This example sets the category names for Chart1 to the values in cells B1:B5 on Sheet1.

Set Charts("Chart1").Axes(xlCategory).CategoryNames = _
    Worksheets("Sheet1").Range("B1:B5")

This example uses an array to set individual category names for Chart1.

Charts("Chart1").Axes(xlCategory).CategoryNames = _
    Array ("1985", "1986", "1987", "1988", "1989")


CBool Function

Description

Converts an expression to a Boolean.

Syntax

CBool(expression)

The expression argument is any valid numeric expression.

Remarks

If expression is zero, False is returned; otherwise, True is returned. If expression can't be interpreted as a numeric value, a run-time error occurs.

See Also

Data Type Summary.

Example

This example uses the CBool function to convert an expression to a Boolean. If the expression evaluates to a nonzero value, CBool returns True; otherwise, it returns False.

A = 5 : B = 5    ' Define variables.
Check = CBool(A = B)    ' Check contains True.
A = 0    ' Define variable.
Check = CBool(A)    ' Check contains False.


CCRecipients Property

Applies To

Mailer Object.

Description

Returns or sets the carbon copy (indirect) recipients of the mailer. Available only in Microsoft Excel for the Apple Macintosh with the PowerTalk mail system extension installed. Read-write.

Remarks

This property is an array of strings specifying the address, in one of the following formats:

  • A record in the Preferred Personal Catalog. These names are one level deep ("Fred" or "June").
  • A full path specifying either a record in a personal catalog ("HD:Excel Folder:My Catalog:Barney") or a plain record ("HD:Folder:Martin").
  • A relative path from the current working folder specifying either a personal catalog record ("My Catalog:Barney") or a plain record ("Martin").
  • A path in a PowerShare catalog tree of the form "CATALOG_NAME:<node>:RECORD_NAME" where <node> is a path to a PowerShare catalog. An example of a complete path is "AppleTalk:North Building Zone:George's Mac".

See Also

BCCRecipients Property, Enclosures Property, Mailer Property, Received Property, SendDateTime Property, Sender Property, SendMailer Method, ToRecipients Property.

Example

This example sets up the Mailer object for workbook one and then sends the workbook.

With Workbooks(1)
    .HasMailer = True
    With .Mailer
        .Subject = "Here is the workbook"
        .ToRecipients = Array("Jean")
        .CCRecipients = Array("Adam", "Bernard")
        .BCCRecipients = Array("Chris")
        .Enclosures = Array("TestFile")
    End With
    .SendMailer
End With


CCur Function

Description

Converts an expression to a Currency.

Syntax

CCur(expression)

The expression argument is any valid numeric or string expression.

Remarks

In general, you can document your code using the data type conversion functions to show that the result of some operation should be expressed as a particular data type rather than the default data type. For example, use CCur to force currency arithmetic in cases where single-precision, double-precision, or integer arithmetic normally would occur.

You should use the CCur function instead of Val to provide internationally-aware conversions from any other data type to a Currency. For example, different decimal separators are properly recognized depending on the locale setting of your computer, as are different thousand separators and various currency options.

If expression lies outside the acceptable range for the Currency data type, an error occurs.

See Also

Data Type Summary.

Example

This example uses the CCur function to convert an expression to a Currency.

MyDouble = 543.214588    ' MyDouble is a Double.

MyCurr = CCur(MyDouble * 2)    ' Convert result (1086.4292) to
    ' Currency.


CDate Function

Description

Converts an expression to a Date.

Syntax

CDate(date)

The date argument is any valid date expression.

Remarks

Use the IsDate function to determine if date can be converted to a date or time. CDate recognizes date and time literals as well as some numbers that fall within the range of acceptable dates. When converting a number to a date, the whole number portion is converted to a date. Any fractional part of the number is converted to a time of day, starting at midnight.

CDate recognizes date formats according to the international settings of your system. The correct order of day, month, and year may not be determined if it is provided in a format other than one of the recognized date settings. In addition, a long date format is not recognized if it also contains the day-of-the-week string.

Note

A CVDate function is also provided for compatibility with previous versions of Visual Basic. However, since there is now an intrinsic Date type, there is no further need for CVDate. The syntax of the CVDate function is identical to the CDate function. The difference is that it returns a Variant whose subtype is Date instead of an actual Date type. The same effect can be achieved by converting an expression to a Date and then assigning it to a Variant. This technique is consistent with the conversion of all other intrinsic types to their equivalent Variant subtypes.

See Also

Data Type Summary, IsDate Function.

Example

This example uses the CDate function to convert a string to a Date. In general, it is bad programming practice to hard code dates/times as strings as shown in this example. Use date literals instead.

MyDate = "February 12, 1969"    ' Define date.
MyShortDate = CDate(MyDate)    ' Convert to Date data type.
MyTime = "4:35:47 PM"    ' Define time.
MyShortTime = CDate(MyTime)    ' Convert to Date data type.


CDbl Function

Description

Converts an expression to a Double.

Syntax

CDbl(expression)

The expression argument is any valid numeric or string expression.

Remarks

In general, you can document your code using the data type conversion functions to show that the result of some operation should be expressed as a particular data type rather than the default data type. For example, use CDbl or CSng to force double- or single-precision arithmetic in cases where currency or integer arithmetic normally would occur.

You should use the CDbl function instead of Val to provide internationally-aware conversions from any other data type to a Double. For example, different decimal separators and thousands separators are properly recognized depending on the locale setting of your system.

See Also

Data Type Summary.

Example

This example uses the CDbl function to convert an expression to a Double.

MyCurr = CCur(234.456784)    ' MyCurr is a Currency.
MyDouble = CDbl(MyCurr * 8.2 * 0.01)    ' Convert result to Double.


Cell Error Values

You can insert a cell error value into a cell or you can test the value of a cell for an error value using the CVErr function. The cell error values have constants assigned to them as shown in the following table.

Constant | Error number | Cell error value
xlErrDiv0 | 2007 | #DIV/0!
xlErrNA | 2042 | #N/A
xlErrName | 2029 | #NAME?
xlErrNull | 2000 | #NULL!
xlErrNum | 2036 | #NUM!
xlErrRef | 2023 | #REF!
xlErrValue | 2015 | #VALUE!

Example

This example inserts the seven cell error values into cells A1:A7 on Sheet1.

myArray = Array(xlErrDiv0, xlErrNA, xlErrName, xlErrNull, _
    xlErrNum, xlErrRef, xlErrValue)
For i = 1 To 7
    Worksheets("Sheet1").Cells(i, 1).Value = CVErr(myArray(i - 1))
Next i

This example displays a message if the active cell on Sheet1 contains a cell error value. You can use this example as a framework for a cell-error-value error handler.

Worksheets("Sheet1").Activate
If IsError(ActiveCell.Value) Then
    errval = ActiveCell.Value
    Select Case errval
        Case CVErr(xlErrDiv0)
            MsgBox "#DIV/0! error"
        Case CVErr(xlErrNA)
            MsgBox "#N/A error"
        Case CVErr(xlErrName)
            MsgBox "#NAME? error"
        Case CVErr(xlErrNull)
            MsgBox "#NULL! error"
        Case CVErr(xlErrNum)
            MsgBox "#NUM! error"
        Case CVErr(xlErrRef)
            MsgBox "#REF! error"
        Case CVErr(xlErrValue)
            MsgBox "#VALUE! error"
        Case Else
            MsgBox "This should never happen!!"
    End Select
End If


CellDragAndDrop Property

Applies To

Application Object.

Description

True if Cell Drag And Drop editing is on. Read-write.

Example

This example turns on the Cell Drag And Drop editing option.

Application.CellDragAndDrop = True


Cells Method

Applies To

Application Object, Range Object, Worksheet Object.

Description

Accessor. Returns a Range object that represents a single cell (Syntax 1 and 2) or a collection of cells (Syntax 3). The action of the Cells method depends on the object to which it is applied, as shown in the following table.

Object type | Action
Application | If the active document is a worksheet, Application.Cells is equivalent to ActiveSheet.Cells, which returns a collection of cells on the active worksheet. Otherwise, the Cells method returns an error.
Range | Returns a collection of cells from the range.
Worksheet | Returns a collection of cells from the worksheet.

Syntax 1

object.Cells(rowIndex, columnIndex)

Syntax 2

object.Cells(rowIndex)

Syntax 3

object.Cells

object

Optional for Application, required for Worksheet and Range. The object that contains the cells. If you specify the Application object (or omit the object qualifier), the Cells method applies to the active sheet in the active workbook. If the active sheet is not a worksheet, this method fails.

rowIndex

Required for Syntax 1. The row number of the cell you want to access, starting with 1 for row 1 (for Application and Worksheet) or the first row in the Range.

Required for Syntax 2. A long integer specifying the index number of the cell you want to access, in row-major order. A1 is Cells(1), A2 is Cells(257) for Application and Worksheet; Range.Cells(1) is the top left cell in the Range.

columnIndex

Required for Syntax 1. A number or string indicating the column number of the cell you want to access, starting with 1 or "A" for column A (for Application or Worksheet) or the first column in the Range.

Remarks

Syntax 1 uses a row number and a column number or letter as index arguments. For more information about this syntax, see the Range object.

Syntax 2 uses a single number as an index argument. The index is 1 for cell A1, 2 for cell B1, 3 for cell C1, 257 for cell A2, and so on.

The rowIndex and columnIndex arguments are relative offsets when you apply the Cells method to a Range object. In other words, specifying a rowIndex of 1 returns cells in the first row of the range, not the first row of the worksheet. For example, if the selection is cell C3, then Selection.Cells(2, 2) returns cell D4 (you can use the method to index outside the original range).

If you apply Syntax 3 to a Range, it returns the same Range object (in other words, it does nothing).

If you apply Syntax 3 to a Worksheet, it returns a collection of all the cells in the worksheet (all the cells, not just the cells that are currently in use).

See Also

Range Method.

Example

This example sets the font size of cell C5 on Sheet1 to 14 points.

Worksheets("Sheet1").Cells(5, 3).Font.Size = 14

This example clears the formula in cell one on Sheet1.

Worksheets("Sheet1").Cells(1).ClearContents

This example sets the font for every cell on Sheet1 to 8-point Arial.

With Worksheets("Sheet1").Cells.Font
    .Name = "Arial"
    .Size = 8
End With

This example loops through cells A1:J4 on Sheet1. If one of the cells has a value less than .001, the example replaces that value with zero (0).

For rwIndex = 1 to 4
    For colIndex = 1 to 10
        If Worksheets("Sheet1").Cells(rwIndex, colIndex) < .001 Then
            Worksheets("Sheet1").Cells(rwIndex, colIndex).Value = 0
        End If
    Next colIndex
Next rwIndex

This example sets the font of cells A1:C5 on Sheet1 to italic.

Worksheets("Sheet1").Activate
Range(Cells(1, 1), Cells(5, 3)).Font.Italic = True

This example scans a column of data named myRange. If a cell has the same value as the cell above it, the example displays the address of the cell that contains the duplicate data.

Set r = Range("myRange")
For n = 1 To r.Rows.Count
    If r. Cells(n, 1) = r. Cells(n + 1, 1) Then
        MsgBox "Duplicate data in " & r. Cells(n + 1, 1).Address
    End If
Next n


CenterFooter Property

Applies To

PageSetup Object.

Description

Returns or sets the center part of the footer. Read-write.

Remarks

Special format codes can be used in the footer text.

See Also

CenterHeader Property, LeftFooter Property, LeftHeader Property, RightFooter Property, RightHeader Property.

Example

This example prints the workbook name and page number at the bottom of each page.

Worksheets("Sheet1").PageSetup.CenterFooter = "&F page &P"


CenterHeader Property

Applies To

PageSetup Object.

Description

Returns or sets the center part of the header. Read-write.

Remarks

Special format codes can be used in the header text.

See Also

CenterFooter Property, LeftFooter Property, LeftHeader Property, RightFooter Property, RightHeader Property.

Example

This example prints the date and page number at the top of each page.

Worksheets("Sheet1").PageSetup.CenterHeader = "&D page &P of &N"


CenterHorizontally Property

Applies To

PageSetup Object.

Description

True if the sheet is centered horizontally on the page. Read-write.

See Also

CenterVertically Property.

Example

This example centers Sheet1 horizontally when the worksheet is printed.

Worksheets("Sheet1").PageSetup.CenterHorizontally = True


CenterVertically Property

Applies To

PageSetup Object.

Description

True if the sheet is centered vertically on the page. Read-write.

See Also

CenterHorizontally Property.

Example

This example centers Sheet1 vertically when the worksheet is printed.

Worksheets("Sheet1").PageSetup.CenterVertically = True


CentimetersToPoints Method

Applies To

Application Object.

Description

Converts a measurement in centimeters into points (0.035 centimeters).

Syntax

object.CentimetersToPoints(centimeters)

object

Required. The Application object.

centimeters

Required. Specifies the centimeter value to convert to points.

See Also

InchesToPoints Method.

Example

This example sets the left margin of Sheet1 to 5 centimeters.

Worksheets("Sheet1").PageSetup.LeftMargin = _
        Application.CentimetersToPoints(5)


ChangeFileAccess Method

Applies To

Workbook Object.

Description

Changes the access permissions for the workbook. This may require loading an updated version from the disk.

Syntax

object.ChangeFileAccess(mode, writePassword, notify)

object

Required. The Workbook object.

mode

Required. Specifies the new access mode (one of xlReadWrite or xlReadOnly).

writePassword

Optional. If the file is write reserved and mode is xlReadWrite, specifies the write-reserved password. Ignored if there is no password for the file or mode is xlReadOnly.

notify

Optional. True if you wish to be notified if the file cannot be immediately accessed. Assumed to be True if omitted.

Remarks

If you have a file open in read-only mode, you do not have exclusive access to the file. If you change a file from read-only to read-write, Microsoft Excel must load a new copy of the file to ensure that no changes were made while you had the file open as read-only.

Example

This example sets the active workbook to read-only.

ActiveWorkbook.ChangeFileAccess Mode:=xlReadOnly


ChangeLink Method

Applies To

Workbook Object.

Description

Changes a link from one document to another.

Syntax

object.ChangeLink(name, newName, type)

object

Required. The Workbook object.

name

Required. Specifies the name of the Microsoft Excel or DDE/OLE link to change, as returned from the LinkSources method.

newName

Required. The new name of the link.

type

Optional. Specifies the link type (either xlExcelLinks or xlOLELinks). If omitted, the default is xlExcelLinks. Use xlOLELinks for both DDE and OLE links.

Example

This example changes a Microsoft Excel link.

ActiveWorkbook.ChangeLink "c:\excel\book1.xls", _
    "c:\excel\book2.xls", xlExcelLinks


ChangeScenario Method

Applies To

Scenario Object.

Description

Changes the scenario to have a new set of changing cells and (optionally) scenario values.

Syntax

object.ChangeScenario(changingCells, values)

object

Required. The Scenario object.

changingCells

Required. A Range that specifies the new set of changing cells for the scenario. The changing cells must be on the same sheet as the scenario.

values

Optional. An array containing the new scenario values for the changing cells. If omitted, the scenario values are assumed to be the current values in the changing cells.

Remarks

If you specify values, the array must contain an element for each cell in the changingCells range, or Microsoft Excel generates an error.

See Also

ChangingCells Property, Comment Property.

Example

This example sets the changing cells for scenario one to the range A1:A10 on Sheet1.

Worksheets("Sheet1").Scenarios(1).ChangeScenario _
    Worksheets("Sheet1").Range("A1:A10")


ChangingCells Property

Applies To

Scenario Object.

Description

Accessor. Returns a Range object that represents the changing cells for a scenario. Read only.

See Also

ChangeScenario Method, Comment Property.

Example

This example selects the changing cells for scenario one on Sheet1.

Worksheets("Sheet1").Activate
ActiveSheet.Scenarios(1).ChangingCells.Select


Characters Method

Applies To

AxisTitle Object, Button Object, Buttons Collection, ChartTitle Object, CheckBox Object, DataLabel Object, DialogFrame Object, DrawingObjects Collection, DropDown Object, DropDowns Collection, EditBox Object, EditBoxes Collection, GroupBox Object, GroupBoxes Collection, Label Object, Labels Collection, OptionButton Object, OptionButtons Collection, Range Object, TextBox Object, TextBoxes Collection.

Description

Accessor. Returns a Characters object that represents a range of characters within the object text. This allows you to format characters within a text string.

Syntax

object.Characters(start, length)

object

Required. The object to which this method applies.

start

Optional. The first character to return. If this argument is one or omitted, this method returns a range of characters starting with the first character.

length

Optional. The number of characters to return. If this argument is omitted, this method returns the remainder of the string after the start character.

Remarks

For a Range object, this method will fail if it is used with arguments and the cell does not contain a text value.

Example

This example formats the third character in cell A1 on Sheet1 as bold.

With Worksheets("Sheet1").Range("A1")
    .Value = "abcdefg"
    .Characters(3, 1).Font.Bold = True
End With


Characters Object

Description

Represents characters in an object containing text. The Characters object lets you access any sequence of characters contained in the full text string.

Accessors

Use the Characters method to return a subset of sequential characters in the text. The following example adds text to cell B1 on the worksheet named "Sheet1" and then makes the second word bold.

With Worksheets("sheet1").Range("b1")
    .Value = "New Title"
    .Characters(5, 5).Font.Bold = True
End With

Remarks

The Characters method is necessary only when you need to change some of the text contained in an object without affecting the rest (you cannot use the Characters method to format a portion of the text if the object does not support rich text). To change all the text at once, you can usually apply the appropriate method or property directly to the object. The following example sets the contents of cell A5 on the worksheet named "Sheet1" to italic.

Worksheets("sheet1").Range("a5").Font.Italic = True

Properties

Application Property, Caption Property, Count Property, Creator Property, Font Property, Parent Property, Text Property.

Methods

Delete Method, Insert Method.


Chart Object

Description

Represents a chart in a workbook, either an embedded chart (contained in a ChartObject in a Worksheet or DialogSheet object) or a separate chart sheet.

Embedded Charts

The ChartObject, which represents the container for an embedded chart on a worksheet or dialog sheet, is a member of the ChartObjects collection. Use the Add method to create a new empty embedded chart and add it to the collection. Use the Chart property to access the chart contained in the specified ChartObject object. The following example sets the pattern for the chart area in embedded chart one on the worksheet named "Sheet1."

Worksheets("sheet1").ChartObjects(1).Chart. _
    ChartArea.Interior.Pattern = xlLightDown

Chart Sheets

The Chart object, which represents a separate chart sheet, is a member of the Charts collection. The Charts collection contains all the Chart objects that represent chart sheets in a workbook. Use the Add method to create a new chart sheet and add it to the collection. To access a single member of the collection, use the Charts method with the index number or name of the chart sheet as an argument.

The chart index number represents the position of the chart sheet on the tab bar of the workbook. Charts(1) is the first (leftmost) chart in the workbook; Charts(Charts.Count) is the last. All chart sheets are included in the index count, even if they are hidden.

The following example changes the color of series one on chart sheet one.

Charts(1).SeriesCollection(1).Interior.Color = RGB(255, 0, 0)

The chart name is shown on the workbook tab for the chart. You can use the Name property to set or return the chart name.

The following example moves the chart named "Sales" to the end of the active workbook.

Charts("sales").Move after:=Sheets(Sheets.Count)

The Chart object is also a member of the Sheets collection. The Sheets collection contains all of the sheets in the workbook (chart sheets, dialog sheets, modules, and worksheets). To access a single member of the collection, use the Sheets method with the index number or name of the sheet as an argument.

Using ActiveChart

When a chart is the active object, you can use the ActiveChart property to refer to it. A chart sheet is active if the user has selected it or it has been activated with the Activate method. The following example activates chart sheet one and then sets the chart type and title.

Charts(1).Activate
With ActiveChart
    .Type = xlLine
    .HasTitle = True
    .ChartTitle.Text = "January Sales"
End With

An embedded chart is active if the user has selected it or the ChartObject object that contains it has been activated with the Activate method. The following example activates embedded chart one on worksheet one and then sets the chart type and title. Notice that once the embedded chart has been activated, the code in this example is the same as the previous example. Using the ActiveChart property allows you to write Visual Basic code that can refer to either an embedded chart or a chart sheet, whichever is active.

Worksheets(1).ChartObjects(1).Activate
ActiveChart.Type = xlLine
ActiveChart.HasTitle = True
ActiveChart.ChartTitle.Text = "January Sales"

Using ActiveSheet

When a chart sheet is the active sheet, you can use the ActiveSheet property to refer to it. The following example uses the Activate method to activate the chart sheet named "Chart1" and then sets the interior color for series one in the chart.

Charts("chart1").Activate
ActiveSheet.SeriesCollection(1).Interior.ColorIndex = 5

Properties

Application Property, Area3DGroup Property, AutoScaling Property, Bar3DGroup Property, ChartArea Property, ChartTitle Property, Column3DGroup Property, Corners Property, Creator Property, DepthPercent Property, DisplayBlanksAs Property, Elevation Property, Floor Property, GapDepth Property, HasAxis Property, HasLegend Property, HasTitle Property, HeightPercent Property, Index Property, Legend Property, Line3DGroup Property, Name Property, Next Property, OnDoubleClick Property, OnSheetActivate Property, OnSheetDeactivate Property, PageSetup Property, Parent Property, Perspective Property, Pie3DGroup Property, PlotArea Property, PlotVisibleOnly Property, Previous Property, ProtectContents Property, ProtectDrawingObjects Property, RightAngleAxes Property, Rotation Property, SizeWithWindow Property, SubType Property, SurfaceGroup Property, Type Property, Visible Property, Walls Property, WallsAndGridlines2D Property.

Methods

Activate Method, ApplyDataLabels Method, Arcs Method, AreaGroups Method, AutoFormat Method (Chart Object), Axes Method, BarGroups Method, Buttons Method, ChartGroups Method, ChartObjects Method, ChartWizard Method, CheckBoxes Method, CheckSpelling Method, ColumnGroups Method, Copy Method, CopyPicture Method, CreatePublisher Method, Delete Method, Deselect Method, DoughnutGroups Method, DrawingObjects Method, Drawings Method, DropDowns Method, Evaluate Method, GroupBoxes Method, GroupObjects Method, Labels Method, LineGroups Method, Lines Method, ListBoxes Method, Move Method, OLEObjects Method, OptionButtons Method, Ovals Method, Paste Method (Chart Object), Pictures Method, PieGroups Method, PrintOut Method, PrintPreview Method, Protect Method, RadarGroups Method, Rectangles Method, SaveAs Method, ScrollBars Method, Select Method, SeriesCollection Method, SetBackgroundPicture Method, Spinners Method, TextBoxes Method, Unprotect Method, XYGroups Method.


Chart Property

Applies To

ChartObject Object.

Description

Accessor. Returns a Chart object that represents the chart contained in the object. Read-only.

Example

This example adds a title to the first embedded chart on Sheet1.

With Worksheets("Sheet1").ChartObjects(1).Chart
    .HasTitle = True
    .ChartTitle.Text = "1995 Rainfall Totals by Month"
End With


ChartArea Object

Description

Represents the chart area of a chart. The chart area on a 2-D chart contains the axes, the chart title, axis titles, and the legend. The chart area on a 3-D chart contains the chart title and the legend. It does not include the plot area (the area within the chart area where the data is plotted). For information about formatting the plot area, see the PlotArea object.

Accessors

The ChartArea property returns the chart area for the specified chart. The following example sets the pattern for the chart area in embedded chart one on the worksheet named "Sheet1."

Worksheets("sheet1").ChartObjects(1).Chart. _
    ChartArea.Interior.Pattern = xlLightDown

Properties

Application Property, Border Property, Creator Property, Font Property, Height Property, Interior Property, Left Property, Name Property, Parent Property, Shadow Property, Top Property, Width Property.

Methods

Clear Method, ClearContents Method, ClearFormats Method, Copy Method, Select Method.


ChartArea Property

Applies To

Chart Object.

Description

Accessor. Returns a ChartArea object that represents the complete chart area for the chart. Read-only.

Example

This example sets the chart area interior color of Chart1 to red and sets the border color to blue.

With Charts("Chart1").ChartArea
    .Interior.ColorIndex = 3
    .Border.ColorIndex = 5
End With


ChartGroup Object

Description

Represents one or more series plotted in a chart using the same format. A chart contains one or more chart groups, each chart group contains one or more series, and each series contains one or more points. For example, a single chart might contain a line chart group, containing all the series plotted using the line chart format, and a bar chart group, containing all the series plotted using the bar chart format.

Accessors

The ChartGroup object is a member of the ChartGroups collection. To access a single member of the collection, use the ChartGroups method with the chart group index number as an argument. The following example adds drop lines to chart group one.

Charts(1).ChartGroups(1).HasDropLines = True

If the chart has been activated, you can use the ActiveChart property:

Charts(1).Activate
ActiveChart.ChartGroups(1).HasDropLines = True

The chart group index number for a particular chart group can change if the chart format used for that group is changed. For this reason, it may be easier to use one of the named chart group shortcut methods to access a particular chart group. The PieGroups method returns the collection of pie chart groups in a chart, the LineGroups method returns the collection of line chart groups, and so on. Each of these methods can be used with an index number to return a single ChartGroup object, or without an index to return a ChartGroups collection. The following chart group methods are available:

AreaGroups Method, BarGroups Method, ColumnGroups Method, DoughnutGroups Method, LineGroups Method, PieGroups Method, DownBars, DropLines, HiLoLines, Series, SeriesLines, UpBars

Properties

Application Property, AxisGroup Property, Creator Property, DoughnutHoleSize Property, DownBars Property, DropLines Property, FirstSliceAngle Property, GapWidth Property, HasDropLines Property, HasHiLoLines Property, HasRadarAxisLabels Property, HasSeriesLines Property, HasUpDownBars Property, HiLoLines Property, Overlap Property, Parent Property, RadarAxisLabels Property, SeriesLines Property, SubType Property, Type Property, UpBars Property, VaryByCategories Property.

Methods

SeriesCollection Method.


ChartGroups Collection Object

Description

A collection of all the ChartGroup objects in the specified chart. Each ChartGroup object represents one or more series plotted in a chart using the same format. A chart contains one or more chart groups, each chart group contains one or more series, and each series contains one or more points. For example, a single chart might contain a line chart group, containing all the series plotted using the line chart format, and a bar chart group, containing all the series plotted using the bar chart format.

Accessors

The ChartGroups collection contains all of the chart groups in one chart. Use the ChartGroups method with an argument to access a single member of the collection or without an argument to access the entire collection at once. You can also use one of the named chart group shortcut methods to access a particular chart group. The PieGroups method returns the collection of pie chart groups in a chart, the LineGroups method returns the collection of line chart groups, and so on. Each of these methods can be used with an index number to return a single ChartGroup object or without an index to return a ChartGroups collection. The following chart group methods are available: AreaGroups Method, BarGroups Method, ColumnGroups Method, DoughnutGroups Method, LineGroups Method, PieGroups Method.

Properties

Application Property, Count Property, Creator Property, Parent Property.

Methods

Item Method.


ChartGroups Method

Applies To

Chart Object.

Description

Accessor. Returns an object that represents a single chart group (a ChartGroup object, Syntax 1) or a collection of all the chart groups in the chart (a ChartGroups object, Syntax 2). Every type of group is included in the returned collection.

Syntax 1

object.ChartGroups(index)

Syntax 2

object.ChartGroups

object

Required. The Chart object.

index

Required for Syntax 1. The number of the chart group.

Example

This example turns on up and down bars for chart group one on Chart1 and then sets their colors. The example should be run on a 2-D line chart containing two series that cross each other at one or more data points.

With Charts("Chart1").ChartGroups(1)
    .HasUpDownBars = True
    .DownBars.Interior.ColorIndex = 3
    .UpBars.Interior.ColorIndex = 5
End With


ChartObject Object

Description

Represents an embedded chart on a sheet. The ChartObject object acts as a container for a Chart object. Properties and methods for the ChartObject object control the appearance and size of the embedded chart on the sheet.

Accessors

The ChartObject object is a member of the ChartObjects collection. The ChartObjects collection contains all the embedded charts on a single sheet. Use the Add method to create a new empty embedded chart and add it to the collection. Use the ChartWizard method to add data and format the new empty chart. Use the Chart property to access the embedded chart contained in the ChartObject object.

To access a single member of the collection, use the ChartObjects method with the index number or name of the embedded chart as an argument.

The following example sets the pattern for the chart area in embedded chart one on the worksheet named "Sheet1."

Worksheets("Sheet1").ChartObjects(1).Chart. _
    ChartArea.Interior.Pattern = xlLightDown

The embedded chart name is shown in the Name Box when the embedded chart is selected. Use the Name property to set or return the name of the ChartObject object. The following example puts rounded corners on the embedded chart named "Chart 1" on the worksheet named "Sheet1."

Worksheets("sheet1").ChartObjects("chart 1").RoundedCorners = True

Properties

Application Property, Border Property, BottomRightCell Property, Chart Property, Creator Property, Enabled Property, Height Property, Index Property, Interior Property, Left Property, Locked Property, Name Property, OnAction Property, Parent Property, Placement Property, PrintObject Property, RoundedCorners Property, Shadow Property, Top Property, TopLeftCell Property, Visible Property, Width Property, ZOrder Property.

Methods

Activate Method, BringToFront Method, Copy Method, CopyPicture Method, Cut Method, Delete Method, Duplicate Method, Select Method, SendToBack Method.


ChartObjects Collection Object

Description

A collection of all the ChartObject objects on the specified chart sheet, dialog sheet, or worksheet. Each ChartObject object represents an embedded chart. The ChartObject object acts as a container for a Chart object. Properties and methods for the ChartObject object control the appearance and size of the embedded chart on the sheet.

Accessors

The ChartObjects collection contains all the embedded charts on a single sheet. Use the Add method to create a new empty embedded chart and add it to the collection. Use the ChartWizard method to add data and format the new empty chart. The following example creates a new embedded chart on the worksheet named "Sheet1" and then adds the data from cells A1:A20 as a line chart.

Dim ch As ChartObject
Set ch = Worksheets("sheet1").ChartObjects.Add(100, 30, 400, 250)
ch.Chart.ChartWizard source:=Worksheets("sheet1").Range("a1:a20"), _
    gallery:=xlLine, title:="New Chart"

Use the ChartObjects method with an argument to access a single member of the collection or without an argument to access the entire collection at once. The following example deletes all of the embedded charts on the worksheet named "Sheet1."

Worksheets("sheet1").ChartObjects.Delete

Properties

Application Property, Border Property, Count Property, Creator Property, Enabled Property, Height Property, Interior Property, Left Property, Locked Property, OnAction Property, Parent Property, Placement Property, PrintObject Property, RoundedCorners Property, Shadow Property, Top Property, Visible Property, Width Property, ZOrder Property.

Methods

Add Method (Graphic Objects and Controls), BringToFront Method, Copy Method, CopyPicture Method, Cut Method, Delete Method, Duplicate Method, Group Method, Item Method, Select Method, SendToBack Method.


ChartObjects Method

Applies To

Chart Object, DialogSheet Object, Worksheet Object.

Description

Accessor. Returns an object that represents a single embedded chart (a ChartObject object, Syntax 1) or a collection of all the embedded charts (a ChartObjects object, Syntax 2) on the sheet.

Syntax 1

object.ChartObjects(index)

Syntax 2

object.ChartObjects

object

Required. The object to which this method applies. If you specify a Chart object, it must be a chart sheet (it cannot be an embedded chart).

index

Required for Syntax 1. The name or number of the chart (can be an array to specify more than one).

Remarks

This method is not equivalent to the Charts method. This method returns embedded charts; the Charts method returns chart sheets. Use the Chart property to return the chart sheet for an embedded chart object.

See Also

Charts Method.

Example

This example adds a title to embedded chart one on Sheet1.

With Worksheets("Sheet1").ChartObjects(1).Chart
    .HasTitle = True
    .ChartTitle.Text = "1995 Rainfall Totals by Month"
End With

This example creates a new series in embedded chart one on Sheet1. The data source for the new series is the range B1:B10 on Sheet1.

Worksheets("Sheet1").ChartObjects(1).Activate
ActiveChart.SeriesCollection.Add _
    source:=Worksheets("Sheet1").Range("B1:B10")

This example clears the formatting of embedded chart one on Sheet1.

Worksheets("Sheet1").ChartObjects(1).Chart.ChartArea.ClearFormats


Charts Collection Object

Description

A collection of all the chart sheets in the specified or active workbook. This does not include charts embedded on worksheets or dialog sheets. For information about embedded charts, see the Chart or ChartObject objects.

Accessors

Use the Add method to create a new chart sheet and add it to the workbook. The following example adds a new chart sheet to the active workbook and places the new chart sheet after the worksheet named "Sheet1."

Charts.Add after:=Worksheets("sheet1")

You can combine the Add method with the ChartWizard method to add a new chart containing data from a worksheet. The following example adds a new line chart based on data in cells A1:A20 on the worksheet named "Sheet1."

With Charts.Add
    .ChartWizard source:=Worksheets("sheet1").Range("a1:a20"), _
        gallery:=xlLine, title:="February Data"
End With

Use the Charts method with an argument to access a single member of the collection or without an argument to access the entire collection at once.

The Sheets collection contains all of the sheets in the workbook (chart sheets, dialog sheets, modules, and worksheets). Use the Sheets method with an argument to access a single member of the collection or without an argument to access the entire collection at once.

Properties

Application Property, Count Property, Creator Property, Parent Property, Visible Property.

Methods

Add Method (Charts Collection), Copy Method, Delete Method, Item Method, Move Method, PrintOut Method, PrintPreview Method, Select Method.


Charts Method

Applies To

Application Object, Workbook Object.

Description

Accessor. Returns an object that represents a single chart (a Chart object, Syntax 1) or a collection of the charts (a Charts object, Syntax 2) in the workbook.

Syntax 1

object.Charts(index)

Syntax 2

object.Charts

object

Optional for Application, required for Workbook. The object to which this method applies.

index

Required for Syntax 1. The name or number of the chart (can be an array to specify more than one).

Remarks

Using this method with no object qualifier is equivalent to ActiveWorkbook.Charts.

See Also

ChartObjects Method.

Example

This example sets the text for the title of Chart1.

With Charts("Chart1")
    .HasTitle = True
    .ChartTitle.Text = "First Quarter Sales"
End With

This example deletes every chart sheet in the active workbook.

ActiveWorkbook.Charts.Delete

This example hides Chart1, Chart3, and Chart5. Note that in this example (and the previous one), the Charts method returns a Sheets object instead of a Charts object.

Charts(Array("Chart1", "Chart3", "Chart5")).Visible = False


ChartSize Property

Applies To

PageSetup Object.

Description

Returns or sets the method used when scaling a chart to fit on a page, as shown in the following table. Read-write.

Value | Meaning
xlScreenSize | Print the chart the same size as it appears on the screen.
xlFitToPage | Print the chart as large as possible, while retaining the chart's height-to-width ratio as shown on the screen.
xlFullPage | Print the chart to fit the page, adjusting the height-to-width ratio as necessary.

Remarks

This property applies only to chart sheets (it cannot be used with embedded charts).

Example

This example scales the first chart in the active workbook to fit a full page.

ActiveWorkbook.Charts(1).PageSetup.ChartSize = xlFullPage


ChartTitle Object

Description

Represents the title in a chart.

Accessors

Use the ChartTitle property to return the title of the specified chart. The following example adds a title to embedded chart one on the worksheet named "Sheet1."

With Worksheets("sheet1").ChartObjects(1).Chart
    .HasTitle = True
    .ChartTitle.Text = "February Sales"
End With

Remarks

The ChartTitle object does not exist and cannot be accessed unless the HasTitle property for the chart is True.

Properties

Application Property, Border Property, Caption Property, Creator Property, Font Property, HorizontalAlignment Property, Interior Property, Left Property, Name Property, Orientation Property, Parent Property, Shadow Property, Text Property, Top Property, VerticalAlignment Property.

Methods

Characters Method, Delete Method, Select Method.


ChartTitle Property

Applies To

Chart Object.

Description

Accessor. Returns a ChartTitle object that represents the title of the specified chart. Read-only.

See Also

AxisTitle Property, HasTitle Property, Title Property.

Example

This example sets the text for the title of Chart1.

With Charts("Chart1")
    .HasTitle = True
    .ChartTitle.Text = "First Quarter Sales"
End With


ChartWizard Method

Applies To

Chart Object.

Description

Modifies the properties of the given chart. Allows a chart to be quickly formatted without setting all the individual properties. This method is non-interactive, and changes only the specified properties.

Syntax

object.ChartWizard(source, gallery, format, plotBy, categoryLabels, seriesLabels, hasLegend, title, categoryTitle, valueTitle, extraTitle)

object

Required. The Chart object.

source

Required if you are creating a chart; the range that contains the source data for the chart. Optional if you are editing an existing chart; the active chart sheet is edited, or the selected chart on the active worksheet is edited.

gallery

Optional. Specifies the chart type (one of xlArea, xlBar, xlColumn, xlLine, xlPie, xlRadar, xlXYScatter, xlCombination, xl3DArea, xl3DBar, xl3DColumn, xl3DLine, xl3DPie, xl3DSurface, or xlDoughnut).

format

Optional. Specifies the option number for the built-in autoformats. Can be a number from 1 to 10, depending on the gallery type. If this argument is omitted, Microsoft Excel chooses a default value based on the gallery type and data source.

plotBy

Optional. Specifies whether the data for each series is in rows or columns (either xlRows or xlColumns).

categoryLabels

Optional. An integer specifying the number of rows or columns within the source range containing category labels. Legal values are from zero to one less than the maximum number of the corresponding categories or series.

seriesLabels

Optional. An integer specifying the number of rows or columns within the source range containing series labels. Legal values are from zero to one less than the maximum number of the corresponding categories or series.

hasLegend

Optional. True to include a legend.

title

Optional. Chart title text.

categoryTitle

Optional. Category axis title text.

valueTitle

Optional. Value axis title text.

extraTitle

Optional. Series axis title for 3-D charts, second value axis title for 2-D charts.

Remarks

If source is omitted and either the selection is not an embedded chart on the active worksheet or the active sheet is not an existing chart, the method fails and an error occurs.

Example

This example reformats Chart1 as a line chart, adds a legend, and adds category and value axis titles.

Charts("Chart1").ChartWizard _
    gallery:=xlLine, _
    hasLegend:=True, categoryTitle:="Year", valueTitle:="Sales"


ChDir Statement

Description

Changes the current directory or folder.

Syntax

ChDir path

The path named argument is a string expression that identifies which directory or folder becomes the new default directory or folder — may include drive. If no drive is specified, ChDir changes the default directory or folder on the current drive.

Remarks

In Microsoft Windows, the ChDir statement changes the default directory but not the default drive. For example, if the default drive is C, the following statement changes the default directory on drive D, but C remains the default drive:

ChDir "D:\TMP"

On the Macintosh, the default drive always changes to whatever drive is specified in path.

See Also

ChDrive Statement, CurDir Function, Dir Function, MkDir Statement, RmDir Statement.

Example

This example uses the ChDir statement to change the current directory or folder.

' Change current directory or folder to "MYDIR".
ChDir "MYDIR"

' In Microsoft Windows.
' Assume "C:" is the current drive. The following statement changes
' the default directory on drive "D:". "C:" remains the current drive.
ChDir "D:\WINDOWS\SYSTEM"

' On the Macintosh.
' Changes default folder and default drive.
ChDir "HD:MY FOLDER"


ChDrive Statement

Description

Changes the current drive.

Syntax

ChDrive drive

The drive named argument is a string expression that specifies an existing drive. If you supply a zero-length argument (""), the current drive doesn't change. In Microsoft Windows, if the argument drive is a multiple-character string, ChDrive uses only the first letter. On the Macintosh, ChDrive changes the current folder to the root folder of the specifed drive.

See Also

ChDir Statement, CurDir Function, MkDir Statement, RmDir Statement.

Example

This example uses the ChDrive statement to change the current drive.

' In Microsoft Windows.
ChDrive "D"    ' Make "D" the current drive.

' On the Macintosh.
' Make "MY DRIVE" the current drive
ChDrive "MY DRIVE:"
' Make "MY DRIVE" the current drive and current folder since its the
' root.
ChDrive "MY DRIVE:MY FOLDER"


CheckBox Object

Description

Represents a check box control on a chart sheet, dialog sheet, or worksheet. You can set the position and size of a check box. On a worksheet or chart, you can also format the border and background of the check box. The font is fixed.

Accessors

The CheckBox object is a member of the CheckBoxes collection. The CheckBoxes collection contains all the CheckBox objects on a single sheet. Use the Add method to create a new check box and add it to the collection.

To access a single member of the collection, use the CheckBoxes method with the index number or name of the check box as an argument.

The following example links check box one on dialog sheet one to cell A1 on the worksheet named "Sheet1." When the value of cell A1 is TRUE, the check box is turned on, and vice versa.

DialogSheets("sheet1").CheckBoxes(1).LinkedCell = "=sheet1!a1"

The check box name is shown in the Name Box when the check box is selected. Use the Name property to set or return the check box name. The following example turns on the check box named "Check Box 5."

DialogSheets(1).CheckBoxes("check box 5").Value = True

Properties

Accelerator Property, Application Property, Border Property, BottomRightCell Property, Caption Property, Creator Property, Display3DShading Property, Enabled Property, Height Property, Index Property, Interior Property, Left Property, LinkedCell Property, Locked Property, LockedText Property, Name Property, OnAction Property, Parent Property, PhoneticAccelerator Property, Placement Property, PrintObject Property, Text Property, Top Property, TopLeftCell Property, Value Property, Visible Property, Width Property, ZOrder Property.

Methods

BringToFront Method, Characters Method, CheckSpelling Method, Copy Method, CopyPicture Method, Cut Method, Delete Method, Duplicate Method, Select Method, SendToBack Method.


CheckBoxes Collection Object

Description

A collection of all the CheckBox objects on the specified chart sheet, dialog sheet, or worksheet. You can set the position and size of a check box. On a worksheet or chart, you can also format the border and background of the check box. The font is fixed.

Accessors

Use the Add method to create a new check box and add it to the collection. The following example adds a new check box to the dialog sheet named "Dialog1." The new check box is positioned inside the dialog frame.

Dim df as DialogFrame
DialogSheets("dialog1").Activate
Set df = ActiveSheet.DialogFrame
ActiveSheet.CheckBoxes.Add df.Left + 10, df.Top + 10, 100, 10

Use the CheckBoxes method with an argument to access a single member of the collection or without an argument to access the entire collection at once. The following example turns off (clears) all of the check boxes on the dialog sheet named "Dialog1."

DialogSheets("dialog1").CheckBoxes.Value = xlOff

Properties

Accelerator Property, Application Property, Border Property, Caption Property, Count Property, Creator Property, Display3DShading Property, Enabled Property, Height Property, Interior Property, Left Property, LinkedCell Property, Locked Property, LockedText Property, OnAction Property, Parent Property, PhoneticAccelerator Property, Placement Property, PrintObject Property, Text Property, Top Property, Value Property, Visible Property, Width Property, ZOrder Property.

Methods

Add Method (Graphic Objects and Controls), BringToFront Method, Characters Method, CheckSpelling Method, Copy Method, CopyPicture Method, Cut Method, Delete Method, Duplicate Method, Group Method, Item Method, Select Method, SendToBack Method.


CheckBoxes Method

Applies To

Chart Object, DialogSheet Object, Worksheet Object.

Description

Accessor. Returns an object that represents a single check box (a CheckBox object, Syntax 1) or a collection of check boxes (a CheckBoxes object, Syntax 2) on the sheet.

Syntax 1

object.CheckBoxes(index)

Syntax 2

object.CheckBoxes

object

Required. The Chart, DialogSheet, or Worksheet object.

index

Required for Syntax 1. Specifies the name or number of the check box (can be an array to specify more than one).

Example

This example sets check box one on Dialog1 to be gray and then displays the dialog box.

With DialogSheets("Dialog1")
    .CheckBoxes(1).Value = xlMixed
    .Show
End With


Checked Property

Applies To

MenuItem Object.

Description

True if the menu item is checked. Read-write.

Example

This example adds a check mark to the first menu item on the first menu on the active menu bar (which is usually the New command on the File menu).

ActiveMenuBar.Menus(1).MenuItems(1).Checked = True


CheckSpelling Method

Applies To

Application Object, Button Object, Buttons Collection, Chart Object, CheckBox Object, DialogFrame Object, DialogSheet Object, DrawingObjects Collection, GroupBox Object, GroupBoxes Collection, GroupObject Object, GroupObjects Collection, Label Object, Labels Collection, OptionButton Object, OptionButtons Collection, Range Object, TextBox Object, TextBoxes Collection, Worksheet Object.

Description

Syntax 1: Checks the spelling of an object. This form has no return value; Microsoft Excel displays the Spelling dialog box.

Syntax 2: Checks the spelling of a single word. Returns True if the word is found in one of the dictionaries, False if it is not.

Syntax 1

object.CheckSpelling(customDictionary, ignoreUppercase, alwaysSuggest)

Syntax 2

object.CheckSpelling(word, customDictionary, ignoreUppercase)

object

Required. The object to which this method applies. Use the Application object to check a single word (Syntax 2).

customDictionary

Optional. A string indicating the filename of the custom dictionary to examine if the word is not found in the main dictionary. If omitted, the currently specified dictionary is used.

ignoreUppercase

Optional. If True, Microsoft Excel will ignore words that are in all uppercase. If False, Microsoft Excel will check words that are in all uppercase. If omitted, the current setting will be used.

alwaysSuggest

Optional. If True, Microsoft Excel will display a list of suggested alternate spellings when an incorrect spelling is found. If False, Microsoft Excel will wait for you to input the correct spelling. If omitted, the current setting will be used.

word

Required (used with Application object only). The word you want to check.

Remarks

To check headers, footers, and objects, use Worksheet.CheckSpelling.

To check only cells and notes, use Worksheet.Cells.CheckSpelling.

Example

This example checks the spelling on Sheet1.

Worksheets("Sheet1").CheckSpelling


ChildField Property

Applies To

PivotField Object.

Description

Accessor. Returns a PivotField object that represents the child pivot field for the specified field (if the field is grouped and has a child field). Read-only.

Remarks

If the specified field has no child field, this property causes an error.

Example

This example displays the name of the child field for the field named "REGION2."

Set pvtTable = Worksheets("Sheet1").Range("A3").PivotTable
MsgBox "The name of the child field is " & _
    pvtTable.PivotFields("REGION2").ChildField.Name


ChildItems Method

Applies To

PivotField Object, PivotItem Object.

Description

Accessor. Returns an object that represents one pivot item (a PivotItem object, Syntax 1) or a collection of all the pivot items (a PivotItems object, Syntax 2) that are group children in the specified field, or children of the specified item. Read-only.

Syntax 1

object.ChildItems(index)

Syntax 2

object.ChildItems

object

Required. The PivotField or PivotItem object.

index

Required for Syntax 1. The number or name of the pivot item to return (can be an array to specify more than one).

Example

This example adds the names of all the child items of the item named "Northwest" to a list box. The list box appears on Sheet1.

Set pvtTable = Worksheets("Sheet1").Range("A3").PivotTable
Set newListBox = Worksheets("Sheet1").ListBoxes.Add _
    (Left:=10, Top:=72, Width:=144, Height:=144)
Set pvtField = pvtTable.PivotFields("REGION2")
For Each pvtItem In pvtField.PivotItems("Northwest").ChildItems
    newListBox.AddItem (pvtItem.Name)
Next pvtItem
Worksheets("Sheet1").Activate


Chr Function

Description

Returns the character associated with the specified character code.

Syntax

Chr(charcode)

The charcode named argument is a number in the range 0 to 255, inclusive, that identifies a character.

Remarks

Numbers from 0 to 31 are the same as standard, nonprintable ASCII codes. For example, Chr(10) returns a linefeed character.

See Also

Asc Function, Str Function.

Example

This example uses the Chr function to return the character associated with the specified character code.

MyChar = Chr(65)    ' Returns A.
MyChar = Chr(97)    ' Returns a.
MyChar = Chr(62)    ' Returns >.
MyChar = Chr(37)    ' Returns %.

This example fills list box one on Dialog1 with the letters A through Z.

For i = 65 To 90
    DialogSheets("Dialog1").ListBoxes(1).AddItem Text:=Chr(i)
Next i

This example creates a line break in a message box by using the Chr function.

msgText = "The current folder is:" & Chr(13) & CurDir()
MsgBox msgText


CInt Function

Description

Converts an expression to an Integer.

Syntax

CInt(expression)

The expression argument is any valid numeric or string expression.

Remarks

In general, you can document your code using the data type conversion functions to show that the result of some operation should be expressed as a particular data type rather than the default data type. For example, use CInt or CLng to force integer arithmetic in cases where currency, single-precision, or double-precision arithmetic normally would occur.

You should use the CInt function instead of Val to provide internationally-aware conversions from any other data type to an Integer. For example, different decimal separators are properly recognized depending on the locale setting of your system, as are different thousand separators.

If expression lies outside the acceptable range for the Integer data type, an error occurs.

Note

CInt differs from the Fix and Int functions that truncate, rather than round, the fractional part of a number. When the fractional part is exactly 0.5, the CInt function always rounds it to the nearest even number. For example, 0.5 rounds to 0, and 1.5 rounds to 2.

See Also

Data Type Summary, Int Function.

Example

This example uses the CInt function to convert a value to an Integer.

MyDouble = 2345.5678    ' MyDouble is a Double.
MyInt = CInt(MyDouble)    ' MyInt contains 2346.


CircularReference Property

Applies To

Worksheet Object.

Description

Accessor. Returns a Range object that represents the range containing the first circular reference on the sheet, or Nothing if there is no circular reference present. The circular reference must be removed before calculation can proceed. Read-only.

Example

This example selects the first cell in the first circular reference on Sheet1.

Worksheets("Sheet1").CircularReference.Select


Clear Method

Applies To

ChartArea Object, Range Object.

Description

Clears the entire range or chart area.

Syntax

object.Clear

object

Required. The ChartArea or Range object.

See Also

ClearContents Method, ClearFormats Method.

Example

This example clears the formulas and formatting in A1:G37 on Sheet1.

Worksheets("Sheet1").Range("A1:G37").Clear

This example clears the chart area (the chart data and formatting) of Chart1.

Charts("Chart1").ChartArea.Clear


ClearArrows Method

Applies To

Worksheet Object.

Description

Clears the tracer arrows on the worksheet. Tracer arrows are added by the auditing feature.

Syntax

object.ClearArrows

object

Required. The Worksheet object.

See Also

ShowDependents Method, ShowErrors Method, ShowPrecedents Method.

Example

This example clears tracer arrows on Sheet1.

Worksheets("Sheet1").ClearArrows


ClearContents Method

Applies To

ChartArea Object, Range Object.

Description

Clears the formulas from the range. Clears the data from a chart but leaves the formatting.

Syntax

object.ClearContents

object

Required. The Chart or Range object.

Example

This example clears the formulas from cells A1:G37 on Sheet1 but leaves the formatting intact.

Worksheets("Sheet1").Range("A1:G37").ClearContents

This example clears the chart data from Chart1 but leaves the formatting intact.

Charts("Chart1").ChartArea.ClearContents


ClearFormats Method

Applies To

ChartArea Object, ErrorBars Object, Floor Object, LegendKey Object, PlotArea Object, Point Object, Range Object, Series Object, Trendline Object, Walls Object.

Description

Clears the formatting of the object.

Syntax

object.ClearFormats

object

Required. The object to which this method applies.

See Also

Clear Method, ClearContents Method.

Example

This example clears all formatting from cells A1:G37 on Sheet1.

Worksheets("Sheet1").Range("A1:G37").ClearFormats

This example clears the formatting of embedded chart one on Sheet1.

Worksheets("Sheet1").ChartObjects(1).Chart.ChartArea.ClearFormats


ClearNotes Method

Applies To

Range Object.

Description

Clears the note and the sound notes from all the cells in the range.

Syntax

object.ClearNotes

object

Required. Clear notes and sound notes from this Range.

See Also

NoteText Method, SoundNote Property.

Example

This example clears all notes and sound notes in columns A through C on Sheet1.

Worksheets("Sheet1").Columns("A:C").ClearNotes


ClearOutline Method

Applies To

Range Object.

Description

Clears the outline for the specified range.

Syntax

object.ClearOutline

object

Required. The Range object.

See Also

AutoOutline Method.

Example

This example clears the outline for the range A1:G37 on Sheet1.

Worksheets("Sheet1").Range("A1:G37").ClearOutline


ClipboardFormats Property

Applies To

Application Object.

Description

Returns the formats currently on the Clipboard, as an array of numeric values. To determine if a particular format is present, compare each element in the array with the appropriate constant shown in the table below. Read-only.

Remarks

This property is available in Microsoft Windows and on the Apple Macintosh. Some formats may be available only on the Apple Macintosh, or only in Microsoft Windows.

This property returns an array of numeric values. To determine if a particular clipboard format is present, compare each element of the array to one of the constants below.

xlClipboardFormatBIFF

xlClipboardFormatBIFF2

xlClipboardFormatBIFF3

xlClipboardFormatBIFF4

xlClipboardFormatBinary

xlClipboardFormatBitmap

xlClipboardFormatCGM

xlClipboardFormatCSV

xlClipboardFormatDIF

xlClipboardFormatDspText

xlClipboardFormatEmbeddedObject

xlClipboardFormatEmbedSource

xlClipboardFormatLink

xlClipboardFormatLinkSource

xlClipboardFormatLinkSourceDesc

xlClipboardFormatMovie

xlClipboardFormatNative

xlClipboardFormatObjectDesc

xlClipboardFormatObjectLink

xlClipboardFormatOwnerLink

xlClipboardFormatPICT

xlClipboardFormatPrintPICT

xlClipboardFormatRTF

xlClipboardFormatScreenPICT

xlClipboardFormatStandardFont

xlClipboardFormatStandardScale

xlClipboardFormatSYLK

xlClipboardFormatTable

xlClipboardFormatText

xlClipboardFormatToolFace

xlClipboardFormatToolFacePICT

xlClipboardFormatVALU

xlClipboardFormatWK1

Example

This example displays a message box if the Clipboard contains a rich-text format (RTF) object. You can create an RTF object by copying text from a Word document.

aFmts = Application.ClipboardFormats
For Each fmt In aFmts
    If fmt = xlClipboardFormatRTF Then
        MsgBox "Clipboard contains rich text"
    End If
Next


CLng Function

Description

Converts an expression to a Long.

Syntax

CLng(expression)

The expression argument is any valid numeric or string expression.

Remarks

In general, you can document your code using the data type conversion functions to show that the result of some operation should be expressed as a particular data type rather than the default data type. For example, use CInt or CLng to force integer arithmetic in cases where currency, single-precision, or double-precision arithmetic normally would occur.

You should use the CLng function instead of Val to provide internationally-aware conversions from any other data type to a Long. For example, different decimal separators are properly recognized depending on the locale setting of your system, as are different thousand separators.

If expression lies outside the acceptable range for the Long data type, an error occurs.

Note

CLng differs from the Fix and Int functions that truncate, rather than round, the fractional part of a number. When the fractional part is exactly 0.5, the CLng function always rounds it to the nearest even number. For example, 0.5 rounds to 0, and 1.5 rounds to 2.

See Also

Data Type Summary, Int Function.

Example

This example uses the CLng function to convert a value to a Long.

MyVal1 = 25427.45 : MyVal2 = 25427.55    ' MyVal1, MyVal2 are Doubles.
MyLong1 = CLng(MyVal1)    ' MyLong1 contains 25427.
MyLong2 = CLng(MyVal2)    ' MyLong2 contains 25428.


Close Method

Applies To

Window Object, Workbook Object, Workbooks Collection.

Description

Closes the object. The Workbooks collection uses Syntax 1. Window and Workbook objects use Syntax 2.

Syntax 1

object.Close

Syntax 2

object.Close(saveChanges, fileName, routeWorkbook)

object

Required. The object to close.

saveChanges

Optional. If there are no changes to the workbook in the window, this argument is ignored. If there are changes to the workbook, and there are other windows open on the workbook, this argument is ignored. If there are changes to the workbook, and there are no other windows open on the workbook, this argument takes the specified action, as shown in the following table.

Value

Action

True

Saves the changes to the workbook. If there is not yet a filename associated with the workbook, then fileName is used. If fileName is omitted, the user is asked to supply a filename.

False

Does not save the changes to this file.

Omitted

Displays a dialog box asking the user whether or not to save changes.

fileName

Optional. Save changes under this filename.

routeWorkbook

Optional. If the workbook does not need to be routed to the next recipient (has no routing slip, or is already routed), this argument is ignored. Otherwise, Microsoft Excel routes the workbook as shown in the following table.

Value | Meaning
True | Sends the workbook to the next recipient.
False | Does not send the workbook.
Omitted | Displays a dialog box asking the user if the workbook should be sent.

Remarks

Closing a workbook from Visual Basic does not run any Auto_Close macros in the workbook. Use the RunAutoMacros method to run the auto close macros.

You cannot close a workbook while a dialog box is displayed. This means that you cannot call this method from an event handler for a dialog-box control. You can use the following steps to close the workbook when the user chooses a button control:

1. Set the DismissButton property for the button to True.

2. Create a module-level status variable

3. Set the status variable to 0 (zero) before you display the dialog box

4. Set the status variable to 1 when the user chooses the control. Choosing the control dismisses the dialog box.

5. Test the status variable. If it is equal to 1, close the workbook.

Example

This example closes BOOK1.XLS and discards any changes.

Workbooks("BOOK1.XLS").Close saveChanges:=False

This example closes all open workbooks. If there are changes in any workbook, Microsoft Excel displays the appropriate prompts and dialog boxes to save changes.

Workbooks.Close


Close Statement

Description

Concludes input/output (I/O) to a file opened using the Open statement.

Syntax

Close [filenumberlist]

The filenumberlist argument can be one or more file numbers using the following syntax, where filenumber is any valid file number:

[#]filenumber][,[#]filenumber] . . .

Remarks

If you omit filenumberlist, all active files opened by the Open statement are closed.

When you close files that were opened for Output or Append, the final buffer of output is written to the operating system buffer for that file. All buffer space associated with the closed file is released.

When the Close statement executes, the association of a file with its file number ends.

See Also

End Statement, Open Statement, Reset Statement, Stop Statement.

Example

This example uses the Close statement to close all three files opened for Output.

For I = 1 To 3    ' Loop 3 times.
    FileName = "TEST" & I    ' Create file name.
    Open FileName For Output As #I    ' Open file.
    Print #I, "This is a test."    ' Write string to file.
Next I
Close        ' Close all 3 open files.


Color Property

Applies To

Border Object, Borders Collection, Font Object, Interior Object.

Description

Returns or sets the primary color of the object, as shown in the following table. The color is a long integer, created with the RGB function. Read-write.

Object | Color
Border | The color of the border.
Borders | The color of all four borders of a range. If they are not the same, returns Null.
Font | The color of the font.
Interior | The cell shading color or drawing object fill color.

Remarks

If the color is Automatic, the Color property returns the automatic color as an RGB value (a long integer). Use the ColorIndex property to determine if the color is Automatic.

Example

This example sets the color of the tick labels on the value axis in Chart1.

Charts("Chart1").Axes(xlValue).TickLabels.Font.Color = RGB(0, 255, 0)


ColorButtons Property

Applies To

Application Object.

Description

True if toolbars are displayed using colored faces. Read-write.

See Also

LargeButtons Property.

Example

This example turns off colored toolbar buttons.

Application.ColorButtons = False


ColorIndex Property

Applies To

Border Object, Borders Collection, Font Object, Interior Object.

Description

Returns or sets the color of the border, font, or interior, as shown in the following table. The color is specified as an index value into the current color palette, or the special constant xlAutomatic to use the automatic fill style. Read-write.

Object | ColorIndex
Border | Color of the border.
Borders | Color of all four borders. Returns Null if all four colors are not the same.
Font | Color of the font. Specify xlAutomatic to use the automatic color.
Interior | Color of the interior fill. Set this property to xlNone to specify no fill. Set this property to xlAutomatic to specify the automatic fill (for drawing objects).

Remarks

This property specifies a color as an index into the workbook color palette. You can use the Colors property to return the current color palette.

See Also

Color Property, Colors Property, PatternColor Property.

Example

The following examples assume that you are using the default color palette.

This example changes the font color in cell A1 on Sheet1 to red.

Worksheets("Sheet1").Range("A1").Font.ColorIndex = 3

This example sets the color of the major gridlines for the value axis in Chart1.

With Charts("Chart1").Axes(xlValue)
    If .HasMajorGridlines Then
        .MajorGridlines.Border.ColorIndex = 5    'set color to blue
    End If
End With

This example sets the chart area interior color of Chart1 to red and sets the border color to blue.

With Charts("Chart1").ChartArea
    .Interior.ColorIndex = 3
    .Border.ColorIndex = 5
End With

This example sets the border color of every graphic object on Sheet1 to cyan.

For Each d In Worksheets("Sheet1").DrawingObjects
    d.Border.ColorIndex = 8
Next d


Colors Property

Applies To

Workbook Object.

Description

Returns or sets an array of colors (from 1 to 56) in the palette for the workbook. Read-write.

See Also

ColorIndex Property.

Example

This example sets the color palette for the active workbook to be the same as the palette for BOOK2.XLS.

ActiveWorkbook.Colors = Workbooks("BOOK2.XLS").Colors


Column Property

Applies To

Range Object.

Description

Returns the first column of the first area in the range, as a number. Read-only.

Remarks

Column A returns 1, column B returns 2, and so on.

To return the number of the last column in the range, use the following example.

myRange.Columns(myRange.Columns.Count).Column

See Also

Columns Method, Row Property, Rows Method.

Example

This example sets the column width of every other column on Sheet1 to 4 points.

For Each col In Worksheets("Sheet1").Columns
    If col.Column Mod 2 = 0 Then
        col.ColumnWidth = 4
    End If
Next col


Column3DGroup Property

Applies To

Chart Object.

Description

Accessor. Returns a ChartGroup object that represents the column chart group on a 3-D chart. Read-only.

See Also

ColumnGroups Method.

Example

This example sets the subtype for the 3-D column chart group in Chart1.

Charts("Chart1").Column3DGroup.SubType = 4


ColumnDifferences Method

Applies To

Range Object.

Description

Accessor. Returns a Range object that represents all the cells whose contents are different than the comparison cell in each column. The comparison cell is the one in the same row as comparison.

Syntax

object.ColumnDifferences(comparison)

object

Required. The range containing the cells to compare.

comparison

Required. A cell in the comparison row.

See Also

RowDifferences Method.

Example

This example selects the cells in column A on Sheet1 whose contents are different from cell A4.

Worksheets("Sheet1").Activate
Set r1 = ActiveSheet.Columns("A").ColumnDifferences( _
    comparison:=ActiveSheet.Range("A4"))
r1.Select


ColumnFields Method

Applies To

PivotTable Object.

Description

Accessor. Returns an object that represents a single pivot field (a PivotField object, Syntax 1) or a collection of the pivot fields (a PivotFields object, Syntax 2) that are currently showing as column fields. Read-only.

Syntax 1

object.ColumnFields(index)

Syntax 2

object.ColumnFields

object

Required. The PivotTable object.

index

Required for Syntax 1. The name or number of the pivot field to return (can be an array to specify more than one).

See Also

DataFields Method, HiddenFields Method, PageFields Method, PivotFields Method, RowFields Method, VisibleFields Method.

Example

This example adds the PivotTable column field names to a list box. The list box appears on Sheet1.

Set pvtTable = Worksheets("Sheet1").Range("A3").PivotTable
Set newListBox = Worksheets("Sheet1").ListBoxes.Add _
    (Left:=10, Top:=72, Width:=144, Height:=144)
For Each clmField In pvtTable.ColumnFields
    newListBox.AddItem (clmField.Name)
Next clmField
Worksheets("Sheet1").Activate


ColumnGrand Property

Applies To

PivotTable Object.

Description

True if the PivotTable shows column grand totals. Read-write.

See Also

RowGrand Property.

Example

This example sets the PivotTable to show column grand totals.

Set pvtTable = Worksheets("Sheet1").Range("A3").PivotTable
pvtTable.ColumnGrand = True


ColumnGroups Method

Applies To

Chart Object.

Description

Accessor. On a 2-D chart, returns an object that represents a single column chart group (a ChartGroup object, Syntax 1), or a collection of the column chart groups (a ChartGroups collection, Syntax 2).

Syntax 1

object.ColumnGroups(index)

Syntax 2

object.ColumnGroups

object

Required. The Chart object.

index

Required for Syntax 1. Specifies the chart group.

See Also

Column3DGroup Property.

Example

This example sets the subtype for column chart group one in Chart1.

Charts("Chart1").ColumnGroups(1).SubType = 3


ColumnRange Property

Applies To

PivotTable Object.

Description

Accessor. Returns a Range object that represents the range that contains the PivotTable column area. Read-only.

See Also

DataBodyRange Property, DataLabelRange Property, PageRange Property, RowRange Property.

Example

This example selects the column headers for the PivotTable.

Worksheets("Sheet1").Activate
Range("A3").Select
ActiveCell.PivotTable.ColumnRange.Select


Columns Method

Applies To

Application Object, Range Object, Worksheet Object.

Description

Accessor. Returns a Range object that represents a single column (Syntax 1) or a collection of columns (Syntax 2).

Syntax 1

object.Columns(index)

Syntax 2

object.Columns

object

Optional for Application, required for Range and Worksheet. The object that contains the columns. If you specify the Application object (or omit the object qualifier), this method applies to the active sheet in the active workbook. If the active sheet is not a worksheet, this method fails.

index

Required for Syntax 1. The name or number of the column.

Remarks

When applied to a Range object that is a multiple selection, this method returns columns from the first area of the range only. For example, if the Range object is a multiple selection with two areas, A1:B2 and C3:D4, Selection.Columns.Count returns 2, not 4. To use this method on a range that may contain a multiple selection, test Areas.Count to determine if the range is a multiple selection, and if it is, then loop over each area in the range; see the third example.

See Also

Range Method, Rows Method.

Example

This example formats the font of column one (column A) on Sheet1 as bold.

Worksheets("Sheet1").Columns(1).Font.Bold = True

This example sets the value of every cell in column one in the range named myRange to zero (0).

Range("myRange").Columns(1).Value = 0

This example displays the number of columns in the selection on Sheet1. If more than one area is selected, the example loops through each area.

Worksheets("Sheet1").Activate
areaCount = Selection.Areas.Count
If areaCount <= 1 Then
    MsgBox "The selection contains " & _
        Selection.Columns.Count & " columns."
Else
    For i = 1 To areaCount
        MsgBox "Area " & i & " of the selection contains " & _
            Selection.Areas(i).Columns.Count & " columns."
    Next i
End If


ColumnWidth Property

Applies To

Range Object.

Description

Returns or sets the width of all columns in the range. Read-write.

Remarks

One unit of column width is equal to the width of a character of the Normal style. For proportional fonts, the width of the character 0 (zero) is used.

Use the Width property to return the width of a column in points.

If all columns in the range have the same width, the ColumnWidth property returns the width. If columns in the range have different widths, the property returns Null.

See Also

RowHeight Property.

Example

This example doubles the width of column A on Sheet1.

With Worksheets("Sheet1").Columns("A")
    .ColumnWidth = .ColumnWidth * 2
End With


CommandUnderlines Property

Applies To

Application Object.

Description

Returns or sets the state of the command underlines, as shown in the following table.

Value | Meaning
xlOn | Command underlines are on.
xlOff | Command underlines are off.
xlAutomatic | Command underlines appear when you activate the menus.

Remarks

In Microsoft Excel for Windows, reading this property always returns xlOn, and setting this property to anything but xlOn is an error.

Example

This example turns off command underlines in Microsoft Excel for the Macintosh.

Application.CommandUnderlines = xlOff


Comment Property

Applies To

Scenario Object.

Description

Returns or sets the comment associated with the scenario. The comment text cannot exceed 255 characters. Read-write.

See Also

ChangeScenario Method, ChangingCells Property.

Example

This example sets the comment for scenario one on Sheet1.

Worksheets("Sheet1").Scenarios(1).Comment = _
    "Worst case July 1993 sales"


Comments Property

Applies To

AddIn Object, Workbook Object.

Description

Returns or sets the comments for the object, as a string. Read-only for AddIn, read-write for Workbook.

Remarks

In Microsoft Excel for Windows 95, this property has been replaced by a built-in OLE document property. For more information about OLE document properties, see BuiltinDocumentProperties.

You cannot use this property with an AddIn object that represents an XLL file or an add-in that was created with the Microsoft Excel 4.0 macro language.

See Also

Author Property, Keywords Property, Subject Property, Title Property.

Example

This example displays the name and comments of the Solver add-in. Note that you can use Chr(13) to create a line break in a message box.

Set a = AddIns("Solver Add-In")
MsgBox a.Name & " description:" & Chr(13) & a.Comments

This example sets the comments for the active workbook.

ActiveWorkbook.Comments = "This workbook has been reviewed."


Comparison Operators

Description

Used to compare expressions.

Syntax

result = expression1 comparisonoperator expression2
result = object1 Is object2
result = string Like pattern

Comparison operators have these parts:

Part | Description
result | Any numeric variable.
expression | Any expression.
comparisonoperator | Any comparison operator.
object | Any object name.
string | Any string expression.
pattern | Any string expression or range of characters.

Remarks

The Is and Like operators have specific comparison functionality that differs from the operators in the following table. The following table contains a list of the comparison operators and the conditions that determine whether result is True, False, or Null:

Operator | Description | True if | False if | Null if
< | Less than | expression1 < expression2 | expression1 >= expression2 | expression1 or expression2 = Null
<= | Less than or equal to | expression1 <= expression2 | expression1 > expression2 | expression1 or expression2 = Null
> | Greater than | expression1 > expression2 | expression1 <= expression2 | expression1 or expression2 = Null
>= | Greater than or equal to | expression1 >= expression2 | expression1 < expression2 | expression1 or expression2 = Null
= | Equal to | expression1 = expression2 | expression1 <> expression2 | expression1 or expression2 = Null
<> | Not equal to | expression1 <> expression2 | expression1 = expression2 | expression1 or expression2 = Null

When comparing two expressions, you may not be able to easily determine whether the expressions are being compared as numbers or as strings. The following table shows how the expressions are compared or what results when either expression is not a Variant:

If | Then
Both expressions are numeric data types (Integer, Long, Single, Double, or Currency) | Perform a numeric comparison.
Both expressions are String | Perform a string comparison.
One expression is a numeric data type and the other is a Variant that is, or can be, a number | Perform a numeric comparison.
One expression is a numeric data type and the other is a string Variant that can't be converted to a number | A Type Mismatch error occurs.
One expression is a String and the other is any Variant (except a Null) | Perform a string comparison.
One expression is Empty and the other is a numeric data type | Perform a numeric comparison, using 0 as the Empty expression.
One expression is Empty and the other is a String | Perform a string comparison, using a zero-length string as the Empty expression.

If expression1 and expression2 are both Variant expressions, their underlying type determines how they are compared. The following table shows how the expressions are compared or what results from the comparison, depending on the underlying type of the Variant:

If | Then
Both Variant expressions are numeric | Perform a numeric comparison.
Both Variant expressions are strings | Perform a string comparison.
One Variant expression is numeric and the other is a string | The numeric expression is less than the string expression.
One Variant expression is Empty and the other is numeric | Perform a numeric comparison, using 0 as the Empty expression.
One Variant expression is Empty and the other is a string | Perform a string comparison, using a zero-length string as the Empty expression.
Both Variant expressions are Empty | The expressions are equal.

Note

If a Currency is compared with a Single or Double, the Single or Double is converted to a Currency. This causes any fractional part of the Single or Double value less than 0.0001 to be lost and may cause two values to compare as equal when they are not. When a Single is compared to a Double, the Double is rounded to the precision of the Single.

See Also

Is Operator, Like Operator, Operator Precedence, Option Compare Statement.

Example

This example shows various uses of comparison operators, which you use to compare expressions.

MyResult = (45 < 35)    ' Returns False.
MyResult = (45 = 45)    ' Returns True.
MyResult = (4 <> 3)    ' Returns True.
MyResult = ("5" > "4")    ' Returns True.
Var1 = "5" : Var2 = 4    ' Initialize variables.
MyResult = (Var1 > Var2)    ' Returns True.
Var1 = 5 : Var2 = Empty
MyResult = (Var1 > Var2)    ' Returns True.
Var1 = 0 : Var2 = Empty
MyResult = (Var1 = Var2)    ' Returns True.


Consolidate Method

Applies To

Range Object.

Description

Consolidates data from multiple ranges on multiple worksheets into a single range on a single worksheet.

Syntax

object.Consolidate(sources, function, topRow, leftColumn, createLinks)

object

Required. The destination range.

sources

Optional. Specifies the sources of the consolidation as an array of text reference strings in R1C1-style notation. The references must include the full path of sheets to consolidate.

function

Optional. The consolidation function (one of xlAverage, xlCount, xlCountNums, xlMax, xlMin, xlProduct, xlStDev, xlStDevP, xlSum, xlVar, or xlVarP).

topRow

Optional. If True, data is consolidated based on column header titles in the top row of the consolidation ranges. If False or omitted, data is consolidated by position.

leftColumn

Optional. If True, data is consolidated based on row titles in the left column of the consolidation ranges. If False or omitted, data is consolidated by position.

createLinks

Optional. If True, the consolidation uses worksheet links. If False, the consolidation copies the data.

See Also

ConsolidationFunction Property, ConsolidationOptions Property, ConsolidationSources Property, Style Property.

Example

This example consolidates data from Sheet2 and Sheet3 onto Sheet1, using the SUM function.

Worksheets("Sheet1").Range("A1").Consolidate _
    sources:=Array("Sheet2!R1C1:R37C6", "Sheet3!R1C1:R37C6"), _
    Function:=xlSum


ConsolidationFunction Property

Applies To

Worksheet Object.

Description

Returns the function code used for the current consolidation (one of xlAverage, xlCount, xlCountNums, xlMax, xlMin, xlProduct, xlStDev, xlStDevP, xlSum, xlVar, or xlVarP). Read-only.

See Also

Consolidate Method, ConsolidationOptions Property, ConsolidationSources Property.

Example

This example displays a message box if the current consolidation is using the SUM function.

If Worksheets("Sheet1").ConsolidationFunction = xlSum Then
    MsgBox "Sheet1 uses the SUM function for consolidation."
End If


ConsolidationOptions Property

Applies To

Worksheet Object.

Description

Returns a three-element array of consolidation options, as shown in the following table. If the element is True, that option is set. Read-only.

Element | Meaning
1 | Labels in top row.
2 | Labels in left column.
3 | Create links for data.

See Also

Consolidate Method, ConsolidationFunction Property, ConsolidationSources Property.

Example

This example displays the consolidation options for Sheet1. The list appears on a new worksheet created by the example.

Set newSheet = Worksheets.Add
aOptions = Worksheets("Sheet1").ConsolidationOptions
newSheet.Range("A1").Value = "Labels in top row"
newSheet.Range("A2").Value = "Labels in left column"
newSheet.Range("A3").Value = "Create links for data"
For i = 1 To 3
    If aOptions(i) = True Then
        newSheet.Cells(i, 2).Value = "True"
    Else
        newSheet.Cells(i, 2).Value = "False"
    End If
Next i
newSheet.Columns("A:B").AutoFit


ConsolidationSources Property

Applies To

Worksheet Object.

Description

Returns an array of string values that name the source sheets for the worksheet's current consolidation. Returns Empty if there is no consolidation on the sheet. Read-only.

See Also

Consolidate Method, ConsolidationFunction Property, ConsolidationOptions Property.

Example

This example displays the names of the source ranges for the consolidation on Sheet1. The list appears on a new worksheet created by the example.

Set newSheet = Worksheets.Add
newSheet.Range("A1").Value = "Consolidation Sources"
aSources = Worksheets("Sheet10").ConsolidationSources
If IsEmpty(aSources) Then
    newSheet.Range("A2").Value = "none"
Else
    For i = 1 To UBound(aSources)
        newSheet.Cells(i + 1, 1).Value = aSources(i)
    Next i
End If
newSheet.Columns("A:B").AutoFit


Const Statement

Description

Declares constants for use in place of literal values.

Syntax

[Public | Private] Const constname [As type] = expression

The Const statement syntax has these parts:

Part | Description
Public | Used at module level to declare constants that are available to all procedures in all modules. Not allowed in procedures.
Private | Used at module level to declare constants that are available only within the module where the declaration is made. Not allowed in procedures.
constname | Name of the constant; follows standard variable naming conventions.
type | Data type of the constant; may be Boolean, Integer, Long, Currency, Single, Double, Date, String, or Variant. Use a separate As type clause for each constant being declared.
expression | Literal, other constant, or any combination including arithmetic or logical operators except Is.

Remarks

If not explicitly specified using either Public or Private, constants are Private by default.

Several constant declarations can be combined on the same line by separating each constant assignment with a comma. If constant declarations are combined in this way, the Public or Private keywords, if used, apply to all of them.

You can't use string concatenation, variables, user-defined or intrinsic functions (such as Chr) in expressions assigned to constants.

If you don't explicitly declare the constant type (using As type), the constant is given a data type that is most appropriate for the expression provided.

Constants declared in Sub, Function, or Property procedures are local to that procedure. A constant declared outside a procedure is defined throughout the module in which it is declared. You can use constants anywhere you would use an expression.

See Also

Deftype Statements, Let Statement.

Example

This example uses the Const statement to declare constants for use in place of literal values.

' Constants are Private by default.
Const MyVar = 459

' Declare Public constant.
Public Const MyString = "HELP"

' Declare Private Integer constant.
Private Const MyInt As Integer = 5

' Declare multiple constants on same line.
Const MyStr = "Hello", MyDouble As Double = 3.4567


ConstrainNumeric Property

Applies To

Application Object.

Description

True if handwriting recognition is limited to numbers and punctuation only. Read-write. This property is available only if you are using Microsoft Windows for Pen Computing. If you try to set this property under any other operating system, an error occurs.

Example

This example limits handwriting recognition to numbers and punctuation only if Microsoft Windows for Pen Computing is running.

If Application.WindowsForPens Then
    Application.ConstrainNumeric = True
End If


Container Property

Applies To

Workbook Object.

Description

Accessor. Returns the object containing the specified embedded workbook. This property is available only in Microsoft Excel for Windows 95. Read-only.

Remarks

Use this property with a contained workbook to return the container object. If the container doesn't support OLE Automation or the workbook isn't embedded, this property fails.

Example

This example hides the second section in the binder that contains the active Microsoft Excel workbook and then sets the value of cell A1 to 345.67. In this example, the binder is Binder1.obd.

Set myBinder = GetObject("Binder1.obd", "Office.Binder")
Set myWorkbook = myBinder.Sections(1).Object
With myWorkbook
    .Container.Sections(2).Visible = False
    .Sheets(1).Cells(1, 1).Value = 345.67
End With


ConvertFormula Method

Applies To

Application Object.

Description

Converts cell references in a formula between the A1 and R1C1 reference styles, between relative and absolute references, or both.

Syntax

object.ConvertFormula(formula, fromReferenceStyle, toReferenceStyle, toAbsolute, relativeTo)

object

Required. The Application object.

formula

Required. A string containing the formula that you want to convert. This must be a valid formula and it must begin with an equal sign.

fromReferenceStyle

Required. The reference style of the formula. May be either xlA1 or xlR1C1.

toReferenceStyle

Optional. The reference style you want returned. May be either xlA1 or xlR1C1. If omitted, the reference style is not changed (the formula stays in the style specified by fromReferenceStyle).

toAbsolute

Optional. Specifies the converted reference type (one of xlAbsolute, xlAbsRowRelColumn, xlRelRowAbsColumn, or xlRelative). If this argument is omitted, the reference type is not changed.

relativeTo

Optional. A Range object that contains one cell. This object determines the cell to which relative references relate.

Example

This example converts a SUM formula that contains R1C1-style references to an equivalent formula that contains A1-style references and then displays the result.

inputFormula = "=SUM(R10C2:R15C2)"
MsgBox Application.ConvertFormula( _
    formula:=inputFormula, _
    fromReferenceStyle:=xlR1C1, _
    toReferenceStyle:=xlA1)


Copy Method

Applies To

Arc Object, Arcs Collection, Button Object, Buttons Collection, Chart Object, ChartArea Object, ChartObject Object, ChartObjects Collection, Charts Collection, CheckBox Object, DialogSheet Object, DialogSheets Collection, Drawing Object, DrawingObjects Collection, Drawings Collection, DropDown Object, DropDowns Collection, EditBox Object, EditBoxes Collection, GroupBox Object, GroupBoxes Collection, GroupObject Object, GroupObjects Collection, Label Object, Labels Collection, Line Object, Lines Collection, ListBox Object, ListBoxes Collection, Module Object, Modules Collection, OLEObject Object, OLEObjects Collection, OptionButton Object, OptionButtons Collection, Oval Object, Ovals Collection, Picture Object, Pictures Collection, Point Object, Range Object, Rectangle Object, Rectangles Collection, ScrollBar Object, ScrollBars Collection, Series Object, Sheets Collection, Spinner Object, Spinners Collection, TextBox Object, TextBoxes Collection, ToolbarButton Object, Worksheet Object, Worksheets Collection.

Description

Syntax 1: Copies the control or drawing object to the Clipboard. Copies a picture of the point or series to the Clipboard.

Syntax 2: Copies the Range to the specified range or to the Clipboard.

Syntax 3: Copies the sheet to another location in the workbook.

Syntax 4: Copies a toolbar button to another position, either on the same toolbar or to another toolbar.

Syntax 1

object.Copy

Syntax 2

object.Copy(destination)

Syntax 3

object.Copy(before, after)

Syntax 4

object.Copy(toolbar, before)

object

Required. The object to which this method applies. Copying a Chart object uses Syntax 3, and copies the entire chart sheet. To copy only the chart area, use Syntax 1 with the ChartArea object.

destination

Optional. Specifies the new range where the specified range will be copied. If this argument is omitted, Microsoft Excel copies the range to the clipboard.

before

Syntax 3: Optional. The sheet before which this sheet will be copied. You cannot specify before if you specify after.

Syntax 4: Required. Specifies the new button position as a number from one to the number of existing buttons + one. Gaps count as one position. Buttons to the right of this position are moved right (or down) to make room for the copied button.

after

Optional. The sheet after which this sheet will be copied. You cannot specify after if you specify before.

toolbar

Required for Syntax 4. Specifies the toolbar object to copy the button to.

Remarks

If you do not specify either before or after, Microsoft Excel creates a new workbook containing the copied sheet.

To copy a button and insert a gap before the copied button, first insert a gap on the destination toolbar using the ToolbarButtons Add method, then copy the button to the position after the new gap.

See Also

Move Method, Paste Method.

Example

This example copies button one on Sheet1 to the Clipboard.

Worksheets("Sheet1").Buttons(1).Copy

This example copies Sheet1, placing the copy after Sheet3.

Worksheets("Sheet1").Copy after := Worksheets("Sheet3")

This example copies the used range of Sheet1, creates a new worksheet, and then pastes the values of the copied range into the new worksheet.

Worksheets("Sheet1").UsedRange.Copy
Set newSheet = Worksheets.Add
newSheet.Range("A1").PasteSpecial Paste:=xlValues

This example copies the formulas in cells A1:D4 on Sheet1 to cells E5:H8 on Sheet2.

Worksheets("Sheet1").Range("A1:D4").Copy _
    destination:=Worksheets("Sheet2").Range("E5")


CopyFace Method

Applies To

ToolbarButton Object.

Description

Copies the specified button face to the Clipboard. This method copies only the bitmap button face, not the button itself.

Syntax

object.CopyFace

object

Required. The ToolbarButton object.

Remarks

This method cannot be used with a toolbar button that is a gap or that has a palette or list attached (such as the Font or Style buttons).

See Also

BuiltIn Property, BuiltInFace Property, PasteFace Method.

Example

This example copies the bitmap face of button one (the New Workbook button) on the Standard toolbar and pastes it onto button three (the Save button).

With Toolbars("Standard")
    .ToolbarButtons(1).CopyFace
    .ToolbarButtons(3).PasteFace
End With


CopyFromRecordset Method

Applies To

Range Object.

Description

Copies the contents of a DAO Recordset object onto a worksheet, beginning at the upper-left corner of the specified range. If the Recordset object contains fields with OLE objects, this method fails. This method is available only in Microsoft Excel for Windows 95.

Syntax

object.CopyFromRecordset(data, maxRows, maxColumns)

object

Required. The destination Range object.

data

Required. The Recordset object to copy into the range.

maxRows

Optional. The maximum number of records to copy onto the worksheet. If omitted, all records in the Recordset object are copied.

maxColumns

Optional. The maximum number of fields to copy onto the worksheet. If omitted, all fields in the Recordset object are copied.

Remarks

Copying begins at the current row of the Recordset object. After copying is completed, the EOF property of the Recordset object is True.

Example

This example copies the field names from a DAO Recordset object into the first row of a worksheet and formats the names as bold. The example then copies the recordset onto the worksheet, beginning at cell A2.

For iCols = 0 to rs.Fields.Count - 1
    ws.Cells(1, iCols + 1).Value = rs.Fields(iCols).Name
Next
ws.Range(ws.Cells(1, 1),  _
    ws.Cells(1, rs.Fields.Count)).Font.Bold = True
ws.Range("A2").CopyFromRecordset rs


CopyObjectsWithCells Property

Applies To

Application Object.

Description

True if drawing objects are cut, copied, extracted, and sorted with cells. Read-write.

Example

This example causes Microsoft Excel to cut, copy, extract, and sort drawing objects with cells.

Application.CopyObjectsWithCells = True


CopyPicture Method

Applies To

Arc Object, Arcs Collection, Button Object, Buttons Collection, Chart Object, ChartObject Object, ChartObjects Collection, CheckBox Object, DialogFrame Object, Drawing Object, DrawingObjects Collection, Drawings Collection, DropDown Object, DropDowns Collection, EditBox Object, EditBoxes Collection, GroupBox Object, GroupBoxes Collection, GroupObject Object, GroupObjects Collection, Label Object, Labels Collection, Line Object, Lines Collection, ListBox Object, ListBoxes Collection, OLEObject Object, OLEObjects Collection, OptionButton Object, OptionButtons Collection, Oval Object, Ovals Collection, Picture Object, Pictures Collection, Range Object, Rectangle Object, Rectangles Collection, ScrollBar Object, ScrollBars Collection, Spinner Object, Spinners Collection, TextBox Object, TextBoxes Collection.

Description

Copies the object to the Clipboard as a Picture. Syntax 2 is used for the Chart object. Syntax 1 is used for all other objects.

Syntax 1

object.CopyPicture(appearance, format)

Syntax 2

object.CopyPicture(appearance, format, size)

object

Required. The object to copy.

appearance

Optional. Specifies how the picture should be copied. If xlScreen or omitted, the picture is copied as closely as possible to the picture displayed on the screen. If xlPrinter, the picture is copied as it would be printed.

format

Optional. Specifies the format of the picture (one of xlPicture or xlBitmap). If omitted, picture format is used.

size

Optional. Specifies the size of the copied picture when the object is a chart that is on a chart sheet (not embedded on a worksheet). If xlPrinter or omitted, the picture is copied as closely as possible to the printed size. If xlScreen, the picture is copied as closely as possible to the size as displayed on the screen.

Remarks

This method creates a Picture object on the Clipboard, regardless of the copied object.

If you copy a range, it must be made up of adjacent cells.

See Also

Copy Method, Paste Method.

Example

This example copies a screen image of cells A1:D4 on Sheet1 to the Clipboard, and then it pastes the bitmap in another location on Sheet1.

Worksheets("Sheet1").Range("A1:D4").CopyPicture xlScreen, xlBitmap
Worksheets("Sheet1").Paste _
    destination:=Worksheets("Sheet1").Range("E6")


Corners Object

Description

Represents the corners of a 3-D chart. The Corners object supports only the Select method. The macro recorder uses this object and method to record selecting the corners of a 3-D chart when you drag the corners to set the chart elevation and rotation. Because you can set these properties directly in Visual Basic, you will not need to use the Corners object. You can delete the line containing this object without affecting the functionality of the code.

Properties

Application Property, Creator Property, Name Property, Parent Property.

Methods

Select Method.


Corners Property

Applies To

Chart Object.

Description

Accessor. Returns a Corners object that represents the corners of a 3-D chart. The corners cannot be formatted; this property can be used only to select the corners of the chart. Read-only.

Example

This example selects the corners of Chart1. The example should be run on a 3-D chart (the Select method fails on any other chart type).

With Charts("Chart1")
    .Activate
    .Corners.Select
End With


Cos Function

Description

Returns the cosine of an angle.

Syntax

Cos(number)

The number named argument can be any valid numeric expression that expresses an angle in radians.

Remarks

The Cos function takes an angle and returns the ratio of two sides of a right triangle. The ratio is the length of the side adjacent to the angle divided by the length of the hypotenuse.

The result lies in the range -1 to 1.

To convert degrees to radians, multiply degrees by pi/180. To convert radians to degrees, multiply radians by 180/pi.

See Also

Atn Function, Derived Math Functions, Sin Function, Tan Function.

Example

This example uses the Cos function to return the cosine of an angle.

MyAngle = 1.3    ' Define angle in radians.
MySecant = 1 / Cos(MyAngle)    ' Calculate secant.


Count Property

Applies To

All collections.

Description

Returns the number of items in the collection. Read-only.

For help about using the Count worksheet function in Visual Basic, see "Using Worksheet Functions in Visual Basic" in online Help.

Example

This example displays the number of menus on the active menu bar.

MsgBox "The active menu bar contains " & _
    ActiveMenuBar.Menus.Count & " menus."

This example displays the number of columns in the selection on Sheet1. The code also tests for a multi-area selection; if one exists, the code loops on the areas of the multi-area selection.

Worksheets("Sheet1").Activate
areaCount = Selection.Areas.Count
If areaCount <= 1 Then
    MsgBox "The selection contains " & _
        Selection.Columns.Count & " columns."
Else
    For i = 1 To areaCount
        MsgBox "Area " & i & " of the selection contains " & _
            Selection.Areas(i).Columns.Count & " columns."
    Next i
End If

This example makes the last character in cell A1 a superscript.

n = Worksheets("Sheet1").Range("A1").Characters.Count
Worksheets("Sheet1").Range("A1").Characters(n, 1).Font.Superscript = _
            True


Count Property (DocumentProperties Collection)

Applies To

DocumentProperties Collection.

Description

Returns the number of document properties in the DocumentProperties collection. Read-only.

To use this property, you should establish a reference to the Microsoft Office 95 Object Library by using the References command (Tools menu).

Example

This example displays the number of document properties in a collection. You must pass a DocumentProperties collection to the procedure.

Sub CountDocumentProperties(dp As DocumentProperties)
    MsgBox "There are " & dp.Count & " properties in the collection."
End Sub

This example displays the number of custom document properties in the active workbook.

MsgBox ActiveWorkbook.CustomDocumentProperties.Count


CreateBackup Property

Applies To

Workbook Object.

Description

True if a backup will be created when this file is saved. Read-only.

Example

This example displays a message if a backup is created when the active workbook is saved.

If ActiveWorkbook.CreateBackup = True Then
    MsgBox "Remember, there is a backup copy of this workbook"
End If


CreateNames Method

Applies To

Range Object.

Description

Creates names in the given range based on text labels in the sheet.

Syntax

object.CreateNames(top, left, bottom, right)

object

Required. Create names in this range.

top

Optional. Corresponds to the Top Row check box in the Create dialog box. Can be True or False.

left

Optional. Corresponds to the Left Column check box in the Create dialog box. Can be True or False.

bottom

Optional. Corresponds to the Bottom Row check box in the Create dialog box. Can be True or False.

right

Optional. Corresponds to the Right Column check box in the Create dialog box. Can be True or False.

Remarks

If you do not specify one of top, left, bottom, or right, Microsoft Excel guesses the location of the text labels based on the shape of the specified range.

See Also

Add Method (Names Collection), Delete Method.

Example

This example creates names for cells B1:B3 based on the text in cells A1:A3. Note that you must include the cells that contain the names in the range, even though the names are created only for cells B1:B3.

Set rangeToName = Worksheets("Sheet1").Range("A1:B3")
rangeToName.CreateNames left:=True


CreateObject Function

Description

Creates an OLE Automation object.

Syntax

CreateObject(class)

The class named argument uses the syntax: "appname.objecttype" and has these parts:

Part | Description
appname | The name of the application providing the object.
objecttype | The type or class of object to create.

Remarks

Note

If an application that supports OLE Automation exposes an object library, it is preferable to use the functions defined within the library for object creation rather than use CreateObject.

Each application that supports OLE Automation provides at least one type of object. For example, a word processing application may provide an application object, a document object, and a toolbar object.

Use this function to create an OLE Automation object and assign the object to an object variable. To do this, use the Set statement to assign the object returned by CreateObject to the object variable. For example:

Set WordBasicObject = CreateObject("Word.Basic")

When this code is executed, the application creating the object is started, if it is not already running (Microsoft Word in this example), and an object of the specified type is created. Once an object is created, you reference it in code using the object variable you defined. In the above example, you access properties and methods of the new object using the object variable, WordBasicObject. For example:

WordBasicObject.Insert "Hello, world."
WordBasicObject.FilePrint
WordBasicObject.FileSaveAs "C:\DOCS\TEST.DOC"

See Also

GetObject Function, Set Statement.


CreatePublisher Method

Applies To

Chart Object, Range Object.

Description

Creates a publisher based on a Chart or a Range. Available only on the Apple Macintosh with System 7 or later.

Syntax

object.CreatePublisher(edition, appearance, size, containsPICT, containsBIFF, containsRTF, containsVALU)

object

Required. The Chart or Range object.

edition

Optional. The filename of the edition to be created. If omitted, a default of <Document Name> Edition #n is used.

appearance

Optional. One of xlPrinter or xlScreen.

size

Optional (used only with Chart objects). One of xlPrinter or xlScreen.

containsPICT

Optional. True if the publisher should include PICT format. Assumed True if not specified.

containsBIFF

Optional. True if the publisher should include BIFF format. Assumed True if not specified for a Range, False for a Chart.

containsRTF

Optional. True if the publisher should include RTF format. Assumed True if not specified for a Range, False for a Chart.

containsVALU

Optional. True if the publisher should include VALU format. Assumed True if not specified for a Range, False for a Chart.

Example

This example creates a publisher based on cells A1:A20 on Sheet1.

Worksheets("Sheet1").Range("A1:A20").CreatePublisher "stock data"


CreateSummary Method

Description

Creates a new worksheet containing a summary report for the scenarios on the specified worksheet.

Syntax

object.CreateSummary(reportType, resultCells)

object

Required. The Scenarios collection object.

reportType

Optional. Specifies the report type (either xlStandardSummary or xlPivotTable). If this argument is omitted, a standard report is created.

resultCells

Optional. A range containing the result cells on the specified worksheet. Normally, this range refers to one or more cells containing the formulas that depend on the changing cell values for your model-that is, the cells that show the results of a particular scenario. If this argument is omitted, no result cells are included in the report.

Example

This example creates a summary of the scenarios on Sheet1, with result cells in the range C4:C9 on Sheet1.

Worksheets("Sheet1").Scenarios.CreateSummary _
    resultCells := Worksheets("Sheet1").Range("C4:C9")


Creator Property

Applies To

All objects.

Description

Returns the application that created this object, as a 32-bit integer. If the object was created by Microsoft Excel, this property returns the string XCEL, which is the hexadecimal number 5843454C. Read-only.

Remarks

The Creator property is designed to be used in Microsoft Excel for the Apple Macintosh, where each application has a four-character creator code. For example, Microsoft Excel has the creator code XCEL.

See Also

Application Property.

Example

This example displays a message about the creator of myObject.

Set myObject = ActiveWorkbook
If myObject.Creator = &h5843454c Then
    MsgBox "This is a Microsoft Excel object"
Else
    MsgBox "This is not a Microsoft Excel object"
End If


Crosses Property

Applies To

Axis Object.

Description

Returns or sets the point on the specified axis where the other axis crosses, as shown in the following table. Read-write.

Value | Meaning
xlAutomatic | Microsoft Excel sets the axis crossing.
xlMinimum | The axis crosses at the minimum value.
xlMaximum | The axis crosses at the maximum value.
xlCustom | The CrossesAt property specifies the crossing point.

Remarks

This property is not available for 3-D charts or radar charts.

This property can be used for both category and value axes. On the category axis, xlMinimum sets the value axis to cross at the first category, and xlMaximum sets the value axis to cross at the last category.

xlMinimum and xlMaximum can have different meanings, depending on the axis.

See Also

CrossesAt Property.

Example

This example sets the value axis in Chart1 to cross the category axis at the maximum x value.

Charts("Chart1").Axes(xlCategory).Crosses = xlMaximum


CrossesAt Property

Applies To

Axis Object.

Description

Returns or sets the point on the value axis where the category axis crosses. Applies only to the value axis. Read-write.

Remarks

Setting this property causes the Crosses property to change to xlCustom.

This property is not available for 3-D charts or radar charts.

See Also

Crosses Property.

Example

This example sets the category axis in Chart1 to cross the value axis at value 3.

With Charts("Chart1").Axes(xlValue)
    .Crosses = xlCustom
    .CrossesAt = 3
End With


CSng Function

Description

Converts an expression to a Single.

Syntax

CSng(expression)

The expression argument is any valid numeric or string expression.

Remarks

In general, you can document your code using the data type conversion functions to show that the result of some operation should be expressed as a particular data type rather than the default data type. For example, use CDbl or CSng to force double- or single-precision arithmetic in cases where currency or integer arithmetic normally would occur.

You should use the CSng function instead of Val to provide internationally-aware conversions from any other data type to a Single. For example, different decimal separators are properly recognized depending on the locale setting of your system, as are different thousand separators.

If expression lies outside the acceptable range for the Single data type, an error occurs.

See Also

Data Type Summary.

Example

This example uses the CSng function to convert a value to a Single.

' MyDouble1, MyDouble2 are Doubles.
MyDouble1 = 75.3421115 : MyDouble2 = 75.3421555
MySingle1 = CSng(MyDouble1)    ' MySingle1 contains 75.34211.
MySingle2 = CSng(MyDouble2)    ' MySingle2 contains 75.34216.


CStr Function

Description

Converts an expression to a String.

Syntax

CStr(expression)

The expression argument is any valid numeric or string expression.

Remarks

In general, you can document your code using the data type conversion functions to show that the result of some operation should be expressed as a particular data type rather than the default data type. For example, use CStr to force the result to be expressed as a String.

You should use the CStr function instead of Str to provide internationally-aware conversions from any other data type to a String. For example, different decimal separators are properly recognized depending on the locale setting of your system.

The data in expression determines what is returned according to the following table:

If expression is | CStr returns
Boolean | String containing True or False (translated as appropriate for locale).
Date | String containing a date in the short-date format of your system.
Null | A run-time error.
Empty | A zero-length String ("").
Error | A String containing the word Error (translated as appropriate for locale) followed by the error number.
Other Numeric | A String containing the number.

See Also

Data Type Summary, Str Function.

Example

This example uses the CStr function to convert a numeric value to a String.

MyDouble = 437.324    ' MyDouble is a Double.
MyString = CStr(MyDouble)    ' MyString contains "437.324".


CurDir Function

Description

Returns the current path.

Syntax

CurDir[(drive)]

The drive argument is a string expression that specifies an existing drive. In Microsoft Windows, if no drive is specified or if drive is zero-length (""), CurDir returns the path for the current drive. On the Macintosh, CurDir ignores any drive specified and simply returns the path for the current drive.

See Also

ChDir Statement, ChDrive Statement, MkDir Statement, RmDir Statement.

Example

This example uses the CurDir function to return the current path.

' In Microsoft Windows.
' Assume current path on C Drive is  "C:\WINDOWS\SYSTEM".
' Assume current path on D Drive is "D:\EXCEL".
' Assume C is the current drive.
MyPath = CurDir    ' Returns "C:\WINDOWS\SYSTEM".
MyPath = CurDir("C")    ' Returns "C:\WINDOWS\SYSTEM".
MyPath = CurDir("D")    ' Returns "D:\EXCEL".

' On the Macintosh.
' Drive letters are ignored. Path for current drive is returned.
' Assume current path on HD Drive is  "HD:MY FOLDER".
' Assume HD is the current drive. Drive MD also exists on the machine.
MyPath = CurDir    ' Returns "HD:MY FOLDER".
MyPath = CurDir("HD")    ' Returns "HD:MY FOLDER".
MyPath = CurDir("MD")    ' Returns "HD:MY FOLDER".


Currency Data Type

Description

Currency variables are stored as 64-bit (8-byte) numbers in an integer format, scaled by 10,000 to give a fixed-point number with 15 digits to the left of the decimal point and 4 digits to the right. This representation provides a range of -922,337,203,685,477.5808 to 922,337,203,685,477.5807. The type-declaration character for Currency is @ (character code 64).

The Currency data type is useful for calculations involving money and for fixed-point calculations in which accuracy is particularly important.

See Also

CCur Function, Data Type Summary, Def type Statements, Long Data Type.


CurrentArray Property

Applies To

Range Object.

Description

Accessor. If the specified cell is part of an array, returns a Range object that represents the entire array. Read-only.

See Also

CurrentRegion Property, HasArray Property.

Example

This example assumes that the active cell is A1 on Sheet1 and that the active cell is part of an array that includes cells A1:A10. The example selects cells A1:A10 on Sheet1.

ActiveCell.CurrentArray.Select


CurrentPage Property

Applies To

PivotField Object.

Description

Returns or sets the current page showing for the page field (only valid for page fields). Read-write.

Remarks

To set this property, set it to the name of the page. Set it to "All" to set all pages showing.

Example

This example sets the current page for the PivotTable on Sheet1 to the page named "Canada."

Set pvtTable = Worksheets("Sheet1").Range("A3").PivotTable
pvtTable.PivotFields("Country").CurrentPage = "Canada"


CurrentRegion Property

Applies To

Range Object.

Description

Accessor. Returns a Range object that represents the current region. The current region is a range bounded by any combination of blank rows and blank columns. Read-only.

Remarks

This property is useful for many operations that automatically expand the selection to include the entire current region, such as the AutoFormat method.

See Also

CurrentArray Property.

Example

This example selects the current region on Sheet1.

Worksheets("Sheet1").Activate
ActiveCell.CurrentRegion.Select

This example assumes that you have a table on Sheet1 that has a header row. The example selects the table, without selecting the header row. The active cell must be somewhere in the table before you run the example.

Set tbl = ActiveCell.CurrentRegion
tbl.Offset(1, 0).Resize(tbl.Rows.Count - 1, tbl.Columns.Count).Select


Cursor Property

Applies To

Application Object.

Description

Returns or sets the appearance of the mouse pointer in Microsoft Excel, as listed in the following table. This property is available only in Microsoft Excel for Windows 95. Read-write.

Value | Meaning
xlNormal | The default pointer
xlWait | The hourglass pointer
xlNorthwestArrow | The northwest-arrow pointer
xlIBeam | The I-beam pointer

Remarks

The Cursor property isn't reset automatically when the macro stops running. You should reset the mouse pointer to xlNormal before your macro stops.

Example

This example changes the mouse pointer to an I-beam, pauses, and then changes the pointer to the default pointer.

Sub ChangeCursor()
    Application.Cursor = xlIBeam
    For x = 1 To 1000
        For y = 1 to 1000
        Next y
    Next x
    Application.Cursor = xlNormal
End Sub


CustomDocumentProperties Property

Applies To

Workbook Object.

Description

Returns a DocumentProperties collection object that represents all the custom document properties for the specified workbook. Read-only.

To use this object, you should establish a reference to the Microsoft Office 95 Object Library by using the References command (Tools menu).

Remarks

This property returns the entire collection of custom document properties. Use the Item method to return a single member of the collection (a DocumentProperty object) by specifying either the name of the property or the collection index as a number.

Because the Item method is the default method for the DocumentProperties collection object, the following statements are identical:

CustomDocumentProperties.Item("Title")
CustomDocumentProperties("Title")

Use the BuiltinDocumentProperties property to return the collection of built-in document properties.

Example

This example displays the names and values of the custom document properties as a list on worksheet one.

rw = 1
Worksheets(1).Activate
For Each p In ActiveWorkbook.CustomDocumentProperties
    Cells(rw, 1).Value = p.Name
    Cells(rw, 2).Value = p.Value
    rw = rw + 1
Next


CustomListCount Property

Applies To

Application Object.

Description

Returns the number of defined custom lists (including built-in lists). Read-only.

See Also

AddCustomList Method, DeleteCustomList Method, GetCustomListContents Method, GetCustomListNum Method.

Example

This example displays the number of custom lists currently defined.

MsgBox "There are currently " & Application.CustomListCount & _
    " defined custom lists."


Cut Method

Applies To

Arc Object, Arcs Collection, Button Object, Buttons Collection, ChartObject Object, ChartObjects Collection, CheckBox Object, Drawing Object, DrawingObjects Collection, Drawings Collection, DropDown Object, DropDowns Collection, EditBox Object, EditBoxes Collection, GroupBox Object, GroupBoxes Collection, GroupObject Object, GroupObjects Collection, Label Object, Labels Collection, Line Object, Lines Collection, ListBox Object, ListBoxes Collection, OLEObject Object, OLEObjects Collection, OptionButton Object, OptionButtons Collection, Oval Object, Ovals Collection, Picture Object, Pictures Collection, Range Object, Rectangle Object, Rectangles Collection, ScrollBar Object, ScrollBars Collection, Spinner Object, Spinners Collection, TextBox Object, TextBoxes Collection.

Description

Cuts the object to the Clipboard or to a specified destination.

Syntax

object.Cut(destination)

object

Required. The object to cut.

destination

Optional (used only with Range objects). Specifies the range where the object should be pasted. If omitted, the object is cut to the Clipboard. The destination range must be a single cell or an enlarged multiple of the range to be cut.

Remarks

The cut range must be made up of adjacent cells.

Only embedded charts can be cut.

See Also

Copy Method, Paste Method.

Example

This example cuts the range A1:G37 on Sheet1 and places it on the Clipboard.

Worksheets("Sheet1").Range("A1:G37").Cut


CutCopyMode Property

Applies To

Application Object.

Description

Returns or sets the Cut or Copy mode status, as shown in the following tables. Read-write.

Return value | Description
False | Not in Cut or Copy mode
xlCopy | In Copy mode
xlCut | In Cut mode

Set value | Description
False | Cancels Cut or Copy mode and removes the moving border.
True | Cancels Cut or Copy mode and removes the moving border. On the Macintosh, this also places the contents of the selection in the Macintosh clipboard.

Example

This example uses a message box to display the Cut or Copy mode status.

Select Case Application.CutCopyMode
    Case Is = False
        MsgBox "Not in Cut or Copy mode"
    Case Is = xlCopy
        MsgBox "In Copy mode"
    Case Is = xlCut
        MsgBox "In Cut mode"
End Select


CVar Function

Description

Converts an expression to a Variant.

Syntax

CVar(expression)

The expression argument is any valid numeric or string expression.

Remarks

In general, you can document your code using the data type conversion functions to show that the result of some operation should be expressed as a particular data type rather than the default data type. For example, use CVar to force the result to be expressed as a Variant.

See Also

Data Type Summary.

Example

This example uses the CVar function to convert an expression to a Variant.

MyInt = 4534    ' MyInt is an Integer.
MyVar = CVar(MyInt & "000")    ' MyVar contains 4534000.


CVErr Function

Description

Returns a Variant of subtype Error containing an error number specified by the user.

Syntax

CVErr(errornumber)

The errornumber argument is any valid error number.

Remarks

Use the CVErr function to create user-defined errors in user-created procedures. For example, if you create a function that accepts several arguments and normally returns a string, you can have your function evaluate the input arguments to ensure they are within acceptable range. If they are not, it is likely that your function will not return what you expect. In this event, CVErr allows you to return an error number that tells you what action to take.

Note that implicit conversion of an Error is not allowed. For example, you can't directly assign the return value of CVErr to a non-Variant variable. However, you can perform an explicit conversion (using CInt, CDbl, and so on) of the value returned by CVErr and assign that to a variable of the appropriate data type.

See Also

Data Type Summary, IsError Function.

Example

This example uses the CVErr function to return an Error Variant. The user-defined function CalculateDouble returns an error if the argument passed to it isn't a number. CVErr is useful for returning user-defined errors from user-defined procedures. Use the IsError function to test if the value is an error.

' Define CalculateDouble Function procedure.
Function CalculateDouble(Number)
    If IsNumeric(Number) Then
        CalculateDouble = Number * 2    ' Return result.
    Else
        CalculateDouble = CVErr(2001)    ' Return a user-defined error
    End If    ' number.
End Function

This example inserts the seven cell error values into cells A1:A7 on Sheet1.

myArray = Array(xlErrDiv0, xlErrNA, xlErrName, xlErrNull, _
    xlErrNum, xlErrRef, xlErrValue)
For i = 1 To 7
    Worksheets("Sheet1").Cells(i, 1).Value = CVErr(myArray(i - 1))
Next i

This example displays a message if the active cell on Sheet1 contains a cell error value. You can use this example as a framework for a cell-error-value error handler.

Worksheets("Sheet1").Activate
If IsError(ActiveCell.Value) Then
    errval = ActiveCell.Value
    Select Case errval
        Case CVErr(xlErrDiv0)
            MsgBox "#DIV/0! error"
        Case CVErr(xlErrNA)
            MsgBox "#N/A error"
        Case CVErr(xlErrName)
            MsgBox "#NAME? error"
        Case CVErr(xlErrNull)
            MsgBox "#NULL! error"
        Case CVErr(xlErrNum)
            MsgBox "#NUM! error"
        Case CVErr(xlErrRef)
            MsgBox "#REF! error"
        Case CVErr(xlErrValue)
            MsgBox "#VALUE! error"
        Case Else
            MsgBox "This should never happen!!"
    End Select
End If


Data Type Summary

The following table shows the supported data types, including their storage sizes and ranges.

Data type | Storage size | Range
Boolean | 2 bytes | True or False.
Integer | 2 bytes | -32,768 to 32,767.
Long (long integer) | 4 bytes | -2,147,483,648 to 2,147,483,647.
Single (single-precision floating-point) | 4 bytes | -3.402823E38 to -1.401298E-45 for negative values; 1.401298E-45 to 3.402823E38 for positive values.
Double (double-precision floating-point) | 8 bytes | -1.79769313486232E308 to -4.94065645841247E-324 for negative values; 4.94065645841247E-324 to 1.79769313486232E308 for positive values.
Currency (scaled integer) | 8 bytes | -922,337,203,685,477.5808 to 922,337,203,685,477.5807.
Date | 8 bytes | January 1, 100 to December 31, 9999.
Object | 4 bytes | Any Object reference.
String | 1 byte per character | 0 to approximately 2 billion (approximately 65,535 for Microsoft Windows version 3.1 and earlier).
Variant | 16 bytes + 1 byte for each character | Any numeric value up to the range of a Double or any character text.
User-defined (using Type) | Number required by elements | The range of each element is the same as the range of its data type.

See Also

Boolean Data Type, Currency Data Type, Date Data Type, Def type Statements, Double Data Type, Integer Data Type, Long Data Type, Object Data Type, Single Data Type, String Data Type, Type Statement, Variant Data Type.


DataBodyRange Property

Applies To

PivotTable Object.

Description

Accessor. Returns a Range object that represents the range that contains the PivotTable data area. Read-only.

See Also

ColumnRange Property, DataLabelRange Property, PageRange Property, RowRange Property.

Example

This example selects the active PivotTable data.

Worksheets("Sheet1").Activate
Range("A3").Select
ActiveCell.PivotTable.DataBodyRange.Select


DataEntryMode Property

Applies To

Application Object.

Description

Returns or sets Data Entry mode, as shown in the following table. When in Data Entry mode, you can enter data only in the unlocked cells of the currently selected range. Read-write.

Value | Meaning
xlOn | Data Entry mode on.
xlOff | Data Entry mode off.
xlStrict | Data Entry mode on, and ESC will not exit the Data Entry mode.

Example

This example turns the Data Entry mode off if it is on.

If (Application.DataEntryMode = xlOn) Or _
    (Application.DataEntryMode = xlStrict) Then
        Application.DataEntryMode = xlOff
End If


DataFields Method

Applies To

PivotTable Object.

Description

Accessor. Returns an object that represents a single pivot field (a PivotField object, Syntax 1) or a collection of the pivot fields (a PivotFields object, Syntax 2) which are currently showing as data fields. Read-only.

Syntax 1

object.DataFields(index)

Syntax 2

object.DataFields

object

Required. The PivotTable object.

index

Required for Syntax 1. The name or number of the pivot field to return (can be an array to specify more than one).

See Also

ColumnFields Method, HiddenFields Method, PageFields Method, PivotFields Method, RowFields Method, VisibleFields Method.

Example

This example adds the PivotTable data field names to a list box. The list box appears on Sheet1.

Set pvtTable = Worksheets("Sheet1").Range("A3").PivotTable
Set newListBox = Worksheets("Sheet1").ListBoxes.Add _
    (Left:=10, Top:=72, Width:=144, Height:=144)
For Each dtaField In pvtTable.DataFields
    newListBox.AddItem (dtaField.Name)
Next dtaField
Worksheets("Sheet1").Activate


DataLabel Object

Description

Represents the data label on a chart point or trendline.

Accessors

For a series, the data labels for all points on the series are contained in a DataLabels collection. For a series without definable points (such as an area series), the DataLabels collection contains a single data label. To access a single member of the collection, use the DataLabels method with the data label index number as an argument. The following example sets the number format for data label five of series one in embedded chart one on worksheet one.

Worksheets(1).ChartObjects(1).Chart _
    .SeriesCollection(1).DataLabels(5).NumberFormat = "0.000"

The DataLabel property returns the data label for a single point. The following example turns on the data label for point two on series one on the chart sheet named "Chart1" and sets the data label text to "Saturday".

With Charts("chart1")
    With .SeriesCollection(1).Points(2)
        .HasDataLabel = True
        .DataLabel.Text = "Saturday"
    End With
End With

On a trendline, the DataLabel property returns the text shown with the trendline. This can be the equation, the R-squared value, or both (if both are showing). The following example sets the trendline text to show only the equation and then places the data label text in cell A1 on the worksheet named "Sheet1."

With Charts("chart1").SeriesCollection(1).Trendlines(1)
    .DisplayRSquared = False
    .DisplayEquation = True
    Worksheets("sheet1").Range("a1").Value = .DataLabel.Text
End With

Properties

Application Property, AutoText Property, Border Property, Caption Property, Creator Property, Font Property, HorizontalAlignment Property, Interior Property, Left Property, Name Property, NumberFormat Property, NumberFormatLinked Property, Orientation Property, Parent Property, Shadow Property, ShowLegendKey Property, Text Property, Top Property, Type Property, VerticalAlignment Property.

Methods

Characters Method, Delete Method, Select Method.


DataLabel Property

Applies To

Point Object, Trendline Object.

Description

Accessor. Returns a DataLabel object that represents the data label associated with the point or trendline. Read-only.

See Also

ApplyDataLabels Method, HasDataLabel Property.

Example

This example turns on the data label for point seven in series three in Chart1, and then it sets the data label color to blue.

With Charts("Chart1").SeriesCollection(3).Points(7)
    .HasDataLabel = True
    .ApplyDataLabels type:=xlValue
    .DataLabel.Font.ColorIndex = 5
End With


DataLabelRange Property

Applies To

PivotTable Object.

Description

Accessor. Returns a Range object that represents the range that contains the PivotTable data field labels. Read-only.

See Also

ColumnRange Property, DataBodyRange Property, PageRange Property, RowRange Property.

Example

This example selects the data field labels in the PivotTable.

Worksheets("Sheet1").Activate
Range("A3").Select
ActiveCell.PivotTable.DataLabelRange.Select


DataLabels Collection Object

Description

A collection of all the DataLabel objects for the specified series. Each DataLabel object represents a data label for a point or trendline. For a series without definable points (such as an area series), the DataLabels collection contains a single data label.

Accessors

Use the DataLabels method with an argument to access a single member of the collection or without an argument to access the entire collection at once. The following example sets the number format for all data labels on series one.

With Worksheets("sheet5").ChartObjects(1).Chart.SeriesCollection(1)
    .HasDataLabels = True
    .DataLabels.NumberFormat = "0.00"
End With

Properties

Application Property, AutoText Property, Border Property, Count Property, Creator Property, Font Property, HorizontalAlignment Property, Interior Property, Name Property, NumberFormat Property, NumberFormatLinked Property, Orientation Property, Parent Property, Shadow Property, ShowLegendKey Property, Type Property, VerticalAlignment Property.

Methods

Delete Method, Item Method, Select Method.


DataLabels Method

Applies To

Series Object.

Description

Accessor. Returns an object that represents a single data label (a DataLabel object, Syntax 1) or a collection of all data labels for the series (a DataLabels collection, Syntax 2).

Syntax 1

object.DataLabels(index)

Syntax 2

object.DataLabels

object

Required. The Series object.

index

Required for Syntax 1. The number of the data label.

Remarks

If the series has the Show Value option on for the data labels, the returned collection can contain up to one label for each point. Data labels can be turned on or off for individual points in the series.

If the series is on an area chart and has the Show Label option on for the data labels, the returned collection contains only a single label, which is the label for the area series.

See Also

DataLabel Property.

Example

This example sets the data labels for series one in Chart1 to show their key, assuming that their values are showing when the example runs.

With Charts("Chart1").SeriesCollection(1)
    .HasDataLabels = True
    With .DataLabels
        .ShowLegendKey = True
        .Type = xlValue
    End With
End With


DataRange Property

Applies To

PivotField Object, PivotItem Object.

Description

Accessor. Returns a Range object as shown in the following table. Read-only.

Object | DataRange
Data field | Data contained in the field
Row, Column, or Page field | Items in the field
Item | Data qualified by the item

Example

This example selects the pivot items in the field named "REGION."

Set pvtTable = Worksheets("Sheet1").Range("A3").PivotTable
Worksheets("Sheet1").Activate
pvtTable.PivotFields("REGION").DataRange.Select


DataSeries Method

Applies To

Range Object.

Description

Creates a data series in the range.

Syntax

object.DataSeries(rowcol, type, date, step, stop, trend)

object

Required. The range where the data series will be created.

rowcol

Optional. Can be xlRows or xlColumns to enter the data series in rows or columns, respectively. If omitted, the size and shape of the range is used.

type

Optional. Can be xlLinear, xlGrowth, xlChronological, or xlAutoFill. If omitted, it is xlLinear.

date

Optional. If the type argument is xlChronological, this indicates the date unit by which to step, either xlDay, xlWeekday, xlMonth, or xlYear. If omitted, it is xlDay.

step

Optional. The step value for the series. If omitted, it is assumed to be 1.

stop

Optional. The stop value for the series. If omitted, the method fills to the end of the range.

trend

Optional. If True, the method creates a linear or growth type of trend. If False or omitted, the method creates a standard data series.

Example

This example creates a series of 12 dates. The series contains the last day of every month in 1996 and is created in the range A1:A12 on Sheet1.

Set dateRange = Worksheets("Sheet1").Range("A1:A12")
Worksheets("Sheet1").Range("A1").Formula = "31-JAN-1996"
dateRange.DataSeries Type:=xlChronological, Date:=xlMonth


DataType Property

Applies To

PivotField Object.

Description

Returns a constant describing the type of data in the pivot field. Can be xlText, xlNumber, or xlDate. Read-only.

Example

This example displays the data type of the field named "ORDER_DATE."

Set pvtTable = Worksheets("Sheet1").Range("A3").PivotTable
Select Case pvtTable.PivotFields("ORDER_DATE").DataType
    Case Is = xlText
        MsgBox "The field contains text data"
    Case Is = xlNumber
        MsgBox "The field contains numeric data"
    Case Is = xlDate
        MsgBox "The field contains date data"
End Select


Date Data Type

Description

Date variables are stored as 64-bit (8-byte) numbers that represent dates ranging from 1 January 100 to 31 December 9999 and times from 0:00:00 to 23:59:59. Any recognizable literal date values can be assigned to Date variables. Literal dates must be enclosed within number sign characters (#). For example, #January 1, 1993# or #1 Jan 93#.

Date variables display dates according to the short date format recognized by your computer. Times display according to the time format (either 12- or 24-hour) recognized by your computer.

When other numeric data types are converted to Date, values to the left of the decimal represent date information while values to the right of the decimal represent time. Midnight is 0 and midday is .5. Negative whole numbers represent dates before 30 December 1899. When Date variables are converted to other numeric data types, they appear only as numbers.

See Also

CDate Function, Data Type Summary, Def type Statements, Double Data Type, Variant Data Type.


Date Function

Description

Returns the current system date.

Syntax

Date

Remarks

To set the system date, use the Date statement.

See Also

CDate Function, Date Statement, Format Function, Now Function, Time Function, Time Statement.

Example

This example uses the Date function to return the current system date.

MyDate = Date    ' MyDate contains current system date.


Date Statement

Description

Sets the current system date.

Syntax

Date = date

For MS-DOS computers, the date argument must be a date from January 1, 1980 through December 31, 2099, or an error occurs. For the Macintosh, date must be a date from January 1, 1904 through December 31, 2040. For all other systems, date is limited to dates from January 1, 100 through December 31, 9999.

Remarks

Note

If you use the Date statement to set the date on computers using versions of MS-DOS earlier than version 3.3, the change remains in effect only until you change it again or turn off your computer. Many computers have a battery-powered CMOS RAM that retains date and time information when the computer is turned off. However, to permanently change the date on computers running earlier versions of MS-DOS, you may have to use your Setup disk or perform some equivalent action. Refer to the documentation for your particular system.

See Also

Date Function, Time Function, Time Statement.

Example

This example uses the Date statement to set the computer system date.

' In the development environment, the date literal will display in short
' format using the locale settings of your code.
MyDate = #February 12, 1985#    ' Assign a date.
Date = MyDate    ' Change system date.


Date1904 Property

Applies To

Workbook Object.

Description

True if this workbook uses the 1904 date system. Read-write.

Example

This example causes Microsoft Excel to use the 1904 date system for the active workbook.

ActiveWorkbook.Date1904 = True


DateSerial Function

Description

Returns a date for a specified year, month, and day.

Syntax

DateSerial(year,month,day)

The DateSerial function syntax has these named-argument parts:

Part | Description
year | Number between 100 and 9999, inclusive, or a numeric expression.
month | Number between 1 and 12, inclusive, or a numeric expression.
day | Number between 1 and 31, inclusive, or a numeric expression.

Remarks

To specify a date, such as December 31, 1991, the range of numbers for each DateSerial argument should be in the normally accepted range for the unit; that is; 1-31 for days and 1-12 for months. However, you can also specify relative dates for each argument using any numeric expression that represents some number of days, months, or years before or after a certain date.

The following example uses numeric expressions instead of absolute date numbers. Here the DateSerial function returns a date that is the day before the first day (1 - 1) of two months before August (8 - 2) of 10 years before 1990 (1990 - 10); in other words, May, 31, 1980.

DateSerial(1990 - 10, 8 - 2, 1 - 1)

For the year argument, values between 0 and 99, inclusive, are interpreted as the years 1900-1999. For all other year arguments, use a complete four-digit year (for example, 1800).

If the date specified by the three arguments, either directly or by expression, falls outside the acceptable range of dates, an error occurs.

See Also

Date Function, Date Statement, DateValue Function, Day Function, Month Function, Now Function, TimeSerial Function, TimeValue Function, Weekday Function, Year Function.

Example

This example uses the DateSerial function to return the date for the specified year, month and day.

' MyDate contains the date for February 12, 1969.
MyDate = DateSerial(1969, 2, 12)    ' Return a date.


DateValue Function

Description

Returns a date.

Syntax

DateValue(date)

The date named argument is normally a string expression representing a date from January 1, 100 through December 31, 9999. However, date can also be any expression that can represent a date, a time, or both a date and time, in that range.

Remarks

If the date argument includes time information, DateValue doesn't return it. However, if date includes invalid time information (such as "89:98"), an error occurs.

If date is a string that includes only numbers separated by valid date separators, DateValue recognizes the order for month, day, and year according to the Short Date format you specified for your system. DateValue also recognizes unambiguous dates that contain month names, either in long or abbreviated form. For example, in addition to recognizing 12/30/1991 and 12/30/91, DateValue also recognizes December 30, 1991 and Dec 30, 1991.

If the year part of date is omitted, DateValue uses the current year from your computer's system date.

See Also

CDate Function, Date Function, Date Statement, DateSerial Function, Day Function, Month Function, Now Function, TimeSerial Function, TimeValue Function, Weekday Function, Year Function.

Example

This example uses the DateValue function to convert a string to a date. In general, it is bad programming practice to hard code dates/times as strings as shown in this example. Use date literals instead.

MyDate = DateValue("February 12, 1969")    ' Return a date.


Day Function

Description

Returns a whole number between 1 and 31, inclusive, representing the day of the month.

Syntax

Day(date)

The date named argument is limited to a date or numbers and strings, in any combination, that can represent a date. If date contains no valid data, Null is returned.

See Also

Date Function, Date Statement, Hour Function, Minute Function, Month Function, Now Function, Second Function, Weekday Function, Year Function.

Example

This example uses the Day function to obtain the day of the month from a specified date.

' In the development environment, the date literal will display in short
' format using the locale settings of your code.
MyDate = #February 12, 1969#    ' Assign a date.
MyDay = Day(MyDate)    ' MyDay contains 12.


DDEAppReturnCode Property

Applies To

Application Object.

Description

Returns the application-specific DDE return code that was contained in the last DDE acknowledge message received by Microsoft Excel. Read-only.

Example

This example sets the variable appErrorCode to the DDE return code.

appErrorCode = Application.DDEAppReturnCode


DDEExecute Method

Applies To

Application Object.

Description

Runs a command or takes other actions in another application via the specified DDE channel.

Syntax

object.DDEExecute(channel, string)

object

Optional. The Application object.

channel

Required. The channel number returned by the DDEInitiate method.

string

Required. The message defined in the receiving application.

Remarks

The DDEExecute method is designed to send commands to another application. You can also use it to send keystrokes to an application, although the SendKeys method is the preferred way to send keystrokes. The string argument can specify any single key; any key combined with ALT, CTRL, or SHIFT, or any combination of those keys (in Windows); or any key combined with COMMAND, CTRL, OPTION, or SHIFT or any combination of those keys (on the Macintosh). Each key is represented by one or more characters, such as "a" for the character a, or "{ENTER}" for the ENTER key.

To specify characters that aren't displayed when you press the key, such as ENTER or TAB, use the codes shown in the following table. Each code in the table represents one key on the keyboard.

Key | Code
BACKSPACE | "{BACKSPACE}" or "{BS}"
BREAK | "{BREAK}"
CAPS LOCK | "{CAPSLOCK}"
CLEAR | "{CLEAR}"
DELETE or DEL | "{DELETE}" or "{DEL}"
DOWN ARROW | "{DOWN}"
END | "{END}"
ENTER (numeric keypad) | "{ENTER}"
ENTER | "~" (tilde)
ESC | "{ESCAPE} or {ESC}"
HELP | "{HELP}"
HOME | "{HOME}"
INS | "{INSERT}"
LEFT ARROW | "{LEFT}"
NUM LOCK | "{NUMLOCK}"
PAGE DOWN | "{PGDN}"
PAGE UP | "{PGUP}"
RETURN | "{RETURN}"
right ARROW | "{RIGHT}"
SCROLL LOCK | "{SCROLLLOCK}"
TAB | "{TAB}"
UP ARROW | "{UP}"
F1 through F15 | "{F1}" through "{F15}"

In Windows, you can also specify keys combined with SHIFT and/or CTRL and/or ALT. On the Macintosh, you can also specify keys combined with SHIFT and/or CTRL and/or OPTION and/or COMMAND. To specify a key combined with another key or keys, use the following table.

To combine with | Precede the key code by
SHIFT | "+" (plus sign)
CTRL | "^" (caret)
ALT or OPTION | "%" (percent sign)
COMMAND | "*" (asterisk)

Example

This example opens a channel to Word 6.0 for Windows, opens the Word document FORMLETR.DOC, and then sends the FilePrint command to WordBasic.

channelNumber = Application.DDEInitiate( _
    app:="WinWord", _
    topic:="C:\WINWORD\FORMLETR.DOC")
Application.DDEExecute channelNumber, "[FILEPRINT]"
Application.DDETerminate channelNumber

This example opens a channel to Word 6.0 for the Macintosh, opens the Word document Form Letter, and then sends the FilePrint command to WordBasic. On the Macintosh, you must use the Shell function to start Word, because the DDEInitiate method does not automatically start Word as it does in Windows. Also, because the Shell function is asynchronous, the macro may call the DDEInitiate method before Word has started. This example demonstrates how you can program around this by putting the DDEInitiate method call in a loop, testing channelNumber until it is no longer an error.

Shell "HD:Form Letter", 6
Do
    channelNumber = Application.DDEInitiate( _
        app:="MSWord", _
        topic:="HD:Form Letter")
Loop Until TypeName(channelNumber) <> "Error"
Application.DDEExecute channelNumber, "[FILEPRINT]"
Application.DDETerminate channelNumber


DDEInitiate Method

Applies To

Application Object.

Description

Opens a DDE channel to an application.

Syntax

object.DDEInitiate(app, topic)

object

Optional. The Application object.

app

Required. A string containing the application name.

topic

Required. A string that describes something in the application to which you are opening a channel, usually a document of that application.

Remarks

If successful, the DDEInitiate method returns the number of the open channel. All subsequent DDE functions use this number to specify the channel.

Example

This example opens a channel to Word 6.0 for Windows, opens the Word document FORMLETR.DOC, and then sends the FilePrint command to WordBasic.

channelNumber = Application.DDEInitiate( _
    app:="WinWord", _
    topic:="C:\WINWORD\FORMLETR.DOC")
Application.DDEExecute channelNumber, "[FILEPRINT]"
Application.DDETerminate channelNumber

This example opens a channel to Word 6.0 for the Macintosh, opens the Word document Form Letter, and then sends the FilePrint command to WordBasic. On the Macintosh, you must use the Shell function to start Word, because the DDEInitiate method does not automatically start Word as it does in Windows. Also, because the Shell function is asynchronous, the macro may call the DDEInitiate method before Word has started. This example demonstrates how you can program around this by putting the DDEInitiate method call in a loop, testing channelNumber until it is no longer an error.

Shell "HD:Form Letter", 6
Do
    channelNumber = Application.DDEInitiate( _
        app:="MSWord", _
        topic:="HD:Form Letter")
Loop Until TypeName(channelNumber) <> "Error"
Application.DDEExecute channelNumber, "[FILEPRINT]"
Application.DDETerminate channelNumber


DDEPoke Method

Applies To

Application Object.

Description

Sends data to an application.

Syntax

object.DDEPoke(channel, item, data)

object

Optional. The Application object.

channel

Required. The channel number returned by the DDEInitiate method.

item

Required. The item to which the data is to be sent.

data

Required. The data to send to the application.

Remarks

An error occurs if the method call is not successful.

Example

This example opens a channel to Word 6.0 for Windows, opens the Word document SALES.DOC, and then inserts the contents of cell A1 (on Sheet1) at the beginning of the document.

channelNumber = Application.DDEInitiate( _
    app:="WinWord", _
    topic:="C:\WINWORD\SALES.DOC")
Set rangeToPoke = Worksheets("Sheet1").Range("A1")
Application.DDEPoke channelNumber, "\StartOfDoc", rangeToPoke
Application.DDETerminate channelNumber

This example opens a channel to Word 6.0 for the Macintosh, opens the Word document Sales Report, and then inserts the contents of cell A1 (on Sheet1) at the beginning of the document. On the Macintosh, you must use the Shell function to start Word, because the DDEInitiate method does not automatically start Word as it does in Windows. Also, because the Shell function is asynchronous, the macro may call the DDEInitiate method before Word has started. This example demonstrates how you can program around this by putting the DDEInitiate method call in a loop, testing channelNumber until it is no longer an error.

Shell "HD:Sales Report", 6
Do
    channelNumber = Application.DDEInitiate( _
        app:="WinWord", _
        topic:="HD:Sales Report")
Loop Until TypeName(channelNumber) <> "Error"
Set rangeToPoke = Worksheets("Sheet1").Range("A1")
Application.DDEPoke channelNumber, "\StartOfDoc", rangeToPoke
Application.DDETerminate channelNumber


DDERequest Method

Applies To

Application Object.

Description

Requests information from the specified application. This method always returns an array; for more information, see the example.

Syntax

object.DDERequest(channel, item)

object

Optional. The Application object.

channel

Required. The channel number returned by the DDEInitiate method.

item

Required. The item to request.

Example

This example opens a channel to the System topic in Word 6.0 for Windows and then uses the Topics item to return a list of all open documents. The list is returned in column A on Sheet1.

channelNumber = Application.DDEInitiate( _
    app:="WinWord", _
    topic:="System")
returnList = Application.DDERequest(channelNumber, "Topics")
For i = LBound(returnList) To UBound(returnList)
    Worksheets("Sheet1").Cells(i, 1).Formula = returnList(i)
Next i
Application.DDETerminate channelNumber

This example opens a channel to the System topic in Word 6.0 for the Macintosh and then uses the Topics item to return a list of all open documents. The list is returned in column A on Sheet1. On the Macintosh, you must use the Shell function to start Word, because the DDEInitiate method does not automatically start Word as it does in Windows. Also, because the Shell function is asynchronous, the macro may call the DDEInitiate method before Word has started. This example demonstrates how you can program around this by putting the DDEInitiate method call in a loop, testing channelNumber until it is no longer an error.

Shell MacID("MSWD"), 6
Do
    channelNumber = Application.DDEInitiate( _
        app:="MSWord", _
        topic:="System")
Loop Until TypeName(channelNumber) <> "Error"
returnList = Application.DDERequest(channelNumber, "Topics")
For i = LBound(returnList) To UBound(returnList)
    Worksheets("Sheet1").Cells(i, 1).Formula = returnList(i)
Next i
Application.DDETerminate channelNumber


DDETerminate Method

Applies To

Application Object.

Description

Closes a channel to another application.

Syntax

object.DDETerminate(channel)

object

Optional. The Application object.

channel

Required. The channel number returned by the DDEInitiate method.

Example

This example opens a channel to Word 6.0 for Windows, opens the Word document FORMLETR.DOC, and then sends the FilePrint command to WordBasic.

channelNumber = Application.DDEInitiate( _
    app:="WinWord", _
    topic:="C:\WINWORD\FORMLETR.DOC")
Application.DDEExecute channelNumber, "[FILEPRINT]"
Application.DDETerminate channelNumber

This example opens a channel to Word 6.0 for the Macintosh, opens the Word document Form Letter, and then sends the FilePrint command to WordBasic. On the Macintosh, you must use the Shell function to start Word, because the DDEInitiate method does not automatically start Word as it does in Windows. Also, because the Shell function is asynchronous, the macro may call the DDEInitiate method before Word has started. This example demonstrates how you can program around this by putting the DDEInitiate method call in a loop, testing channelNumber until it is no longer an error.

Shell "HD:Form Letter", 6
Do
    channelNumber = Application.DDEInitiate( _
        app:="MSWord", _
        topic:="HD:Form Letter")
Loop Until TypeName(channelNumber) <> "Error"
Application.DDEExecute channelNumber, "[FILEPRINT]"
Application.DDETerminate channelNumber


Debug Object

Description

The Debug object is accessed with the keyword Debug, and is used to send output to the Debug window at run time.

Methods

Print Method


Declare Statement

Description

Used at module level to declare references to external procedures in a dynamic-link library (DLL) or Macintosh code resource.

Syntax 1

[Public | Private ] Declare Sub name [CDecl] Lib "libname" [Alias "aliasname" ][([arglist])]

Syntax 2

[Public | Private ] Declare Function name [CDecl] Lib "libname" [Alias "aliasname" ] [([arglist])][As type]

The Declare statement syntax has these parts:

Part | Description
Public | Used to declare procedures that are available to all other procedures in all modules.
Private | Used to declare procedures that are available only within the module where the declaration is made.
Sub | Indicates that the procedure doesn't return a value.
Function | Indicates that the procedure returns a value that can be used in an expression.
name | Any valid procedure name.
CDecl | For the Macintosh only. Indicates that the procedure uses C language argument order, naming conventions, and calling conventions.
Lib | Indicates that a DLL or code resource contains the procedure being declared. The Lib clause is required for all declarations.
libname | Name of the DLL or code resource that contains the declared procedure.
Alias | Indicates that the procedure being called has another name in the DLL or is in a Macintosh code resource. This is useful when the external procedure name is the same as a keyword. You can also use Alias when a DLL procedure has the same name as a Public variable or constant or any other procedure in the same scope. Alias is also useful if any characters in the DLL procedure name aren't allowed in names.
aliasname | Name of the procedure in the DLL or code resource.
 | In Microsoft Windows, if the first character is not a #, aliasname is the name of the procedure's entry point in the DLL. If # is the first character, all characters that follow must indicate the ordinal number of the procedure's entry point.
 | On the Macintosh, the syntax to specify the code resource type is as follows:
 | "[resourcetype]$[resourcename]"
 | The resourcetype is any valid 4-character constant. If omitted, the default resourcetype is CODE. The resourcename is the procedure name in the code resource. If resourcename is omitted, it is assumed to be the same as name.
arglist | List of variables representing arguments that are passed to the procedure when it is called.
type | Data type of the value returned by a Function procedure; may be Boolean, Integer, Long, Currency, Single, Double, Date, String (variable length only), Object, Variant, a user-defined type, or an object type.

The arglist argument has the following syntax and parts:

[Optional][ByVal | ByRef][ParamArray] varname[( )][As type]

Part | Description
Optional | Indicates that an argument is not required. If used, all subsequent arguments in arglist must also be optional and declared using the Optional keyword. All Optional arguments must be Variant. Optional can't be used for any argument if ParamArray is used.
ByVal | Indicates that the argument is passed by value.
ByRef | Indicates that the argument is passed by reference.
ParamArray | Used only as the last argument in arglist to indicate that the final argument is an Optional array of Variant elements. The ParamArray keyword allows you to provide an arbitrary number of arguments. May not be used with ByVal, ByRef, or Optional.
varname | Name of the variable representing the argument being passed to the procedure; follows standard variable naming conventions.
type | Data type of the argument passed to the procedure; may be Boolean, Integer, Long, Currency, Single, Double, Date, String (variable length only), Object, Variant, a user-defined type, or an object type.

Remarks

For Function procedures, the data type of the procedure determines the data type it returns. You can use an As clause following the arglist to specify the return type of the function. Within arglist you can use an As clause to specify the data type of any of the arguments passed to the procedure. In addition to specifying any of the standard data types, you can specify As Any in the arglist to inhibit type checking and allow any data type to be passed to the procedure.

Empty parentheses indicate that the Sub or Function procedure has no arguments and that arguments should be checked to ensure that none are passed. In the following example, First takes no arguments. If you use arguments in a call to First, an error occurs:

Declare Sub First Lib "MyLib" ()

If you include an argument list, the number and type of arguments are checked each time the procedure is called. In the following example, First takes one Long argument:

Declare Sub First Lib "MyLib" (X As Long)

Note

You can't have fixed-length strings in the argument list of a Declare statement because only variable-length strings can be passed to procedures. Fixed-length strings can appear as procedure arguments, but they are converted to variable-length strings before being passed.

See Also

Call Statement.

Example

This example shows how the Declare statement is used at the module level to declare a reference to an external procedure in a dynamic-link library (DLL) or Macintosh code resource.

' In Microsoft Windows.
Declare Sub MessageBeep Lib "User" (ByVal N As Integer)

' On the Macintosh.
Declare Sub MessageAlert Lib "MyHd:MyAlert" Alias "MyAlert" (ByVal N _
As Integer)


DefaultButton Property

Applies To

Button Object, Buttons Collection, DialogSheet Object, DrawingObjects Collection.

Description

For Button objects, this property is True if the button is the default button for a user-defined dialog box. When the user presses the ENTER key, the default button is selected, and Microsoft Excel runs the macro identified by the button's OnAction property. Applies only to buttons on a dialog sheet. Read-write.

For DialogSheet objects, this property is the name of the button that is the default button while a dialog box is running. Read-write.

Remarks

When the dialog box is not displayed, this property can be used with the Button object to return or set the initial default button (the default button when the dialog is first displayed). Only one button on the dialog box can be the default button. Setting this property resets the property for all other buttons on the dialog sheet.

While the dialog box is running, use this property in an event procedure to return or set the current default button. In this case, the property is the button ID as a string, and the property is applied to the DialogSheet object. You cannot apply this property to a Button object while the dialog box is running.

See Also

CancelButton Property.

Example

This example sets button four to be the initial default button for Dialog1. You can only set the initial default button when the dialog box is not running.

DialogSheets("Dialog1").Buttons(4).DefaultButton = True

This example sets button five to be the current default button on Dialog1. You can only set the current default button while the dialog box is running (which means that this example must be in an event procedure for another control on Dialog1).

With DialogSheets("Dialog1")
    .DefaultButton = .Buttons(5).Name
End With


DefaultFilePath Property

Applies To

Application Object.

Description

Returns or sets the default path Microsoft Excel uses when it opens files. Read-write.

Example

This example displays the current default file path.

MsgBox "The current default file path is " & _
    Application.DefaultFilePath


Deftype Statements

Description

Used at module level to set the default data type for variables and Function procedures whose names start with the specified characters.

Syntax

DefBool letterrange[,letterrange] . . .

DefInt letterrange[,letterrange] . . .

DefLng letterrange[,letterrange] . . .

DefCur letterrange[,letterrange] . . .

DefSng letterrange[,letterrange] . . .

DefDbl letterrange[,letterrange] . . .

DefDate letterrange[,letterrange] . . .

DefStr letterrange[,letterrange] . . .

DefObj letterrange[,letterrange] . . .

DefVar letterrange[,letterrange] . . .

The argument letterrange has the following syntax:

letter1[-letter2]

The arguments letter1 and letter2 specify the name range for which you can set a default data type. Each argument represents the first letter of the variable or Function procedure name and can be any letter of the alphabet. The case of letters in letterrange isn't significant.

Remarks

The statement name determines the data type:

Statement | Data Type
DefBool | Boolean
DefInt | Integer
DefLng | Long
DefCur | Currency
DefSng | Single
DefDbl | Double
DefDate | Date
DefStr | String
DefObj | Object
DefVar | Variant

For example, in the following program fragment, Message is a string variable:

DefStr A-Q
. . .
Message = "Out of stack space."

A Def type statement affects only the module where it is used. For example, a DefInt statement in one module affects only the default data type of variables and Function procedures declared in that module; the default data type of variables in other modules is unaffected. If not explicitly declared with a Def type statement, the default data type for all variables and all Function procedures is Variant.

When you specify a letter range, it usually defines the data type for variables that begin with letters in the lower 128 characters of the character set. However, when you specify the letter range A-Z, you set the default to the specified data type for all variables, including any that begin with international characters from the extended part of the character set (128-255).

Once the range A-Z has been specified, you can't further redefine any subranges of variables using Def type statements. In fact, once a range has been specified, if you include a previously defined letter in another Def type statement, an error occurs. However, you can explicitly specify the data type of any variable, defined or not, using a Dim statement with an As type clause. For example, you can use the following code at module level to define a variable as a Double even though the default data type is Integer:

DefInt A-Z
Dim TaxRate As Double

Def type statements don't affect elements of user-defined types since they must be explicitly declared.

See Also

Let Statement.

Example

This example shows various uses of the Def type statements to set default data types of variables and function procedures whose names start with specified characters. The default data type can be overridden only by explicit assignment using the Dim statement. Def type statements can only be used at the module-level.

' Variable names beginning with A through K default to Integer.
DefInt A-K
' Variable names beginning with L through Z default to String.
DefStr L-Z
CalcVar = 4    ' Initialize Integer.
StringVar = "Hello there"    ' Initialize String.
AnyVar = "Hello"     ' Causes "Type mismatch" error.
Dim Calc As Double    ' Explicitly set the type to Double.
Calc = 2.3455    ' Assign a Double.

' Deftype statements also apply to function procedures.
CalcNum = ATestFunction(4)    ' Call user-defined function.

' ATestFunction function procedure definition.
Function ATestFunction(INumber)
    ATestFunction = INumber * 2    ' Return value is an integer.
End Function


Delete Method

Applies To

Arc Object, Arcs Collection, Axis Object, AxisTitle Object, Button Object, Buttons Collection, Characters Object, Chart Object, ChartObject Object, ChartObjects Collection, Charts Collection, ChartTitle Object, CheckBox Object, DataLabel Object, DataLabels Collection, DialogSheet Object, DialogSheets Collection, DownBars Object, Drawing Object, DrawingObjects Collection, Drawings Collection, DropDown Object, DropDowns Collection, DropLines Object, EditBox Object, EditBoxes Collection, ErrorBars Object, Gridlines Object, GroupBox Object, GroupBoxes Collection, GroupObject Object, GroupObjects Collection, HiLoLines Object, Label Object, Labels Collection, Legend Object, LegendEntry Object, LegendKey Object, Line Object, Lines Collection, ListBox Object, ListBoxes Collection, Menu Object, MenuBar Object, MenuItem Object, Module Object, Modules Collection, Name Object, OLEObject Object, OLEObjects Collection, OptionButton Object, OptionButtons Collection, Oval Object, Ovals Collection, Picture Object, Pictures Collection, Point Object, Range Object, Rectangle Object, Rectangles Collection, Scenario Object, ScrollBar Object, ScrollBars Collection, Series Object, SeriesLines Object, Sheets Collection, SoundNote Object, Spinner Object, Spinners Collection, Style Object, TextBox Object, TextBoxes Collection, TickLabels Object, Toolbar Object, ToolbarButton Object, Trendline Object, UpBars Object, Worksheet Object, Worksheets Collection.

Description

Deletes the object. Syntax 2 applies only to Range objects.

Syntax 1

object.Delete

Syntax 2

object.Delete(shift)

object

Required. The object to which this method applies. Syntax 2 applies only to Range objects.

shift

Optional. Specifies how to shift cells to replace the deleted cells (either xlToLeft, or xlUp). If this argument is omitted, Microsoft Excel selects a default based on the shape of the range.

Remarks

Attempts to delete a built-in Toolbar or MenuBar object will fail, but will not cause an error. This allows you to use a For Each loop to delete all custom tool bars or menu bars.

Deleting a Point or LegendKey deletes the entire series.

You can delete custom document properties, but you cannot delete a built-in document property.

Example

This example deletes cells A1:D10 on Sheet1, and shifts remaining cells to the left.

Worksheets("Sheet1").Range("A1:D10").Delete shift:=xlToLeft

This example deletes oval one on Sheet1.

Worksheets("Sheet1").Ovals(1).Delete

This example deletes all graphic objects and controls (check boxes, buttons, and so on) on Sheet1.

Worksheets("Sheet1").DrawingObjects.Delete

This example deletes every worksheet in the active workbook without displaying the confirmation dialog box.

Application.DisplayAlerts = False
For Each w In Worksheets
    w.Delete
Next w
Application.DisplayAlerts = True

This example sorts the data in the first column on Sheet1 and then deletes rows that contain duplicate data.

Worksheets("Sheet1").Range("A1").Sort _
        key1:=Worksheets("Sheet1").Range("A1")
Set currentCell = Worksheets("Sheet1").Range("A1")
Do While Not IsEmpty(currentCell)
    Set nextCell = currentCell.Offset(1, 0)
    If nextCell.Value = currentCell.Value Then
        currentCell.EntireRow.Delete
    End If
    Set currentCell = nextCell
Loop


Delete Method (DocumentProperty Object)

Applies To

DocumentProperty Object.

Description

Deletes a custom document property (you cannot delete a built-in document property).

To use this method, you should establish a reference to the Microsoft Office 95 Object Library by using the References command (Tools menu).

Example

This example deletes a custom document property. You must pass a DocumentProperty object to the procedure.

Sub DeleteCustomDocumentProperty(dp As DocumentProperty)
    dp.Delete
End Sub

This example deletes the "Total Sales" custom document property

ActiveWorkbook.CustomDocumentProperties("Total Sales").Delete


DeleteChartAutoFormat Method

Applies To

Application Object.

Description

Removes a custom chart autoformat from the list of available chart autoformats.

Syntax

object.DeleteChartAutoFormat(name)

object

Required. The Application object.

name

Required. Specifies the name of the custom autoformat to remove.

See Also

AddChartAutoFormat Method, SetDefaultChart Method.

Example

This example deletes the custom autoformat named "Presentation Chart".

Application.DeleteChartAutoFormat name:="Presentation Chart"


DeleteCustomList Method

Applies To

Application Object.

Description

Deletes a custom list.

Syntax

object.DeleteCustomList(listNum)

object

Required. The Application object.

listNum

Required. The custom list number. This number must be greater than or equal to five (Microsoft Excel has four built-in custom lists that cannot be deleted).

Remarks

This method generates an error if the list number is less than five or a matching custom list does not exist.

See Also

AddCustomList Method, CustomListCount Property, GetCustomListContents Method, GetCustomListNum Method.

Example

This example deletes a custom list.

n = Application.GetCustomListNum(Array("cogs", "sprockets", _
    "widgets", "gizmos"))
Application.DeleteCustomList n


DeleteNumberFormat Method

Applies To

Workbook Object.

Description

Deletes a custom number format from the workbook.

Syntax

object.DeleteNumberFormat(numberFormat)

object

Required. The Workbook object.

numberFormat

Required. A string that names the number format to delete.

Example

This example deletes the number format "000-00-0000" from the active workbook.

ActiveWorkbook.DeleteNumberFormat("000-00-0000")


DeleteReplacement Method

Applies To

AutoCorrect Object.

Description

Deletes an entry from the array of AutoCorrect replacements. This method is available only in Microsoft Excel for Windows 95.

Syntax

object.DeleteReplacement(what)

object

Required. The AutoCorrect object.

what

Required. A string specifying the text to be replaced, as it appears in the row to be deleted from the array of AutoCorrect replacements. If this string doesn't exist in the array of AutoCorrect replacements, the method fails.

See Also

AddReplacement Method, ReplacementList Property.

Example

This example removes the word "Temperature" from the array of AutoCorrect replacements.

With Application.AutoCorrect
    .DeleteReplacement "Temperature"
End With


Delivery Property

Applies To

RoutingSlip Object.

Description

Returns or sets the delivery method used when routing (one of xlOneAfterAnother or xlAllAtOnce). Read-write before routing starts, read-only once routing is in progress.

Example

This example sends BOOK1.XLS to three recipients, one after the other.

Workbooks("BOOK1.XLS").HasRoutingSlip = True
With Workbooks("BOOK1.XLS").RoutingSlip
    .Delivery = xlOneAfterAnother
    .Recipients = Array("Adam Bendel", "Jean Selva", "Bernard Gabor")
    .Subject = "Here is BOOK1.XLS"
    .Message = "Here is the workbook. What do you think?"
End With
Workbooks("BOOK1.XLS").Route


Dependents Property

Applies To

Range Object.

Description

Accessor. Returns a Range object that represents the range that contains all of the dependents of a cell. This may be a multiple selection (a union of Range objects) if there is more than one dependent. Read-only.

See Also

DirectDependents Property, DirectPrecedents Property, Precedents Property, ShowDependents Method.

Example

This example selects the dependents of cell A1 on Sheet1.

Worksheets("Sheet1").Activate
Range("A1").Dependents.Select


DepthPercent Property

Applies To

Chart Object.

Description

Returns or sets the depth of a 3-D chart as a percentage of the chart width (between 20 and 2000 percent). Read-write.

See Also

HeightPercent Property.

Example

This example sets the chart depth of Chart1 to be 50 percent of its width. The example should be run on a 3-D chart.

Charts("Chart1").DepthPercent = 50


Derived Math Functions

The following is a list of nonintrinsic math functions that can be derived from the intrinsic math functions:

Function | Derived equivalents
Secant | Sec(X) = 1 / Cos(X)
Cosecant | Cosec(X) = 1 / Sin(X)
Cotangent | Cotan((X) = 1 / Tan(X)
Inverse Sine | Arcsin(X) = Atn(X / Sqr(-X * X + 1))
Inverse Cosine | Arccos(X) = Atn(-X / Sqr(-X * X + 1)) + 1.5708
Inverse Secant | Arcsec(X) = Atn(X / Sqr(X * X - 1)) + Sgn((X) -1) * 1.5708
Inverse Cosecant | Arccosec(X) = Atn(X / Sqr(X * X - 1)) + (Sgn(X) - 1) * 1.5708
Inverse Cotangent | Arccotan(X) = Atn(X) + 1.5708
Hyperbolic Sine | HSin(X) = (Exp(X) - Exp(-X)) / 2
Hyperbolic Cosine | HCos(X) = (Exp(X) + Exp(-X)) / 2
Hyperbolic Tangent | HTan(X) = (Exp(X) - Exp(-X)) / (Exp(X) + Exp(-X))
Hyperbolic Secant | HSec(X) = 2 / (Exp(X) + Exp(-X))
Hyperbolic Cosecant | HCosec(X) = 2 / (Exp(X) - Exp(-X))
Hyperbolic Cotangent | HCotan(X) = (Exp(X) + Exp(-X)) / (Exp(X) - Exp(-X))
Inverse Hyperbolic Sine | HArcsin(X) = Log(X + Sqr(X * X + 1))
Inverse Hyperbolic Cosine | HArccos(X) = Log(X + Sqr(X * X - 1))
Inverse Hyperbolic Tangent | HArctan(X) = Log((1 + X) / (1 - X)) / 2
Inverse Hyperbolic Secant | HArcsec(X) = Log((Sqr(-X * X + 1) + 1) / X)
Inverse Hyperbolic Cosecant | HArccosec(X) = Log((Sgn(X) * Sqr(X * X + 1) +1) / X)
Inverse Hyperbolic Cotangent | HArccotan(X) = Log((X + 1) / (X - 1)) / 2
Logarithm to base N | LogN(X) = Log(X) / Log(N)

See Also

Atn Function, Cos Function, Exp Function, Log Function, Sin Function, Sqr Function, Tan Function.


Deselect Method

Applies To

Chart Object.

Description

Cancels the selection for the specified chart.

Syntax

object.Deselect

object

Required. The Chart object.

See Also

Select Method, Selection Property.

Example

This example is equivalent to pressing ESC in the active chart. The example should be run on a chart that has a component (such as an axis) selected.

ActiveChart.Deselect


Dialog Object

Description

Represents a built-in Microsoft Excel dialog box. The only useful thing you can do with a Dialog object is use it with the Show method to display the dialog box. Do not confuse the Dialog object with the DialogSheet object, which represents a custom dialog sheet, or the DialogFrame object, which represents the boundaries of the custom dialog box on a dialog sheet.

Accessors

The Dialog object is a member of the Dialogs collection. The Dialogs collection contains all Microsoft Excel built-in dialog boxes. You cannot create a new built-in dialog box or add one to the collection.

To access a single member of the collection, use the Dialogs method with an argument. The following example runs the built-in File Open dialog box. The Show method returns True if Microsoft Excel successfully opens a file, or False if the user cancels the dialog box.

dlgAnswer = Application.Dialogs(xlDialogOpen).Show

The Microsoft Excel Visual Basic object library includes built-in constants for many of the built-in dialog boxes. Each constant is formed from the prefix "xlDialog" followed by the name of the dialog box. For example, the Apply Names dialog box constant is xlDialogApplyNames, and the Find File dialog box constant is xlDialogFindFile. To see a list of the available constants using the Object Browser, select the Constants module in the Excel library, and scroll down the Methods/Properties list until you see the constants beginning with "xlDialog."

Properties

Application Property, Creator Property, Parent Property.

Methods

Show Method.


DialogBox Method

Applies To

Range Object.

Description

Displays a dialog box defined by a dialog-box definition table on a Microsoft Excel version 4.0 macro sheet. Returns the number of the chosen control, or False if the user chooses the Cancel button.

Syntax

object.DialogBox

object

Required. A range on a Microsoft Excel 4.0 macro sheet that contains a dialog-box definition table.

Remarks

This method is included for backward compatibility with the Microsoft Excel version 4.0 macro language.

Example

This example runs a Microsoft Excel version 4.0 dialog box and then displays the return value in a message box. The dialogRange variable refers to the dialog box definition table on the Microsoft Excel version 4.0 macro sheet Macro1.

Set dialogRange = Excel4MacroSheets("Macro1").Range("myDialogBox")
result = dialogRange.DialogBox
MsgBox result


DialogFrame Object

Description

Represents the dialog frame. The dialog frame provides the backdrop for user-defined dialog boxes. It has no formatting properties, only a position, a size, and a caption. Only one dialog frame exists per dialog sheet, and it cannot be deleted or moved in front of any other graphic object. Dialog frames do not exist on worksheets.

Accessors

The DialogFrame property returns the dialog frame for the dialog sheet. The following example adds a new check box to the dialog sheet named "Dialog1." The new check box is positioned relative to the upper-left corner of the dialog frame.

Dim df as DialogFrame
DialogSheets("dialog1").Activate
Set df = ActiveSheet.DialogFrame
ActiveSheet.CheckBoxes.Add df.Left + 10, df.Top + 10, 100, 10

Remarks

When a dialog sheet is first shown, Microsoft Excel runs any procedure assigned to the OnAction property for the dialog frame.

The position of the dialog frame on the dialog sheet does not affect where the custom dialog is positioned when it is shown in a modal window. There is no way to set a custom position for the running dialog frame.

Properties

Application Property, Caption Property, Creator Property, Height Property, Left Property, Locked Property, LockedText Property, Name Property, OnAction Property, Parent Property, Text Property, Top Property, Width Property.

Methods

Characters Method, CheckSpelling Method, CopyPicture Method, Select Method.


DialogFrame Property

Applies To

DialogSheet Object.

Description

Accessor. Returns a DialogFrame object that represents the dialog frame on the specified dialog sheet. Read only.

Example

This example sets the height and width of the dialog box frame for Dialog1.

With DialogSheets("Dialog1").DialogFrame
    .Height = 144
    .Width = 196
End With


Dialogs Collection Object

Description

A collection of all the Dialog objects in the Microsoft Excel application. Each Dialog object represents a built-in Microsoft Excel dialog box. The only useful thing you can do with a Dialog object is use it with the Show method to display the dialog box. Do not confuse the Dialog object with the DialogSheet object, which represents a custom dialog sheet, or the DialogFrame object, which represents the boundaries of the custom dialog box on a dialog sheet. The Dialogs collection contains all Microsoft Excel built-in dialog boxes. You cannot create a new built-in dialog box or add one to the collection.

Accessors

Use the Dialogs method with an argument to access a single member of the collection or without an argument to access the entire collection at once. The Microsoft Excel Visual Basic object library includes built-in constants for many of the built-in dialog boxes. Each constant is formed from the prefix "xlDialog" followed by the name of the dialog box. For example, the Apply Names dialog box constant is xlDialogApplyNames, and the Find File dialog box constant is xlDialogFindFile. To see a list of the available constants using the Object Browser, select the Constants module in the Excel library, and scroll down the Methods/Properties list until you see the constants beginning with "xlDialog."

The following example runs the built-in File Open dialog box. The Show method returns True if Microsoft Excel successfully opens a file, or False if the user cancels the dialog box.

dlgAnswer = Application.Dialogs(xlDialogOpen).Show

Properties

Application Property, Count Property, Creator Property, Parent Property.

Methods

Item Method.


Dialogs Method

Applies To

Application Object.

Description

Accessor. Returns an object that represents a single built-in dialog (a Dialog object, Syntax 1) or a collection of all built-in dialogs (a Dialogs object, Syntax 2). Read-only.

Syntax 1

object.Dialogs(index)

Syntax 2

object.Dialogs

object

Required. The Application object.

index

Required for Syntax 1. A built-in constant. See the following Remarks section for more information.

Remarks

Using the Dialogs and Show methods, you can display approximately 200 built-in dialog boxes. Each dialog box has a constant assigned to it; these constants all begin with "xlDialog."

For a table of the available constants and their corresponding argument lists, see "Built-In Dialog Box Argument Lists" in online help.

You can also use the Object Browser to browse the list of dialog box constants. On the View menu, click Object Browser. In the Object Browser, select the Microsoft Excel library, and then select the Constants object. Scroll through the list in the Methods/Properties box until you find the constants that begin with "xlDialog." The constants correspond to dialog box names; for example, the constant for the Find File dialog box is xlDialogFindFile.

The Dialogs method may fail if you try to show a dialog box in an incorrect context. For example, to display the Format Data Labels dialog box (using the Visual Basic expression Application.Dialogs(xlDialogDataLabel).Show), the active sheet must be a chart, otherwise the method fails.

See Also

Show Method.

Example

This example displays the dialog box for the Open command on the File menu.

Application.Dialogs(xlDialogOpen).Show


DialogSheet Object

Description

Represents a single dialog sheet in a workbook. Do not confuse a dialog sheet with the Dialog object, which represents a built-in Microsoft Excel dialog box, or the DialogFrame object, which represents the boundaries of the custom dialog box on a dialog sheet.

Accessors

The DialogSheet object is a member of the DialogSheets collection. The DialogSheets collection contains all the DialogSheet objects in a workbook. Use the Add method to create a new dialog sheet and add it to the collection. To access a single member of the collection, use the DialogSheets method with the index number or name of the dialog sheet as an argument.

The dialog sheet index number represents the position of the dialog sheet on the tab bar of the workbook. DialogSheets(1) is the first (leftmost) dialog sheet in the workbook; DialogSheets(DialogSheets.Count) is the last. All dialog sheets are included in the index count, even if they are hidden. The following example runs dialog sheet one in the active workbook.

DialogSheets(1).Show

The dialog sheet name is shown on the workbook tab for the dialog sheet. Use the Name property to set or return the dialog sheet name. The following example runs the dialog sheet named "Test Dialog."

DialogSheets("test dialog").Show

The DialogSheet object is also a member of the Sheets collection. The Sheets collection contains all of the sheets in the workbook (chart sheets, dialog sheets, modules, and worksheets). To access a single member of the collection, use the Sheets method with the index number or name of the sheet as an argument.

DialogSheets in Add-Ins

When you write code in an add-in to display a dialog sheet that is also contained in the add-in, you must use the ThisWorkbook property to return a reference to the add-in workbook. You cannot use ActiveWorkbook, and you cannot use Workbooks("workbook name"). This can be confusing, because all three of these methods will work until you create an add-in from your workbook. Once your code is running in an add-in, however, only ThisWorkbook (which returns the workbook where the code is running) can be used to access to add-in workbook.

The following example displays the dialog sheet named "Add-In Dialog" in the running workbook.

ThisWorkbook.DialogSheets("add-in dialog").Show

Using ActiveSheet

When a dialog sheet is the active sheet, you can use the ActiveSheet property to refer to it. The following example uses the Activate method to activate dialog sheet one and then runs the dialog sheet.

DialogSheets(1).Activate
ActiveSheet.Show

Note that after the example activates the dialog sheet, it uses the ActiveSheet property, not the ActiveDialog property, to return the active dialog sheet. The ActiveSheet property returns the active sheet in the workbook, while the ActiveDialog property returns the topmost running dialog sheet in the workbook. In this example, the dialog sheet is not running and cannot be accessed with the ActiveDialog property.

Properties

Application Property, Creator Property, DefaultButton Property, DialogFrame Property, DisplayAutomaticPageBreaks Property, Focus Property, Index Property, Name Property, Next Property, OnDoubleClick Property, OnSheetActivate Property, OnSheetDeactivate Property, PageSetup Property, Parent Property, Previous Property, ProtectContents Property, ProtectDrawingObjects Property, Visible Property.

Methods

Activate Method, Arcs Method, Buttons Method, ChartObjects Method, CheckBoxes Method, CheckSpelling Method, Copy Method, Delete Method, DrawingObjects Method, Drawings Method, DropDowns Method, EditBoxes Method, Evaluate Method, GroupBoxes Method, GroupObjects Method, Hide Method, Labels Method, Lines Method, ListBoxes Method, Move Method, OLEObjects Method, OptionButtons Method, Ovals Method, Paste Method (DialogSheet or Worksheet Object), PasteSpecial Method (DialogSheet or Worksheet Object), Pictures Method, PrintOut Method, PrintPreview Method, Protect Method, Rectangles Method, SaveAs Method, ScrollBars Method, Select Method, Show Method, Spinners Method, TextBoxes Method, Unprotect Method.


DialogSheets Collection Object

Description

A collection of all the DialogSheet objects in the specified or active workbook. Do not confuse a dialog sheet with the Dialog object, which represents a built-in Microsoft Excel dialog box, or the DialogFrame object, which represents the boundaries of the custom dialog box on a dialog sheet.

Accessors

Use the Add method to create a new dialog sheet and add it to the workbook. The following example adds a new dialog sheet before sheet one in the active workbook.

DialogSheets.Add before:=Sheets(1)

Use the DialogSheets method with an argument to access a single member of the collection or without an argument to access the entire collection at once. The following example moves all the dialog sheets in the active workbook to the end of the workbook.

DialogSheets.Move after:=Sheets(Sheets.Count)

The Sheets collection contains all of the sheets in the workbook (chart sheets, dialog sheets, modules, and worksheets). Use the Sheets method with an argument to access a single member of the collection or without an argument to access the entire collection at once.

Properties

Application Property, Count Property, Creator Property, Parent Property, Visible Property.

Methods

Add Method (DialogSheets Collection), Copy Method, Delete Method, Item Method, Move Method, PrintOut Method, PrintPreview Method, Select Method.

See Also

Charts Collection, Modules Collection, Sheets Method, Worksheets Collection.


DialogSheets Method

Applies To

Application Object, Workbook Object.

Description

Accessor. Returns an object that represents a single dialog sheet (a DialogSheet object, Syntax 1) or a collection of all dialog sheets (a DialogSheets object, Syntax 2) in the workbook. Read-only.

Syntax 1

object.DialogSheets(index)

Syntax 2

object.DialogSheets

object

Optional for Application, required for Workbook. The object that contains dialog sheets.

index

Required for Syntax 1. The name or number of the dialog sheet to return.

Remarks

Using this method with no object qualifier is a shortcut for ActiveWorkbook.DialogSheets.

Example

This example displays the custom dialog box on Dialog1. The loop causes the dialog box to be displayed again if you click the Cancel button.

Do
    returnVal = DialogSheets("Dialog1").Show
Loop Until returnVal = True


Dim Statement

Description

Declares variables and allocates storage space.

Syntax

Dim varname[([subscripts])][As type][,varname[([subscripts])][As type]] . . .

The Dim statement syntax has these parts:

Part | Description
varname | Name of the variable; follows standard variable naming conventions.
subscripts | Dimensions of an array variable; up to 60 multiple dimensions may be declared. The subscripts argument uses the following syntax:
 | [lower To] upper [,[lower To] upper] . . .
type | Data type of the variable; may be Boolean, Integer, Long, Currency, Single, Double, Date, String (for variable-length strings), String * length (for fixed-length strings), Object, Variant, a user-defined type, or an object type. Use a separate As type clause for each variable you declare.

Remarks

Variables declared with Dim at the module level are available to all procedures within the module. At the procedure level, variables are available only within the procedure.

Use the Dim statement at module or procedure level to declare the data type or object type of a variable. For example, the following statement declares a variable as an Integer.

Dim NumberOfEmployees As Integer

If you do not specify a data type or object type, and there is no Def type statement in the module, the variable is Variant by default.

When variables are initialized, a numeric variable is initialized to 0, a variable-length string is initialized to a zero-length string, and a fixed-length string is filled with zeros. Variant variables are initialized to Empty. Each element of a user-defined type variable is initialized as if it was a separate variable. A variable that refers to an object must be assigned an existing object using the Set statement before it can be used. Until it is assigned an object, the declared object variable has the special value Nothing, which indicates that it does not refer to any particular instance of an object.

You can also use the Dim statement with empty parentheses to declare dynamic arrays. After declaring a dynamic array, use the ReDim statement within a procedure to define the number of dimensions and elements in the array. If you try to redeclare a dimension for an array variable whose size was explicitly specified in a Private, Public or Dim statement, an error occurs.

Tip

When you use the Dim statement in a procedure, it is a generally accepted programming practice to put the Dim statement at the beginning of the procedure.

See Also

Array Function, Option Base Statement, Private Statement, Public Statement, ReDim Statement, Set Statement, Static Statement, Type Statement.

Example

This example shows various uses of the Dim statement to declare variables. The Dim statement is also used to declare arrays. The default lower bound for array subscripts is 0 and can be overridden at the module level using the Option Base statement.

' AnyValue and MyValue are declared as Variant by default with values
' set to Empty.
Dim AnyValue, MyValue

'  Explicitly declare a variable of type Integer.
Dim Number As Integer

' Multiple declarations on a single line. AnotherVar is of type Variant
' since its type is omitted.
Dim AnotherVar, Choice As Boolean, BirthDate As Date

' DayArray is an array of Variants with 51 elements indexed,
' starting at 0 thru 50, assuming Option Base is set to 0 (default) for
' the current module.
Dim DayArray(50)

' Matrix is a two-dimensional array of integers.
Dim Matrix(3,4) As Integer
' MyMatrix is a three-dimensional array of doubles with explicit
' bounds.
Dim MyMatrix(1 To 5,  4 To 9,  3 To 5) As Double

' BirthDay is an array of dates with indexes from 1 to 10.
Dim BirthDay(1 To 10) As Date

' MyArray is a dynamic array.
Dim MyArray()


Dir Function

Description

Returns the name of a file, directory, or folder that matches a specified pattern or file attribute, or the volume label of a drive.

Syntax

Dir[(pathname[,attributes])]

Elements

The Dir function syntax has these parts:

Part | Description
pathname | String expression that specifies a file name — may include directory or folder, and drive. Null is returned if pathname is not found.
attributes | Constant or numeric expression, the sum of which specifies file attributes. If omitted, all normal files are returned that match pathname.

The attributes argument has these constants and values:

Constant | Value | File Attribute
vbNormal | 0 | Normal.
vbHidden | 2 | Hidden.
vbSystem | 4 | System — not available on the Macintosh.
vbVolume | 8 | Volume label; if specified, all attributes are ignored — not available on the Macintosh.
vbDirectory | 16 | Directory or folder.

Note

These constants are specified by Visual Basic. As a result, the names can be used anywhere in your code in place of the actual values.

Remarks

Dir supports the use of '*' (multiple character) and '?' (single character) wildcards to specify multiple files. However, on the Macintosh, these characters are treated as valid file name characters and can't be used as wildcards to specify multiple files.

Since the Macintosh does not support wildcards, use the file type to identify groups of files. You can use the MacID function to specify file type instead of using the file names. For example, the following statement returns the name of the first "TEXT" file in the current folder:

Dir("", MacID("TEXT"))

If you use the MacID function with Dir in Microsoft Windows, an error occurs.

Any attribute value greater than 256 is considered a MacID value.

You must specify pathname the first time you call the Dir function, or an error occurs. If you also specify file attributes, pathname must be included.

Dir returns the first file name that matches pathname. To get any additional file names that match pathname, call Dir again with no arguments. When no more file names match, Dir returns a zero-length string. Once a zero-length string is returned, you must specify pathname in subsequent calls or an error occurs. You can change to a new pathname without retrieving all of the file names that match the current pathname. However, you can't recursively call the Dir function.

Tip

Because file names are retrieved in no particular order, you may want to store returned file names in an array and then sort the array.

See Also

ChDir Statement, CurDir Function, MacID Function.


DirectDependents Property

Applies To

Range Object.

Description

Accessor. Returns a Range object that represents the range that contains all of the direct dependents of a cell. This may be a multiple selection (a union of Range objects) if there is more than one dependent. Read-only.

See Also

Dependents Property, DirectPrecedents Property, Precedents Property, ShowDependents Method.

Example

This example selects the direct dependents of cell A1 on Sheet1.

Worksheets("Sheet1").Activate
Range("A1").DirectDependents.Select


DirectPrecedents Property

Applies To

Range Object.

Description

Accessor. Returns a Range object that represents the range that contains all of the direct precedents of a cell. This may be a multiple selection (a union of Range objects) if there is more than one precedent. Read-only.

See Also

Dependents Property, DirectDependents Property, Precedents Property, ShowPrecedents Method.

Example

This example selects the direct precedents of cell A1 on Sheet1.

Worksheets("Sheet1").Activate
Range("A1").DirectPrecedents.Select


DismissButton Property

Applies To

Button Object, Buttons Collection, DrawingObjects Collection.

Description

True if the button will automatically close a user-defined dialog box when the button is clicked. Any number of buttons on a dialog sheet can have the DismissButton property set to True. Read-write.

Remarks

When you click a button that has the DismissButton property set to True, three steps are taken:

1. The button's OnAction procedure runs. If you want to do any custom data validation, do it in this procedure. If validation fails, you can set the DismissButton property to False, in which case the dialog box remains visible. Remember to reset the DismissButton property to True when validation passes.

2. When the OnAction procedure ends, edit boxes in the dialog box are automatically validated to ensure that they contain data of the type specified by their InputType properties. If automatic validation fails, Microsoft Excel displays an alert, the offending edit box gets the focus, and the dialog box remains visible.

3. If automatic validation passes, the dialog box closes and the Show method that called the dialog sheet returns True.

If no button in the dialog box has the DismissButton property set to True, then you must explicitly call the Hide method or cancel the dialog box to close it.

See Also

CancelButton Property, Hide Method, InputType Property, OnAction Property, Show Method.

Example

This example sets the DismissButton property for every button on Dialog1.

For Each bt in DialogSheets("Dialog1").Buttons
    bt.DismissButton = True
Next bt


Display3DShading Property

Applies To

CheckBox Object, DrawingObjects Collection, DropDown Object, DropDowns Collection, GroupBox Object, GroupBoxes Collection, ListBox Object, ListBoxes Collection, OptionButton Object, OptionButtons Collection, ScrollBar Object, ScrollBars Collection, Spinner Object, Spinners Collection.

Description

True if the control uses 3-D visual effects. This property applies only to controls on worksheets and charts. Read-write.

Example

This example sets check box one on Sheet1 to use 3-D shading.

Worksheets("Sheet1").CheckBoxes(1).Display3DShading = True


DisplayAlerts Property

Applies To

Application Object.

Description

True if Microsoft Excel displays certain alerts and messages while a macro is running. Read-write.

Remarks

Defaults to True. Set this property to False if you do not want to be disturbed by prompts and alert messages while a macro is running, and want Microsoft Excel to choose the default response.

If you set this property to False, Microsoft Excel sets it back to True when your macro stops running.

This property is not effective from outside Microsoft Excel. For example, you can set this property to False from another application (using OLE Automation), but Microsoft Excel will immediately reset it to True. Because OLE Automation calls are processed as single-line macros and Microsoft Excel resets this property whenever a macro stops running, the property is reset immediately after you set it.

Example

This example closes the workbook BOOK1.XLS and does not prompt the user to save changes. Any changes to BOOK1.XLS are not saved.

Application.DisplayAlerts = False
Workbooks("BOOK1.XLS").Close
Application.DisplayAlerts = True

This example suppresses the message that appears when you initiate a DDE channel to an application that is not running.

Application.DisplayAlerts = False
channelNumber = Application.DDEInitiate( _
    app:="WinWord", _
    topic:="C:\WINWORD\FORMLETR.DOC")
Application.DisplayAlerts = True
Application.DDEExecute channelNumber, "[FILEPRINT]"
Application.DDETerminate channelNumber


DisplayAutomaticPageBreaks Property

Applies To

DialogSheet Object, Worksheet Object.

Description

True if automatic page breaks should be displayed for this sheet. Read-write.

Example

This example causes Sheet1 to display automatic page breaks.

Worksheets("Sheet1").DisplayAutomaticPageBreaks = True


DisplayBlanksAs Property

Applies To

Chart Object.

Description

Returns or sets how blank cells are plotted on a chart (one of xlNotPlotted, xlInterpolated, or xlZero). Read-write.

Example

This example causes Microsoft Excel not to plot blank cells in Chart1.

Charts("Chart1").DisplayBlanksAs = xlNotPlotted


DisplayClipboardWindow Property

Applies To

Application Object.

Description

Apple Macintosh only. True if the Clipboard window is displayed. Set this property to True to display the Clipboard window. Read-write.

Remarks

In Microsoft Windows, this property retains its value, but does nothing.

Example

This example displays the Clipboard window.

Application.DisplayClipboardWindow = True


DisplayDrawingObjects Property

Applies To

Workbook Object.

Description

Returns or sets how drawing objects are displayed, as shown in the following table. Read-write.

Value | Meaning
xlAll | Show all drawing objects.
xlPlaceholders | Show only placeholders.
xlHide | Hide all drawing objects.

Example

This example hides all the drawing objects in the active workbook.

ActiveWorkbook.DisplayDrawingObjects = xlHide


DisplayEquation Property

Applies To

Trendline Object.

Description

True if the equation for the trendline is displayed on the chart (in the same data label as the R-squared value). Setting this property to True automatically turns on data labels. Read-write.

See Also

Add Method, DisplayRSquared Property.

Example

This example displays the R-squared value and equation for trendline one in Chart1. The example should be run on a 2-D column chart that has a trendline for the first series.

With Charts("Chart1").SeriesCollection(1).Trendlines(1)
    .DisplayRSquared = True
    .DisplayEquation = True
End With


DisplayExcel4Menus Property

Applies To

Application Object.

Description

True if Microsoft Excel displays version 4.0 menu bars. Read-write.

Example

This example switches to Microsoft Excel version 7.0 menus if version 4.0 menus are currently in use.

If Application.DisplayExcel4Menus = True Then
    Application.DisplayExcel4Menus = False
End If


DisplayFormulaBar Property

Applies To

Application Object.

Description

True if the formula bar is displayed. Read-write.

Example

This example hides the formula bar.

Application.DisplayFormulaBar = False


DisplayFormulas Property

Applies To

Window Object.

Description

True if the window is displaying formulas, or False if the window is displaying values. Read-write.

Remarks

This property applies only to worksheets and macro sheets.

Example

This example changes the active window in BOOK1.XLS to display formulas.

Workbooks("BOOK1.XLS").Worksheets("Sheet1").Activate
ActiveWindow.DisplayFormulas = True


DisplayFullScreen Property

Applies To

Application Object.

Description

True if Microsoft Excel is in full-screen mode. Read-write.

Remarks

Full-screen mode maximizes the application window to cover the entire screen and hides the application title bar (in Microsoft Windows). Toolbars, the status bar, and the formula bar maintain separate display settings for full-screen and normal mode.

Example

This example causes Microsoft Excel to display in full-screen mode.

Application.DisplayFullScreen = True


DisplayGridlines Property

Applies To

Window Object.

Description

True if gridlines are displayed. Read-write.

Remarks

This property applies only to worksheets and macro sheets.

This property affects only displayed gridlines. Use the PrintGridlines property to control gridline printing.

Example

This example toggles the display of gridlines in the active window in BOOK1.XLS.

Workbooks("BOOK1.XLS").Worksheets("Sheet1").Activate
ActiveWindow.DisplayGridlines = Not(ActiveWindow.DisplayGridlines)


DisplayHeadings Property

Applies To

Window Object.

Description

True if both row and column headings are displayed, False if no headings are displayed. Read-write.

Remarks

This property applies only to worksheets and macro sheets.

This property affects only displayed headings. Use the PrintHeadings property to control heading printing.

Example

This example turns off row and column headings in the active window in BOOK1.XLS.

Workbooks("BOOK1.XLS").Worksheets("Sheet1").Activate
ActiveWindow.DisplayHeadings = False


DisplayHorizontalScrollBar Property

Applies To

Window Object.

Description

True if the horizontal scroll bar is displayed. Read-write.

See Also

DisplayScrollBars Property, DisplayVerticalScrollBar Property, TabRatio Property.

Example

This example turns on the horizontal scroll bar for the active window.

ActiveWindow.DisplayHorizontalScrollBar = True


DisplayInfoWindow Property

Applies To

Application Object.

Description

True if the Info window is displayed. Set this property to True to display the Info window. Read-write.

Example

This example displays the Info window.

Application.DisplayInfoWindow = True


DisplayNoteIndicator Property

Applies To

Application Object.

Description

True if cells containing notes display cell tips and contain note indicators (small dots in their upper-right corners). Read-write.

Example

This example hides the note indicators.

Application.DisplayNoteIndicator = True


DisplayOutline Property

Applies To

Window Object.

Description

True if outline symbols are displayed. Read-write.

Remarks

This property applies only to worksheets and macro sheets.

Example

This example displays outline symbols for the active window in BOOK1.XLS.

Workbooks("BOOK1.XLS").Worksheets("Sheet1").Activate
ActiveWindow.DisplayOutline = True


DisplayRecentFiles Property

Applies To

Application Object.

Description

True if the most recently used (MRU) file list is displayed on the File menu. Read-write.

Example

This example turns off the list of most recently used files.

Application.DisplayRecentFiles = False


DisplayRightToLeft Property

Applies To

Window Object.

Description

True if the window displays right-to-left instead of left-to-right. Read-write.

Remarks

This property is only available in Arabic and Hebrew Microsoft Excel.

Example

This example sets window one to display right-to-left.

ActiveWorkbook.Windows(1).DisplayRightToLeft = True


DisplayRSquared Property

Applies To

Trendline Object.

Description

True if the R-squared value of the trendline is displayed on the chart (in the same data label as the equation). Setting this property to True automatically turns on data labels. Read-write.

See Also

Add Method, DisplayEquation Property.

Example

This example displays the R-squared value and equation for trendline one in Chart1. The example should be run on a 2-D column chart that has a trendline for the first series.

With Charts("Chart1").SeriesCollection(1).Trendlines(1)
    .DisplayRSquared = True
    .DisplayEquation = True
End With


DisplayScrollBars Property

Applies To

Application Object.

Description

True if scroll bars are visible for all workbooks. Read-write.

See Also

DisplayHorizontalScrollBar Property, DisplayVerticalScrollBar Property.

Example

This example turns off scroll bars for all workbooks.

Application.DisplayScrollBars = False


DisplayStatusBar Property

Applies To

Application Object.

Description

True if the status bar is displayed. Read-write.

See Also

StatusBar Property.

Example

This example saves the current state of the DisplayStatusBar property and then sets the property to True so the status bar is visible.

saveStatusBar = Application.DisplayStatusBar
Application.DisplayStatusBar = True


DisplayVerticalScrollBar Property

Applies To

DrawingObjects Collection, EditBox Object, EditBoxes Collection, Window Object.

Description

True if the vertical scroll bar is displayed. Read-write.

See Also

DisplayHorizontalScrollBar Property, DisplayScrollBars Property.

Example

This example turns on the vertical scroll bar for the active window.

ActiveWindow.DisplayVerticalScrollBar = True


DisplayWorkbookTabs Property

Applies To

Window Object.

Description

True if the workbook tabs are displayed. Read-write.

See Also

TabRatio Property.

Example

This example turns on the workbook tabs.

ActiveWindow.DisplayWorkbookTabs = True


DisplayZeros Property

Applies To

Window Object.

Description

True if zero values are displayed. Read-write.

Remarks

This property applies only to worksheets and macro sheets.

Example

This example sets the active window in BOOK1.XLS to display zero values.

Workbooks("BOOK1.XLS").Worksheets("Sheet1").Activate
ActiveWindow.DisplayZeros = True


Do...Loop Statement

Description

Repeats a block of statements while a condition is True or until a condition becomes True.

Syntax 1

Do [{While | Until} condition]
[statements]
[Exit Do]
[statements]
Loop

Syntax 2

Do
 [statements]
[Exit Do]
[statements]
Loop [{While | Until}condition]

The Do...Loop statement syntax has these parts:

Part | Description
condition | Expression that is True or False.
statements | One or more statements that are repeated while or until condition is True.

Remarks

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

When used within nested Do...Loop statements, Exit Do transfers control to the loop that is one nested level above the loop where it occurs.

See Also

Exit Statement, For...Next Statement, While...Wend Statement.

Example

This example shows how Do...Loop statements can be used. The inner Do...Loop statement loops 10 times, sets the value of the flag to False, and exits prematurely using the Exit Do statement. The outer loop exits immediately upon checking the value of the flag.

Check = True : Counter = 0    ' Initialize variables.
Do    ' Outer Loop.
    Do While Counter < 20    ' Inner Loop.
        Counter = Counter + 1    ' Increment Counter.
        If Counter = 10 Then    ' If condition is true.
            Check = False    ' Set value of flag to False.
            Exit Do    ' Exit inner loop.
        End If
    Loop
Loop Until Check = False    ' Exit outer loop immediately.

This example sorts the data in the first column on Sheet1 and then deletes rows that contain duplicate data.

Worksheets("Sheet1").Range("A1").Sort _
    key1:=Worksheets("Sheet1").Range("A1")
Set currentCell = Worksheets("Sheet1").Range("A1")
Do While Not IsEmpty(currentCell)
    Set nextCell = currentCell.Offset(1, 0)
    If nextCell.Value = currentCell.Value Then
        currentCell.EntireRow.Delete
    End If
    Set currentCell = nextCell
Loop


DocumentProperties Collection Object (Microsoft Office 95 Object Library)

Description

Represents a collection of document properties. Each document property is represented by a DocumentProperty object.

To use this object, you should establish a reference to the Microsoft Office 95 Object Library by using the References command (Tools menu).

Accessors

Each workbook has a collection of built-in document properties and a collection of custom document properties. Each collection is represented by a DocumentProperties object, and each collection contains individual DocumentProperty objects.

Use the BuiltinDocumentProperties property to return the collection of built-in document properties, and use the CustomDocumentProperties property to return the collection of custom document properties.

Use the Add method to create a new custom document property and add it to the collection (you cannot create a built-in document property).

The following example creates a list on worksheet one of all the built-in document properties for the active workbook.

rw = 1
Worksheets(1).Activate
For Each p In ActiveWorkbook.BuiltinDocumentProperties
    Cells(rw, 1).Value = p.Name
    Cells(rw, 2).Value = p.Value
    rw = rw + 1
Next

Properties

Count Property (DocumentProperties Collection), Parent Property (DocumentProperties Collection).

Methods

Add Method (DocumentProperties Collection), Item Method (DocumentProperties Collection).


DocumentProperty Object (Microsoft Office 95 Object Library)

Description

Represents a single document property. The DocumentProperty object is a member of the DocumentProperties collection.

To use this object, you should establish a reference to the Microsoft Office 95 Object Library by using the References command (Tools menu).

Accessors

Each workbook has a collection of built-in document properties and a collection of custom document properties. Each collection is represented by a DocumentProperties object, and each collection contains individual DocumentProperty objects.

Use the BuiltinDocumentProperties property to return the collection of built-in document properties, and use the CustomDocumentProperties property to return the collection of custom document properties. Use the Item method to return a single member of the collection.

The following example sets the value of the built-in document property named "Title."

ActiveWorkbook.BuiltinDocumentProperties.Item("Title") _
    .Value = "Year-End Sales Results"

Properties

LinkSource Property (DocumentProperty Object), LinkToContent Property (DocumentProperty Object), Name Property (DocumentProperty Object), Parent Property (DocumentProperty Object), Type Property (DocumentProperty Object), Value Property (DocumentProperty Object).

Methods

Delete Method (DocumentProperty Object).


DoEvents Statement

Description

Yields execution so that the operating system can process other events.

Syntax

DoEvents

Remarks

DoEvents passes control to the operating system. Control is not returned until the operating system has finished processing the events in its queue and, for Microsoft Windows only, all keys in the SendKeys queue have been sent.

If parts of your code take up too much processor time, use DoEvents periodically to relinquish control to the operating system so that events, such as keyboard input and mouse clicks, can be processed without significant delay.

Caution

Make sure the procedure that has given up control with DoEvents is not executed again from a different part of your code before the first DoEvents call returns; this could cause unpredictable results. In addition, do not use DoEvents if other applications could possibly interact with your procedure in unforeseen ways during the time you have yielded control.

Example

This example uses the DoEvents Statement to cause execution to yield to the operating system once every 1000 iterations of the loop.

For I = 1 To 150000    ' Start loop.
    If I Mod 1000 = 0 Then     ' If loop has repeated 1000 times.
        DoEvents    ' Yield to operating system.
    End If
Next I    ' Increment loop counter.


Double Data Type

Description

Double (double-precision floating-point) variables are stored as 64-bit (8-byte) numbers ranging in value from -1.79769313486232E308 to -4.94065645841247E-324 for negative values and from 4.94065645841247E-324 to 1.79769313486232E308 for positive values. The type-declaration character for Double is # (character code 35).

See Also

CDbl Function, Data Type Summary, Def type Statements, Single Data Type.


DoubleClick Method

Applies To

Application Object.

Description

Equivalent to double-clicking the active cell.

Syntax

object.DoubleClick

object

Required. The Application object.

See Also

OnDoubleClick Property.

Example

This example double-clicks the active cell on Sheet1.

Worksheets("Sheet1").Activate
Application.DoubleClick


DoughnutGroups Method

Applies To

Chart Object.

Description

Accessor. On a 2-D chart, returns an object that represents a single doughnut chart group (a ChartGroup object, Syntax 1), or a collection of the doughnut chart groups (a ChartGroups collection, Syntax 2).

Syntax 1

object.DoughnutGroups(index)

Syntax 2

object.DoughnutGroups

object

Required. The Chart object.

index

Required for Syntax 1. Specifies the chart group.

Example

This example sets the starting angle for doughnut group one in Chart1.

Charts("Chart1").DoughnutGroups(1).FirstSliceAngle = 45


DoughnutHoleSize Property

Applies To

ChartGroup Object.

Description

Returns or sets the size of the hole in a doughnut chart group. The hole size is expressed as a percentage of the chart size from 10 to 90 percent. Read-write.

Example

This example sets the hole size for doughnut group one in Chart1. The example should be run on a 2-D doughnut chart.

Charts("Chart1").DoughnutGroups(1).DoughnutHoleSize = 10


DownBars Object

Description

Represents the down bars in a chart group. Down bars connect points on series one with lower values on the last series in the chart group (the lines go down from series one). Only 2-D line groups that contain at least two series can have down bars. There is no singular DownBar object; you must turn up bars and down bars on or off for all points in a chart group at once.

Accessors

The DownBars property returns the down bars for a chart group. The following example turns on up and down bars for chart group one in embedded chart one on the worksheet named "Sheet5." The example then sets the up bar color to blue and the down bar color to red.

With Worksheets("sheet5").ChartObjects(1).Chart.ChartGroups(1)
    .HasUpDownBars = True
    .UpBars.Interior.Color = RGB(0, 0, 255)
    .DownBars.Interior.Color = RGB(255, 0, 0)
End With

Remarks

If the HasUpDownBars property is False, most properties of the DownBars object are disabled.

Properties

Application Property, Border Property, Creator Property, Interior Property, Name Property, Parent Property.

Methods

Delete Method, Select Method.

See Also

UpBars Object.


DownBars Property

Applies To

ChartGroup Object.

Description

Accessor. Returns a DownBars object that represents the down bars on a line chart. Applies only to line charts. Read-only.

See Also

HasUpDownBars Property, UpBars Property.

Example

This example turns on up and down bars for chart group one in Chart1 and then sets their colors. The example should be run on a 2-D line chart having two series that cross each other at one or more data points.

With Charts("Chart1").ChartGroups(1)
    .HasUpDownBars = True
    .DownBars.Interior.ColorIndex = 3
    .UpBars.Interior.ColorIndex = 5
End With


Draft Property

Applies To

PageSetup Object.

Description

True if the sheet will be printed without graphics. Read-write.

Remarks

Setting this property to True makes printing faster (at the expense of not printing graphics).

See Also

PrintObject Property.

Example

This example turns off graphics printing for Sheet1.

Worksheets("Sheet1").PageSetup.Draft = True


Drawing Object

Description

Represents a graphic object created by the Freehand, Freeform, or Filled Freeform buttons.

Accessors

The Drawing object is a member of the Drawings collection. The Drawings collection contains all the Drawing objects on a single sheet. Do not confuse the Drawings collection with the DrawingObjects collection, which contains all the graphic objects and controls on a single sheet. Use the Add method to create a new drawing and add it to the collection.

To access a single member of the collection, use the Drawings method with the index number or name of the drawing as an argument.

The following example sets the interior color for drawing one on the worksheet named "Sheet1."

Worksheets("sheet1").Drawings(1).Interior.Color = RGB(0, 0, 255)

The drawing name is shown in the Name Box when the drawing is selected. Use the Name property to return or set the name of the drawing. The following example aligns the left edge of the drawing named "Drawing 1" with the left edge of cell C5.

Worksheets("sheet1").Drawings("drawing 1").Left = _
    Worksheets("sheet1").Range("c5").Left

Properties

Application Property, Border Property, BottomRightCell Property, Creator Property, Enabled Property, Height Property, Index Property, Interior Property, Left Property, Locked Property, Name Property, OnAction Property, Parent Property, Placement Property, PrintObject Property, Shadow Property, Top Property, TopLeftCell Property, Vertices Property, Visible Property, Width Property, ZOrder Property.

Methods

AddVertex Method, BringToFront Method, Copy Method, CopyPicture Method, Cut Method, Delete Method, Duplicate Method, Reshape Method, Select Method, SendToBack Method.


DrawingObjects Collection Object

Description

The DrawingObjects collection contains all the graphic objects, controls, ChartObject objects, Picture objects, and OLEObject objects on a sheet. There is no singular DrawingObject object; each member of the DrawingObjects collection is an object of a particular type, such as a CheckBox object, an Arc object, or a Picture object.

Accessors

Use the Add method for the particular object type (Arcs.Add, or Ovals.Add, for example) to create a new graphic object or control and add it to the DrawingObjects collection. There is no Add method for the DrawingObjects collection.

While Picture objects, ChartObject objects, and OLEObject objects are all contained in the DrawingObjects collection, it is usually easier to use the accessor methods for those individual objects. For more information, see the Pictures method, the ChartObjects method, and the OLEObjects method.

Use the DrawingObjects method with no arguments to access the entire collection at once. The following example deletes all DrawingObject objects on the dialog sheet named "Dialog1."

DialogSheets("dialog1").DrawingObjects.Delete

To access a single member of the collection, use the DrawingObjects method with the index number or object name as an argument.

The following example deletes DrawingObject object one on the worksheet named "Sheet1."

Worksheets("sheet1").DrawingObjects(1).Delete

The name of the object is shown in the Name Box when the object is selected. Use the Name property to set or return the name. The following example activates the dialog sheet named "Dialog1" and then changes the text on the buttons named "Button 2" and "Button 3." Note that the Buttons method could have been used where this example uses the DrawingObjects method.

With DialogSheets("dialog1")
    .DrawingObjects("button 2").Text = "On"
    .DrawingObjects("button 3").Text = "Off"
End With

Because the DrawingObjects method returns all members of the collection, regardless of object type, it may be more convenient to use the accessor method for a particular object type. For example, use the Ovals method to return the collection of ovals on the sheet, or the OptionButtons method to return the collection of option buttons. For more information, see the appropriate object topic.

Properties

Accelerator Property, AddIndent Property, Application Property, ArrowHeadLength Property, ArrowHeadStyle Property, ArrowHeadWidth Property, AutoSize Property, Border Property, CancelButton Property, Caption Property, Count Property, Creator Property, DefaultButton Property, DismissButton Property, Display3DShading Property, DisplayVerticalScrollBar Property, DropDownLines Property, Enabled Property, Font Property, Height Property, HelpButton Property, HorizontalAlignment Property, InputType Property, Interior Property, LargeChange Property, Left Property, LinkedCell Property, List Property, ListFillRange Property, ListIndex Property, Locked Property, LockedText Property, Max Property, Min Property, MultiLine Property, MultiSelect Property, OnAction Property, Orientation Property, Parent Property, PhoneticAccelerator Property, Placement Property, PrintObject Property, RoundedCorners Property, Selected Property, Shadow Property, SmallChange Property, Text Property, Top Property, Value Property, VerticalAlignment Property, Vertices Property, Visible Property, Width Property, ZOrder Property.

Methods

AddItem Method, BringToFront Method, Characters Method, CheckSpelling Method, Copy Method, CopyPicture Method, Cut Method, Delete Method, Duplicate Method, Group Method, Item Method, LinkCombo Method, RemoveAllItems Method, RemoveItem Method, Reshape Method, Select Method, SendToBack Method, Ungroup Method.


DrawingObjects Method

Applies To

Chart Object, DialogSheet Object, Worksheet Object.

Description

Accessor. Returns an object that represents a single drawing object (Syntax 1) or a collection of all the drawing objects (Syntax 2) on the sheet. Returns all drawing objects, including graphic objects, pictures, embedded objects, and embedded charts.

Syntax 1

object.DrawingObjects(index)

Syntax 2

object.DrawingObjects

object

Required. The Chart, DialogSheet, or Worksheet object.

index

Required for Syntax 1. The name or number of the drawing object. Can be an array to return several drawing objects.

See Also

DrawingObjects Collection.

Example

This example deletes drawing object three on Sheet1.

Worksheets("Sheet1").DrawingObjects(3).Delete

This example deletes every drawing object on Sheet1.

Worksheets("Sheet1").DrawingObjects.Delete

This example adds arrowheads to every graphic object on Sheet1 that has the word "Line" in its name.

For Each d In Worksheets("Sheet1").DrawingObjects
    If d.Name Like "*Line*" Then
        d.ArrowHeadLength = xlLong
        d.ArrowHeadStyle = xlOpen
        d.ArrowHeadWidth = xlNarrow
    End If
Next


Drawings Collection Object

Description

A collection of all the Drawing objects (graphic object created by the Freehand, Freeform, or Filled Freeform buttons) on the specified chart sheet, dialog sheet, or worksheet.

Accessors

Use the Drawings method with an argument to access a single member of the collection or without an argument to access the entire collection at once. The following example deletes all of the drawings on worksheet one in the active workbook.

Worksheets(1).Drawings.Delete

Use the Add method to create a new drawing and add it to the collection. You must specify two initial vertices for the drawing. Use the AddVertex method to add vertices once the drawing has been created. The following example creates a new drawing.

With Worksheets("sheet1").Drawings.Add(10, 10, 100, 100, False)
    .AddVertex 150, 150
    .AddVertex 200, 150
End With

You can use the macro recorder to create a more complex example. Turn on the macro recorder (click Record Macro on the Tools menu), and draw a complex freeform drawing. Then turn off the macro recorder, and examine the recorded Visual Basic code.

Properties

Application Property, Border Property, Count Property, Creator Property, Enabled Property, Height Property, Interior Property, Left Property, Locked Property, OnAction Property, Parent Property, Placement Property, PrintObject Property, Shadow Property, Top Property, Visible Property, Width Property, ZOrder Property.

Methods

Add Method (Drawings Collection), BringToFront Method, Copy Method, CopyPicture Method, Cut Method, Delete Method, Duplicate Method, Group Method, Item Method, Reshape Method, Select Method, SendToBack Method.


Drawings Method

Applies To

Chart Object, DialogSheet Object, Worksheet Object.

Description

Accessor. Returns an object that represents a single drawing (a Drawing object, Syntax 1) or a collection of drawings (a Drawings object, Syntax 2) on the sheet. Drawings are created by the Freeform, Freehand, and Filled Freeform buttons on the Drawing toolbar.

Syntax 1

object.Drawings(index)

Syntax 2

object.Drawings

object

Required. The Chart, DialogSheet, or Worksheet object.

index

Required for Syntax 1. The name or number of the drawing to return. More than one index can be specified.

Example

This example brings drawing one to the front of Sheet1.

Worksheets("Sheet1").Drawings(1).BringToFront


DropDown Object

Description

Represents a drop-down list box on the specified chart sheet, dialog sheet, or worksheet, or a combination drop-down edit box on the specified dialog sheet. A user can click an item in the drop-down list or, in combination drop-down edit boxes, type text in the edit box.

You can fill the drop-down list either by specifying a range of cells that contains list items (using the ListFillRange property) or by specifying each item (using the AddItem and RemoveItem methods or the List property).

Accessors

The DropDown object is a member of the DropDowns collection. The DropDowns collection contains all the DropDown objects on a single sheet. Use the Add method to create a new drop-down list box and add it to the collection. Set the editable argument to True to create a combination drop-down edit box (you can only create a combination drop-down edit box on a dialog sheet).

To access a single member of the collection, use the DropDowns method with the index number or name of the drop-down list box as an argument.

Example

The following example sets the items that appears in the drop-down list box when the dialog sheet runs.

DialogSheets(1).DropDowns(1).List = _
    Array("cogs", "widgets", "gadgets", "sprockets")

The drop-down list box name is shown in the Name Box when the drop-down list box is selected. Use the Name property to set or return the drop-down list box name.

The following example sets the list input range for the drop-down list box named "Drop Down 9." When the dialog sheet runs, the contents of cells A1:A10 on the worksheet named "Sheet1" will appear in the drop-down list box.

DialogSheets(1).DropDowns("drop down 9") _
    .ListFillRange = "=sheet1!a1:a10"

Properties

Application Property, BottomRightCell Property, Caption Property, Creator Property, Display3DShading Property, DropDownLines Property, Enabled Property, Height Property, Index Property, Left Property, LinkedCell Property, LinkedObject Property, List Property, ListCount Property, ListFillRange Property, ListIndex Property, Locked Property, Name Property, OnAction Property, Parent Property, Placement Property, PrintObject Property, Text Property, Top Property, TopLeftCell Property, Value Property, Visible Property, Width Property, ZOrder Property.

Methods

AddItem Method, BringToFront Method, Characters Method, Copy Method, CopyPicture Method, Cut Method, Delete Method, Duplicate Method, RemoveAllItems Method, RemoveItem Method, Select Method, SendToBack Method.


DropDownLines Property

Applies To

DrawingObjects Collection, DropDown Object, DropDowns Collection.

Description

Returns or sets the number of list lines displayed in the drop-down portion of a drop-down list box. Read-write.

Remarks

This property is ignored on the Apple Macintosh.

Example

This example sets the number of list lines in drop-down list box one on Dialog1.

DialogSheets("Dialog1").DropDowns(1).DropDownLines = 10


DropDowns Collection Object

Description

A collection of all the DropDown objects on the specified chart sheet, dialog sheet, or worksheet. Each DropDown object represents a drop-down list box or a combination drop-down edit box. A user can click an item in the drop-down list or, in combination drop-down edit boxes, type text in the edit box.

Accessors

Use the Add method to create a drop-down list box and add it to the collection. Set the editable argument to True to create a combination drop-down edit box (you can only create a combination drop-down edit box on a dialog sheet). The following example adds a new drop-down list box to dialog sheet one. The new drop-down list box is positioned relative to the upper-left corner of the dialog frame.

Dim df As DialogFrame
Set df = DialogSheets(1).DialogFrame
DialogSheets(1).DropDowns.Add df.Left + 10, df.Top + 20, 100, 10

Use the DropDowns method with an argument to access a single member of the collection or without an argument to access the entire collection at once. The following example sets the Value property for all the drop-down list boxes on dialog sheet one; each drop-down list box on the sheet will initially display the first item in its list the next time the dialog sheet runs.

DialogSheets(1).DropDowns.Value = 1

Properties

Application Property, Caption Property, Count Property, Creator Property, Display3DShading Property, DropDownLines Property, Enabled Property, Height Property, Left Property, LinkedCell Property, List Property, ListFillRange Property, ListIndex Property, Locked Property, OnAction Property, Parent Property, Placement Property, PrintObject Property, Text Property, Top Property, Value Property, Visible Property, Width Property, ZOrder Property.

Methods

Add Method (DropDowns Collection), AddItem Method, BringToFront Method, Characters Method, Copy Method, CopyPicture Method, Cut Method, Delete Method, Duplicate Method, Group Method, Item Method, RemoveAllItems Method, RemoveItem Method, Select Method, SendToBack Method.


DropDowns Method

Applies To

Chart Object, DialogSheet Object, Worksheet Object.

Description

Accessor. Returns an object that represents a single drop-down list box control (a DropDown object, Syntax 1) or a collection of drop-down list box controls (a DropDowns object, Syntax 2) on the sheet.

Syntax 1

object.DropDowns(index)

Syntax 2

object.DropDowns

object

Required. The Chart, DialogSheet, or Worksheet object.

index

Required for Syntax 1. Specifies the name or number of the drop-down list box control (can be an array to specify more than one).

Example

This example sets the number of list lines in drop-down list box one on Dialog1.

DialogSheets("Dialog1").DropDowns(1).DropDownLines = 10


DropLines Object

Description

Represents the drop lines in a chart group. Drop lines connect the points in the chart with the x-axis. Only line and area chart groups can have drop lines. There is no singular DropLine object; you must turn drop lines on or off for all points in a chart group at once.

Accessors

The DropLines property returns the drop lines for a chart group. The following example turns on drop lines for chart group one in embedded chart one on the worksheet named "Sheet1" and then sets the drop line color.

Worksheets("sheet1").ChartObjects(1).Activate
ActiveChart.ChartGroups(1).HasDropLines = True
ActiveChart.ChartGroups(1).DropLines.Border.ColorIndex = 3

Remarks

If the HasDropLines property is False, most properties of the DropLines object are disabled.

Properties

Application Property, Border Property, Creator Property, Name Property, Parent Property.

Methods

Delete Method, Select Method.


DropLines Property

Applies To

ChartGroup Object.

Description

Accessor. Returns a DropLines object that represents the drop lines for a series on a line or area chart. Applies only to line or area charts. Read-write.

See Also

HasDropLines Property.

Example

This example turns on drop lines for chart group one in Chart1 and then sets their line style, weight, and color. The example should be run on a 2-D line chart that has one series.

With Charts("Chart1").ChartGroups(1)
    .HasDropLines = True
    With .DropLines.Border
        .LineStyle = xlThin
        .Weight = xlMedium
        .ColorIndex = 3
    End With
End With


Duplicate Method

Applies To

Arc Object, Arcs Collection, Button Object, Buttons Collection, ChartObject Object, ChartObjects Collection, CheckBox Object, Drawing Object, DrawingObjects Collection, Drawings Collection, DropDown Object, DropDowns Collection, EditBox Object, EditBoxes Collection, GroupBox Object, GroupBoxes Collection, GroupObject Object, GroupObjects Collection, Label Object, Labels Collection, Line Object, Lines Collection, ListBox Object, ListBoxes Collection, OLEObject Object, OLEObjects Collection, OptionButton Object, OptionButtons Collection, Oval Object, Ovals Collection, Picture Object, Pictures Collection, Rectangle Object, Rectangles Collection, ScrollBar Object, ScrollBars Collection, Spinner Object, Spinners Collection, TextBox Object, TextBoxes Collection.

Description

Duplicates the object and returns a reference to the new copy.

Syntax

object.Duplicate

object

Required. The object to which this method applies.

Example

This example duplicates oval one on Sheet1 and then selects the copy.

Set dOval = Worksheets("Sheet1").Ovals(1).Duplicate
dOval.Select


Edit Method

Applies To

ToolbarButton Object.

Description

Starts the button editor for the specified toolbar button.

Syntax

object.Edit

object

Required. The ToolbarButton object.

Remarks

This method cannot be used with a toolbar button that is a gap or a toolbar button that has a palette or list attached (such as the Font or Style buttons).

Example

This example starts the button editor for the Print button, which is button five on the Standard toolbar.

Application.Toolbars("Standard").ToolbarButtons(5).Edit


EditBox Object

Description

Represents an edit box on a dialog sheet (edit boxes cannot be used on worksheets). Edit boxes allow the user to enter text or numbers. Unlike other controls, edit boxes do not have a Value property or a LinkedCell property. An edit box on a dialog sheet can be linked to a list box to form a combination list edit box, using the LinkCombo method or the Combination List Edit Box button on the Forms toolbar.

Accessors

The EditBox object is a member of the EditBoxes collection. The EditBoxes collection contains all the EditBox objects on a single sheet. Use the Add method to create a new edit box and add it to the collection.

To access a single member of the collection, use the EditBoxes method with the edit box name or index number as an argument.

The following example sets the text appearing in edit box one on the dialog sheet named "Dialog1."

DialogSheets("dialog1").EditBoxes(1).Text = "widgets"

The edit box name is shown in the Name Box when the edit box is selected. Use the Name property to set or return the edit box name. The following example sets the allowed input type for the edit box named "Edit Box 14" on the dialog sheet named "Dialog1."

DialogSheets("dialog1").EditBoxes("edit box 14").InputType = xlInteger

Properties

Application Property, BottomRightCell Property, Caption Property, Creator Property, DisplayVerticalScrollBar Property, Enabled Property, Height Property, Index Property, InputType Property, Left Property, LinkedObject Property, Locked Property, MultiLine Property, Name Property, OnAction Property, Parent Property, PasswordEdit Property, Placement Property, PrintObject Property, Text Property, Top Property, TopLeftCell Property, Visible Property, Width Property, ZOrder Property.

Methods

BringToFront Method, Characters Method, Copy Method, CopyPicture Method, Cut Method, Delete Method, Duplicate Method, Select Method, SendToBack Method.

See Also

TextBox Object


EditBoxes Collection Object

Description

A collection of all the EditBox objects on the specified dialog sheet (edit boxes cannot be used on worksheets). Edit boxes allow the user to enter text or numbers. Unlike other controls, edit boxes do not have a Value property or a LinkedCell property. Edit boxes that are linked to list boxes to form combination list edit boxes are included in the ListBoxes collection.

Accessors

Use the Add method to create a new edit box and add it to the collection. The following example adds a new edit box to the dialog sheet named "Dialog1." The new edit box is positioned relative to the upper-left corner of the dialog frame.

Dim df As DialogFrame
Set df = DialogSheets("dialog1").DialogFrame
DialogSheets("dialog1").EditBoxes.Add df.Left + 10, _
    df.Top + 20, 100, 10

Use the EditBoxes method with an argument to access a single member of the collection or without an argument to access the entire collection at once. The following example empties all the edit boxes on the dialogsheet named "Dialog1."

DialogSheets("dialog1").EditBoxes.Text = ""

Properties

Application Property, Caption Property, Count Property, Creator Property, DisplayVerticalScrollBar Property, Enabled Property, Height Property, InputType Property, Left Property, Locked Property, MultiLine Property, OnAction Property, Parent Property, PasswordEdit Property, Placement Property, PrintObject Property, Text Property, Top Property, Visible Property, Width Property, ZOrder Property.

Methods

Add Method (Graphic Objects and Controls), BringToFront Method, Characters Method, Copy Method, CopyPicture Method, Cut Method, Delete Method, Duplicate Method, Group Method, Item Method, Select Method, ToBack Method.


EditBoxes Method

Applies To

DialogSheet Object.

Description

Accessor. Returns an object that represents a single edit box control (an EditBox object, Syntax 1) or a collection of edit box controls (an EditBoxes object, Syntax 2) on the sheet.

Syntax 1

object.EditBoxes(index)

Syntax 2

object.EditBoxes

object

Required. The DialogSheet object.

index

Required for Syntax 1. Specifies the name or number of the edit box (can be an array to specify me than one).

Example

This example sets the text in edit box one on Dialog1.

DialogSheets("Dialog1").EditBoxes(1).Text = "Start here"


EditDirectlyInCell Property

Applies To

Application Object.

Description

True if Microsoft Excel allows editing in cells. Read-write.

Example

This example enables editing in cells.

Application.EditDirectlyInCell = True


EditionOptions Method

Applies To

Workbook Object.

Description

Sets options for publishers and subscribers in the workbook. Available only on the Apple Macintosh running System 7.

Syntax

object.EditionOptions(type, option, name, reference, appearance, chartSize, formats)

object

Required. The Workbook object.

type

Required. Specifies the edition type to change (either xlPublisher or xlSubscriber).

option

Required. Specifies the type of information to set for the edition. If type is xlPublisher, then option can be one of xlCancel, xlSendPublisher, xlSelect, xlAutomaticUpdate, xlManualUpdate, or xlChangeAttributes. If type is xlSubscriber, then option can be one of xlCancel, xlUpdateSubscriber, xlOpenSource, xlAutomaticUpdate, or xlManualUpdate.

name

Optional. Specifies the name of the edition, as returned from the LinkSources method. If name is omitted, reference must be specified.

reference

Optional (required if name is not specified). Specifies the edition reference as text in R1C1-style form. This argument is required if there is more than one publisher or subscriber with the same edition name in the workbook, or if the name argument is omitted.

appearance

Optional. If option is xlChangeAttributes, specifies whether the edition is published as shown on screen (xlScreen) or as shown when printed (xlPrinter).

chartSize

Optional. If option is xlChangeAttributes and the published object is a chart, specifies the size of the edition (either xlScreen or xlPrinter). If the edition is not a chart, omit this argument.

formats

Optional. If option is xlChangeAttributes, specifies the format of the published edition. Can be any combination of xlPICT, xlBIFF, xlRTF, or xlVALU.


Elevation Property

Applies To

Chart Object.

Description

Returns or sets the elevation of the 3-D chart view, in degrees. Read-write.

Remarks

The chart elevation is the height at which you view the chart, in degrees. The default is 15 for most chart types. The value of this property must be between -90 and 90, except for 3-D bar charts, where it must be between 0 and 44.

See Also

Perspective Property, Rotation Property.

Example

This example sets the chart elevation of Chart1 to 34 degrees. The example should be run on a 3-D chart (the Elevation property fails on 2-D charts).

Charts("Chart1").Elevation = 34


EnableAnimations Property

Applies To

Application Object.

Description

True if animated insertion and deletion is enabled. When animation is enabled, inserted worksheet rows and columns slowly appear, and deleted worksheet rows and columns slowly disappear. This property is available only in Microsoft Excel for Windows 95. Read-write.

Example

This example turns off animated insertion and deletion.

Application.EnableAnimations = False


EnableAutoComplete Property

Applies To

Application Object.

Description

True if the AutoComplete feature is enabled. This property is available only in Microsoft Excel for Windows 95. Read-write.

See Also

AutoComplete Method.

Example

This example enables the AutoComplete feature.

Application.EnableAutoComplete = True


EnableAutoFilter Property

Applies To

Worksheet Object.

Description

True if AutoFilter arrows are enabled when user-interface-only protection is turned on. This property is available only in Microsoft Excel for Windows 95. Read-write.

See Also

Protect Method, Unprotect Method.

Remarks

This property applies to each worksheet and isn't saved with the worksheet or session.

Example

This example enables the AutoFilter arrows on a protected worksheet.

ActiveSheet.EnableAutoFilter = True
ActiveSheet.Protect contents:=True, userInterfaceOnly:=True


EnableCancelKey Property

Applies To

Application Object.

Description

Controls how Microsoft Excel handles CTRL+BREAK (or ESC or COMMAND+PERIOD) user interruptions of the running procedure, as shown in the following table. Read-write.

Value | Meaning
xlDisabled | Cancel key trapping is completely disabled.
xlInterrupt | Interrupt the current procedure and allow the user to debug or end the procedure.
xlErrorHandler | The interrupt is sent to the running procedure as an error, trappable by an error handler setup with an On Error GoTo statement. The trappable error code is 18.

Remarks

Use this property very carefully. If you use xlDisabled, there is no way to interrupt a runaway loop or other non–self-terminating code. If you use xlErrorHandler but your error handler always returns using the Resume statement, there is also no way to stop runaway code.

The EnableCancelKey property is always reset to xlInterrupt whenever Microsoft Excel returns to the idle state and no code is running. To trap or disable cancellation in your procedure you must explicitly change the EnableCancelKey property every time the procedure is called.

Example

This example shows how the EnableCancelKey property can be used to set up a custom cancellation handler.

On Error GoTo handleCancel
Application.EnableCancelKey = xlErrorHandler
MsgBox "This may take a long time: press ESC to cancel"
For x = 1 To 1000000    ' Do something 1,000,000 times (long!)
    ' do something here
Next x

handleCancel:
If Err = 18 Then
    MsgBox "You cancelled"
End If


Enabled Property

Applies To

Arc Object, Arcs Collection, Button Object, Buttons Collection, ChartObject Object, ChartObjects Collection, CheckBox Object, Drawing Object, DrawingObjects Collection, Drawings Collection, DropDown Object, DropDowns Collection, EditBox Object, EditBoxes Collection, GroupBox Object, GroupBoxes Collection, GroupObject Object, GroupObjects Collection, Label Object, Labels Collection, Line Object, Lines Collection, ListBox Object, ListBoxes Collection, Menu Object, MenuItem Object, OLEObject Object, OLEObjects Collection, OptionButton Object, OptionButtons Collection, Oval Object, Ovals Collection, Picture Object, Pictures Collection, Rectangle Object, Rectangles Collection, ScrollBar Object, ScrollBars Collection, Spinner Object, Spinners Collection, TextBox Object, TextBoxes Collection, ToolbarButton Object.

Description

True if the control, drawing object, or menu item is enabled. Read-write, except for Menu, which is write-only.

Remarks

A disabled menu item is gray. A disabled toolbar button beeps when it is pressed.

See Also

Pushed Property.

Example

This example disables all buttons on the Standard toolbar that have custom images.

For Each btn In Application.Toolbars("Standard").ToolbarButtons
    If (Not btn.BuiltInFace And Not btn.IsGap) Then
        btn.Enabled = False
    End If
Next btn


EnableOutlining Property

Applies To

Worksheet Object.

Description

True if outlining symbols are enabled when user-interface-only protection is turned on. This property is available only in Microsoft Excel for Windows 95. Read-write.

Remarks

This property applies to each worksheet and isn't saved with the worksheet or session.

See Also

Protect Method, Unprotect Method.

Example

This example enables outlining symbols on a protected worksheet.

ActiveSheet.EnableOutlining = True
ActiveSheet.Protect contents:=True, userInterfaceOnly:=True


EnablePivotTable Property

Applies To

Worksheet Object.

Description

True if PivotTable controls and actions are enabled when user-interface-only protection is turned on. This property is available only in Microsoft Excel for Windows 95. Read-write.

Remarks

This property applies to each worksheet and isn't saved with the worksheet or session.

There must be a sufficient number of unlocked cells below and to the right of the PivotTable for Microsoft Excel to recalculate and display the PivotTable.

Use the OnDoubleClick property to disable double-clicking in the PivotTable.

See Also

Protect Method, Unprotect Method.

Example

This example enables PivotTable controls on a protected worksheet.

ActiveSheet.EnablePivotTable = True
ActiveSheet.Protect contents:=True, userInterfaceOnly:=True


EnableTipWizard Property

Applies To

Application Object.

Description

True if the TipWizard is enabled. Read-write.

Example

This example enables the TipWizard.

Application.EnableTipWizard = True


Enclosures Property

Applies To

Mailer Object.

Description

Returns or sets the enclosed files attached to the workbook mailer, as an array of strings, with each string indicating the path name of a file to attach as an enclosure. Relative paths are allowed, and are assumed to be based on the current folder. Available only in Microsoft Excel for the Apple Macintosh with the PowerTalk mail system extension installed. Read-write.

See Also

BCCRecipients Property, CCRecipients Property, Mailer Property, Received Property, SendDateTime Property, Sender Property, SendMailer Method, Subject Property, ToRecipients Property.

Example

This example sets up the Mailer object for workbook one and then sends the workbook.

With Workbooks(1)
    .HasMailer = True
    With .Mailer
        .Subject = "Here is the workbook"
        .ToRecipients = Array("Jean")
        .CCRecipients = Array("Adam", "Bernard")
        .BCCRecipients = Array("Chris")
        .Enclosures = Array("TestFile")
    End With
    .SendMailer
End With


End Method

Applies To

Range Object.

Description

Returns a Range object that represents the cell at the end of the region that contains the source range. Equivalent to pressing END+UP ARROW, END+DOWN ARROW, END+LEFT ARROW, or END+RIGHT ARROW.

Syntax

object.End(direction)

object

Required. A cell in the range.

direction

Required. Specifies the direction to move. One of xlToLeft, xlToRight, xlUp, or xlDown.

Example

This example selects the cell at the top of column B in the region containing cell B4.

Range("B4").End(xlUp).Select

This example selects the cell at the end of row 4 in the region containing cell B4.

Range("B4").End(xlToRight).Select

This example extends the selection from cell B4 to the last cell in row four that contains data.

Worksheets("Sheet1").Activate
Range("B4", Range("B4").End(xlToRight)).Select


End Statement

Description

Ends a procedure or block.

Syntax

End

End Function

End If

End Property

End Select

End Sub

End Type

End With

The End statement syntax has these forms:

Statement | Description
End | Terminates procedure execution. Never required by itself but may be placed anywhere in a procedure to close files opened with the Open statement and to clear variables.
End Function | Required to end a Function statement.
End If | Required to end a block If...Then...Else statement.
End Property | Required to end a Property Let, Property Get, or Property Set procedure.
End Select | Required to end a Select Case statement.
End Sub | Required to end a Sub statement.
End Type | Required to end a user-defined type definition (Type statement).
End With | Required to end a With statement.

Remarks

Note

When executed, the End statement resets all module-level variables and all static local variables in all modules. If you need to preserve the value of these variables, use Stop instead. You can then resume execution while preserving the value of those variables.

See Also

Exit Statement, Function Statement, If...Then...Else Statement, Property Get Statement, Property Let Statement, Property Set Statement, Select Case Statement, Stop Statement, Sub Statement, Type Statement, With Statement.

Example

This example uses the End Statement to end code execution, a Select Case block, and a Sub procedure.

Sub EndStatementDemo()
    For Number = 1 To 2    ' Loop 2 times.
        Select Case Number    ' Evaluate Number.
            Case 1    ' If Number equals 1.
                Debug.Print Number     ' Print value to Debug window.
            Case Else    ' If Number does not equal 1.
                End    ' Terminate procedure execution.
        End Select    ' End of Select Case Statement.
    Next Number
End Sub    ' End of Sub procedure.


EndStyle Property

Applies To

ErrorBars Object.

Description

Returns or sets the end style for the error bars (either xlCap or xlNoCap). Read-write.

Example

This example sets the end style for the error bars for series one in Chart1. The example should be run on a 2-D line chart that has Y error bars for the first series.

Charts("Chart1").SeriesCollection(1).ErrorBars.EndStyle = xlCap


EntireColumn Property

Applies To

Range Object.

Description

Accessor. Returns a Range object that represents the entire column (or columns) that contain the specified range. Read-only.

See Also

EntireRow Property.

Example

This example selects the entire column that contains the active cell. The example must be run from a worksheet.

ActiveCell.EntireColumn.Select


EntireRow Property

Applies To

Range Object.

Description

Accessor. Returns a Range object that represents the entire row (or rows) that contain the specified range. Read-only.

See Also

EntireColumn Property.

Example

This example selects the entire row that contains the active cell. The example must be run from a worksheet.

ActiveCell.EntireRow.Select


EOF Function

Description

Returns a value that indicates whether the end of a file has been reached.

Syntax

EOF(filenumber)

The filenumber named argument is any valid file number.

Remarks

Use EOF to avoid an error when attempting to get input past the end of a file.

False is returned unless the end of the file has been reached; then True is returned. When used with files opened for Random or Binary access, EOF returns False unless the last executed Get statement is unable to read an entire record; then True is returned.

See Also

Loc Function, LOF Function, Open Statement.

Example

This example uses the EOF function to detect the end of a file. For purposes of this example, assume that MyFile is a text file with a few lines of text.

Open "MyFile" For Input As #1    ' Open file for input.
Do While Not EOF(1)    ' Check for end of file.
    Line Input #1, InputData    ' Read line of data.
    Debug.Print InputData    ' Print to Debug window.
Loop
Close #1    ' Close file.


Eqv Operator

Description

Used to perform a logical equivalence on two expressions.

Syntax

result = expression1 Eqv expression2

The Eqv operator syntax has these parts:

Part | Description
result | Any numeric variable.
expression1 | Any expression.
expression2 | Any expression.

Remarks

If either expression is a Null, result is also a Null. When neither expression is a Null, result is determined according to the following table:

If expression1 is | And expression2 is | The result is
True | True | True
True | False | False
False | True | False
False | False | True

The Eqv operator performs a bit-wise comparison of identically positioned bits in two numeric expressions and sets the corresponding bit in result according to the following truth table:

If bit in expression1 is | And bit in expression2 is | The result is
0 | 0 | 1
0 | 1 | 0
1 | 0 | 0
1 | 1 | 1

See Also

Operator Precedence.

Example

This example uses the Eqv operator to perform logical equivalence on two expressions.

A = 10: B = 8: C = 6 : D = Null    ' Initialize variables.
MyCheck = A > B Eqv B > C    ' Returns True.
MyCheck = B > A Eqv B > C    ' Returns False.
MyCheck = A > B Eqv B > D    ' Returns Null.
MyCheck = A Eqv B            ' Returns -3 (bit-wise comparison).


Erase Statement

Description

Reinitializes the elements of fixed-size arrays and deallocates dynamic-array storage space.

Syntax

Erase arraylist

The arraylist argument is one or more comma-delimited array variables to be erased.

Remarks

It is important to know whether an array is fixed-size (ordinary) or dynamic because Erase behaves differently depending on the type of array. No memory is recovered for fixed-size arrays. Erase sets the elements of a fixed array as follows:

Type of array | Effect of Erase on fixed-array elements
Fixed numeric array | Sets each element to zero.
Fixed string array (variable length) | Sets each element to zero-length ("").
Fixed string array (fixed length) | Sets each element to zero.
Fixed Variant array | Sets each element to Empty.
Array of user-defined types | Sets each element as if it were a separate variable.
Array of objects | Sets each element to the special value Nothing.

Erase frees the memory used by dynamic arrays. Before your program can refer to the dynamic array again, it must redeclare the array variable's dimensions using a ReDim statement.

See Also

Array Function, Dim Statement, Private Statement, Public Statement, ReDim Statement, Static Statement.

Example

This example uses the Erase statement to reinitialize the elements of fixed-size arrays and deallocate dynamic-array storage space.

' Declare array variables.
Dim NumArray(10) As Integer    ' Integer array.
Dim StrVarArray(10) As String    ' Variable-string array.
Dim StrFixArray(10) As String * 10    ' Fixed-string array.
Dim VarArray(10) As Variant    ' Variant array.
Dim DynamicArray() As Integer    ' Dynamic array.
ReDim DynamicArray(10)    ' Allocate storage space.
Erase NumArray    ' Each element set to 0.
Erase StrVarArray    ' Each element set to "".
Erase StrFixArray    ' Each element set to 0.
Erase VarArray    ' Each element set to Empty.
Erase DynamicArray    ' Free memory used by array.


Err Statement

Description

Sets Err to a specific value.

Syntax

Err = errornumber

The errornumber argument can be any valid error number or 0, which means no run-time error occurred.

Remarks

Err is used to record whether a run-time error has occurred and identifies the error. Use the Err statement to set Err to a nonzero, whole number to communicate error information between procedures. For example, you might use one of the unassigned run-time error numbers as an application-specific error number. To determine which error numbers are being used, use the Error function, the Error statement, or both. To avoid conflict with existing error numbers, create user-defined errors by defining your first error at 65,535 and work down from there.

You can also set Err to 0 using any form of the Resume or On Error statement or by executing an Exit Sub, Exit Function or Exit Property statement within an error handler. In addition, the Error statement can set Err to any value to simulate any run-time error.

See Also

Err Function, Error Function, Error Statement.

Example

This example shows how the Err statement is used to clear an error by setting Err to 0. Error number 55 is generated to illustrate its usage.

On Error Resume Next    ' Enable error handling.
Open "TESTFILE" For Output as #1    ' Open file for output.
Kill "TESTFILE"    ' Attempt to delete open file.
Select Case Err    ' Evaluate Error Number.
    Case 55    ' "File already open" error.
        Close #1    ' Close open file.
        Kill "TESTFILE"    ' Delete file.
        Err = 0    ' Reset Err to 0.
    Case Else
        ' Handle other situations here...
End Select


Err, Erl Functions

Description

Returns error status.

Syntax

Err

Erl

Remarks

After an error occurs, the Err function returns a number that is the run-time error number, identifying the error. The Erl function returns a number that is the line number of the line in which the error occurred, or the numbered line most closely preceding it.

Because Err and Erl return meaningful values only after an error has occurred, they are usually used in error-handling routines to determine the error and corrective action. Both Err and Erl are reset to 0 after any form of the Resume or On Error statement and after an Exit Sub or Exit Function statement within an error-handling routine.

Caution

If you set up an error handler using On Error GoTo and that error handler calls another procedure, the value of Err and Erl may be reset to 0. To make sure that the value doesn't change, assign the values of Err or Erl to variables before calling another procedure or before executing Resume, On Error, Exit Sub, Exit Function, or Exit Property.

You can directly set the value returned by the Err function using the Err statement. You can set values for both Err and Erl indirectly using the Error statement.

The Erl function returns only a line number, not a line label, located at or before the line producing the error. Line numbers greater than 65,529 are treated as line labels and can't be returned by Erl. If your procedure has no line numbers, or if there is no line number before the point at which an error occurs, Erl returns 0.

See Also

Err Statement, Error Function, Error Statement, On Error Statement, Resume Statement.

Example

This example shows an error-handling routine which uses the Err and Erl functions. If there are no additional errors, Err returns error number 11 and Erl returns line 1030.

Sub ErrDemo()
1010  On Error GoTo ErrorHandler    ' Set up an error handler.
1020  B = 1: C = 0    ' Initialize variables.
1030  A = B \ C    ' Cause a "Division by zero" error.
1040  Exit Sub
ErrorHandler:    ' Error handler.
    ErrorNumber = Err     ' Get run-time error number.
    ErrorLine = Erl    ' Get line number.
    Resume Next    ' Resume execution at next line.
End Sub


Error Function

Description

Returns the error message that corresponds to a given error number.

Syntax

Error[(errornumber)]

The errornumber argument can be any valid error number. If errornumber is not defined, an error occurs. If omitted, the message corresponding to the most recent run-time error is returned. If no run-time error has occurred, Error returns a zero-length string ("").

Remarks

Use the Err function to return the error number for the most recent run-time error.

See Also

Err Function, Error Statement.

Example

This example uses the Error function to print error messages that correspond to the specified error numbers.

For ErrorNumber = 61 To 64    ' Loop through values 61 - 64.
    Debug.Print Error(ErrorNumber)    ' Print error to Debug window.
Next ErrorNumber


Error Statement

Description

Simulates the occurrence of an error.

Syntax

Error errornumber

The errornumber can be any valid error number.

Remarks

If errornumber is defined, the Error statement simulates the occurrence of that error; that is, it sets the value of Err to errornumber.

To define your own error numbers, use a number greater than any of the standard error numbers. To avoid conflict with existing error numbers, create user-defined errors by defining your first error at 65,535 and work down from there.

If an Error statement is executed when no error-handling routine is enabled, an error message is displayed and execution stops. If the Error statement specifies an error number that is not used, an error message is displayed.

See Also

Err Function, Error Function, On Error Statement, Resume Statement.

Example

This example uses the Error statement to simulate error 11.

On Error Resume Next    ' Enable error handling.
Error 11    ' Simulate the "Division by zero" error.


ErrorBar Method

Applies To

Series Object.

Description

Applies error bars to the series.

Syntax

object.ErrorBar(direction, include, type, amount, minusValues)

object

Required. The Series object.

direction

Optional. Specifies the error bar direction (can be xlX or xlY; X is only available for scatter charts). If omitted, error bars are applied in the Y direction.

include

Optional. Specifies the error bar parts to include (one of xlPlusValues, xlMinusValues, xlNone, or xlBoth). If omitted, both error bars are included.

type

Optional. Specifies the error bar type (one of xlFixedValue, xlPercent, xlStDev, xlStError, or xlCustom).

amount

Optional. The error amount. Used for only the positive error amount when type = xlCustom.

minusValues

Optional. The negative error amount when type = xlCustom.

See Also

ErrorBars Property, HasErrorBars Property.

Example

This example applies standard error bars in the Y direction for series one in Chart1. The error bars are applied in the positive and negative directions. The example should be run on a 2-D line chart.

Charts("Chart1").SeriesCollection(1).ErrorBar _
    direction:=xlY, include:=xlBoth, type:=xlStError


ErrorBars Object

Description

Represents the error bars on a chart series. Error bars indicate the degree of uncertainty for chart data. Only series in area, bar, column, line, and scatter groups on a 2-D chart can have error bars. Only series in scatter groups can have x and y error bars. There is no singular ErrorBar object; you must turn x error bars or y error bars on or off for all points on a series at once.

Accessors

The ErrorBars property returns the error bars for a chart series. The following example turns on error bars for series one in embedded chart one on the worksheet named "Sheet1" and then sets the end style for the error bars.

Worksheets("sheet1").ChartObjects(1).Activate
ActiveChart.SeriesCollection(1).HasErrorBars = True
ActiveChart.SeriesCollection(1).ErrorBars.EndStyle = xlNoCap

Remarks

The ErrorBar method changes the error bar format and type.

Properties

Application Property, Border Property, Creator Property, EndStyle Property, Name Property, Parent Property.

Methods

ClearFormats Method, Delete Method, Select Method.


ErrorBars Property

Applies To

Series Object.

Description

Accessor. Returns an ErrorBars object that represents the error bars for the series. Read-only.

See Also

ErrorBar Method, HasErrorBars Property.

Example

This example sets the error bar color for series one in Chart1. The example should be run on a 2-D line chart that has error bars for series one.

With Charts("Chart1").SeriesCollection(1)
    .ErrorBars.Border.ColorIndex = 8
End With


Evaluate Method

Applies To

Application Object, Chart Object, DialogSheet Object, Worksheet Object.

Description

Converts a Microsoft Excel name to an object or to a value.

Syntax

object.Evaluate(name)

object

Optional for Application, required for Chart, DialogSheet, and Worksheet. Contains the named object.

name

Required. The name of the object, using the naming convention of Microsoft Excel.

Remarks

The following names in Microsoft Excel may be used with this method:

A1-style references. Any reference to a single cell using A1 notation. All references are considered to be absolute references.

Ranges. You may use the range, intersect, and union operators (colon, space, and comma) with references.

Defined names in the language of the macro.

External references using the ! operator. These references could be to a cell or a name defined in another workbook, for example, Evaluate("[BOOK1.XLS]Sheet1!A1").

Graphic objects using their Microsoft Excel name ("Oval 3", for example). You cannot use the number alone.

Note

Using square brackets (for example, "[A1:C5]") is identical to calling the Evaluate method with a string argument. For example, the following expression pairs are equivalent.

[a1].Value = 25
Evaluate("A1").Value = 25
trigVariable = [SIN(45)]
trigVariable = Evaluate("SIN(45)")
Set firstCellInSheet = Workbooks("BOOK1.XLS").Sheets(4).[A1]
Set firstCellInSheet = Workbooks("BOOK1.XLS").Sheets(4).Evaluate("A1")

The advantage of using square brackets is that it is shorter. The advantage of using Evaluate is that the argument is a string, so you can construct the string in your code or use a Visual Basic variable.

Example

This example turns on bold formatting in cell A1 on Sheet1.

Worksheets("Sheet1").Activate
boldCell = "A1"
Application.Evaluate(boldCell).Font.Bold = True


Excel4IntlMacroSheets Method

Applies To

Application Object, Workbook Object.

Description

Accessor. Returns an object that represents a Microsoft Excel 4.0 international macro sheet (a Worksheet object, Syntax 1) or a collection of all Microsoft Excel 4.0 international macro sheets (a Worksheets object, Syntax 2) in the workbook. Read-only.

Syntax 1

object.Excel4IntlMacroSheets(index)

Syntax 2

object.Excel4IntlMacroSheets

object

Optional for Application, required for Workbook. The object that contains Microsoft Excel 4.0 international macro sheets.

index

Required for Syntax 1. The name or number of the Microsoft Excel 4.0 international macro sheet to return.

Remarks

Using this method with no object qualifier is a shortcut for ActiveWorkbook.Excel4IntlMacroSheets.

See Also

Excel4MacroSheets Method, Worksheets Method.

Example

This example displays the number of Microsoft Excel 4.0 international macro sheets in the active workbook.

MsgBox "There are " & ActiveWorkbook.Excel4IntlMacroSheets.Count & _
    " Microsoft Excel 4.0 international macro sheets in this workbook."


Excel4MacroSheets Method

Applies To

Application Object, Workbook Object.

Description

Accessor. Returns an object that represents a Microsoft Excel 4.0 macro sheet (a Worksheet object, Syntax 1) or a collection of all Microsoft Excel 4.0 macro sheets (a Worksheets object, Syntax 2) in the workbook. Read-only.

Syntax 1

object.Excel4MacroSheets(index)

Syntax 2

object.Excel4MacroSheets

object

Optional for Application, required for Workbook. The object that contains Microsoft Excel 4.0 macro sheets.

index

Required for Syntax 1. The name or number of the Microsoft Excel 4.0 macro sheet to return.

Remarks

Using this method with no object qualifier is a shortcut for ActiveWorkbook.Excel4MacroSheets.

See Also

Excel4IntlMacroSheets Method, Worksheets Method.

Example

This example displays the number of Microsoft Excel 4.0 macro sheets in the active workbook.

MsgBox "There are " & ActiveWorkbook.Excel4MacroSheets.Count & _
    " Microsoft Excel 4.0 macro sheets in this workbook."


ExclusiveAccess Method

Applies To

Workbook Object.

Description

Assigns the current user exclusive access to the workbook that's open as a shared list. Returns True if the workbook is successfully made an exclusive, nonshared list. This method is available only in Microsoft Excel for Windows 95.

Syntax

object.ExclusiveAccess

object

Required. The Workbook object.

Remarks

The ExclusiveAccess method saves any changes you've made to the workbook and requires other users who have the workbook open to save changes to a different file.

If the specified workbook isn't open as a shared list, ExclusiveAccess fails. To determine whether a workbook is open as a shared list, use the MultiUserEditing property.

See Also

MultiUserEditing Property, SaveAs Method.

Example

This example determines whether the active workbook is open as a shared list. If it is, the example assigns the current user exclusive access.

If ActiveWorkbook.MultiUserEditing Then
    ActiveWorkbook.ExclusiveAccess
End If


ExecuteExcel4Macro Method

Applies To

Application Object.

Description

Runs a Microsoft Excel 4.0 macro function and returns the results of the function. Returned type depends on the function. Read-write.

Syntax

object.ExecuteExcel4Macro(string)

object

Optional. The Application object.

string

Required. A Microsoft Excel 4.0 macro language function without the equal sign. All references must be given as R1C1 strings. If string contains embedded double quotation marks, then you must double them. For example, to run the macro function =MID("sometext",1,4), string would have to be "MID(""sometext"",1,4)".

Remarks

The Microsoft Excel 4.0 macro is not evaluated in the context of the current workbook or sheet. This means that any references should be external and should specify an explicit workbook name. For example, to run a Microsoft Excel 4.0 macro "My_Macro" in Book1 you must use "Book1!My_Macro()". If you do not specify the workbook name, this method fails.

See Also

Run Method.

Example

This example runs the GET.CELL(42) macro function on cell C3 on Sheet1 and displays the result in a message box. The GET.CELL(42) macro function returns the horizontal distance from the left edge of the active window to the left edge of the active cell. This macro function has no direct Visual Basic equivalent.

Worksheets("Sheet1").Activate
Range("C3").Select
MsgBox ExecuteExcel4Macro("GET.CELL(42)")


Exit Statement

Description

Exits a block of Do...Loop, For...Next, Function, Sub, or Property code.

Syntax

Exit Do

Exit For

Exit Function

Exit Property

Exit Sub

The Exit statement syntax has these forms:

Statement | Description
Exit Do | Provides a way to exit a Do...Loop statement. It can be used only inside a Do...Loop statement. Exit Do transfers control to the statement following the Loop statement. When used within nested Do...Loop statements, Exit Do transfers control to the loop that is one nested level above the loop where it occurs.
Exit For | Provides a way to exit a For loop. It can be used only in a For...Next or For Each...Next loop. Exit For transfers control to the statement following the Next statement. When used within nested For loops, Exit For transfers control to the loop that is one nested level above the loop where it occurs.
Exit Function | Immediately exits the Function procedure in which it appears. Execution continues with the statement following the statement that called the Function.
Exit Property | Immediately exits the Property procedure in which it appears. Execution continues with the statement following the statement that called the Property procedure.
Exit Sub | Immediately exits the Sub procedure in which it appears. Execution continues with the statement following the statement that called the Sub.

Remarks

Do not confuse Exit statements with End statements. Exit does not define the end of a structure.

See Also

Do...Loop Statement, End Statement, For...Next Statement, Function Statement, Property Get Statement, Property Let Statement, Property Set Statement, Stop Statement, Sub Statement.

Example

This example uses the Exit statement to exit a For...Next loop, a Do...Loop, and a Sub procedure.

Sub ExitStatementDemo()
    Do    ' Set up infinite loop.
    For I = 1 To 1000    ' Loop 1000 times.
    MyNum = Int(Rnd * 1000)    ' Generate random numbers.
    Select Case MyNum    ' Evaluate random number.
    Case 7: Exit For    ' If 7, exit For...Next.
    Case 29: Exit Do    ' If 29, exit Do...Loop.
    Case 54: Exit Sub    ' If 54, exit Sub procedure.
    End Select
    Next I
    Loop
End Sub


Exp Function

Description

Returns e (the base of natural logarithms) raised to a power.

Syntax

Exp(number)

The number named argument can be any valid numeric expression.

Remarks

If the value of number exceeds 709.782712893, an error occurs. The constant e is approximately 2.718282.

Note

The Exp function complements the action of the Log function and is sometimes referred to as the antilogarithm.

See Also

Derived Math Functions, Log Function.

Example

This example uses the Exp function to return e raised to a power.

' Define angle in radians.
MyAngle = 1.3
' Calculate hyperbolic sine.
MyHSin = (Exp(MyAngle) - Exp(- 1 * MyAngle)) / 2


Explosion Property

Applies To

Point Object, Series Object.

Description

Returns or sets the percentage of pie-chart or doughnut-chart slice explosion. Zero is no explosion (the tip of the slice is in the center of the pie). Read-write.

Example

This example sets the explosion value for point two in Chart1. The example should be run on a pie chart.

Charts("Chart1").SeriesCollection(1).Points(2).Explosion = 20


Extend Method

Applies To

SeriesCollection Collection.

Description

Adds new data points to an existing series collection.

Syntax

object.Extend(source, rowcol, categoryLabels)

object

Required. The SeriesCollection object.

source

Required. Specifies the new data to be added to the SeriesCollection object, either as a Range or an array of data points.

rowcol

Optional. Specifies whether the new values are in the rows (xlRows) or columns (xlColumns) of the given range source. If this argument is omitted, Microsoft Excel attempts to determine where the values are by the size and orientation of the selected range or dimensions of the array. This argument is ignored if the source data is in an array.

categoryLabels

Optional. Ignored if source is an array. True if the first row or column contains the name of the category labels. False if the first row or column contains the first data point of the series. If this argument is omitted, Microsoft Excel attempts to determine the category label location from the contents of the first row or column.

See Also

Add Method (SeriesCollection Collection).

Example

This example extends the series on Chart1 by adding the data in cells B1:B6 on Sheet1.

Charts("Chart1").SeriesCollection.Extend _
        source:=Worksheets("Sheet1").Range("B1:B6")


FileAttr Function

Description

Returns file mode or operating system file handle information for files opened using the Open statement.

Syntax

FileAttr(filenumber,returnType)

The FileAttr function syntax has these named-argument parts:

Part | Description
filenumber | Any valid file number.
returnType | Number indicating the type of information to return: specify 1 to return a value indicating the file mode; specify 2 to return the operating system file handle.

Return Values

When the returnType argument is 1, the following return values indicate the file mode:

Value | File Mode
1 | Input
2 | Output
4 | Random
8 | Append
32 | Binary

See Also

GetAttr Function, Open Statement, SetAttr Statement.

Example

This example uses the FileAttr function to return the file mode and file handle of an open file.

FileNum = 1    ' Assign file number.
Open "TESTFILE" For Append As FileNum    ' Open file.
Handle = FileAttr(FileNum, 1)    ' Returns 8 (Append file mode).
Mode = FileAttr(FileNum, 2)    ' Returns file handle.
Close FileNum    ' Close file.


FileConverters Property

Applies To

Application Object.

Description

Returns a list of installed file converters as a text array. Each row in the array contains information about a single file converter, as shown in the following table. Returns Null if there are no converters installed. Read-only.

Column | Contents
1 | The long name of the converter, including the file type search string in Microsoft Windows (for example "Lotus 1-2-3 Files (*.wk*)").
2 | The path name of the converter DLL or code resource.
3 | The file extension search string in Microsoft Windows or the four-character file type on the Apple Macintosh.

Example

This example displays a message if the Multiplan file converter is installed.

installedCvts = Application.FileConverters
foundMultiplan = False
If Not IsNull(installedCvts) Then
    For arrayRow = 1 To UBound(installedCvts, 1)
        If installedCvts(arrayRow, 1) Like "*Multiplan*" Then
            foundMultiplan = True
            Exit For
        End If
    Next arrayRow
End If
If foundMultiplan = True Then
    MsgBox "Multiplan converter is installed"
Else
    MsgBox "Multiplan converter is not installed"
End If


FileCopy Statement

Description

Copies a file.

Syntax

FileCopy source, destination

The FileCopy statement syntax has these named argument parts:

Part | Description
source | String expression that specifies the name of the file to be copied — may include directory or folder, and drive.
destination | String expression that specifies the target file name — may include directory or folder, and drive.

Remarks

Open files can only be copied for read-only access.

See Also

Kill Statement, Name Statement.

Example

This example uses the FileCopy statement to copy one file to another. For purposes of this example, assume that SRCFILE is a file containing some data.

SourceFile = "SRCFILE"    ' Define source file name.
DestinationFile = "DESTFILE"    ' Define target file name.
FileCopy SourceFile, DestinationFile    ' Copy source to target.


FileDateTime Function

Description

Returns a date that indicates the date and time when a file was created or last modified .

Syntax

FileDateTime(pathname)

The pathname named argument is a string expression that specifies a file name — may include directory or folder, and drive.

See Also

FileLen Function, GetAttr Function.

Example

This example uses the FileDateTime function to get the date and time when a file was created or last modified. The format of the date and time displayed is based on the locale settings of your system.

' Assume TESTFILE was last modified on February 12 1993 at 4:35:47 PM.
' Assume United States/English locale settings.
MyStamp = FileDateTime("TESTFILE")    ' Returns "2/12/93 4:35:47 PM".


FileFormat Property

Applies To

Workbook Object.

Description

Returns the file format and/or type of the workbook, as shown in the following list. Read-only.

xlAddIn

xlCSV

xlCSVMac

xlCSVMSDOS

xlCSVWindows

xlDBF2

xlDBF3

xlDBF4

xlDIF

xlExcel2

xlExcel3

xlExcel4

xlExcel4Workbook

xlIntlAddIn

xlIntlMacro

xlNormal

xlSYLK

xlTemplate

xlText

xlTextMac

xlTextMSDOS

xlTextWindows

xlTextPrinter

xlWK1

xlWK3

xlWKS

xlWQ1

xlWK3FM3

xlWK1FMT

xlWK1ALL

Remarks

The following additional formats are available in Far East Microsoft Excel: xlWJ2WD1, xlExcel2FarEast, and xlWorks2FarEast.

Example

This example saves the active workbook in Normal file format if its current file format is WK3.

If ActiveWorkbook.FileFormat = xlWK3 Then
    ActiveWorkbook.SaveAs fileFormat:=xlNormal
End If


FileLen Function

Description

Returns the length of a file in bytes.

Syntax

FileLen(pathname)

The pathname named argument is a string expression that specifies a file name — may include directory or folder, and drive.

Remarks

If the specified file is open when the FileLen function is called, the value returned represents the last saved disk size of the file.

To obtain the length of an open file, use the LOF function.

See Also

FileDateTime Function, GetAttr Function, LOF Function.

Example

This example uses the FileLen function to return the length of a file in bytes. For purposes of this example, assume that TESTFILE is a file containing some data.

MySize = FileLen("TESTFILE")    ' Returns file length (bytes).


FillAcrossSheets Method

Applies To

Sheets Collection, Worksheets Collection.

Description

Copies a range to the same area on all other worksheets in a collection.

Syntax

object.FillAcrossSheets(range, type)

object

Required. The Sheets or Worksheets object.

range

Required. Specifies the range to fill across the worksheets in the collection. The range must be from a worksheet within the collection.

type

Optional. Specifies how to copy the range (one of xlAll, xlContents, or xlFormulas). The default is xlAll if this argument is omitted.

Example

This example fills the range A1:C5 on Sheet1, Sheet5, and Sheet7 with the contents of the same range on Sheet1.

x = Array("Sheet1", "Sheet5", "Sheet7")
Sheets(x).FillAcrossSheets _
    Worksheets("Sheet1").Range("A1:C5")


FillDown Method

Applies To

Range Object.

Description

Fills down from the top cell or cells of the range to the bottom. Copies the contents and formats of the cell or cells in the top row of a range into the rest of the rows in the range.

Syntax

object.FillDown

object

Required. The range to fill.

See Also

AutoFill Method, FillLeft Method, FillRight Method, FillUp Method.

Example

This example fills the range A1:A10 on Sheet1, based on the contents of cell A1.

Worksheets("Sheet1").Range("A1:A10").FillDown


FillLeft Method

Applies To

Range Object.

Description

Fills left from the rightmost cell or cells of the range to the left. Copies the contents and formats of the cell or cells in the right column of a range into the rest of the columns in the range.

Syntax

object.FillLeft

object

Required. The range to fill.

See Also

AutoFill Method, FillDown Method, FillRight Method, FillUp Method.

Example

This example fills the range A1:M1 on Sheet1, based on the contents of cell M1.

Worksheets("Sheet1").Range("A1:M1").FillLeft


FillRight Method

Applies To

Range Object.

Description

Fills right from the leftmost cell or cells of the range to the right. Copies the contents and formats of the cell or cells in the left column of a range into the rest of the columns in the range.

Syntax

object.FillRight

object

Required. The range to fill.

See Also

AutoFill Method, FillDown Method, FillLeft Method, FillUp Method.

Example

This example fills the range A1:M1 on Sheet1, based on the contents of cell A1.

Worksheets("Sheet1").Range("A1:M1").FillRight


FillUp Method

Applies To

Range Object.

Description

Fills up from the bottom cell or cells of the range to the top. Copies the contents and formats of the cell or cells in the bottom row of a range into the rest of the rows in the range.

Syntax

object.FillUp

object

Required. The range to fill.

See Also

AutoFill Method, FillDown Method, FillLeft Method, FillRight Method.

Example

This example fills the range A1:A10 on Sheet1, based on the contents of cell A10.

Worksheets("Sheet1").Range("A1:A10").FillUp


FilterMode Property

Applies To

Worksheet Object.

Description

True if the worksheet is in filter mode. Read-only.

Remarks

This property will be True if the worksheet contains a filtered list in which there are hidden rows.

See Also

AdvancedFilter Method, AutoFilter Method, AutoFilterMode Property, ShowAllData Method.

Example

This example displays the filter status of Sheet1 in a message box.

If Worksheets("Sheet1").FilterMode = True Then
    MsgBox "Filter mode is on"
Else
    MsgBox "Filter mode is off"
End If


Find Method

Applies To

Range Object.

Description

Finds specific information in a range, and returns a Range object that represents the first cell where it is found. Returns Nothing if no match is found. Does not affect the selection or active cell.

For help about using the Find worksheet function in Visual Basic, see "Using Worksheet Functions in Visual Basic" in online Help.

Syntax

object.Find(what, after, lookIn, lookAt, searchOrder, searchDirection, matchCase, matchByte)

object

Required. The range to search.

what

Required. The contents for which you want to search. May be a string or any Microsoft Excel data type.

after

Optional. The first cell after which you want to search. This corresponds to the position of the active cell when a search is done from the user interface. Note that after must be one cell in the range. If this argument is omitted, the top left cell of the range is used as the starting point for the search. Remember that the search begins after this cell; the specified cell is not searched until the method wraps back around to this cell.

lookIn

Optional. One of xlFormulas, xlValues, or xlNotes.

lookAt

Optional. May be xlWhole or xlPart.

searchOrder

Optional. One of xlByRows (to search row-major) or xlByColumns (to search column-major).

searchDirection

Optional. xlNext or xlPrevious; if omitted it is xlNext.

matchCase

Optional. If True, case-sensitive search is performed.

matchByte

Optional. Used only in Far East Microsoft Excel. If True, double-byte characters match only double-byte characters. If False, double-byte characters can match their single-byte equivalents.

Remarks

The settings for lookIn, lookAt, searchOrder, matchCase, and matchByte are saved each time you use this method. If you do not specify values for these arguments the next time you call the method, the saved values are used. Setting these arguments changes the settings in the Find dialog box, and changing the settings in the Find dialog box changes the saved values that are used if you omit the arguments. To avoid problems, explicitly set these arguments each time you use this method.

The FindNext and FindPrevious methods can be used to repeat the search.

When the search reaches the end of the specified search range, it wraps around to the beginning of the range. To stop a search when this wraparound occurs, save the address of the first found cell, and then test each successive found-cell address against this saved address.

To find cells matching more complicated patterns, use For Each with the Like operator. For example, the following code searches for all cells in the range A1:C5 that use a font starting with the letters "Cour". When it finds a match, it changes the font to Times New Roman:

For Each c In [A1:C5]
    If c.Font.Name Like "Cour*" Then
        c.Font.Name = "Times New Roman"
    End If
Next

See Also

FindNext Method, FindPrevious Method, Replace Method.

Example

This example finds the first occurrence of the word Phoenix in column B on Sheet1 and then displays the address of the cell that contains this word. If the word is not found, the example diplays a message.

Set foundCell = Worksheets("Sheet1").Columns("B").Find("Phoenix")
If foundCell Is Nothing Then
    MsgBox "The word was not found"
Else
    MsgBox "The word was found in cell " & foundCell.Address
End If


FindFile Method

Applies To

Application Object.

Description

Displays the File Open dialog box.

Syntax

object.FindFile

object

Required. The Application object.

Remarks

This method displays the File Open dialog box and allows the user to open a file. If a new file is opened successfully, this method returns True. If the user cancels the dialog box, this method returns False.

Example

This example displays the Open dialog box.

Application.FindFile


FindNext Method

Applies To

Range Object.

Description

Continues a search started with the Find method. Finds the next cell matching the same conditions and returns a Range object that represents that cell. Does not affect the selection or active cell.

Syntax

object.FindNext(after)

object

Required. The range to search.

after

Optional. The first cell after which you want to search. This corresponds to the position of the active cell when a search is done from the user interface. If omitted, the top left cell of the range is used as the starting point for the search. Remember that the search begins after this cell; the specified cell is not searched until the method wraps back around to this cell.

Remarks

When the search reaches the end of the specified search range, it wraps around to the beginning of the range. To stop a search when this wraparound occurs, save the address of the first found cell, and then test each successive found-cell address against this saved address.

See Also

Find Method, FindPrevious Method, Replace Method.

Example

This example changes all occurrences of the word Phoenix in column A on Sheet1 to the word Flagstaff.

Set foundCell = Worksheets("Sheet1").Columns("A").Find("Phoenix")
Do While Not (foundCell Is Nothing)
    foundCell.Value = "Flagstaff"
    Set foundCell = Worksheets("Sheet1").Columns("A").FindNext
Loop


FindPrevious Method

Applies To

Range Object.

Description

Continues a search started with the Find method. Finds the previous cell matching the same conditions and returns a Range object that represents that cell. Does not affect the selection or active cell.

Syntax

object.FindPrevious(after)

object

Required. The range to search.

after

Optional. The first cell before which you want to search. This corresponds to the position of the active cell when a search is done from the user interface. If omitted, the top left cell of the range is used as the starting point for the search. Remember that the search begins before this cell; the specified cell is not searched until the method wraps back around to this cell.

Remarks

When the search reaches the beginning of the specified search range, it wraps around to the end of the range. To stop a search when this wraparound occurs, save the address of the first found cell, and then test each successive found-cell address against this saved address.

See Also

Find Method, FindNext Method, Replace Method.

Example

This example shows how the FindPrevious method is used with the Find and FindNext methods. Before running this example, make sure that Sheet1 contains at least two occurrences of the word Phoenix in column B.

Set fc = Worksheets("Sheet1").Columns("B").Find(what:="Phoenix")
    MsgBox "The first occurrence is in cell " & fc.Address
Set fc = Worksheets("Sheet1").Columns("B").FindNext(after:=fc)
    MsgBox "The next occurrence is in cell " & fc.Address
Set fc = Worksheets("Sheet1").Columns("B").FindPrevious(after:=fc)
    MsgBox "The previous occurrence is in cell " & fc.Address


FirstPageNumber Property

Applies To

PageSetup Object.

Description

Returns or sets the first page number that will be used for printing this sheet (the default value is xlAutomatic). Read-write.

Example

This example sets the first page number of Sheet1 to 100.

Worksheets("Sheet1").PageSetup.FirstPageNumber = 100


FirstSliceAngle Property

Applies To

ChartGroup Object.

Description

Returns or sets the angle of the first pie or doughnut slice for a pie, 3-D pie, or doughnut chart, in degrees clockwise from vertical. Applies only to pie, 3-D pie, and doughnut charts. Read-write.

Example

This example sets the angle for the first slice in chart group one in Chart1. The example should be run on a 2-D pie chart.

Charts("Chart1").ChartGroups(1).FirstSliceAngle = 15


FitToPagesTall Property

Applies To

PageSetup Object.

Description

Returns or sets how many pages tall the worksheet will be scaled to when it is printed. The Zoom property must be False, or this property is ignored. Read-write.

Remarks

If this property is False, Microsoft Excel scales the worksheet according to the FitToPagesWide property.

This property applies only to worksheets.

Example

This example causes Sheet1 to print exactly one page wide and tall.

With Worksheets("Sheet1").PageSetup
    .Zoom = False
    .FitToPagesTall = 1
    .FitToPagesWide = 1
End With


FitToPagesWide Property

Applies To

PageSetup Object.

Description

Returns or sets how many pages wide the worksheet will be scaled when it is printed. The Zoom property must be False, or this property is ignored. Read-write.

Remarks

If this property is False, Microsoft Excel scales the worksheet according to the FitToPagesTall property.

This property applies only to worksheets.

Example

This example causes Sheet1 to print exactly one page wide and tall.

With Worksheets("Sheet1").PageSetup
    .Zoom = False
    .FitToPagesTall = 1
    .FitToPagesWide = 1
End With


FixedDecimal Property

Applies To

Application Object.

Description

All data entered after this property is set to True will be formatted with the number of fixed decimal places set by the FixedDecimalPlaces property.

Example

This example sets the FixedDecimal property to True and then sets the FixedDecimalPlaces property to 4. Entering "30000" after running this example produces "3" on the worksheet, and entering "12500" produces "1.25."

Application.FixedDecimal = True
Application.FixedDecimalPlaces = 4


FixedDecimalPlaces Property

Applies To

Application Object.

Description

Returns or sets the number of fixed decimal places used when the FixedDecimal property is set to True. Read-write.

Example

This example sets the FixedDecimal property to True and then sets the FixedDecimalPlaces property to 4. Entering "30000" after running this example produces "3" on the worksheet, and entering "12500" produces "1.25."

Application.FixedDecimal = True
Application.FixedDecimalPlaces = 4


Floor Object

Description

Represents the floor of a 3-D chart.

Accessors

The Floor property returns the floor for the specified chart. The following example sets the floor color for embedded chart one on the worksheet named "Sheet1." The example will fail if the chart is not a 3-D chart.

Worksheets("sheet1").ChartObjects(1).Activate
ActiveChart.Floor.Interior.Color = RGB(0, 255, 255)

Properties

Application Property, Border Property, Creator Property, Interior Property, Name Property, Parent Property.

Methods

ClearFormats Method, Select Method.


Floor Property

Applies To

Chart Object.

Description

Returns a Floor object that represents the floor of the 3-D chart. Read-only.

For help about using the Floor worksheet function in Visual Basic, see Using Worksheet Functions in Visual Basic.

Example

This example sets the chart floor color of Chart1 to blue. The example should be run on a 3-D chart (the Floor property fails on 2-D charts).

Charts("Chart1").Floor.Interior.ColorIndex = 5


Focus Property

Applies To

DialogSheet Object.

Description

Returns or sets the dynamic focus of the running dialog box, as a string containing the ID for the control with the focus. The control with the focus is where user keyboard input is directed, and the focus is visually indicated by a dashed rectangle around the control or around selections within the control. Read-write.

Remarks

Reading and setting this property while the dialog is not running will cause an error. While the dialog is running, setting this property will attempt to change the focus to the specified control. Not all controls will accept the focus, and the dialog manager may refuse to move the focus under certain conditions. Reading this property always returns the ID of the control with the focus.

Example

This example sets the focus to button one in the running dialog box and then displays the button name in a message box. The example should be the event procedure for a control or dialog box frame on a dialog sheet.

ActiveDialog.Focus = ActiveDialog.Buttons(1).Name
MsgBox ActiveDialog.Focus


Font Object

Description

Contains font attributes (font name, font size, color, and so on) for an object.

Accessors

The Font property returns the Font object. The font attributes are properties of the Font object. The following example makes cells A1:C5 bold on the worksheet named "Sheet1."

Worksheets("sheet1").Range("a1:c5").Font.Bold = True

If you do not want to format all the text contained in a cell or graphic object at once, use the Characters method to return a subset of the text.

Properties

Application Property, Background Property, Bold Property, Color Property, ColorIndex Property, Creator Property, FontStyle Property, Italic Property, Name Property, OutlineFont Property, Parent Property, Shadow Property, Size Property, Strikethrough Property, Subscript Property, Superscript Property, Underline Property.


Font Property

Applies To

AxisTitle Object, Button Object, Buttons Collection, Characters Object, ChartArea Object, ChartTitle Object, DataLabel Object, DataLabels Collection, DrawingObjects Collection, GroupObject Object, GroupObjects Collection, Legend Object, LegendEntry Object, Range Object, Style Object, TextBox Object, TextBoxes Collection, TickLabels Object.

Description

Accessor. Returns a Font object that represents font of the specified object. Read-only.

See Also

Font Object.

Example

This example sets the font in cell B5 on Sheet1 to 14-point bold italic.

With Worksheets("Sheet1").Range("B5").Font
    .Size = 14
    .Bold = True
    .Italic = True
End With


FontStyle Property

Applies To

Font Object.

Description

Returns or sets the font style (as a string). Read-write.

Remarks

Changing this property may affect other Font properties (such as Bold and Italic).

See Also

Background Property, Bold Property, Color Property, ColorIndex Property, Font Object, Italic Property, Name Property, OutlineFont Property, Shadow Property, Size Property, Strikethrough Property, Subscript Property, Superscript Property, Underline Property.

Example

This example sets the font style for cell A1 on Sheet1 to bold and italic.

Worksheets("Sheet1").Range("A1").Font.FontStyle = "Bold Italic"


FooterMargin Property

Applies To

PageSetup Object.

Description

Returns or sets the distance from the bottom of the page to the footer, in points (1/72 inch). Read-write.

See Also

BottomMargin Property, HeaderMargin Property, LeftMargin Property, RightMargin Property, TopMargin Property.

Example

This example sets the footer margin of Sheet1 to 0.5 inch.

Worksheets("Sheet1").PageSetup.FooterMargin = _
        Application.InchesToPoints(0.5)


For Each...Next Statement

Description

Repeats a group of statements for each element in an array or collection.

Syntax

For Each element In group
 [statements]
[Exit For]
[statements]
Next [element]

The For Each...Next statement syntax has these parts:

Part | Description
element | Variable used to iterate through the elements of the collection or array. For collections, element can only be a Variant variable, a generic Object variable, or any specific OLE Automation object variable. For arrays, element can only be a Variant variable.
group | Name of an object collection or array (except an array of user-defined types).
statements | One or more statements that are executed on each item in collection.

Important

When using For Each... Next with arrays, you can only read the value contained in the array elements indicated by the control variable element. You cannot set the value by assigning a value to element.

Remarks

The For Each block is entered if there is at least one element in group. Once the loop has been entered, all the statements in the loop are executed for the first element in group. Then, as long as there are more elements in group, the statements in the loop continue to execute for each element. When there are no more elements in group, the loop is exited and execution continues with the statement following the Next statement.

The Exit For can only be used within a For Each...Next or For...Next control structure to provide an alternate way to exit. Any number of Exit For statements may be placed anywhere in the loop. The Exit For is often used with the evaluation of some condition (for example, If...Then), and transfers control to the statement immediately following Next.

You can nest For Each...Next loops by placing one For Each...Next loop within another. However, each loop element must be unique.

Note

If you omit element in a Next statement, execution continues as if you had included it. If a Next statement is encountered before its corresponding For statement, an error occurs.

You can't use the For Each...Next statement with an array of user-defined types because a Variant can't contain a user-defined type.

See Also

Do...Loop Statement, Exit Statement, For...Next Statement, While...Wend Statement.

Example

This example uses the For Each...Next statement to search the Text property of all elements in a collection for the existence of the string "Hello". In the example, MyObject is a text-related object and is an element of the collection MyCollection. Both are generic names used for illustration purposes only.

Found = False    ' Initialize variable.
For Each MyObject In MyCollection    ' Iterate through each element.
    If MyObject.Text = "Hello" Then    ' If Text equals "Hello".
        Found = True    ' Set Found to True.
        Exit For    ' Exit loop.
    End If
Next

This example loops on cells A1:D10 on Sheet1. If one of the cells has a value less than 0.001, the code replaces the value with 0 (zero).

For Each c in Worksheets("Sheet1").Range("A1:D10")
    If c.Value < .001 Then
        c.Value = 0
    End If
Next c

This example loops on the range named "TestRange" and displays the number of empty cells in the range.

numBlanks = 0
For Each c In Range("TestRange")
    If c.Value = "" Then
        numBlanks = numBlanks + 1
    End If
Next c
MsgBox "There are " & numBlanks & " empty cells in this range."

This example closes and saves changes to all workbooks except the one that is running the example.

For Each w In Workbooks
    If w.Name <> ThisWorkbook.Name Then
        w.Close savechanges:=True
    End If
Next w

This example deletes every worksheet in the active workbook without displaying the confirmation dialog box.

Application.DisplayAlerts = False
For Each w In Worksheets
    w.Delete
Next w
Application.DisplayAlerts = True

This example creates a new worksheet and then inserts a list of all names in the active workbook, including their formulas in A1-style notation in the language of the user.

Set newSheet = ActiveWorkbook.Worksheets.Add
i = 1
For Each nm In ActiveWorkbook.Names
    newSheet.Cells(i, 1).Value = nm.NameLocal
    newSheet.Cells(i, 2).Value = "'" & nm.RefersToLocal
    i = i + 1
Next nm


For...Next Statement

Description

Repeats a group of statements a specified number of times.

Syntax

For counter = start To end [Step step]
[statements]
[Exit For]
[statements]
Next [counter]

The For...Next statement syntax has these parts:

Part | Description
counter | Numeric variable used as a loop counter. The variable can't be any array element or any element of a user-defined type.
start | Initial value of counter.
end | Final value of counter.
step | Amount counter is changed each time through the loop. If not specified, step defaults to one.
statements | One or more statements between For and Next that are executed the specified number of times.

Remarks

The step argument can be either positive or negative. The value of the step argument determines loop processing as follows:

Value | Loop executes if
Positive or 0 | counter <= end
Negative | counter >= end

Once the loop starts and all statements in the loop have executed, step is added to counter. At this point, either the statements in the loop execute again (based on the same test that caused the loop to execute initially), or the loop is exited and execution continues with the statement following the Next statement.

Tip

Changing the value of counter while inside a loop can make it more difficult to read and debug.

The Exit For can only be used within a For Each...Next or For...Next control structure to provide an alternate way to exit. Any number of Exit For statements may be placed anywhere in the loop. The Exit For is often used with the evaluation of some condition (for example, If...Then), and transfers control to the statement immediately following Next.

You can nest For...Next loops by placing one For...Next loop within another. Give each loop a unique variable name as its counter. The following construction is correct:

For I = 1 To 10
    For J = 1 To 10
        For K = 1 To 10
            . . .
        Next K
    Next J
Next I

Note

If you omit counter in a Next statement, execution continues as if you had included it. If a Next statement is encountered before its corresponding For statement, an error occurs.

See Also

Do...Loop Statement, Exit Statement, For Each...Next Statement, While...Wend Statement.

Example

This example uses the For...Next statement to create a string that contains 10 instances of the numbers 0 through 9, each string separated from the other by a single space. The outer loop uses a loop counter variable that is decremented each time through the loop.

For Words = 10 To 1 Step -1     ' Set up 10 repetitions.
    For Chars = 0 To 9    ' Set up 10 repetitions.
        MyString = MyString & Chars    ' Append number to string.
    Next Chars
    MyString = MyString & " "    ' Append a space.
Next Words

This example displays the number of columns in the selection on Sheet1. The code also tests for a multiple-area selection; if one exists, the code loops on the areas of the selection.

Worksheets("Sheet1").Activate
areaCount = Selection.Areas.Count
If areaCount <= 1 Then
    MsgBox "The selection contains " & _
        Selection.Columns.Count & " columns."
Else
    For i = 1 To areaCount
        MsgBox "Area " & i & " of the selection contains " & _
            Selection.Areas(i).Columns.Count & " columns."
    Next i
End If

This example creates a new worksheet and then inserts a list of the active workbook's sheet names in the first column.

Set newSheet = Sheets.Add(Type:=xlWorksheet)
For i = 1 To Sheets.Count
    newSheet.Cells(i, 1).Value = Sheets(i).Name
Next i

This example selects every other item in list box one on Sheet1.

Dim items() As Boolean
Set lbox = Worksheets("Sheet1").ListBoxes(1)
ReDim items(1 To lbox.ListCount)
For i = 1 To lbox.ListCount
    If i Mod 2 = 1 Then
        items(i) = True
    Else
        items(i) = False
    End If
Next
lbox.MultiSelect = xlExtended
lbox.Selected = items


Format Function

Description

Formats an expression according to instructions contained in a format expression.

Syntax

Format(expression[,format])

The Format function syntax has these parts:

Part | Description
expression | Any valid expression.
format | A valid named or user-defined format expression.

Remarks

To Format These | Do This
Numbers | Use predefined named numeric formats or create user-defined numeric formats.
Dates and times | Use predefined named date/time formats or create user-defined date/time formats.
Date and time serial numbers | Use date and time formats or numeric formats.
Strings | Create your own user-defined string formats.

If you try to format a number without specifying format, Format provides the same functionality as the Str function. However, positive numbers formatted as strings using Format lack the leading space reserved for displaying the sign of the value; whereas, those converted using Str retain the leading space.

Example

This example shows various uses of the Format function to format values using both named and user-defined formats. For the date separator (/), time separator (:) and AM/ PM literal, the actual formatted output displayed by your system depends on the settings at the time. When times and dates are listed back in the development environment, the short time and short date formats of the code locale are used. When displayed by running code, the short time and short date formats of the system locale are used, which may be different from the code locale. For this example, English - US is assumed.

' MyTime and MyDate will be displayed in the development environment
' using current system short time and short date settings.
MyTime = #17:04:23#
MyDate = #January 27, 1993#

' Returns current system time in the system-defined long time format.
MyStr = Format(Time, "Long Time")

' Returns current system date in the system-defined long date format.
MyStr = Format(Date, "Long Date")
MyStr = Format(MyTime, "h:m:s")    ' Returns "17:4:23".
MyStr = Format(MyTime, "hh:mm:ss AMPM")    ' Returns "05:04:23 PM".
MyStr = Format(MyDate, "dddd, mmm d yyyy")    ' Returns
    ' "Wednesday, Jan 27 1993".
' If format is not supplied, a string is returned.
MyStr = Format(23)    ' Returns "23".

' User-defined formats.
MyStr = Format(5459.4, "##,##0.00")    ' Returns "5,459.40".
MyStr = Format(334.9, "###0.00")    ' Returns "334.90".
MyStr = Format(5, "0.00%")    ' Returns "500.00%".
MyStr = Format("HELLO", "<")    ' Returns "hello".
MyStr = Format("This is it", ">")    ' Returns "THIS IS IT".

Different Formats for Different Numeric Values

A format expression for numbers can have from one to four sections separated by semicolons. (If the format argument contains one of the predefined formats, only one section is allowed.)

If you use | The result is
One section only | The format expression applies to all values.
Two sections | The first section applies to positive values and zeros, the second to negative values.
Three sections | The first section applies to positive values, the second to negative values, and the third to zeros.
Four sections | The first section applies to positive values, the second to negative values, the third to zeros, and the fourth to Null values.

The following example has two sections: the first defines the format for positive values and zeros; the second section defines the format for negative values.

"$#,##0;($#,##0)"

If you include semicolons with nothing between them, the missing section is printed using the format of the positive value. For example, the following format displays positive and negative values using the format in the first section and displays "Zero" if the value is zero.

"$#,##0;;\Z\e\r\o"

Examples

Some sample format expressions for numbers are shown below. (These examples all assume that your system's locale setting is English-US.) The first column contains the format strings. The other columns contain the output that results if the formatted data has the value given in the column headings.

Format (format) | Positive 5 | Negative 5 | Decimal .5 | Null
Zero-length string | 5 | -5 | 0.5 |
0 | 5 | -5 | 1 |
0.00 | 5.00 | -5.00 | 0.50 |
#,##0 | 5 | -5 | 1 |
#,##0.00;;;Nil | 5.00 | -5.00 | 0.50 | Nil
$#,##0;($#,##0) | $5 | ($5) | $1 |
$#,##0.00;($#,##0.00) | $5.00 | ($5.00) | $0.50 |
0% | 500% | -500% | 50% |
0.00% | 500.00% | -500.00% | 50.00% |
0.00E+00 | 5.00E+00 | -5.00E+00 | 5.00E-01 |
0.00E-00 | 5.00E00 | -5.00E00 | 5.00E-01 |

Different Formats for Different String Values

A format expression for strings can have one section, or two sections separated by a semicolon.

If you use | The result is
One section only | The format applies to all string data.
Two sections | The first section applies to string data, the second to Null values and zero-length strings.

Named Date/Time Formats

The following table identifies the predefined date and time format names:

Format Name | Description
General Date | Display a date and/or time. For real numbers, display a date and time (for example, 4/3/93 05:34 PM); if there is no fractional part, display only a date (for example, 4/3/93); if there is no integer part, display time only (for example, 05:34 PM). Date display is determined by your system settings.
Long Date | Display a date according to your system's long date format.
Medium Date | Display a date using the medium date format appropriate for the language version of the host application.
Short Date | Display a date using your system's short date format.
Long Time | Display a time using your system's long time format: includes hours, minutes, seconds.
Medium Time | Display time in 12-hour format using hours and minutes and the AM/PM designator.
Short Time | Display a time using the 24-hour format (for example, 17:45).

Named Numeric Formats

The following table identifies the predefined numeric format names:

Format name | Description
General Number | Display number as is, with no thousand separators.
Currency | Display number with thousand separator, if appropriate; display negative numbers enclosed in parentheses; display two digits to the right of the decimal separator. Note that output is based on system settings.
Fixed | Display at least one digit to the left and two digits to the right of the decimal separator.
Standard | Display number with thousands separator, at least one digit to the left and two digits to the right of the decimal separator.
Percent | Display number multiplied by 100 with a percent sign (%) appended to the right; always displays two digits to the right of the decimal separator.
Scientific | Use standard scientific notation.
Yes/No | Display No if number is 0; otherwise, display Yes.
True/False | Display False if number is 0; otherwise, display True.
On/Off | Display Off if number is 0; otherwise, display On.

User-Defined Date/Time Formats

The following table identifies characters you can use to create user-defined date/time formats:

Character | Description
: | Time separator. In some locales, other characters may be used to represent the time separator. The time separator separates hours, minutes, and seconds when time values are formatted. The actual character used as the time separator in formatted output is determined by your system settings.
/ | Date separator. In some locales, other characters may be used to represent the date separator. The date separator separates the day, month, and year when date values are formatted. The actual character used as the date separator in formatted output is determined by your system settings.
c | Display the date as ddddd and display the time as t t t t t, in that order. Display only date information if there is no fractional part to the date serial number; display only time information if there is no integer portion.
d | Display the day as a number without a leading zero (1-31).
dd | Display the day as a number with a leading zero (01-31).
ddd | Display the day as an abbreviation (Sun-Sat).
dddd | Display the day as a full name (Sunday-Saturday).
ddddd | Display a date as a complete date (including day, month, and year), formatted according to your system's short date format setting. For Microsoft Windows, the default short date format is m/d/yy.
dddddd | Display a date serial number as a complete date (including day, month, and year) formatted according to the long date setting recognized by your system. For Microsoft Windows, the default long date format is mmmm dd, yyyy.
w | Display the day of the week as a number (1 for Sunday through 7 for Saturday).
ww | Display the week of the year as a number (1-53).
m | Display the month as a number without a leading zero (1-12). If m immediately follows h or hh, the minute rather than the month is displayed.
mm | Display the month as a number with a leading zero (01-12). If m immediately follows h or hh, the minute rather than the month is displayed.
mmm | Display the month as an abbreviation (Jan-Dec).
mmmm | Display the month as a full month name (January-December).
q | Display the quarter of the year as a number (1-4).
y | Display the day of the year as a number (1-366).
yy | Display the year as a 2-digit number (00-99).
yyyy | Display the year as a 4-digit number (100-9999).
h | Display the hour as a number without leading zeros (0-23).
hh | Display the hour as a number with leading zeros (00-23).
n | Display the minute as a number without leading zeros (0-59).
nn | Display the minute as a number with leading zeros (00-59).
s | Display the second as a number without leading zeros (0-59).
ss | Display the second as a number with leading zeros (00-59).
t t t t t | Display a time as a complete time (including hour, minute, and second), formatted using the time separator defined by the time format recognized by your system. A leading zero is displayed if the leading zero option is selected and the time is before 10:00 A.M. or P.M. The default time format is h:mm:ss.
AM/PM | Use the 12-hour clock and display an uppercase AM with any hour before noon; display an uppercase PM with any hour between noon and 11:59 P.M.
am/pm | Use the 12-hour clock and display a lowercase AM with any hour before noon; display a lowercase PM with any hour between noon and 11:59 P.M.
A/P | Use the 12-hour clock and display an uppercase A with any hour before noon; display an uppercase P with any hour between noon and 11:59 P.M.
a/p | Use the 12-hour clock and display a lowercase A with any hour before noon; display a lowercase P with any hour between noon and 11:59 P.M.
AMPM | Use the 12-hour clock and display the AM string literal as defined by your system with any hour before noon; display the PM string literal as defined by your system with any hour between noon and 11:59 P.M. AMPM can be either uppercase or lowercase, but the case of the string displayed matches the string as defined by your system settings. For Microsoft Windows, the default format is AM/PM.

Examples

The following are examples of user-defined date and time formats for December 7, 1958:

Format | Display
m/d/yy | 12/7/58
d-mm | 7-Dec
d-mmmm-yy | 7-December-58
d-mmmm | 7 December
mmmm-yy | December 58
hh:mm AM/PM | 08:50 PM
h:mm:ss a/p | 8:50:35 p
h:mm | 20:50
h:mm:ss | 20:50:35
m/d/yy h:mm | 12/7/58 20:50

User-Defined Numeric Formats

The following table identifies characters you can use to create user-defined number formats:

Character

Description

None

No formatting

Display the number with no formatting.

0

Digit placeholder

Display a digit or a zero. If the expression has a digit in the position where the 0 appears in the format string, display it; otherwise, display a zero in that position.

If the number has fewer digits than there are zeros (on either side of the decimal) in the format expression, display leading or trailing zeros. If the number has more digits to the right of the decimal separator than there are zeros to the right of the decimal separator in the format expression, round the number to as many decimal places as there are zeros. If the number has more digits to the left of the decimal separator than there are zeros to the left of the decimal separator in the format expression, display the extra digits without modification.

#

Digit placeholder

Display a digit or nothing. If the expression has a digit in the position where the # appears in the format string, display it; otherwise, display nothing in that position.

This symbol works like the 0 digit placeholder, except that leading and trailing zeros aren't displayed if the number has the same or fewer digits than there are # characters on either side of the decimal separator in the format expression.

.

Decimal placeholder

In some locales, a comma is used as the decimal separator. The decimal placeholder determines how many digits are displayed to the left and right of the decimal separator. If the format expression contains only number signs to the left of this symbol, numbers smaller than 1 begin with a decimal separator. If you always want a leading zero displayed with fractional numbers, use 0 as the first digit placeholder to the left of the decimal separator instead. The actual character used as a decimal placeholder in the formatted output depends on the Number Format recognized by your system.

%

Percentage placeholder

The expression is multiplied by 100. The percent character (%) is inserted in the position where it appears in the format string.

,

Thousand separator

In some locales, a period is used as a thousand separator. The thousand separator separates thousands from hundreds within a number that has four or more places to the left of the decimal separator. Standard use of the thousand separator is specified if the format contains a thousand separator surrounded by digit placeholders (0 or #). Two adjacent thousand separators or a thousand separator immediately to the left of the decimal separator (whether or not a decimal is specified) means "scale the number by dividing it by 1000, rounding as needed." You can scale large numbers using this technique. For example, you can use the format string "##0,," to represent 100 million as 100. Numbers smaller than 1 million are displayed as 0. Two adjacent thousand separators in any position other than immediately to the left of the decimal separator are treated simply as specifying the use of a thousand separator. The actual character used as the thousand separator in the formatted output depends on the Number Format recognized by your system.

:

Time separator

In some locales, other characters may be used to represent the time separator. The time separator separates hours, minutes, and seconds when time values are formatted. The actual character used as the time separator in formatted output is determined by your system settings.

/

Date separator

In some locales, other characters may be used to represent the date separator. The date separator separates the day, month, and year when date values are formatted. The actual character used as the date separator in formatted output is determined by your system settings.

E- E+ e- e+

Scientific format

If the format expression contains at least one digit placeholder (0 or #) to the right of E-, E+, e-, or e+, the number is displayed in scientific format and E or e is inserted between the number and its exponent. The number of digit placeholders to the right determines the number of digits in the exponent. Use E- or e- to place a minus sign next to negative exponents. Use E+ or e+ to place a minus sign next to negative exponents and a plus sign next to positive exponents.

- + $ ( ) space

Display a literal character

To display a character other than one of those listed, precede it with a backslash (\) or enclose it in double quotation marks (" ").

\

Display the next character in the format string

Many characters in the format expression have a special meaning and can't be displayed as literal characters unless they are preceded by a backslash. The backslash itself isn't displayed. Using a backslash is the same as enclosing the next character in double quotation marks. To display a backslash, use two backslashes (\\).

Examples of characters that can't be displayed as literal characters are the date- and time-formatting characters (a, c, d, h, m, n, p, q, s, t, w, y, and /:), the numeric-formatting characters (#, 0, %, E, e, comma, and period), and the string-formatting characters (@, &, <, >, and !).

"ABC"

Display the string inside the double quotation marks

To include a string in format from within code, you must use Chr(34) to enclose the text (34 is the character code for a double quotation mark).

Example

Some sample format expressions for numbers are shown below. (These examples all assume that your system's locale setting is English-US.) The first column contains the format strings. The other columns contain the output that results if the formatted data has the value given in the column headings.

Format (format) | Positive 5 | Negative 5 | Decimal .5 | Null
Zero-length string | 5 | -5 | 0.5 |
0 | 5 | -5 | 1 |
0.00 | 5.00 | -5.00 | 0.50 |
#,##0 | 5 | -5 | 1 |
#,##0.00;;;Nil | 5.00 | -5.00 | 0.50 | Nil
$#,##0;($#,##0) | $5 | ($5) | $1 |
$#,##0.00;($#,##0.00) | $5.00 | ($5.00) | $0.50 |
0% | 500% | -500% | 50% |
0.00% | 500.00% | -500.00% | 50.00% |
0.00E+00 | 5.00E+00 | -5.00E+00 | 5.00E-01 |
0.00E-00 | 5.00E00 | -5.00E00 | 5.00E-01 |

User-Defined String Formats

You can use any of the following characters to create a format expression for strings:

Character | Description
@ | Character placeholder Display a character or a space. If the string has a character in the position where the @ appears in the format string, display it; otherwise, display a space in that position. Placeholders are filled from right to left unless there is an ! character in the format string. See below.
& | Character placeholder Display a character or nothing. If the string has a character in the position where the & appears, display it; otherwise, display nothing. Placeholders are filled from right to left unless there is an ! character in the format string. See below.
< | Force lowercase Display all characters in lowercase format.
> | Force uppercase Display all characters in uppercase format.
! | Force left to right fill of placeholders The default is to fill from right to left.


Formula Property

Applies To

Button Object, Buttons Collection, Picture Object, Pictures Collection, Range Object, Series Object, TextBox Object, TextBoxes Collection.

Description

Returns or sets the object's formula, in A1-style notation and the language of the macro. Read-write.

Remarks

If the cell contains a constant, this property returns the constant. If the cell is empty, it returns an empty string. If the cell contains a formula, it returns the formula as a string, in the same format as it would be displayed in the formula bar (including the equal sign).

If you set the value or formula of a cell to a date, Microsoft Excel checks to see if that cell is already formatted with one of the date or time number formats. If not, it changes the number format to the default short date number format.

If the range is a one- or two-dimensional range, you can set the formula to a Visual Basic array of the same dimensions. Similarly, you can put the formula into a Visual Basic array.

Setting the formula of a multi-cell range fills all cells in the range with the formula.

When used with a Picture object, the formula must use absolute A1-style notation.

See Also

FormulaArray Property, FormulaLocal Property, FormulaR1C1 Property, FormulaR1C1Local Property.

Example

This example sets the formula for cell A1 on Sheet1.

Worksheets("Sheet1").Range("A1").Formula = "=$A$4+$A$10"


FormulaArray Property

Applies To

Range Object.

Description

Returns or sets the formula of a range, entered as an array. Returns (or can be set to) a single formula or a Visual Basic array. If the specified range is not array-entered, this property returns Null. Read-write.

Remarks

If you use this property to array-enter a formula, the formula must use the R1C1 reference style, not the A1 reference style; see the second example.

See Also

Formula Property.

Example

This example enters the number 3 as an array constant in cells A1:C5 on Sheet1.

Worksheets("Sheet1").Range("A1:C5").FormulaArray = "=3"

This example array-enters the formula =SUM(R1C1:R3C3) in cells E1:E3 on Sheet1.

Worksheets("Sheet1").Range("E1:E3").FormulaArray = _
    "=Sum(R1C1:R3C3)"


FormulaHidden Property

Applies To

Range Object, Style Object.

Description

True if the formula will be hidden when the workbook or worksheet is protected. Read-write.

Remarks

Do not confuse this property with the Hidden property.

See Also

Locked Property, Protect Method, Unprotect Method.

Example

This example hides the formulas in column A on Sheet1 when the worksheet is protected.

Worksheets("Sheet1").Columns("A").FormulaHidden = True


FormulaLocal Property

Applies To

Range Object, Series Object.

Description

Returns or sets the formula for the object, using A1-style references in the user's language. Read-write.

Remarks

If the cell contains a constant, this property returns the constant. If the cell is empty, it returns an empty string. If the cell contains a formula, it returns the formula as a string, in the same format as it would be displayed in the formula bar (including the equal sign).

If you set the value or formula of a cell to a date, Microsoft Excel checks to see if that cell is already formatted with one of the date or time number formats. If not, it changes the number format to the default short date number format.

If the range is a one- or two-dimensional range, you can set the formula to a Visual Basic array of the same dimensions. Similarly, you can put the formula into a Visual Basic array.

Setting the formula of a multi-cell range fills all cells in the range with the formula.

See Also

Formula Property, FormulaArray Property, FormulaR1C1 Property, FormulaR1C1Local Property.

Example

Assume that you enter the formula =SUM(A1:A10) in cell A11 on Sheet1, using the American English version of Microsoft Excel. If you then open the workbook on a computer that is running the German version and run the following example, the example displays the formula =SUMME(A1:A10) in a message box.

MsgBox Worksheets(1).Range(A11).FormulaLocal


FormulaR1C1 Property

Applies To

Range Object, Series Object.

Description

Returns or sets the formula for the object, using R1C1-style notation in the language of the macro. Read-write.

Remarks

If the cell contains a constant, this property returns the constant. If the cell is empty, it returns an empty string. If the cell contains a formula, it returns the formula as a string, in the same format as it would be displayed in the formula bar (including the equal sign).

If you set the value or formula of a cell to a date, Microsoft Excel checks to see if that cell is already formatted with one of the date or time number formats. If not, it changes the number format to the default short date number format.

If the range is a one- or two-dimensional range, you can set the formula to a Visual Basic array of the same dimensions. Similarly, you can put the formula into a Visual Basic array.

Setting the formula of a multi-cell range fills all cells in the range with the formula.

See Also

Formula Property, FormulaArray Property, FormulaLocal Property, FormulaR1C1Local Property.

Example

This example sets the formula for cell B1 on Sheet1.

Worksheets("Sheet1").Range("B1").FormulaR1C1 = "=SQRT(R1C1)"


FormulaR1C1Local Property

Applies To

Range Object, Series Object.

Description

Returns or sets the formula for the object, using R1C1-style notation in the user's language.

Remarks

If the cell contains a constant, this property returns the constant. If the cell is empty, it returns an empty string. If the cell contains a formula, it returns the formula as a string, in the same format as it would be displayed in the formula bar (including the equal sign).

If you set the value or formula of a cell to a date, Microsoft Excel checks to see if that cell is already formatted with one of the date or time number formats. If not, it changes the number format to the default short date number format.

If the range is a one- or two-dimensional range, you can set the formula to a Visual Basic array of the same dimensions. Similarly, you can put the formula into a Visual Basic array.

Setting the formula of a multi-cell range fills all cells in the range with the formula.

See Also

Formula Property, FormulaArray Property, FormulaLocal Property, FormulaR1C1 Property.

Example

Assume that you enter the formula =SUM(A1:A10) in cell A11 on Sheet1, using the American English version of Microsoft Excel. If you then open the workbook on a computer that is running the German version and run the following example, the example displays the formula =SUMME(Z1S1:Z10S1) in a message box.

MsgBox Worksheets(1).Range("A11").FormulaR1C1Local


Forward Property

Applies To

Trendline Object.

Description

Returns or sets the number of periods (or units on a scatter chart) that the trendline extends forward. Read-write.

See Also

Backward Property, ForwardMailer Method.

Example

This example sets the number of units the trendline on Chart1 extends forward and backward. The example should be run on a 2-D column chart that contains a single series with a trendline.

With Charts("Chart1").SeriesCollection(1).Trendlines(1)
    .Forward = 5
    .Backward = .5
End With


ForwardMailer Method

Applies To

Workbook Object.

Description

Sets up the workbook mailer for forwarding by creating a new mailer that is preset with the subject and enclosures of the existing mailer. Valid only when the workbook has a received mailer attached (you can only forward a workbook you have received). Available only in Microsoft Excel for the Apple Macintosh with the PowerTalk mail system extension installed.

Syntax

object.ForwardMailer

object

Required. The Workbook object.

Remarks

After you use this method to set up a workbook mailer for forwarding, you can change the mailer settings (if necessary) with the Mailer property and then use the SendMailer method to forward the workbook.

This method generates an error if it is used in Microsoft Windows.

See Also

Mailer Property, MailSystem Property, SendMailer Method.

Example

This example forwards the active workbook.

ActiveWorkbook.ForwardMailer


FreeFile Function

Description

Returns the next file number available for use by the Open statement.

Syntax

FreeFile[(rangenumber)]

The rangenumber argument specifies the range from which the next free file number is to be returned. Specify a 0 (default) to return a file number in the range 1 to 255, inclusive. Specify a 1 to return a file number in the range 256 to 511.

Remarks

Use FreeFile when you need to supply a file number and you want to make sure the file number is not already in use.

See Also

Open Statement.

Example

This example uses the FreeFile function to return the next available file number. Five files are opened for output within the loop and some sample data is written to each.

For MyIndex = 1 to 5    ' Loop 5 times.
    FileNumber = FreeFile    ' Get unused file
    ' number.
    Open "TEST" & MyIndex For Output As #FileNumber    ' Create file name.
    Write #FileNumber, "This is a sample"    ' Output text.
    Close #FileNumber    ' Close file.
Next MyIndex


FreezePanes Property

Applies To

Window Object.

Description

True if split panes are frozen. Read-write.

Remarks

It is possible for FreezePanes to be True and Split to be False, or vice versa.

This property applies only to worksheets and macro sheets.

Example

This example freezes split panes in the active window in BOOK1.XLS.

Workbooks("BOOK1.XLS").Worksheets("Sheet1").Activate
ActiveWindow.FreezePanes = True


FullName Property

Applies To

AddIn Object, Workbook Object.

Description

Returns the name of the object, including its path on disk, as a string. Read-only.

Remarks

This property is equivalent to the Path property, followed by the current file system separator, followed by the Name property.

Example

This example displays the path and filename of every add-in.

For Each a In AddIns
    MsgBox a.FullName
Next a

This example displays the path and filename of the active workbook (assuming that the workbook has been saved).

MsgBox ActiveWorkbook.FullName


Function Property

Applies To

PivotField Object.

Description

Returns or sets the function used to summarize the PivotField (data fields only). Can be one of xlAverage, xlCount, xlCountNums, xlMax, xlMin, xlProduct, xlStDev, xlStDevP, xlSum, xlVar, or xlVarP. Read-write.

Example

This example sets the Sum of 1994 field in PivotTable1 to use the SUM function.

ActiveSheet.PivotTables("PivotTable1"). _
    PivotFields("Sum of 1994").Function = xlSum


Function Statement

Description

Declares the name, arguments, and code that form the body of a Function procedure.

Syntax

[Public | Private][Static] Function name [(arglist)][As type]
[statements]
[name = expression]
[Exit Function]
[statements]
[name = expression]
End Function

The Function statement syntax has these parts:

Part | Description
Public | Indicates that the Function procedure is accessible to all other procedures in all modules. If used in a private module (one that contains an Option Private statement) the procedure is not available outside the project.
Private | Indicates that the Function procedure is accessible only to other procedures in the module where it is declared.
Static | Indicates that the Function procedure's local variables are preserved between calls. The Static attribute doesn't affect variables that are declared outside the Function, even if they are used in the procedure.
name | Name of the Function; follows standard variable naming conventions.
arglist | List of variables representing arguments that are passed to the Function procedure when it is called. Multiple variables are separated by commas.
type | Data type of the value returned by the Function procedure; may be Boolean, Integer, Long, Currency, Single, Double, Date, String (except fixed length), Object, Variant or any user-defined type. Arrays of any type can't be returned, but a Variant containing an array can.
statements | Any group of statements to be executed within the body of the Function procedure.
expression | Return value of the Function.

The arglist argument has the following syntax and parts:

[Optional][ByVal | ByRef][ParamArray] varname[( )][As type]

Part | Description
Optional | Indicates that an argument is not required. If used, all subsequent arguments in arglist must also be optional and declared using the Optional keyword. All Optional arguments must be Variant. Optional can't be used for any argument if ParamArray is used.
ByVal | Indicates that the argument is passed by value.
ByRef | Indicates that the argument is passed by reference.
ParamArray | Used only as the last argument in arglist to indicate that the final argument is an Optional array of Variant elements. The ParamArray keyword allows you to provide an arbitrary number of arguments. May not be used with ByVal, ByRef, or Optional.
varname | Name of the variable representing the argument; follows standard variable naming conventions.
type | Data type of the argument passed to the procedure; may be Boolean, Integer, Long, Currency, Single, Double, Date, String (variable length only), Object, Variant, a user-defined type, or an object type.

Remarks

If not explicitly specified using either Public or Private, Function procedures are Public by default. If Static is not used, the value of local variables is not preserved between calls.

All executable code must be in procedures. You can't define a Function procedure inside another Function, Sub, or Property procedure.

The Exit Function keywords cause an immediate exit from a Function procedure. Program execution continues with the statement following the statement that called the Function procedure. Any number of Exit Function statements can appear anywhere in a Function procedure.

Like a Sub procedure, a Function procedure is a separate procedure that can take arguments, perform a series of statements, and change the values of its arguments. However, unlike a Sub procedure, a Function procedure can be used on the right hand side of an expression in the same way you use any intrinsic function, such as Sqr, Cos, or Chr, when you want to use the value returned by the function.

You call a Function procedure using the function name, followed by the argument list in parentheses, in an expression. If the function has no arguments, you still must include the parentheses. See the Call statement for specific information on how to call Function procedures.

Caution

Function procedures can be recursive; that is, they can call themselves to perform a given task. However, recursion can lead to stack overflow. The Static keyword is usually not used with recursive Function procedures.

To return a value from a function, assign the value to the function name. Any number of such assignments can appear anywhere within the procedure. If no value is assigned to name, the procedure returns a default value: a numeric function returns 0, a string function returns a zero-length string (""), and a Variant function returns Empty. A function that returns an object reference returns Nothing if no object reference is assigned to name (using Set) within the Function.

The following example shows how to assign a return value to a function named BinarySearch. In this case, False is assigned to the name to indicate that some value was not found.

Function BinarySearch(. . .) As Boolean
. . .
    ' Value not found. Return a value of False.
    If lower > upper Then
        BinarySearch = False
        Exit Function
    End If
. . .
End Function

Variables used in Function procedures fall into two categories: those that are explicitly declared within the procedure and those that are not. Variables that are explicitly declared in a procedure (using Dim or the equivalent) are always local to the procedure. Other variables used but not explicitly declared in a procedure are also local unless they are explicitly declared at some higher level outside the procedure.

Caution

A procedure can use a variable that is not explicitly declared in the procedure, but a name conflict can occur if anything you have defined at the module level has the same name. If your procedure refers to an undeclared variable that has the same name as another procedure, constant or variable, it is assumed that your procedure is referring to that module-level name. Explicitly declare variables to avoid this kind of conflict. You can use an Option Explicit statement to force explicit declaration of variables.

Caution

Arithmetic expressions may be rearranged to increase internal efficiency. Avoid using a Function procedure in an arithmetic expression when the function changes the value of variables in the same expression.

See Also

Call Statement, Dim Statement, Option Explicit Statement, Property Get Statement, Property Let Statement, Property Set Statement, Set Statement, Static Statement, Sub Statement.

Example

This example uses the Function statement to declare the name, arguments and code that form the body of a Function procedure.

' The following user-defined function returns the square root of the
' argument passed to it.
Function CalculateSquareRoot(NumberArg As Double) As Double
    If NumberArg < 0 Then    ' Evaluate argument.
        Exit Function    ' Exit to calling procedure.
    Else
        CalculateSquareRoot = Sqr(NumberArg)    ' Return square root.
    EndIf
End Function

' Using the ParamArray keyword enables a function to accept a variable
' number of arguments. In the following definition, FirstArg is passed
' by value.
Function CalcSum(ByVal FirstArg As Integer, ParamArray OtherArgs())
' If the function is invoked as...
ReturnValue = CalcSum(4,3,2,1)
' Local variables get the following values: FirstArg=4, OtherArgs(1)=3,
' OtherArgs(2) = 2 and so on, assuming default lower bound for
' arrays = 1.

' If a function's arguments are defined as...
Function MyFunc(MyStr As String, Optional MyArg1, Optional MyArg2)
' It can be invoked in the following ways.
RetVal = MyFunc("Hello", 2, "World")    ' All 3 arguments supplied.
RetVal = MyFunc("Test", , 5)    ' Second argument omitted.
RetVal = MyFunc("Test")    ' First argument only.


FunctionWizard Method

Applies To

Range Object.

Description

Starts the Function Wizard for the upper left cell of the range.

Syntax

object.FunctionWizard

object

Required. The Range object.

Example

This example starts the Function Wizard for the active cell on Sheet1.

Worksheets("Sheet1").Activate
ActiveCell.FunctionWizard


GapDepth Property

Applies To

Chart Object.

Description

Returns or sets the distance between the data series in a 3-D chart, as a percentage of the marker width (between 0 and 500). Read-write.

Example

This example sets the distance between the data series in Chart1 to 200 percent of the marker width. The example should be run on a 3-D chart.

Charts("Chart1").GapDepth = 200


GapWidth Property

Applies To

ChartGroup Object.

Description

Returns or sets the space between bar or column clusters as a percentage of the width of a bar or column. This property must be between 0 and 500. Read-write.

See Also

Overlap Property.

Example

This example sets the space between column clusters in Chart1 to be 50 percent of the width of a column.

Charts("Chart1").ChartGroups(1).GapWidth = 50


Get Statement

Description

Reads from an open disk file into a variable.

Syntax

Get [#]filenumber,[recnumber],varname

The Get statement syntax has these parts:

Part | Description
filenumber | Any valid file number.
recnumber | Record number (Random mode files) or byte number (Binary mode files) at which reading begins.
varname | Valid variable name into which data is read.

Remarks

The first record/byte in a file is at position 1, the second record/byte is at position 2, and so on. If you omit recnumber, the next record or byte (the one after the last Get or Put statement or the one pointed to by the last Seek function) is read. Delimiting commas must be included, for example:

Get #4,,FileBuffer

For files opened in Random mode, the following rules apply:

  • If the length of the data being read is less than the length specified in the Len clause of the Open statement, Get still reads subsequent records on record-length boundaries. The space between the end of one record and the beginning of the next record is padded with the existing contents of the file buffer. Because the amount of padding data can't be determined with any certainty, it is generally a good idea to have the record length match the length of the data being read.
  • If the variable being read into is a variable-length string, Get reads a 2-byte descriptor containing the string length and then the data that goes into the variable. Therefore, the record length specified by the Len clause in the Open statement must be at least 2 bytes greater than the actual length of the string.
  • If the variable being read into is a Variant of numeric type, Get reads 2 bytes identifying the VarType of the Variant and then the data that goes into the variable. For example, when reading a Variant of VarType 3, Get reads 6 bytes: 2 bytes identifying the Variant as VarType 3 (Long) and 4 bytes containing the Long data. The record length specified by the Len clause in the Open statement must be at least 2 bytes greater than the actual number of bytes required to store the variable.
  • If the variable being read into is a String Variant (VarType 8), Get reads 2 bytes identifying the VarType, 2 bytes indicating the length of the string, and then the string data. The record length specified by the Len clause in the Open statement must be at least 4 bytes greater than the actual length of the string.
  • If the variable being read into is any other type of variable (not a variable-length string or a Variant), Get reads only the variable data. The record length specified by the Len clause in the Open statement must be greater than or equal to the length of the data being read.
  • Get reads elements of user-defined types as if each were being read individually except that there is no padding between elements. The record length specified by the Len clause in the Open statement must be greater than or equal to the sum of all the bytes required to read the individual elements.

For files opened in Binary mode, all of the Random rules apply except that:

  • In Binary mode, the Len clause in the Open statement has no effect. Get reads all variables from disk contiguously; that is, with no padding between records.
  • Get reads variable-length strings that aren't elements of user-defined types without expecting the 2-byte length descriptor. The number of bytes read equals the number of characters already in the string. For example, the following statements read 10 bytes from file number 1:

    VarString = String(10," ")
Get #1,,VarString

See Also

Open Statement, Put Statement, Type Statement, VarType Function.

Example

This example uses the Get statement to read data from a disk file into a variable. For purposes of this example, assume that TESTFILE is a file containing five records of the user-defined type Record.

Type Record    ' Define user-defined type.
    ID As Integer
    Name As String * 20
End Type
Dim MyRecord As Record    ' Declare variable.
' Open sample file for random access.
Open "TESTFILE" For Random As #1 Len = Len(MyRecord)
' Read the sample file using the Get statement.
Position = 3    ' Define record number.
Get #1, Position, MyRecord    ' Read third record.
Close #1    ' Close file.


GetAttr Function

Description

Returns a number representing the attributes of a file, directory or folder, or volume label.

Syntax

GetAttr(pathname)

The pathname named argument is a string expression that specifies a file name — may include directory or folder, and drive.

Return Values

The value returned by GetAttr is the sum of the following attribute values:

Value | Constant | File Attribute
0 | vbNormal | Normal.
1 | vbReadonly | Read-only.
2 | vbHidden | Hidden.
4 | vbSystem | System file — not available on the Macintosh.
8 | vbVolume | Volume label — not available on the Macintosh.
16 | vbDirectory | Directory or folder.
32 | vbArchive | File has changed since last backup — not available on the Macintosh.

Note

These constants are specified by Visual Basic. As a result, the names can be used anywhere in your code in place of the actual values.

Remarks

To determine which attributes are set, use the And operator to perform a bit-wise comparison of the value returned by the GetAttr function and the value of the individual file attribute you want. If the result is not zero, that attribute is set for the named file. For example, the return value of the following And expression is zero if the Archive attribute is not set:

Result = GetAttr(FName) And vbArchive

A nonzero value is returned if the Archive attribute is set.

See Also

FileAttr Function, SetAttr Statement.

Example

This example uses the GetAttr statement to determine the attributes of a file and directory or folder.

' Assume file TESTFILE has hidden attribute set.
MyAttr = GetAttr("TESTFILE")    ' Returns 2.

' Assume file TESTFILE has hidden and read-only attributes set.
MyAttr = GetAttr("TESTFILE")    ' Returns 3.

' Assume MYDIR is a directory or folder.
MyAttr = GetAttr("MYDIR")    ' Returns 16.


GetCustomListContents Method

Applies To

Application Object.

Description

Returns a custom list (an array of strings) for a specified list number.

Syntax

object.GetCustomListContents(listNum)

object

Required. The Application object.

listNum

Required. The list number.

See Also

AddCustomList Method, CustomListCount Property, DeleteCustomList Method, GetCustomListNum Method.

Example

This example writes the elements of the first custom list in column one on Sheet1.

Sub foo()
On Error GoTo err_handler
listArray = Application.GetCustomListContents(1)
For i = LBound(listArray, 1) To UBound(listArray, 1)
    Worksheets("sheet1").Cells(i, 1).Value = listArray(i)
Next i
Exit Sub

err_handler:
    MsgBox "Custom list does not exist"
End Sub


GetCustomListNum Method

Applies To

Application Object.

Description

Returns the custom list number for an array of strings. Both built-in and custom defined lists can be matched using this method.

Syntax

object.GetCustomListNum(listArray)

object

Required. The Application object.

listArray

Required. An array of strings.

Remarks

This method generates an error if a corresponding list does not exist.

See Also

AddCustomList Method, CustomListCount Property, DeleteCustomList Method, GetCustomListContents Method.

Example

This example deletes a custom list.

n = Application.GetCustomListNum(Array("cogs", "sprockets", _
    "widgets", "gizmos"))
Application.DeleteCustomList n


GetObject Function

Description

Retrieves an OLE Automation object from a file.

Syntax

GetObject([pathname][,class])

The GetObject function syntax has these named-argument parts:

Part | Description
pathname | The full path and name of the file containing the object to retrieve. If pathname is omitted, class is required.
class | A string representing the class of the object.

The class argument uses the syntax: "appname.objecttype" and has these parts:

Part | Description
appname | The name of the application providing the object.
objecttype | The type or class of object to create.

Remarks

Note

If an application which supports OLE Automation exposes an object library, it is preferable to use the functions defined within the library for object access rather than use GetObject.

Use the GetObject function to access an OLE Automation object from a file and assign the object to an object variable. To do this, use the Set statement to assign the object returned by GetObject to the object variable. For example:

Set CADObject = GetObject("C:\CAD\SCHEMA.CAD")

When this code is executed, the application associated with the specified file name is started and the object in the specified file is activated.

If pathname is a zero-length string (""), GetObject returns a new object instance of the specified type. If the pathname argument is omitted entirely, GetObject returns the currently active object of the specified type. If no object of the specified type exists, an error occurs.

The above example shows how to activate an entire file. However, some applications allow you to activate part of a file. To do this, add an exclamation point (!) to the end of the file name followed by a string that identifies the part of the file you want to activate. For information on how to create this string, see the documentation for the application that created the object.

For example, in a drawing application you might have multiple layers to a drawing stored in a file. You could use the following code to activate a layer within a drawing called SCHEMA.CAD:

Set LayerObject = GetObject("C:\CAD\SCHEMA.CAD!Layer3")

If you do not specify the object's class, the OLE.DLLs determine the application to invoke and the object to activate based on the file name you provide. Some files, however, may support more than one class of object. For example, a drawing might support three different types of objects: an application object, a drawing object, and a toolbar object, all of which are part of the same file. To specify which object in a file you want to activate, use the optional class argument. For example:

Set MyObject = GetObject("C:\DRAWINGS\SAMPLE.DRW", "FIGMENT.DRAWING")

In the above example, FIGMENT is the name of a drawing application and DRAWING is one of the object types it supports.

Once an object is activated, you reference it in code using the object variable you defined. In the above example, you access properties and methods of the new object using the object variable MyObject. For example:

MyObject.Line 9, 90
MyObject.InsertText 9, 100, "Hello, world."
MyObject.SaveAs "C:\DRAWINGS\SAMPLE.DRW"

See Also

CreateObject Function, Set Statement.


GetOpenFilename Method

Applies To

Application Object.

Description

Displays the standard Open dialog box and gets a filename from the user without actually opening any files.

Syntax

object.GetOpenFilename(fileFilter, filterIndex, title, buttonText, multiSelect)

object

Required. The Application object.

fileFilter

Optional. A string specifying file filtering criteria.

In Microsoft Windows, this string consists of pairs of file filter strings followed by the MS-DOS wildcard file filter specification, with each part and each pair separated by commas. Each separate pair is listed in the File Type drop-down list box. For example, the following string specifies two file filters-text and addin: "Text Files (*.txt),*.txt,Add-In Files (*.xla),*.xla".

To use multiple MS-DOS wildcard expressions for a single file filter type, separate the wildcard expressions with semicolons. For example: "Visual Basic Files (*.bas; *.txt),*.bas;*.txt".

If omitted on Windows, this argument defaults to "All Files (*.*),*.*".

On the Apple Macintosh, this string is a list of comma-separated file type codes, ("TEXT,XLA,XLS4"). Spaces are significant and should not be inserted before or after the comma separators unless they are part of the file type code. If omitted, this argument defaults to all file types.

filterIndex

Optional. Microsoft Windows only (ignored on the Apple Macintosh). Specifies the index number of the default file filtering criteria from one to the number of filters specified in fileFilter. If this argument is omitted or greater than the number of filters present, the first file filter is used.

title

Optional. Microsoft Windows only (ignored on the Apple Macintosh). Specifies the dialog title. If this argument is omitted, the dialog title is "Open".

buttonText

Optional. Apple Macintosh only (ignored in Microsoft Windows). Specifies the text used for the Open button in the dialog box. If this argument is omitted, the button text is "Open".

multiSelect

Optional. If True, multiple filenames are allowed. If False or omitted, only a single filename can be selected.

Remarks

This method returns the selected filename or the name entered by the user. The returned name may include a path specification. If multiSelect is True, the return value is an array of the selected filenames (even if only one file name is selected). Returns False if the user cancels the dialog box.

This method may change the current drive or directory.

See Also

GetSaveAsFilename Method, Open Method.

Example

This example displays the Open dialog box, with the file filter set to text files. If the user chooses a filename, the code displays that filename in a message box.

fileToOpen = Application.GetOpenFilename("Text Files (*.txt), *.txt")
If fileToOpen <> False Then
    MsgBox "Open " & fileToOpen
End If

This is the same example in Microsoft Excel for the Macintosh.

fileToOpen = Application.GetOpenFilename("TEXT")
If fileToOpen <> False Then
    MsgBox "Open " & fileToOpen
End If


GetSaveAsFilename Method

Applies To

Application Object.

Description

Displays the standard Save As dialog box and gets a filename from the user without actually saving any files.

Syntax

object.GetSaveAsFilename(initialFilename, fileFilter, filterIndex, title, buttonText)

object

Required. The Application object.

initialFilename

Optional. Specifies the suggested filename. If this argument is omitted, Microsoft Excel uses the active workbook's name.

fileFilter

Optional. A string specifying file filtering criteria.

In Microsoft Windows, this string consists of pairs of file filter strings followed by the MS-DOS wildcard file filter specification, with each part and each pair separated by commas. Each separate pair is listed in the File Type drop-down list box. For example, the following string specifies two file filters-text and addin: "Text Files (*.txt), *.txt, Add-In Files (*.xla), *.xla"

To use multiple MS-DOS wildcard expressions for a single file filter type, separate the wildcard expressions with semicolons. For example: "Visual Basic Files (*.bas; *.txt),*.bas;*.txt"

If omitted on Windows, this argument defaults to "All Files (*.*),*.*".

On the Apple Macintosh, this string is a list of comma-separated file type codes, ("TEXT,XLA,XLS4"). Spaces are significant and should not be inserted before or after the comma separators unless they are part of the file type code. If omitted, this argument defaults to all file types.

filterIndex

Optional. Microsoft Windows only (ignored on the Apple Macintosh). Specifies the index number of the default file filtering criteria from one to the number of filters specified in fileFilter. If this argument is omitted or greater than the number of filters present, the first file filter is used.

title

Optional. Specifies the dialog title. If this argument is omitted, the default title is used.

buttonText

Optional. Apple Macintosh only (ignored in Microsoft Windows). Specifies the text used for the Save button in the dialog box. If this argument is omitted, the button text is "Save".

Remarks

This method returns the selected filename or the name entered by the user. The returned name may include a path specification. Returns False if the user cancels the dialog box.

This method may change the current drive or directory.

See Also

GetOpenFilename Method, Save Method, SaveAs Method.

Example

This example displays the Save As dialog box, with the file filter set to text files. If the user chooses a filename, the code displays that filename in a message box.

fileSaveName = Application.GetSaveAsFilename( _
    fileFilter:="Text Files (*.txt), *.txt")
If fileSaveName <> False Then
    MsgBox "Save as " & fileSaveName
End If

This is the same example in Microsoft Excel for the Macintosh.

fileSaveName = Application.GetSaveAsFilename( _
    fileFilter:="TEXT")
If fileSaveName <> False Then
    MsgBox "Save as " & FileSaveName
End If


GoalSeek Method

Applies To

Range Object.

Description

Calculates the values necessary to achieve a specific goal. If the goal is an amount returned by a formula, this calculates a value that, when supplied to your formula, causes the formula to return the number you want. Returns True if the goal seek is successful.

Syntax

object.GoalSeek(goal, changingCell)

object

Required. The specified range must be a single cell.

goal

Required. The value you want returned in this cell.

changingCell

Required. A Range object indicating which cell should be changed to achieve the target value.

Example

This example assumes that Sheet1 has a cell named "Polynomial" containing the formula =(X^3)+(3*X^2)+6 and another cell named "X" that is empty. The example finds a value for X so that Polynomial contains the value 15.

Worksheets("Sheet1").Range("Polynomial").GoalSeek _
    goal:=15, _
    changingCell:=Worksheets("Sheet1").Range("X")


GoSub...Return Statement

Description

Branch to and return from a subroutine within a procedure.

Syntax

GoSub line
. . .
line
. . .
Return

The line argument can be any line label or line number.

Remarks

You can use GoSub and Return anywhere in a procedure, but GoSub and the corresponding Return must be in the same procedure. A subroutine can contain more than one Return statement, but the first Return statement encountered causes the flow of execution to branch back to the statement immediately following the most recently executed GoSub statement.

Note

You can't enter or exit Sub procedures with GoSub...Return.

Tip

Creating separate procedures which you can call may provide a more structured alternative to using GoSub...Return.

See Also

End Statement; GoTo Statement; On...GoSub, On...GoTo Statements; Sub Statement.

Example

This example uses GoSub to call a subroutine within a Sub procedure. The Return statement causes the execution to resume at the statement immediately following the Gosub statement. The Exit Sub statement is used to prevent control from accidentally flowing into the subroutine.

Sub GosubDemo()
    Num = 10    ' Initialize variable.
    GoSub MyRoutine    ' Branch to subroutine.
    Debug.Print Num    ' Print value upon return.
    Exit Sub    ' Exit Sub procedure.
MyRoutine:    ' Start of subroutine.
    Num = Num \ 2    ' Halve the value.
    Return    ' Return from subroutine.
End Sub


Goto Method

Applies To

Application Object.

Description

Selects any range or Visual Basic procedure in any workbook, and activates that workbook if it is not already active.

Syntax

object.Goto(reference, scroll)

object

Required. The Application object.

reference

Optional. Specifies the destination. Can be a Range object, a string containing a cell reference in R1C1 notation, or a string containing a Visual Basic procedure name. If this argument is omitted, the destination is the last range you used the Goto method to select.

scroll

Optional. If this argument is True, Microsoft Excel scrolls the window so that the top left corner of the range appears in the top left corner of the window. If False or omitted, Microsoft Excel does not scroll the window.

Remarks

This method differs from the Select method in the following ways.

  • If you specify a range on a sheet that is not on top, Microsoft Excel will switch to that sheet before selecting. (If you use Select with a range on a sheet that is not on top, the range will be selected but the sheet will not be activated).
  • This method has a scroll argument that lets you scroll the destination window.
  • When you use the Goto method, the previous selection (before the Goto method runs) is added to the array of previous selections (for more information, see the PreviousSelections property). You can use this feature to quickly jump between up to four selections.
  • The Select method has a replace argument; the Goto method does not.

See Also

Select Method.

Example

This example selects cell A154 on Sheet1 and then scrolls through the worksheet to display the range.

Application.Goto reference:=Worksheets("Sheet1").Range("A154"), _
    scroll:=True


GoTo Statement

Description

Branches unconditionally to a specified line within a procedure.

Syntax

GoTo line

The line argument can be any line label or line number.

Remarks

GoTo can branch only to lines within the procedure where it appears.

Note

Too many GoTo statements can be difficult to read and debug. Use structured control statements (Do...Loop, For...Next, If...Then...Else, Select Case) whenever possible.

See Also

Do...Loop Statement, For...Next Statement, GoSub...Return Statement, If...Then...Else Statement, Select Case Statement.

Example

This example uses the GoTo statement to branch to line labels within a procedure.

Sub GotoStatementDemo()
    Number = 1     ' Initialize variable.
    ' Evaluate Number and branch to appropriate label.
    If Number = 1 Then GoTo Line1 Else GoTo Line2

Line1:
    MyString = "Number equals 1"
    GoTo LastLine    ' Go to LastLine.
Line2:
    ' The following statement never gets executed.
    MyString = "Number equals 2"
LastLine:
    Debug.Print MyString    ' Print 1 in Debug window.
End Sub


GridlineColor Property

Applies To

Window Object.

Description

Returns or sets the gridline color as an RGB value. Read-write.

See Also

DisplayGridlines Property, GridlineColorIndex Property.

Example

This example sets the gridline color in the active window in BOOK1.XLS to red.

Workbooks("BOOK1.XLS").Worksheets("Sheet1").Activate
ActiveWindow.GridlineColor = RGB(255,0,0)


GridlineColorIndex Property

Applies To

Window Object.

Description

Returns or sets the gridline color as an index into the current color palette. Read-write.

Remarks

Set this property to xlAutomatic to specify the automatic color.

See Also

Colors Property, DisplayGridlines Property, GridlineColor Property.

Example

This example sets the active window gridline color to blue.

ActiveWindow.GridlineColorIndex = 5


Gridlines Object

Description

Represents major gridlines or minor gridlines on a chart axis. Gridlines extend the tick marks on a chart axis to make it easier to see the values associated with the data markers. There is no singular GridLine object; you must turn all gridlines for an axis on or off at once.

Accessors

The MajorGridlines property returns the major gridlines for the axis. The MinorGridlines property returns the minor gridlines. There is no GridLines property or collection; you must access the major and minor gridlines separately.

The following example turns on major gridlines for the category axis on the chart sheet named "Chart1" and then formats the gridlines to be blue dashed lines.

Charts("chart1").Axes(xlCategory).HasMajorGridlines = True
Charts("chart1").Axes(xlCategory).MajorGridlines.Border.Color = _
    RGB(0, 0, 255)
Charts("chart1").Axes(xlCategory).MajorGridlines.Border.LineStyle = _
    xlDash

Properties

Application Property, Border Property, Creator Property, Name Property, Parent Property.

Methods

Delete Method, Select Method.


Group Method

Applies To

Arcs Collection, Buttons Collection, ChartObjects Collection, DrawingObjects Collection, Drawings Collection, DropDowns Collection, EditBoxes Collection, GroupBoxes Collection, GroupObjects Collection, Labels Collection, Lines Collection, ListBoxes Collection, OLEObjects Collection, OptionButtons Collection, Ovals Collection, Pictures Collection, Range Object, Rectangles Collection, ScrollBars Collection, Spinners Collection, TextBoxes Collection.

Description

Syntax 1: Demotes a range in an outline (in other words, increases its outline level). The range should be an entire row or column, or a range of rows or columns.

Groups a discontinuous range in a PivotTable.

Groups multiple controls or drawing objects together; returns a new GroupObject object.

Syntax 2: Performs numeric or date grouping in a pivot field.

Syntax 1

object.Group

Syntax 2

object.Group(start, end, by, periods)

object

Required. The object to which this method applies. For syntax 2, the Range object must be a single cell in the data range of the pivot field. The method will fail (without displaying any error message) if you attempt to apply the method to more than one cell. To see how to use the Group method in this way, see the second example.

start

Optional. The first value to be grouped. If omitted or True, the first value in the field is used.

end

Optional. The last value to be grouped. If omitted or True, the last value in the field is used.

by

Optional. If the field is numeric, specifies the size of each group.

If the field is a date, specifies the number of days in each group if element four of the periods array is True. Otherwise by is ignored.

If this argument is omitted, a default group size is automatically chosen.

periods

Optional. An array of Boolean values specifying the period for the group, as shown in the following table.

Array element

Period

1

Seconds

2

Minutes

3

Hours

4

Days

5

Months

6

Quarters

7

Years

If an element of the array is True, a group is created for the corresponding time. If the element is False, no group is created. This argument is ignored if the field is not a date field.

See Also

OutlineLevel Property, Ungroup Method.

Example

This example creates a group from drawing objects one, three, and five on Sheet1.

Set myGroup = Worksheets("Sheet1").DrawingObjects(Array(1, 3, 5)).Group
Worksheets("Sheet1").Activate
myGroup.Select

This example groups the field named "ORDER_DATE" by 10-day periods.

Set pvtTable = Worksheets("Sheet1").Range("A3").PivotTable
Set groupRange = pvtTable.PivotFields("ORDER_DATE").DataRange
groupRange.Cells(1).Group by:=10, periods:=Array(False, False, False, True, False, False, False)


GroupBox Object

Description

Represents a static frame used to label and group sets of option buttons (OptionButton objects) and other controls on a chart sheet, dialog sheet, or worksheet. Group boxes control how option buttons select and clear. All option buttons with an upper-left corner contained within the group box boundaries are considered to be part of a group, and only one option button within that group can be turned on at any given time.

Group boxes have no font or background formatting, but group boxes on dialog sheets do have an accelerator key. Group boxes can be positioned and sized.

Do not confuse GroupBox objects, which group option buttons on a dialog sheet, with GroupObject objects, which combine objects into a single logical collection but do not affect dialog sheet behavior.

Accessors

The GroupBox object is a member of the GroupBoxes collection. The GroupBoxes collection contains all the GroupBox objects on a single sheet. Use the Add method to create a new group box and add it to the collection.

To access a single member of the collection, use the GroupBoxes method with the index number or name of the group box as an argument.

The following example sets the caption for group box one on the dialog sheet named "Dialog1."

DialogSheets("dialog1").GroupBoxes(1).Caption = "Test Group"

The group box name is shown in the Name Box when the group box is selected. Use the Name property to set or return the group box name. The following example hides the group box named "Group Box 14" on dialog sheet one.

DialogSheets(1).GroupBoxes("group box 14").Visible = False

Properties

Accelerator Property, Application Property, BottomRightCell Property, Caption Property, Creator Property, Display3DShading Property, Enabled Property, Height Property, Index Property, Left Property, Locked Property, LockedText Property, Name Property, OnAction Property, Parent Property, PhoneticAccelerator Property, Placement Property, PrintObject Property, Text Property, Top Property, TopLeftCell Property, Visible Property, Width Property, ZOrder Property.

Methods

BringToFront Method, Characters Method, CheckSpelling Method, Copy Method, CopyPicture Method, Cut Method, Delete Method, Duplicate Method, Select Method, SendToBack Method.


GroupBoxes Collection Object

Description

A collection of all the GroupBox objects on the specified chart sheet, dialog sheet, or worksheet. Each GroupBox object represents a static frame used to label and group sets of option buttons (OptionButton objects) and other controls. Group boxes control how option buttons select and clear. All option buttons with an upper-left corner contained within the group box boundaries are considered to be part of a group, and only one option button within that group can be turned on at any given time.

Do not confuse GroupBox objects, which group option buttons on a dialog sheet, with GroupObject objects, which combine objects into a single logical collection but do not affect dialog sheet behavior.

Accessors

Use the Add method to create a new group box and add it to the collection. The following example creates a new group box on dialog sheet one.

DialogSheets(1).GroupBoxes.Add 77, 44, 82, 63

Use the GroupBoxes method with an argument to access a single member of the collection or without an argument to access the entire collection at once. The following example deletes all of the group boxes on the worksheet named "Sheet1."

Sheets("sheet1").GroupBoxes.Delete

Properties

Accelerator Property, Application Property, Caption Property, Count Property, Creator Property, Display3DShading Property, Enabled Property, Height Property, Left Property, Locked Property, LockedText Property, OnAction Property, Parent Property, PhoneticAccelerator Property, Placement Property, PrintObject Property, Text Property, Top Property, Visible Property, Width Property, ZOrder Property.

Methods

Add Method (Graphic Objects and Controls), BringToFront Method, Characters Method, CheckSpelling Method, Copy Method, CopyPicture Method, Cut Method, Delete Method, Duplicate Method, Group Method, Item Method, Select Method, SendToBack Method.


GroupBoxes Method

Applies To

Chart Object, DialogSheet Object, Worksheet Object.

Description

Accessor. Returns an object that represents a single group box control (a GroupBox object, Syntax 1) or a collection of group box controls (a GroupBoxes object, Syntax 2) on the sheet.

Syntax 1

object.GroupBoxes(index)

Syntax 2

object.GroupBoxes

object

Required. The Chart, DialogSheet, or Worksheet object.

index

Required for Syntax 1. Specifies the name or number of the group box (can be an array to specify more than one).

Example

This example sets the title for group box one on Dialog1.

DialogSheets("Dialog1").GroupBoxes.Text = "Choose one"


GroupLevel Property

Applies To

PivotField Object.

Description

Returns the placement of the specified field within a group of fields (if the field is a member of a grouped set of fields). Read-only.

Remarks

The highest-level parent field (leftmost parent field) is GroupLevel one, its child is GroupLevel two, and so on.

Example

This example displays a message box if the field that contains the active cell is the highest-level parent field.

Worksheets("Sheet1").Activate
If ActiveCell.PivotField.GroupLevel = 1 Then
    MsgBox "This is the highest-level parent field."
End If


GroupObject Object

Description

Represents a group of graphic objects and controls. A group is created using either the Group method or the Group Objects button on the Drawing toolbar.

Do not confuse GroupObject objects, which combine objects into a single logical collection but do not affect dialog sheet behavior, with GroupBox objects, which group option buttons on a dialog sheet.

Accessors

The GroupObject object is a member of the GroupObjects collection. The GroupObjects collection contains all the GroupObject objects on a single sheet. Use the Group method to create a new group and add it to the collection. The following example creates a group containing all of the rectangles on worksheet one and then sets the position of the group.

Dim g As GroupObject
Set g = Worksheets(1).Rectangles.Group
g.Left = Worksheets(1).Range("c1").Left
g.Top = Worksheets(1).Range("c1").Top

To access a single member of the collection, use the GroupObjects method with the index number or name of the group as an argument.

The following example sets the interior color for all objects in group one on worksheet one.

Worksheets(1).GroupObjects(1).Interior.Color = RGB(0, 255, 0)

The group name is shown in the Name Box when the group is selected. Use the Name property to set or return the group name. The following example sets the border style for all objects in the group named "Group 24."

Worksheets(1).GroupObjects("group 24").Border.LineStyle = xlDashDot

Properties

AddIndent Property, Application Property, ArrowHeadLength Property, ArrowHeadStyle Property, ArrowHeadWidth Property, AutoSize Property, Border Property, BottomRightCell Property, Creator Property, Enabled Property, Font Property, Height Property, HorizontalAlignment Property, Index Property, Interior Property, Left Property, Locked Property, Name Property, OnAction Property, Orientation Property, Parent Property, Placement Property, PrintObject Property, RoundedCorners Property, Shadow Property, Top Property, TopLeftCell Property, VerticalAlignment Property, Visible Property, Width Property, ZOrder Property.

Methods

BringToFront Method, CheckSpelling Method, Copy Method, CopyPicture Method, Cut Method, Delete Method, Duplicate Method, Select Method, SendToBack Method, Ungroup Method.


GroupObjects Collection Object

Description

A collection of all the GroupObject objects on the specified chart sheet, dialog sheet, or worksheet. Each GroupObject represents a group of graphic objects and controls. Unlike other collection objects, the GroupObjects object has no Add method. Groups are created and added to the collection using either the Group method or the Group Objects button on the Drawing toolbar.

Do not confuse GroupObject objects, which combine objects into a single logical collection but do not affect dialog sheet behavior, with GroupBox objects, which group option buttons on a dialog sheet.

Accessors

Use the GroupObjects method with an argument to access a single member of the collection or without an argument to access the entire collection at once. The following example ungroups all of the graphic object groups on the worksheet named "Sheet1."

Worksheets("sheet1").GroupObjects.Ungroup

Properties

AddIndent Property, Application Property, ArrowHeadLength Property, ArrowHeadStyle Property, ArrowHeadWidth Property, AutoSize Property, Border Property, Count Property, Creator Property, Enabled Property, Font Property, Height Property, HorizontalAlignment Property, Interior Property, Left Property, Locked Property, OnAction Property, Orientation Property, Parent Property, Placement Property, PrintObject Property, RoundedCorners Property, Shadow Property, Top Property, VerticalAlignment Property, Visible Property, Width Property, ZOrder Property.

Methods

BringToFront Method, CheckSpelling Method, Copy Method, CopyPicture Method, Cut Method, Delete Method, Duplicate Method, Group Method, Item Method, Select Method, SendToBack Method, Ungroup Method.


GroupObjects Method

Applies To

Chart Object, DialogSheet Object, Worksheet Object.

Description

Accessor. Returns an object that represents a single group (a GroupObject object, Syntax 1) or a collection of all the groups (a GroupObjects object, Syntax 2) on the sheet.

Syntax 1

object.GroupObjects(index)

Syntax

object.GroupObjects

object

Required. The Chart, DialogSheet or Worksheet object.

index

Required for Syntax 1. The name or number of the group (can be an array to specify more than one).

Example

This example ungroups the graphic objects in group one on Sheet1.

Worksheets("Sheet1").GroupObjects(1).Ungroup


HasArray Property

Applies To

Range Object.

Description

True if the specified cell is a part of an array. Read-only.

See Also

CurrentArray Property.

Example

This example displays a message if the active cell on Sheet1 is part of an array.

Worksheets("Sheet1").Activate
If ActiveCell.HasArray =True Then
    MsgBox "The active cell is part of an array"
End If


HasAutoFormat Property

Applies To

PivotTable Object.

Description

True if the PivotTable is automatically formatted when it is refreshed or when fields are moved. Read-write.

Example

This example causes the PivotTable to be automatically reformatted when it is refreshed or when fields are moved.

Set pvtTable = Worksheets("Sheet1").Range("A3").PivotTable
pvtTable.HasAutoFormat = True


HasAxis Property

Applies To

Chart Object.

Description

Indicates which axes exist on the chart, as a two-dimensional array of Boolean values. Read-write.

The first array dimension indicates the axis (one of xlCategory, xlValue, or xlSeries). Series axes apply only to 3-D charts.

The second array dimension indicates the axis group (xlPrimary or xlSecondary). Read-write. 3-D charts have only one set of axes.

Remarks

Microsoft Excel may create or delete axes if you change the chart type or change the AxisGroup property.

See Also

Axes Collection.

Example

This example turns on the primary value axis for Chart1.

Charts("Chart1").HasAxis(xlValue, xlPrimary) = True


HasDataLabel Property

Applies To

Point Object.

Description

True if the point has a data label. Read-write.

See Also

ApplyDataLabels Method, DataLabel Property, HasDataLabels Property.

Example

This example turns on the data label for point seven in series three in Chart1, and then it sets the data label color to blue.

With Charts("Chart1").SeriesCollection(3).Points(7)
    .HasDataLabel = True
    .ApplyDataLabels type:=xlValue
    .DataLabel.Font.ColorIndex = 5
End With


HasDataLabels Property

Applies To

Series Object.

Description

True if the series has data labels. Read-write.

See Also

ApplyDataLabels Method, DataLabel Property, HasDataLabel Property.

Example

This example turns on data labels for series three in Chart1.

With Charts("Chart1").SeriesCollection(3)
    .HasDataLabels = True
    .ApplyDataLabels type:=xlValue
End With


HasDropLines Property

Applies To

ChartGroup Object.

Description

True if the line or area chart has drop lines. Applies only to line and area charts. Read-write.

See Also

DropLines Property.

Example

This example turns on drop lines for chart group one in Chart1 and then sets their line style, weight, and color. The example should be run on a 2-D line chart that has one series.

With Charts("Chart1").ChartGroups(1)
    .HasDropLines = True
    With .DropLines.Border
        .LineStyle = xlThin
        .Weight = xlMedium
        .ColorIndex = 3
    End With
End With


HasErrorBars Property

Applies To

Series Object.

Description

True if the series has error bars. This property is not available on 3-D charts. Read-write.

See Also

ErrorBar Method, ErrorBars Property.

Example

This example removes error bars for series one in Chart1. The example should be run on a 2-D line chart that has error bars for series one.

Charts("Chart1").SeriesCollection(1).HasErrorBars = False


HasFormula Property

Applies To

Range Object.

Description

True if all cells in the range contain formulas; False if no cell in the range contains a formula; Null otherwise. Read-only.

Example

This example prompts the user to select a range on Sheet1. If every cell in the selected range contains a formula, the example displays a message.

Worksheets("Sheet1").Activate
Set rr = Application.InputBox( _
    prompt:="Select a range on this worksheet", _
    Type:=8)
If rr.HasFormula = True Then
    MsgBox "Every cell in the selection contains a formula"
End If


HasHiLoLines Property

Applies To

ChartGroup Object.

Description

True if the line chart has high-low lines. Applies only to line charts. Read-write.

See Also

HiLoLines Property.

Example

This example turns on high-low lines for chart group one in Chart1 and then sets line style, weight, and color. The example should be run on a 2-D line chart that has three series of stock-quote-like data (high-low-close).

With Charts("Chart1").ChartGroups(1)
    .HasHiLoLines = True
    With .HiLoLines.Border
        .LineStyle = xlThin
        .Weight = xlMedium
        .ColorIndex = 3
    End With
End With


HasLegend Property

Applies To

Chart Object.

Description

True if the chart has a legend. Read-write.

See Also

Legend Property.

Example

This example turns on the legend for Chart1 and then sets the legend font color to blue.

Charts("Chart1").HasLegend = True
Charts("Chart1").Legend.Font.ColorIndex = 5


HasMailer Property

Applies To

Workbook Object.

Description

True if the workbook has a mailer. Available only in Microsoft Excel for the Apple Macintosh with the PowerTalk mail system extension installed. Read-write.

See Also

Mailer Property, MailSystem Property, SendMailer Method.

Example

This example replies to the sender of the active workbook.

Set original = ActiveWorkbook
If original.HasMailer Then
    original.Reply
    original.Mailer.Subject = "Here's my reply"
    ActiveWorkbook.SendMailer
End If


HasMajorGridlines Property

Applies To

Axis Object.

Description

True if the axis has major gridlines. Only axes in the primary axis group can have gridlines. Read-write.

See Also

AxisGroup Property, HasMinorGridlines Property, MajorGridlines Property, MinorGridlines Property.

Example

This example sets the color of the major gridlines for the value axis in Chart1.

With Charts("Chart1").Axes(xlValue)
    If .HasMajorGridlines Then
        .MajorGridlines.Border.ColorIndex = 3    'set color to red
    End If
End With


HasMinorGridlines Property

Applies To

Axis Object.

Description

True if the axis has minor gridlines. Only axes in the primary axis group can have gridlines. Read-write.

See Also

AxisGroup Property, HasMajorGridlines Property, MajorGridlines Property, MinorGridlines Property.

Example

This example sets the color of the minor gridlines for the value axis in Chart1.

With Charts("Chart1").Axes(xlValue)
    If .HasMinorGridlines Then
        .MinorGridlines.Border.ColorIndex = 4    'set color to green
    End If
End With


HasPassword Property

Applies To

Workbook Object.

Description

True if the workbook has a protection password. Read-only.

Remarks

You can assign a protection password to a workbook with the SaveAs method.

Example

This example displays a message if the active workbook has a protection password.

If ActiveWorkbook.HasPassword = True Then
    MsgBox "Remember to obtain the workbook password" & Chr(13) & _
        " from the Network Administrator."
End If


HasRadarAxisLabels Property

Applies To

ChartGroup Object.

Description

True if a radar chart has axis labels. Applies only to radar charts. Read-write.

See Also

RadarAxisLabels Property.

Example

This example turns on radar axis labels for chart group one in Chart1 and sets their color. The example should be run on a radar chart.

With Charts("Chart1").ChartGroups(1)
    .HasRadarAxisLabels = True
    .RadarAxisLabels.Font.ColorIndex = 3
End With


HasRoutingSlip Property

Applies To

Workbook Object.

Description

True if the workbook has a RoutingSlip. Read-write.

Remarks

Setting this property to True creates a routing slip with default values. Setting the property to False deletes the routing slip.

See Also

RoutingSlip Property.

Example

This example creates a routing slip for BOOK1.XLS and then sends the workbook to three recipients, one after another.

Workbooks("BOOK1.XLS").HasRoutingSlip = True
With Workbooks("BOOK1.XLS").RoutingSlip
    .Delivery = xlOneAfterAnother
    .Recipients = Array("Adam Bendel", "Jean Selva", "Bernard Gabor")
    .Subject = "Here is BOOK1.XLS"
    .Message = "Here is the workbook. What do you think?"
End With
Workbooks("BOOK1.XLS").Route


HasSeriesLines Property

Applies To

ChartGroup Object.

Description

True if a stacked column or bar chart has series lines. Applies only to stacked column and bar charts. Read-write.

See Also

SeriesLines Property.

Example

This example turns on series lines for chart group one in Chart1 and then sets their line style, weight, and color. The example should be run on a 2-D stacked column chart that has two or more series.

With Charts("Chart1").ChartGroups(1)
    .HasSeriesLines = True
    With .SeriesLines.Border
        .LineStyle = xlThin
        .Weight = xlMedium
        .ColorIndex = 3
    End With
End With


HasTitle Property

Applies To

Axis Object, Chart Object.

Description

True if the axis or chart has a visible title. Read-write.

Remarks

An axis title is an AxisTitle object.

A chart title is a ChartTitle object.

Example

This example adds an axis label to the category axis in Chart1.

With Charts("Chart1").Axes(xlCategory)
    .HasTitle = True
    .AxisTitle.Text = "July Sales"
End With


HasUpDownBars Property

Applies To

ChartGroup Object.

Description

True if a line chart has up and down bars. Applies only to line charts. Read-write.

See Also

DownBars Property, UpBars Property.

Example

This example turns on up and down bars for chart group one in Chart1 and then sets their colors. The example should be run on a 2-D line chart containing two series that cross each other at one or more data points.

With Charts("Chart1").ChartGroups(1)
    .HasUpDownBars = True
    .DownBars.Interior.ColorIndex = 3
    .UpBars.Interior.ColorIndex = 5
End With


HeaderMargin Property

Applies To

PageSetup Object.

Description

Returns or sets the distance from the top of the page to the header, in points (1/72 inch). Read-write.

See Also

BottomMargin Property, FooterMargin Property, LeftMargin Property, RightMargin Property, TopMargin Property.

Example

This example sets the header margin of Sheet1 to 0.5 inch.

Worksheets("Sheet1").PageSetup.HeaderMargin = _
        Application.InchesToPoints(0.5)


Height Property

Applies To

Application Object, Arc Object, Arcs Collection, Button Object, Buttons Collection, ChartArea Object, ChartObject Object, ChartObjects Collection, CheckBox Object, DialogFrame Object, Drawing Object, DrawingObjects Collection, Drawings Collection, DropDown Object, DropDowns Collection, EditBox Object, EditBoxes Collection, GroupBox Object, GroupBoxes Collection, GroupObject Object, GroupObjects Collection, Label Object, Labels Collection, Legend Object, Line Object, Lines Collection, ListBox Object, ListBoxes Collection, OLEObject Object, OLEObjects Collection, OptionButton Object, OptionButtons Collection, Oval Object, Ovals Collection, Picture Object, Pictures Collection, PlotArea Object, Range Object, Rectangle Object, Rectangles Collection, ScrollBar Object, ScrollBars Collection, Spinner Object, Spinners Collection, TextBox Object, TextBoxes Collection, Toolbar Object, Window Object.

Description

Returns or sets the height of an object, in points (1/72 inch).

Remarks

The height set or returned depends on the specified object.

Object type | Height
Application | Height of the main Application window. On the Apple Macintosh this is always equal to the total height of the screen, in points. Setting this value to something else on the Macintosh will have no effect. In Windows, if the window is minimized, this property is read-only and refers to the height of the icon. If the window is maximized, this property cannot be set. Use the WindowState property to determine the window state.
Range | Height of the range. Read-only.
Toolbar | Height of the toolbar. Returns the exact height of the toolbar in points. Use the Width property to change the size of the toolbar. Read-only.
Window | Height of the window. Use the UsableHeight property to determine the maximum size for the window. You cannot set this property if the window is maximized or minimized. Use the WindowState property to determine the window state.
Arc, Button, ChartArea, ChartObject, CheckBox, DialogFrame, Drawing, DrawingObjects, DropDown, EditBox, GroupBox, GroupObject, Label, Legend, Line, ListBox, OLEObject, OptionButton, Oval, Picture, PlotArea, Rectangle, ScrollBar, Spinner, TextBox | Height of the object. If you set the height for an entire collection of objects (using Ovals.Height = 100, for example), the height of each object changes in proportion to its existing height (this mimics the behavior of selecting all the objects and then dragging a handle to change the height of the selection). This means that the height of each object changes, but they are not all set to the same height. To set every object in the collection to the same height, you must iterate the collection and set the height of each individual object.

You can use negative numbers to set the Height and Width properties of the following drawing objects: Arc, Button, CheckBox, Drawing, DropDown, EditBox, GroupBox, GroupObject, Label, Line, ListBox, OLEObject, OptionButton, Oval, Picture, Rectangle, ScrollBar, Spinner, and TextBox. This causes the object to reflect or translate (the behavior depends on the object), after which the Top and Left properties change to describe the new position. The Height and Width properties always return positive numbers.

See Also

Left Property, Top Property, Width Property.

Example

This example sets the height of oval one on Sheet1 to 1 inch (72 points).

Worksheets("Sheet1").Ovals(1).Height = 72

This example sets the height of every button on Sheet1 to 18 points.

For Each b In Worksheets("Sheet1").Buttons
    b.Height = 18
Next b


HeightPercent Property

Applies To

Chart Object.

Description

Returns or sets the height of a 3-D chart as a percentage of the chart width (between 5 and 500 percent). Read-write.

See Also

DepthPercent Property.

Example

This example sets the height of Chart1 to 80 percent of its width. The example should be run on a 3-D chart.

Charts("Chart1").HeightPercent = 80


Help Method

Applies To

Application Object.

Description

Displays a Help topic.

Syntax

object.Help(helpFile, helpContextID)

object

Required. The Application object.

helpFile

Optional. The name of the online Help file you wish to display. If this argument is not specified, Microsoft Excel's Help file is used.

helpContextID

Optional. Specifies the context ID for the Help topic. If this argument is not specified, the Help Topics dialog box is displayed.

Example

This example displays the contents screen for the Help file OTISAPP.HLP.

Application.Help "OTISAPP.HLP"


HelpButton Property

Applies To

Button Object, Buttons Collection, DrawingObjects Collection.

Description

Applies only to buttons in a user-defined dialog box. If True, then pressing the Help key runs the macro identified by the button's OnAction property. If False, pressing the Help key does nothing. The Help key is F1 in Windows and COMMAND+? on the Macintosh. Read-write.

Remarks

Only one button in the dialog box can have the HelpButton property set to True at any given time; setting the property resets it for all other buttons in the dialog box.

If the user presses the Help key in a dialog box that has no Help button, nothing happens.

See Also

Help Method.

Example

This example displays the name of the Help button in Dialog1.

For Each b In DialogSheets("Dialog1").Buttons
    If b.HelpButton = True Then
        MsgBox "Help button is " & b.Name
    End If
Next b


HelpContextID Property

Applies To

MenuItem Object, ToolbarButton Object.

Description

Returns or sets the Help context ID (a number) for the Help topic attached to the menu item or toolbar button. Read-write. Microsoft Windows only.

Remarks

To use this property, you must also set the HelpFile property.

See Also

HelpFile Property, StatusBar Property.

Example

This example adds a new menu item to the Help menu on the Visual Basic Module menu bar, and then it sets the status bar text, the Help filename, and the Help context ID for the new menu item (note that the HelpFile and HelpContextId properties are Windows-only properties).

Set menuObj = MenuBars(xlModule).Menus("Help")
Set newMenuItem = menuObj.MenuItems.Add(Caption:="&Read Me First", _
                OnAction:="readmeMacro", _
                Before:=1)
newMenuItem.StatusBar = "Read this topic before you begin"
newMenuItem.HelpFile = "C:\xl5\vba_xl.hlp"
newMenuItem.HelpContextID = 65535


HelpFile Property

Applies To

MenuItem Object, ToolbarButton Object.

Description

Returns or sets the Help filename, as a string, for the Help topic attached to the menu item or toolbar button. Read-write. Microsoft Windows only.

Remarks

To use this property, you must also set the HelpContextID property.

See Also

HelpContextID Property, StatusBar Property.

Example

This example adds a new menu item to the Help menu on the Visual Basic Module menu bar, and then it sets the status bar text, the Help filename, and the Help context ID for the new menu item (note that the HelpFile and HelpContextId properties are Windows-only properties).

Set menuObj = MenuBars(xlModule).Menus("Help")
Set newMenuItem = menuObj.MenuItems.Add(Caption:="&Read Me First", _
                OnAction:="readmeMacro", _
                Before:=1)
newMenuItem.StatusBar = "Read this topic before you begin"
newMenuItem.HelpFile = "C:\xl5\vba_xl.hlp"
newMenuItem.HelpContextID = 65535


Hex Function

Description

Returns a string representing the hexadecimal value of a number.

Syntax

Hex(number)

The number named argument is any valid numeric expression.

Remarks

If number is not already a whole number, it is rounded to the nearest whole number before being evaluated.

If number is | Hex returns
Null | An error.
Empty | Zero (0).
Any other number | Up to eight hexadecimal characters.

You can represent hexadecimal numbers directly by preceding numbers in the proper range with &H. For example, &H10 represents decimal 16 in hexadecimal notation.

See Also

Oct Function.

Example

This example uses the Hex function to return the hexadecimal value of a number.

MyHex = Hex(5)    ' Returns 5.
MyHex = Hex(10)    ' Returns A.
MyHex = Hex(459)    ' Returns 1CB.


Hidden Property

Applies To

Range Object, Scenario Object.

Description

Range object: True if the rows or columns are hidden. The specified range must span an entire column or row. Read-write.

Scenario object: True if the scenario is hidden. The default value is False. Read-write.

Remarks

Do not confuse this property with the FormulaHidden property.

Example

This example hides column C on Sheet1.

Worksheets("Sheet1").Columns("C").Hidden = True


HiddenFields Method

Applies To

PivotTable Object.

Description

Accessor. Returns an object that represents a single pivot field (a PivotField object, Syntax 1) or a collection of the pivot fields (a PivotFields object, Syntax 2) that are currently not showing as row, column, page or data fields. Read-only.

Syntax 1

object.HiddenFields(index)

Syntax 2

object.HiddenFields

object

Required. The PivotTable object.

index

Required for Syntax 1. The name or number of the pivot field to return (can be an array to specify more than one).

See Also

ColumnFields Method, DataFields Method, PageFields Method, PivotFields Method, RowFields Method, VisibleFields Method.

Example

This example adds the hidden field names to a list box. The list box appears on Sheet1.

Set pvtTable = Worksheets("Sheet1").Range("A3").PivotTable
Set newListBox = Worksheets("Sheet1").ListBoxes.Add _
    (Left:=10, Top:=72, Width:=144, Height:=144)
For Each hdnField In pvtTable.HiddenFields
    newListBox.AddItem (hdnField.Name)
Next hdnField
Worksheets("Sheet1").Activate


HiddenItems Method

Applies To

PivotField Object.

Description

Accessor. Returns an object that represents one hidden pivot item (a PivotItem object, Syntax 1) or a collection of all the hidden pivot items (a PivotItems object, Syntax 2) in the specified field. Read-only.

Syntax 1

object.HiddenItems(index)

Syntax 2

object.HiddenItems

object

Required. The PivotField object.

index

Required for Syntax 1. The number or name of the pivot item to return (can be an array to specify more than one).

See Also

ChildItems Method, ParentItems Method, PivotItems Method, VisibleItems Method.

Example

This example adds the names of all the hidden items in the field named "ORDER_DATE" to a list box. The list box appears on Sheet1.

Set pvtTable = Worksheets("Sheet1").Range("A3").PivotTable
Set newListBox = Worksheets("Sheet1").ListBoxes.Add _
    (Left:=10, Top:=72, Width:=144, Height:=144)
Set pvtField = pvtTable.PivotFields("ORDER_DATE")
For Each pvtItem In pvtField.HiddenItems
    newListBox.AddItem (pvtItem.Name)
Next pvtItem
Worksheets("Sheet1").Activate


Hide Method

Applies To

DialogSheet Object.

Description

Hides a dialog box. If the dialog box is not currently displayed, an error occurs.

Syntax

object.Hide(cancel)

object

Required. The DialogSheet object.

cancel

Optional. If True, the dialog box is canceled without validating edit-box contents. If False or omitted, edit box contents are validated before returning. No macros assigned to Cancel or OK buttons are run in either case.

Remarks

If cancel is False and edit fields in the dialog box could not be validated then this method returns False, and the dialog box does not exit. Otherwise, this method returns True.

Example

This example hides the active dialog box.

ActiveDialog.Hide


HiLoLines Object

Description

Represents the high-low lines in a chart group. High-low lines connect the highest point with the lowest point for every category in the chart group. Only 2-D line groups can have high-low lines. There is no singular HiLoLine object; you must turn high-low lines on or off for all points in a chart group at once.

Accessors

The HiLoLines property returns the high-low lines for a chart group. The following example uses the AutoFormat method to create a high-low-close stock chart in embedded chart one (the chart must contain three series). The example then makes the high-low lines blue.

Worksheets(1).ChartObjects(1).Activate
ActiveChart.AutoFormat gallery:=xlLine, format:=8
ActiveChart.ChartGroups(1).HiLoLines.Border.Color = RGB(0, 0, 255)

Remarks

If the HasHiLoLines property is False, most properties of the HiLoLines object are disabled.

Properties

Application Property, Border Property, Creator Property, Name Property, Parent Property.

Methods

Delete Method, Select Method.


HiLoLines Property

Applies To

ChartGroup Object.

Description

Accessor. Returns a HiLoLines object that represents the high-low lines for a series on a line chart. Applies only to line charts. Read-only.

See Also

HasHiLoLines Property.

Example

This example turns on high-low lines for chart group one in Chart1 and then sets their line style, weight, and color. The example should be run on a 2-D line chart that has three series of stock-quote-like data (high-low-close).

With Charts("Chart1").ChartGroups(1)
    .HasHiLoLines = True
    With .HiLoLines.Border
        .LineStyle = xlThin
        .Weight = xlMedium
        .ColorIndex = 3
    End With
End With


HorizontalAlignment Property

Applies To

AxisTitle Object, Button Object, Buttons Collection, ChartTitle Object, DataLabel Object, DataLabels Collection, DrawingObjects Collection, GroupObject Object, GroupObjects Collection, Range Object, Style Object, TextBox Object, TextBoxes Collection.

Description

Returns or sets the horizontal alignment for the object. Can be one of xlCenter, xlDistributed, xlJustify, xlLeft, or xlRight for all objects. In addition, the Range or Style object can be set to xlCenterAcrossSelection, xlFill, or xlGeneral. Read-write.

Remarks

The xlDistributed alignment style works only in Far East versions of Microsoft Excel.

See Also

AddIndent Property, VerticalAlignment Property.

Example

This example applies left alignment to the range A1:A5 on Sheet1.

Worksheets("Sheet1").Range("A1:A5").HorizontalAlignment = xlLeft


Hour Function

Description

Returns a whole number between 0 and 23, inclusive, representing the hour of the day.

Syntax

Hour(time)

The time named argument is limited to a time or numbers and strings, in any combination, that can represent a time. If time contains no valid data, Null is returned.

See Also

Day Function, Minute Function, Now Function, Second Function, Time Function, Time Statement.

Example

This example uses the Hour function to obtain the hour from a specified time.

' In the development environment, the time (date literal) will display
' in short format using the locale settings of your code.
MyTime = #4:35:17 PM#    ' Assign a time.
MyHour = Hour(MyTime)    ' MyHour contains 16.


Id Property

Applies To

ToolbarButton Object.

Description

The button identification number of the button (built-in buttons only). Read-only.

Example

This example displays the button ID number for button one on the Formatting toolbar.

buttonId = Toolbars("Formatting").ToolbarButtons(1).Id
MsgBox "This button's ID number is " & buttonId

This example creates a two-column list of the button names and button ID numbers for the Standard toolbar. The list is placed in the first two columns on worksheet one.

i = 1
For Each btn In Toolbars("Standard").ToolbarButtons
    If btn.IsGap = False Then
        Worksheets(1).Cells(i, 1) = btn.Name
        Worksheets(1).Cells(i, 2) = btn.Id
        i = i + 1
    End If
Next btn


If...Then...Else Statement

Description

Conditionally executes a group of statements, depending on the value of an expression.

Syntax 1

If condition Then statements [Else elsestatements ]

Syntax 2

If condition Then
[statements]
[ElseIf condition-n Then
[elseifstatements]] . . .
[Else
[elsestatements]]
End If

Syntax 1 has these parts:

Part | Description
condition | Numeric or string expression that evaluates True or False.
statements | One or more statements separated by colons; executed if condition is True.
elsestatements | One or more statements separated by colons; executed if condition is False.

Syntax 2 has these parts:

Part | Description
condition | Expression that is True or False.
statements | One or more statements executed if condition is True.
condition-n | Numeric or string expression that evaluates True or False.
elseifstatements | One or more statements executed if associated condition-n is True.
elsestatements | One or more statements executed if no previous condition-n expressions are True.

Remarks

You can use the single-line form (Syntax 1) for short, simple tests. However, the block form (Syntax 2) provides more structure and flexibility than the single-line form and is usually easier to read, maintain, and debug.

Note

With Syntax 1 it is possible to have multiple statements executed as the result of an If...Then decision, but they must all be on the same line and separated by colons, as in the following statement:

If A > 10 Then A = A + 1 : B = B + A : C = C + B

When executing a block If (Syntax 2), condition is tested. If condition is True, the statements following Then are executed. If condition is False, each ElseIf condition (if any) is evaluated in turn. When a True condition is found, the statements immediately following the associated Then are executed. If none of the ElseIf conditions are True (or if there are no ElseIf clauses), the statements following Else are executed. After executing the statements following Then or Else, execution continues with the statement following End If.

The Else and ElseIf clauses are both optional. You can have as many ElseIf clauses as you want in a block If, but none can appear after an Else clause. Block If statements can be nested; that is, contained within one another.

What follows the Then keyword is examined to determine whether or not a statement is a block If. If anything other than a comment appears after Then on the same line, the statement is treated as a single-line If statement.

A block If statement must be the first statement on a line. The Else, ElseIf, and End If parts of the statement can have only a line number or line label preceding them. The block If must end with an End If statement.

Tip

Select Case may be more useful when evaluating a single expression that has several possible actions.

See Also

Select Case Statement.

Example

This example shows uses of the If...Then...Else statement.

Number = 53    ' Initialize variable.
If Number < 10 Then
    Digits = 1
ElseIf Number < 100 Then
' Condition evaluates to True so the next statement is executed.
    Digits = 2
Else
    Digits = 3
End If
' Assign a value using the single line form of syntax.
If Digits = 1 Then MyString = "One" Else MyString = "More than one"

This example loops on cells A1:D10 on Sheet1. If one of the cells has a value less than 0.001, the code replaces the value with 0 (zero).

For Each c in Worksheets("Sheet1").Range("A1:D10")
    If c.Value < .001 Then
        c.Value = 0
    End If
Next c

This example loops on the range named "TestRange" and displays the number of empty cells in the range.

numBlanks = 0
For Each c In Range("TestRange")
    If c.Value = "" Then
        numBlanks = numBlanks + 1
    End If
Next c
MsgBox "There are " & numBlanks & " empty cells in this range."

This example sets the standard font to Arial (in Windows) or Geneva (on the Macintosh).

If Application.OperatingSystem Like "*Macintosh*" Then
    Application.StandardFont = "Geneva"
Else
    Application.StandardFont = "Arial"
End If


IgnoreRemoteRequests Property

Applies To

Application Object.

Description

True if remote DDE requests are ignored. Read-write.

Example

This example sets the IgnoreRemoteRequests property to True so that remote DDE requests are ignored.

Application.IgnoreRemoteRequests = True


Imp Operator

Description

Used to perform a logical implication on two expressions.

Syntax

result = expression1 Imp expression2

The Imp operator syntax has these parts:

Part | Description
result | Any numeric variable.
expression1 | Any expression.
expression2 | Any expression.

Remarks

The following table illustrates how result is determined:

If expression1 is | And expression2 is | The result is
True | True | True
True | False | False
True | Null | Null
False | True | True

If expression1 is | And expression2 is | The result is
False | False | True
False | Null | True
Null | True | True
Null | False | Null
Null | Null | Null

The Imp operator performs a bit-wise comparison of identically positioned bits in two numeric expressions and sets the corresponding bit in result according to the following truth table:

If bit in expression1 is | And bit in expression2 is | The result is
0 | 0 | 1
0 | 1 | 1
1 | 0 | 0
1 | 1 | 1

See Also

Operator Precedence.

Example

This example uses the Imp Operator to perform logical implication on two expressions.

A = 10: B = 8: C = 6 : D = Null    ' Initialize variables.
MyCheck = A > B Imp B > C    ' Returns True.
MyCheck = A > B Imp C > B    ' Returns False.
MyCheck = B > A Imp C > B    ' Returns True.
MyCheck = B > A Imp C > D    ' Returns True.
MyCheck = C > D Imp B > A    ' Returns Null.
MyCheck = B Imp A    ' Returns -1 (bit-wise comparison).


Import Method

Applies To

SoundNote Object.

Description

Imports a sound note from a file.

Syntax

object.Import(file, resource)

object

Required. The SoundNote object.

file

Required. The name of the file containing sounds.

resource

Required for the Apple Macintosh (not used with Microsoft Windows). The name or number of the sound resource in the file to import.

See Also

Play Method, Record Method.

Example

This example adds a sound note to cell A1 on Sheet1.

Worksheets("Sheet1").Range("A1").SoundNote.Import "C:\SOUNDS\CHIMES.WAV"

This is the same example in Microsoft Excel for the Macintosh.

Worksheets("Sheet1").Range("A1").SoundNote.Import "HD:Sounds:Sound Note 1"


InchesToPoints Method

Applies To

Application Object.

Description

Converts a measurement in inches into points (1/72 inch).

Syntax

object.InchesToPoints(inches)

object

Required. The Application object.

inches

Required. Specifies the inch value to convert to points.

See Also

CentimetersToPoints Method.

Example

This example sets the left margin of Sheet1 to 2.5 inches.

Worksheets("Sheet1").PageSetup.LeftMargin = _
        Application.InchesToPoints(2.5)


IncludeAlignment Property

Applies To

Style Object.

Description

True if the style includes the AddIndent, HorizontalAlignment, VerticalAlignment, WrapText, and Orientation properties. Read-write.

See Also

IncludeBorder Property, IncludeFont Property, IncludeNumber Property, IncludePatterns Property, IncludeProtection Property.

Example

This example sets the style attached to cell A1 on Sheet1 to include alignment format.

Worksheets("Sheet1").Range("A1").Style.IncludeAlignment = True


IncludeBorder Property

Applies To

Style Object.

Description

True if the style includes the Borders properties. Read-write.

See Also

IncludeAlignment Property, IncludeFont Property, IncludeNumber Property, IncludePatterns Property, IncludeProtection Property.

Example

This example sets the style attached to cell A1 on Sheet1 to include border format.

Worksheets("Sheet1").Range("A1").Style.IncludeBorder = True


IncludeFont Property

Applies To

Style Object.

Description

True if the style includes the Font property. Read-write.

See Also

IncludeAlignment Property, IncludeBorder Property, IncludeNumber Property, IncludePatterns Property, IncludeProtection Property.

Example

This example sets the style attached to cell A1 on Sheet1 to include font format.

Worksheets("Sheet1").Range("A1").Style.IncludeFont = True


IncludeNumber Property

Applies To

Style Object.

Description

True if the style includes the NumberFormat property. Read-write.

See Also

IncludeAlignment Property, IncludeBorder Property, IncludeFont Property, IncludePatterns Property, IncludeProtection Property.

Example

This example sets the style attached to cell A1 on Sheet1 to include number format.

Worksheets("Sheet1").Range("A1").Style.IncludeNumber = True


IncludePatterns Property

Applies To

Style Object.

Description

True if the style includes the Interior properties. Read-write.

See Also

IncludeAlignment Property, IncludeBorder Property, IncludeFont Property, IncludeNumber Property, IncludeProtection Property.

Example

This example sets the style attached to cell A1 on Sheet1 to include pattern format.

Worksheets("Sheet1").Range("A1").Style.IncludePatterns = True


IncludeProtection Property

Applies To

Style Object.

Description

True if the style includes the FormulaHidden and Locked protection properties. Read-write.

See Also

IncludeAlignment Property, IncludeBorder Property, IncludeFont Property, IncludeNumber Property, IncludePatterns Property.

Example

This example sets the style attached to cell A1 on Sheet1 to include protection format.

Worksheets("Sheet1").Range("A1").Style.IncludeProtection = True


Index Property

Applies To

Arc Object, Button Object, Chart Object, ChartObject Object, CheckBox Object, DialogSheet Object, Drawing Object, DropDown Object, EditBox Object, GroupBox Object, GroupObject Object, Label Object, LegendEntry Object, Line Object, ListBox Object, Menu Object, MenuBar Object, MenuItem Object, Module Object, Name Object, OLEObject Object, OptionButton Object, Oval Object, Pane Object, Picture Object, Rectangle Object, Scenario Object, ScrollBar Object, Spinner Object, TextBox Object, Trendline Object, Window Object, Worksheet Object.

Description

Returns the index number of the object within the collection of similar objects. Read-only.

For help about using the Index worksheet function in Visual Basic, see "Using Worksheet Functions in Visual Basic" in online Help.

Example

This example displays the tab number of the sheet name that you type. For example, if Chart1 is the third tab in the active workbook, the example displays the number 3 in a message box.

sheetname = InputBox("Type a sheet name, such as Sheet12 or Module1")
MsgBox "This sheet is tab number " & Sheets(sheetname).Index


InnerDetail Property

Applies To

PivotTable Object.

Description

Returns or sets the name of the field which will be shown as detail when the ShowDetail property is True for the innermost row or column field. Read-write.

See Also

ShowDetail Property.

Example

This example displays the name of the field that will be shown as detail when the ShowDetail property is True for the innermost row field or column field.

Set pvtTable = Worksheets("Sheet1").Range("A3").PivotTable
MsgBox pvtTable.InnerDetail


Input # Statement

Description

Reads data from an open sequential file and assigns the data to variables.

Syntax

Input #filenumber,varlist

The Input # statement syntax has these parts:

Part | Description
filenumber | Any valid file number.
varlist | Comma-delimited list of variables that are assigned values read from the file: can't be an array or object variable. However, variables that describe an element of an array or user-defined type may be used.

Remarks

When read, standard string or numeric data is assigned to variables as is. The following table illustrates how other input data is treated:

Data | Value assigned to variable
Delimiting comma or blank line | Empty.
#NULL# | Null.
#TRUE# or #FALSE# | True or False.
#yyyy-mm-dd hh:mm:ss# | The date and/or time represented by the expression.
#ERROR errornumber# | errornumber (variable is a Variant tagged as an error).

Double quotation marks (") within input data are ignored.

Data items in a file must appear in the same order as the variables in varlist and be matched with variables of the same data type. If a variable is numeric and the data is not, zero is assigned to the variable.

If the end of the file is reached while a data item is being input, the input is terminated and an error occurs.

Note

In order to correctly read data from a file into variables, you should always use the Write # statement instead of the Print # statement to write the data to the files. Using Write # ensures that each separate data field is properly delimited.

See Also

Input Function, Write # Statement.

Example

This example uses the Input # statement to read data from a file into two variables. For purposes of this example, assume that TESTFILE is a file with a few lines of data written to it using the Write # statement; that is, each line contains a string in quotations and a number separated by a comma, for example, ("Hello", 234).

Open "TESTFILE" For Input As #1    ' Open file for input.
Do While Not EOF(1)    ' Loop until end of file.
    Input #1, MyString, MyNumber    ' Read data into variables.
    Debug.Print MyString, MyNumber    ' Print data to Debug window.
Loop
Close #1    ' Close file.


Input Function

Description

Returns characters (bytes) from an open sequential file.

Syntax

Input(number,[#]filenumber)

The Input function syntax has these parts:

Part | Description
number | Any valid numeric expression specifying the number of characters to return.
filenumber | Any valid file number.

Remarks

Use this function only with files opened in Input or Binary mode.

Unlike the Input # statement, the Input function returns all of the characters it reads including commas, carriage returns, linefeeds, quotation marks, and leading spaces.

Note

Another function (InputB) is provided for use with the double-byte character sets (DBCS) used in some Asian locales. Instead of specifying the number of characters to return, number specifies the number of bytes. In areas where DBCS is not used, InputB behaves the same as Input.

See Also

Input # Statement.

Example

This example uses the Input function to read one character at a time from a file and print it to the Debug window. For purposes of this example, assume that TESTFILE is a text file with a few lines of sample data.

Open "TESTFILE" For Input As #1    ' Open file.
Do While Not EOF(1)    ' Loop until end of file.
    MyChar = Input(1, #1)    ' Get one character.
    Debug.Print MyChar    ' Print to Debug window.
Loop
Close #1    ' Close file.


InputBox Function

Description

Displays a prompt in a dialog box, waits for the user to input text or choose a button, and returns the contents of the text box.

Syntax

InputBox(prompt[,title][,default][,xpos][,ypos][,helpfile,context])

The InputBox function syntax has these named-argument parts:

Part | Description
prompt | String expression displayed as the message in the dialog box. The maximum length of prompt is approximately 1024 characters, depending on the width of the characters used. If prompt consists of more than one line, be sure to include a carriage return (character code 13), or carriage return linefeed (character code 10) between each line.
title | String expression displayed in the title bar of the dialog box. If you omit title, nothing is placed in the title bar.
default | String expression displayed in the text box as the default response if no other input is provided. If you omit default, the text box is displayed empty.
xpos | Numeric expression that specifies, in twips, the horizontal distance of the left edge of the dialog box from the left edge of the screen. If xpos is omitted, the dialog box is horizontally centered.
ypos | Numeric expression that specifies, in twips, the vertical distance of the upper edge of the dialog box from the top of the screen. If ypos is omitted, the dialog box is vertically positioned approximately one-third of the way down the screen.
helpfile | String expression that identifies the Help file to use to provide context-sensitive Help for the dialog box. If helpfile is provided, context must also be provided.
context | Numeric expression that is the Help context number the Help author assigned to the appropriate Help topic. If context is provided, helpfile must also be provided.

Remarks

When both helpfile and context are supplied, a Help button is automatically added to the dialog box.

If the user chooses OK or presses Enter, the InputBox function returns whatever is in the text box. If the user chooses Cancel, the function returns a zero-length string ("").

In Microsoft Excel, the prompt string cannot contain more than 256 characters.

See Also

MsgBox Function.

Example

This example shows various ways to use the InputBox function to prompt the user to enter a value. If the x and y positions are omitted, the dialog is automatically centered for the respective axes. The variable MyValue contains the value entered by the user if the user chooses OK or presses ENTER. If the user chooses Cancel, a zero-length string is returned.

Message = "Enter a value between 1 and 3"    ' Set prompt.
Title = "InputBox Demo"    ' Set title.
Default = "1"    ' Set default.
' Display message, title, and default value.
MyValue = InputBox(Message, Title, Default)

' Use helpfile and context. The help button is added automatically.
MyValue = InputBox(Message, Title, , , , "DEMO.HLP", 10)

' Display dialog at position 100,100
MyValue = InputBox(Message, Title, Default, 100, 100)


InputBox Method

Applies To

Application Object.

Description

Displays a dialog box for user input. Returns the information entered in the dialog box.

Syntax

object.InputBox(prompt, title, default, left, top, helpFile, helpContextID, type)

object

Required. The Application object.

prompt

Required. The message to be displayed in the dialog box. This may be a string, a number, a date, or a Boolean value.

title

Optional. The title for the input box. If this argument is omitted, the default title is "Input".

default

Optional. Specifies a value to be put in the edit box when the dialog box is initially displayed. If this argument is omitted, the edit box is left empty. This value may be a Range object.

left

Optional. Specifies an x position for the dialog box, in points, from the top left of the screen. One point is 1/72 inch.

top

Optional. Specifies a y position for the dialog box, in points, from the top left of the screen.

helpFile

Optional. The name of the online Help file for this input box. If the helpFile and helpContextID arguments are present, a Help button will appear in the dialog.

helpContextID

Optional. The context ID of the Help topic in helpFile.

type

Optional. Specifies the return data type. If this argument is omitted, the dialog box returns text. May have one of the following values:

Value

Meaning

0

A formula

1

A number

2

Text (a string)

4

A logical value (True or False)

8

A cell reference, as a Range object

16

An error value, such as #N/A

64

An array of values

You can use the sum of the allowable values for type. For example, for an input box that can accept text or numbers, set type equal to 1 + 2.

Remarks

Use InputBox to display a simple dialog box so you can enter information to be used in a macro. The dialog box has an OK and a Cancel button. If you choose the OK button, InputBox returns the value entered in the dialog box. If you choose the Cancel button, InputBox returns False.

If type = 0, InputBox returns the formula in the form of text, for example, "=2*PI()/360". If there are any references in the formula, they are returned as A1-style references. (Use ConvertFormula to convert between reference styles.)

If type = 8, InputBox returns a Range object. You must use the Set statement to assign the result to a Range object, as shown in the following example.

Set myRange = Application.InputBox(prompt := "Sample", type := 8)

If you do not use the Set statement, the variable is set to the value in the Range, rather than the Range itself.

If you use the InputBox method to ask the user for a formula, you must use the FormulaLocal property to assign the formula to a Range object. The input formula will be in the user's language. The InputBox method differs from the InputBox function because it allows selective validation of the user's input, and it can be used with Microsoft Excel objects, error values and formulas. Note that Application.InputBox calls the InputBox method; InputBox with no object qualifier calls the InputBox function.

Example

This example prompts the user for a number.

myNum = Application.InputBox("Enter a number")

This example prompts the user to select a cell on Sheet1. The example uses the type argument to ensure that the return value is a valid cell reference (a Range object).

Worksheets("Sheet1").Activate
Set myCell = Application.InputBox( _
    prompt:="Select a cell", Type:=8)


InputType Property

Applies To

DrawingObjects Collection, EditBox Object, EditBoxes Collection.

Description

Returns or sets what type of input validation is applied to the contents of an edit box (one of xlFormula, xlInteger, xlNumber, xlReference, or xlText). Read-write.

Example

This example sets edit box one on Dialog1 to require an integer.

DialogSheets("Dialog1").EditBoxes(1).InputType = xlInteger


Insert Method

Applies To

Characters Object, Pictures Collection, Range Object.

Description

Syntax 1 (Range object): Inserts a cell or a range of cells into the worksheet or macro sheet and shifts other cells away to make space.

Syntax 2 (Characters object): Inserts a string before the selected characters.

Syntax 3 (Pictures object): Inserts the specified file as a picture.

Syntax 1

object.Insert(shift)

Syntax 2

object.Insert(string)

Syntax 3

object.Insert(filename, converter)

object

Required. Insert cells at this range (Syntax 1) or insert string before this character (Syntax 2).

shift

Optional. Specifies which way to shift the cells, either xlToRight or xlDown. If omitted, a default is used based on the shape of the range.

string

Required. The string to insert.

filename

Required. Specifies the file to insert.

converter

Required. Specifies the picture converter to use when loading the file. Can be one of xlBMP, xlWMF, xlPLT, xlCGM, xlHGL, xlPIC, xlEPS, xlDRW, xlTIF, xlWPG, xlDXF, xlPCX, or xlPCT.

Example

This example inserts a new row before row four on Sheet1.

Worksheets("Sheet1").Rows(4).Insert

This example inserts new cells at the range A1:C5 on Sheet1 and shifts cells down.

Worksheets("Sheet1").Range("A1:C5").Insert shift:=xlDown

This example inserts a new row at the active cell. The example must be run from a worksheet.

ActiveCell.EntireRow.Insert

This example replaces the first three characters in text box one on Sheet1 with the string "New" formatted as bold.

With Worksheets("Sheet1").TextBoxes(1).Characters(1, 3)
    .Insert "New"
    .Font.Bold = True
End With

This example adds the string "Done" to the end of text box one on Sheet1 by inserting the new string after the last character in the text box.

With Worksheets("Sheet1").TextBoxes(1)
    .Characters(.Characters.Count + 1).Insert String:="Done"
End With


InsertFile Method

Applies To

Module Object.

Description

Adds text from a file to the end of the module.

Syntax

object.InsertFile(fileName, merge)

object

Required. The Module object.

fileName

Required. The name of the file containing the text that you wish to insert.

merge

Optional. If True, the new file is merged, so that all declarations are at the top of the module and all procedures are below the declarations. If False or omitted, the new file is inserted at the insertion point.

Remarks

You cannot insert text into a running code module. This applies both to running procedures as well as modules containing code that is stacked waiting to run after the current procedure returns.

Example

This example adds text from a file to Module2. Note that you cannot use the InsertFile method to add text to the module that contains the running example. Run the example from Module1 after inserting a new macro module (Module2).

Modules("Module2").InsertFile fileName:="MYMACRO.TXT"


Installed Property

Applies To

AddIn Object.

Description

True if the add-in is installed. Read-write.

Remarks

Setting this property to True installs the add-in and calls its Auto_Add functions. Setting this property to False removes the add-in and calls its Auto_Remove functions.

Example

This example uses a message box to display the installation status of the Solver add-in.

Set a = AddIns("Solver Add-In")
If a.Installed = True Then
    MsgBox "The Solver add-in is installed"
Else
    MsgBox "The Solver add-in is not installed"
End If


InStr Function

Description

Returns the position of the first occurrence of one string within another.

Syntax

InStr([start,]string1,string2[,compare])

The InStr function syntax has these parts:

Part | Description
start | Numeric expression that sets the starting position for each search. If omitted, search begins at the first character position. If start contains no valid data, an error occurs. Start is required if compare is specified.
string1 | String expression being searched. If string1 contains no valid data, Null is returned.
string2 | String expression sought. If string2 contains no valid data, Null is returned.
compare | Number specifying the type of string comparison. Specify 1 to perform a textual case-insensitive comparison. Specify 0 (default) to perform a binary comparison. If compare is Null, an error occurs. Start is required if compare is specified. If compare is omitted, the setting of Option Compare is used to determine the type of comparison.

Return Values

Value | Description
0 | string1 is zero-length.
start | string2 is zero-length.
0 | string2 not found.
Position at which match is found | string2 is found within string1.
0 | start > string2.

Remarks

Note

When Option Compare Text is specified, comparisons are textual and case-insensitive. When Option Compare Binary is specified, comparisons are strictly binary.

Note

Another function (InStrB) is provided for use with the double-byte character sets (DBCS) used in some Asian locales. Instead of returning the character position of the first occurrence of one string within another, InStrB returns the byte position. In areas where DBCS is not used, InStrB behaves the same as InStr.

See Also

Option Compare Statement.

Example

This example uses the InStr function to return the position of the first occurrence of one string within another.

SearchString ="XXpXXpXXPXXP"    ' String to search in.
SearchChar = "P"    ' Search for "P".

' A textual comparison starting at position 4. Returns 6.
MyPos = InStr(4, SearchString, SearchChar, 1)

' A binary comparison starting at position 1. Returns 9.
MyPos = InStr(1, SearchString, SearchChar, 0)

' Comparison is binary by default (if last argument is omitted).
MyPos = InStr(SearchString, SearchChar)    ' Returns 9.

MyPos = InStr(1, SearchString, "W")    ' Returns 0.


Int Function, Fix Function

Description

Returns the integer portion of a number.

Syntax

Int(number)
Fix(number)

The number argument can be any valid numeric expression. If number contains no valid data, Null is returned.

Remarks

Both Int and Fix remove the fractional part of number and return the resulting integer value.

The difference between Int and Fix is that if number is negative, Int returns the first negative integer less than or equal to number, whereas Fix returns the first negative integer greater than or equal to number. For example, Int converts -8.4 to -9, and Fix converts -8.4 to -8.

Fix(number) is equivalent to:

Sgn(number) * Int(Abs(number))

See Also

CInt Function.

Example

This example illustrates how the Int and Fix functions return integer portions of numbers. In the case of a negative number argument, the Int function returns the first negative integer less than or equal to the number; whereas, the Fix function returns the first negative integer greater than or equal to the number.

MyNumber = Int(99.8)    ' Returns 99.
MyNumber = Fix(99.2)    ' Returns 99.
MyNumber = Int(-99.8)    ' Returns -100.
MyNumber = Fix(-99.8)    ' Returns -99.
MyNumber = Int(-99.2)    ' Returns -100.
MyNumber = Fix(-99.2)    ' Returns -99.


Integer Data Type

Description

Integer variables are stored as 16-bit (2-byte) numbers ranging in value from -32,768 to 32,767. The type-declaration character for Integer is % (character code 37).

You can also use Integer variables to represent enumerated values. An enumerated value can contain a finite set of unique whole numbers, each of which has special meaning in the context in which it is used. Enumerated values provide a convenient way to select among a known number of choices. For example, when asking the user to select a color from a list, you could have 0 = black, 1 = white, and so on. It is good programming practice to define constants using the Const statement for each enumerated value.

See Also

CInt Function, Data Type Summary, Def type Statements, Long Data Type, Variant Data Type.


Interactive Property

Applies To

Application Object.

Description

True if Microsoft Excel is in interactive mode; this property is usually True. If you set it to False, Microsoft Excel will block all input from the keyboard and mouse (except input to dialog boxes that are displayed by your code). Blocking user input will prevent the user from interfering with the macro as it moves or activates Microsoft Excel objects. Read-write.

Remarks

This property is useful if you are using DDE, AppleEvents, or OLE Automation to communicate with Microsoft Excel from another application.

If you set this property to False, don't forget to set it back to True. Microsoft Excel will not set this property back to True when your macro stops running.

Example

This example sets the Interactive property to False while it is using DDE in Windows and then sets this property back to True when it is done. This prevents the user from interfering with the macro.

Application.Interactive = False
Application.DisplayAlerts = False
channelNumber = Application.DDEInitiate( _
    app:="WinWord", _
    topic:="C:\WINWORD\FORMLETR.DOC")
Application.DDEExecute channelNumber, "[FILEPRINT]"
Application.DDETerminate channelNumber
Application.DisplayAlerts = True
Application.Interactive = True


Intercept Property

Applies To

Trendline Object.

Description

Returns or sets the point where the trendline crosses the value axis. Read-write.

For help about using the Intercept worksheet function in Visual Basic, see "Using Worksheet Functions in Visual Basic" in online Help.

Remarks

Setting this property causes the InterceptIsAuto property to be set to False.

See Also

InterceptIsAuto Property.

Example

This example causes trendline one in Chart1 to cross the value axis at 5. The example should be run on a 2-D column chart that contains a single series with a trendline.

Charts("Chart1").SeriesCollection(1).Trendlines(1).Intercept = 5


InterceptIsAuto Property

Applies To

Trendline Object.

Description

True if the point where the trendline crosses the value axis is automatically determined by the regression. Read-write.

Remarks

Setting the Intercept property causes this property to be set to False.

See Also

Intercept Property.

Example

This example causes Microsoft Excel to automatically determine the trendline intercept point for Chart1. The example should be run on a 2-D column chart that contains a single series with a trendline.

Charts("Chart1").SeriesCollection(1).Trendlines(1).InterceptIsAuto = _
        True


Interior Object

Description

Represents the interior of an object. Both cells (Range objects) and graphic objects use the Interior object.

Accessors

The Interior property returns the interior of an object. The following example sets the interior color for all the ovals on the worksheet named "Sheet1."

Worksheets("sheet1").Ovals.Interior.ColorIndex = 3

Properties

Application Property, Color Property, ColorIndex Property, Creator Property, Parent Property, Pattern Property, PatternColor Property, PatternColorIndex Property.


Interior Property

Applies To

Arc Object, Arcs Collection, AxisTitle Object, ChartArea Object, ChartObject Object, ChartObjects Collection, ChartTitle Object, CheckBox Object, DataLabel Object, DataLabels Collection, DownBars Object, Drawing Object, DrawingObjects Collection, Drawings Collection, Floor Object, GroupObject Object, GroupObjects Collection, Legend Object, LegendKey Object, OLEObject Object, OLEObjects Collection, OptionButton Object, OptionButtons Collection, Oval Object, Ovals Collection, Picture Object, Pictures Collection, PlotArea Object, Point Object, Range Object, Rectangle Object, Rectangles Collection, Series Object, Style Object, TextBox Object, TextBoxes Collection, UpBars Object, Walls Object.

Description

Accessor. Returns an Interior object that represents the interior of the specified object. Read-only.

Example

This example sets the interior color for cell A1 onSheet1 to cyan.

Worksheets("Sheet1").Range("A1").Interior.ColorIndex = 8


International Property

Applies To

Application Object.

Description

Returns a 45-element array containing information about the current country and international settings. Read-only.

Syntax

object.International(index)

object

Required. The Application object.

index

Optional. Specifies a single setting to return, as shown in the following table.

Index

Built-in constant

Type

Meaning

1

xlCountryCode

number

Country version of Microsoft Excel.

2

xlCountrySetting

number

Current country setting in the Microsoft Windows Control Panel or the country number as determined by your Apple system software.

3

xlDecimalSeparator

text

Decimal separator.

4

xlThousandsSeparator

text

Zero or thousands separator.

5

xlListSeparator

text

List separator.

6

xlUpperCaseRowLetter

text

Uppercase Row letter (for R1C1 references).

7

xlUpperCaseColumnLetter

text

Uppercase Column letter.

8

xlLowerCaseRowLetter

text

Lowercase Row letter.

9

xlLowerCaseColumnLetter

text

Lowercase Column letter.

10

xlLeftBracket

text

Character used instead of the left bracket ([) in R1C1 relative references.

11

xlRightBracket

text

Character used instead of the right bracket (]).

12

xlLeftBrace

text

Character used instead of the left brace ({) in array literals.

13

xlRightBrace

text

Character used instead of the right brace (}).

14

xlColumnSeparator

text

Character used to separate columns in array literals.

15

xlRowSeparator

text

Character used to separate rows.

16

xlAlternateArraySeparator

text

Alternate array item separator to use if the current array separator is the same as the decimal separator.

17

xlDateSeparator

text

Date separator (/ in US).

18

xlTimeSeparator

text

Time separator (: in US).

19

xlYearCode

text

Year symbol in number formats (y in US).

20

xlMonthCode

text

Month symbol (m).

21

xlDayCode

text

Day symbol (d).

22

xlHourCode

text

Hour symbol (h).

23

xlMinuteCode

text

Minute symbol (m).

24

xlSecondCode

text

Second symbol (s).

25

xlCurrencyCode

text

Currency symbol ($).

26

xlGeneralFormatName

text

Name of the General number format.

27

xlCurrencyDigits

number

Number of decimal digits to use in currency formats.

28

xlCurrencyNegative

number

Indicates the currency format for negative currencies:
0 = ($x) or (x$)
1 = -$x or -x$
2 = $-x or x-$
3 = $x- or x$-
Note: The position of the currency symbol is determined by 37.

29

xlNoncurrencyDigits

number

Number of decimal digits to use in non-currency formats.

30

xlMonthNameChars

number

Number of characters to use in month names.

31

xlWeekdayNameChars

number

Number of characters to use in weekday names.

32

xlDateOrder

number

Indicates the date order:
0 = month-day-year
1 = day-month-year
2 = year-month-day

33

xl24HourClock

Boolean

True if using 24-hour time; False if using 12-hour time.

34

xlNonEnglishFunctions

Boolean

True if not displaying functions in English.

35

xlMetric

Boolean

True if using the metric system; False if using the English measurement system.

36

xlCurrencySpaceBefore

Boolean

True if adding a space before the currency symbol.

37

xlCurrencyBefore

Boolean

True if the currency symbol precedes the currency values; False if it goes after.

38

xlCurrencyMinusSign

Boolean

True if using a minus sign for negative numbers; False if using parentheses.

39

xlCurrencyTrailingZeros

Boolean

True if trailing zeros are displayed for zero currency values.

40

xlCurrencyLeadingZeros

Boolean

True if leading zeros are displayed for zero currency values.

41

xlMonthLeadingZero

Boolean

True if a leading zero is displayed in months when months are displayed as numbers.

42

xlDayLeadingZero

Boolean

True if a leading zero is displayed in days.

43

xl4DigitYears

Boolean

True if using 4-digit years; False if using 2-digit years.

44

xlMDY

Boolean

True if the date order is Month-Day-Year when dates are displayed in the long form; False if the date order is Day-Month-Year.

45

xlTimeLeadingZero

Boolean

True if the leading zero is shown in the time.

Example

This example displays the international decimal separator.

MsgBox "The decimal separator is " & _
    Application.International(xlDecimalSeparator)


Intersect Method

Applies To

Application Object.

Description

Returns the rectangular intersection of two or more ranges.

Syntax

object.Intersect(arg1, arg2, ...)

object

Optional. The Application object.

arg1, arg2, ...

Required. The intersecting ranges. At least two Range objects must be specified.

See Also

Union Method.

Example

This example selects the intersection of two named ranges, rg1 and rg2, on Sheet1. If the ranges do not intersect, the example displays a message.

Worksheets("Sheet1").Activate
Set isect = Application.Intersect(Range("rg1"), Range("rg2"))
If isect Is Nothing Then
    MsgBox "Ranges do not intersect"
Else
    isect.Select
End If


InvertIfNegative Property

Applies To

LegendKey Object, Point Object, Series Object.

Description

True if Microsoft Excel inverts the pattern in the item when it corresponds to a negative number. Read-write.

Example

This example inverts the pattern for negative values in series one in Chart1. The example should be run on a 2-D column chart.

Charts("Chart1").SeriesCollection(1).InvertIfNegative = True


Is Operator

Description

Used to compare two object reference variables.

Syntax

result = object1 Is object2

The Is operator syntax has these parts:

Part | Description
result | Any numeric variable.
object1 | Any object name.
object2 | Any object name.

Remarks

If object1 and object2 both refer to the same object, result is True; if they do not, result is False. Two variables can be made to refer to the same object in several ways.

In the following example, A has been set to refer to the same object as B:

Set A = B

The following example makes A and B refer to the same object as C:

Set A = C
Set B = C

See Also

Comparison Operators, Operator Precedence, Set Statement.

Example

This example uses the Is operator to compare two object references. All the object variables used here are generic names and for illustration purposes only.

Set YourObject = MyObject    ' Assign object references.
Set ThisObject = MyObject
Set ThatObject = OtherObject
MyCheck = YourObject Is ThisObject    ' Returns True.
MyCheck = ThatObject Is ThisObject    ' Returns False.
' Assume MyObject <> OtherObject
MyCheck = MyObject Is ThatObject    ' Returns False.

This example selects the intersection of two named ranges, rg1 and rg2, on Sheet1. If the ranges do not intersect, the example displays a message.

Worksheets("Sheet1").Activate
Set isect = Application.Intersect(Range("rg1"), Range("rg2"))
If isect Is Nothing Then
    MsgBox "Ranges do not intersect"
Else
    isect.Select
End If

This example finds the first occurrence of the word "Phoenix" in column B on Sheet1 and then displays the address of the cell that contains this word. If the word is not found, the example diplays a message.

Set foundCell = Worksheets("Sheet1").Columns("B").Find("Phoenix")
If foundCell Is Nothing Then
    MsgBox "The word was not found"
Else
    MsgBox "The word was found in cell " & foundCell.Address
End If


IsArray Function

Description

Returns a value indicating whether a variable is an array.

Syntax

IsArray(varname)

The varname named argument can be any variable.

Remarks

IsArray returns True if the variable is an array; otherwise, it returns False.

See Also

Array Function, IsDate Function, IsEmpty Function, IsError Function, IsMissing Function, IsNull Function, IsNumeric Function, IsObject Function, TypeName Function, Variant Data Type, VarType Function.

Example

This example uses the IsArray function to check if a variable is an array.

Dim MyArray(1 To 5) As Integer    ' Declare array variable.
YourArray = Array(1, 2, 3)    ' Use Array function.
MyCheck = IsArray(MyArray)    ' Returns True.
MyCheck = IsArray(YourArray)    ' Returns True.


IsDate Function

Description

Returns a value indicating whether an expression can be converted to a date.

Syntax

IsDate(expression)

The expression named argument can be any date or string expression recognizable as a date or time.

Remarks

IsDate returns True if the expression is a date or can legally be converted to a date; otherwise, it returns False. The range of valid dates is January 1, 100 A.D. through December 31, 9999 A.D.

See Also

CDate Function, Date Data Type, IsArray Function, IsEmpty Function, IsError Function, IsMissing Function, IsNull Function, IsNumeric Function, IsObject Function, TypeName Function, Variant Data Type, VarType Function.

Example

This example uses the IsDate function to determine if an expression can be converted to a date.

MyDate = "February 12, 1969" : YourDate = #2/12/69# : NoDate = "Hello"
MyCheck = IsDate(MyDate)    ' Returns True.
MyCheck = IsDate(YourDate)    ' Returns True.
MyCheck = IsDate(NoDate)    ' Returns False.


IsEmpty Function

Description

Returns a value indicating whether a variable has been initialized.

Syntax

IsEmpty(expression)

The expression named argument can be any numeric or string expression. However, because IsEmpty is used to determine if individual variables are initialized, the expression argument is most often a single variable name.

Remarks

IsEmpty returns True if the variable is Empty; otherwise, it returns False. False is always returned if expression contains more than one variable.

See Also

IsArray Function, IsDate Function, IsError Function, IsMissing Function, IsNull Function, IsNumeric Function, IsObject Function, TypeName Function, Variant Data Type, VarType Function.

Example

This example uses the IsEmpty function to determine whether or not a variable has been initialized.

MyCheck = IsEmpty(MyVar)    ' Returns True.
MyVar = Null    ' Assign Null.
MyCheck = IsEmpty(MyVar)    ' Returns False.
MyVar = Empty    ' Assign Empty.
MyCheck = IsEmpty(MyVar)    ' Returns True.

This example sorts the data in the first column on Sheet1 and then deletes rows that contain duplicate data.

Worksheets("Sheet1").Range("A1").Sort _
    key1:=Worksheets("Sheet1").Range("A1")
Set currentCell = Worksheets("Sheet1").Range("A1")
Do While Not IsEmpty(currentCell)
    Set nextCell = currentCell.Offset(1, 0)
    If nextCell.Value = currentCell.Value Then
        currentCell.EntireRow.Delete
    End If
    Set currentCell = nextCell
Loop


IsError Function

Description

Returns a value indicating whether an expression is an error value.

Syntax

IsError(expression)

The expression named argument can be any numeric expression used to indicate an error value.

Remarks

Error values are created by converting real numbers to error values using the CVErr function. The IsError function is used to determine if a numeric expression represents an error. IsError returns True if the expression argument indicates an error; otherwise, it returns False.

See Also

CVErr Function, IsArray Function, IsDate Function, IsEmpty Function, IsMissing Function, IsNull Function, IsNumeric Function, IsObject Function, TypeName Function, Variant Data Type, VarType Function.

Example

This example uses the IsError function to check if a numeric expression is an error value. The CVErr function is used to return an Error Variant from a user-defined function.

' Assume UserFunction is a user-defined function procedure that returns
' an error value; e.g., return value assigned with the statement
' UserFunction = CVErr(32767) where 32767 is a user-defined number.
ReturnVal = UserFunction()
MyCheck = IsError(ReturnVal)    ' Returns True.


IsGap Property

Applies To

ToolbarButton Object.

Description

True if the button is really a gap (an extended space between buttons). Read-only.

Example

This example displays the number of separator gaps on the Standard toolbar.

gapCount = 0
For Each btn In Toolbars("Standard").ToolbarButtons
    If btn.IsGap Then
        gapCount = gapCount + 1
    End If
Next btn
MsgBox "There are " & gapCount & " gaps on the Standard toolbar"


IsMissing Function

Description

Returns a value indicating whether an optional argument has been passed to a procedure.

Syntax

IsMissing(argname)

The argname named argument is the name of an optional procedure argument.

Remarks

The IsMissing function is used in a procedure that has optional arguments, including ParamArray arguments, to determine whether an argument has been passed to the procedure. IsMissing returns True if no value has been passed for the specified argument; otherwise, it returns False.

See Also

Function Statement, IsArray Function, IsDate Function, IsEmpty Function, IsError Function, IsNull Function, IsNumeric Function, IsObject Function, Property Get Statement, Property Let Statement, Property Set Statement, Sub Statement, TypeName Function, Variant Data Type, VarType Function.

Example

This example uses the IsMissing function to check if an optional argument has been passed to a user-defined procedure.

' The following statements call the user-defined function procedure.
ReturnValue = ReturnTwice()    ' Returns Null.
ReturnValue = ReturnTwice(2)    ' Returns 4.

' Function procedure definition.
Function ReturnTwice(Optional A)
    If IsMissing(A) Then
        ' If argument is missing, return a Null.
        ReturnTwice = Null
    Else
        ' If argument is present, return twice the value.
        ReturnTwice = A * 2
    End If
End Function


IsNull Function

Description

Returns a value that indicates whether an expression contains no valid data (Null).

Syntax

IsNull(expression)

The expression named argument can be any numeric or string expression.

Remarks

IsNull returns True if expression is Null, that is, it contains no valid data; otherwise, IsNull returns False. If expression consists of more than one variable, Null in any variable causes True to be returned for the entire expression.

The Null value indicates that the Variant contains no valid data. Null is not the same as Empty, which indicates that a variable has not yet been initialized. It is also not the same as a zero-length string, which is sometimes referred to as a null string.

Important

Use the IsNull function to determine whether an expression contains a Null value. Expressions that you might expect to evaluate True under some circumstances, such as If Var = Null and If Var <> Null, are always False. This is because any expression containing a Null is itself Null and therefore False.

See Also

IsArray Function, IsDate Function, IsEmpty Function, IsError Function, IsMissing Function, IsNumeric Function, IsObject Function, TypeName Function, Variant Data Type, VarType Function.

Example

This example uses the IsNull function to determine if a variable contains a Null.

MyCheck = IsNull(MyVar)    ' Returns False.
MyVar = ""
MyCheck = IsNull(MyVar)    ' Returns False.
MyVar = Null
MyCheck = IsNull(MyVar)    ' Returns True.

This example creates a list of registered functions, placing each registered function in a separate row on Sheet1. Column A contains the full path and filename of the DLL or code resource, column B contains the function name, and column C contains the argument data type code.

theArray = Application.RegisteredFunctions
If IsNull(theArray) Then
    MsgBox "No registered functions"
Else
    For i = LBound(theArray) To UBound(theArray)
        For j = 1 To 3
            Worksheets("Sheet1").Cells(i, j).Formula = theArray(i, j)
        Next j
    Next i
End If


IsNumeric Function

Description

Returns a value indicating whether an expression can be evaluated as a number.

Syntax

IsNumeric(expression)

The expression named argument can be any numeric or string expression.

Remarks

IsNumeric returns True if the entire expression is recognized as a number; otherwise, it returns False.

IsNumeric returns False if expression is a date expression.

See Also

IsArray Function, IsDate Function, IsEmpty Function, IsError Function, IsMissing Function, IsNull Function, IsObject Function, TypeName Function, Variant Data Type, VarType Function.

Example

This example uses the IsNumeric function to determine if a variable can be evaluated as a number.

MyVar = "53"    ' Assign value.
MyCheck = IsNumeric(MyVar)    ' Returns True.
MyVar = "459.95"    ' Assign value.
MyCheck = IsNumeric(MyVar)    ' Returns True.
MyVar = "45 Help"    ' Assign value.
MyCheck = IsNumeric(MyVar)    ' Returns False.


IsObject Function

Description

Returns a value indicating whether an expression references a valid OLE Automation object.

Syntax

IsObject(expression)

The expression named argument can be any expression.

Remarks

IsObject returns True if expression is a valid reference to an actual object; otherwise, it returns False.

See Also

IsArray Function, IsDate Function, IsEmpty Function, IsError Function, IsMissing Function, IsNull Function, IsNumeric Function, Object Data Type, Set Statement, TypeName Function, Variant Data Type, VarType Function.

Example

This example uses the IsObject function to determine if a variable references a valid object. MyObject and YourObject are object variables of the same type. They are generic names used here for illustration purposes only.

Dim MyInt As Integer    ' Declare variable.
Set YourObject = MyObject    ' Assign an object reference.
MyCheck = IsObject(YourObject)    ' Returns True.
MyCheck = IsObject(MyInt)    ' Returns False.


Italic Property

Applies To

Font Object.

Description

True if the font is italic. Read-write.

Example

This example sets the font to italic for the range A1:A5 on Sheet1.

Worksheets("Sheet1").Range("A1:A5").Font.Italic = True


Item Method

Applies To

All collections.

Description

Accessor. Returns part of a collection. The Item method works like the accessor method for a collection. For example, the following two lines of code are equivalent.

ActiveWorkbook.Worksheets.Item(1)
ActiveWorkbook.Worksheets(1)

For more information about accessing an individual member of a collection, see the accessor method or property listed in the following table.

AddIns | EditBoxes | PivotItems
Arcs | Excel4IntlMacroSheets | PivotTables
AreaGroups | Excel4MacroSheets | Points
Axes | GroupBoxes | RadarGroups
BarGroups | GroupObjects | Range
Borders | HiddenFields | Rectangles
BuiltinDocumentProperties | HiddenItems | RowFields
Buttons | Labels | Rows
Cells | LegendEntries | Scenarios
Characters | LineGroups | ScrollBars
ChartGroups | Lines | SeriesCollection
ChartObjects | ListBoxes | Sheets
Charts | MenuBars | ShortcutMenus
CheckBoxes | MenuItems | Spinners
ChildItems | Menus | Styles
ColumnFields | Modules | TextBoxes
ColumnGroups | Names | ToolbarButtons
Columns | OLEObjects | Toolbars
CustomDocumentProperties | OptionButtons | Trendlines
DataFields | Ovals | VisibleFields
DialogSheets | PageFields | VisibleItems
Dialogs | Panes | Windows
DoughnutGroups | ParentItems | Workbooks
DrawingObjects | Pictures | Worksheets
Drawings | PieGroups | XYGroups
DropDowns | PivotFields |


Item Method (DocumentProperties Collection)

Applies To

DocumentProperties Collection.

Description

Accessor. Returns a single DocumentProperty object from the collection of document properties.

To use this method, you should establish a reference to the Microsoft Office 95 Object Library by using the References command (Tools menu).

Remarks

Because the Item method is the default method for the DocumentProperties collection object, the following statements are identical.

CustomDocumentProperties.Item(1)
CustomDocumentProperties(1)

You can refer to document properties either by index value or by name. The following list shows the available built-in document property names:

Title, Subject, Author, Keywords, Comments, Template, Last Author, Revision Number, Application Name, Last Print Date, Creation Date, Last Save Time, Total Editing Time, Number of Pages, Number of Words, Number of Characters, Security, Category, Format, Manager, Company, Number of Bytes, Number of Lines, Number of Paragraphs, Number of Slides, Number of Notes, Number of Hidden Slides, Number of Multimedia Clips

Container applications aren't required to define values for every built-in document property. If the application doesn't define a value for one of the built-in document properties, reading the Value property for that document property causes an error.

Example

This example displays the names of the document properties in a collection. You must pass a DocumentProperties collection to the procedure.

Sub DisplayPropertyNames(dp As DocumentProperties)
    Dim i As Integer
    For i = 1 To dp.Count
        MsgBox dp.Item(i).Name
    Next
End Sub

This example creates a list containing the names of the built-in document properties in the active workbook.

Set wk = Worksheets(1)
Set builtinProps = ActiveWorkbook.BuiltinDocumentProperties
For i = 1 To builtinProps.Count
    wk.Cells(i, 1).Value = builtinProps.Item(i).Name
Next


Iteration Property

Applies To

Application Object.

Description

True if Microsoft Excel will use iteration to resolve circular references. Read-write.

See Also

MaxChange Property, MaxIterations Property.

Example

This example sets the Iteration property to True, so that circular references are resolved by iteration.

Application.Iteration = True


Justify Method

Applies To

Range Object.

Description

Rearranges the text in a range so that it fills the range evenly.

Syntax

object.Justify

object

Required. The range to justify.

Remarks

If the range is not large enough, Microsoft Excel displays a message that text will extend below the range. If you choose the OK button, justified text will replace the contents in cells extending beyond the selected range. To prevent this message from appearing, set the DisplayAlerts property to False, in which case the text will always replace the contents in cells below the range.

Example

This example justifies text in cell A1 on Sheet1.

Worksheets("Sheet1").Range("A1").Justify


Keywords Property

Applies To

AddIn Object, Workbook Object.

Description

Returns or sets the keywords for the object, as a string. Read-only for AddIn, read-write for Workbook.

Remarks

In Microsoft Excel for Windows 95, this property has been replaced by a built-in OLE document property. For more information about OLE document properties, see BuiltinDocumentProperties.

You cannot use this property with an AddIn object that represents an XLL file or an add-in that was created with the Microsoft Excel 4.0 macro language.

See Also

Author Property, Comments Property, Subject Property, Title Property.

Example

This example sets the keywords for the active workbook.

ActiveWorkbook.Keywords = "Sales, West Region, 1995"


Kill Statement

Description

Deletes files from a disk.

Syntax

Kill pathname

The pathname named argument is a string expression that specifies one or more file names to be deleted — may include directory or folder, and drive.

Remarks

Kill supports the use of '*' (multiple character) and '?' (single character) wildcards to specify multiple files. However, on the Macintosh, these characters are treated as valid file name characters and can't be used as wildcards to specify multiple files.

Since the Macintosh does not support wildcards, use the file type to identify groups of files to delete. You can use the MacID function to specify file type instead of repeating the command with separate file names. For example, the following statement deletes all 'TEXT' files in the current folder.

Kill MacID("TEXT")

If you use the MacID function with Kill in Microsoft Windows, an error occurs.

An error occurs if you try to use Kill to delete an open file.

To delete directories, use the RmDir statement.

See Also

MacID Function, RmDir Statement.

Example

This example uses the Kill statement to delete a file from a disk. Since the Macintosh does not support wildcards, you can use the MacID function to specify the file type instead of the file name.

' Assume TESTFILE is a file containing some data.
Kill "TestFile"    ' Delete file.

' In Microsoft Windows.
' Delete all *.txt files in current directory.
Kill "*.txt"

' On the Macintosh.
' Use the MacID function to delete all PICT files in current folder
Kill MacID("PICT")


Label Object

Description

Represents a static text object on a chart sheet, dialog sheet, or worksheet. Labels have no font or background formatting, but labels on dialog sheets do have an accelerator key. Labels can be positioned and sized.

Accessors

The Label object is a member of the Labels collection. The Labels collection contains all the Label objects on a single sheet. Use the Add method to create a new label and add it to the collection.

To access a single member of the collection, use the Labels method with the index number or name of the label as an argument.

The following example sets the text in label one on the dialog sheet named "Dialog1."

DialogSheets("dialog1").Labels(1).Text = "Options"

The label name is shown in the Name Box when the label is selected. Use the Name property to set or return the label name. The following example hides the label named "Option Label" on the dialog sheet named "Dialog1."

DialogSheets("dialog1").Labels("option label").Visible = False

Properties

Accelerator Property, Application Property, BottomRightCell Property, Caption Property, Creator Property, Enabled Property, Height Property, Index Property, Left Property, Locked Property, LockedText Property, Name Property, OnAction Property, Parent Property, PhoneticAccelerator Property, Placement Property, PrintObject Property, Text Property, Top Property, TopLeftCell Property, Visible Property, Width Property, ZOrder Property.

Methods

BringToFront Method, Characters Method, CheckSpelling Method, Copy Method, CopyPicture Method, Cut Method, Delete Method, Duplicate Method, Select Method, SendToBack Method.


LabelRange Property

Applies To

PivotField Object, PivotItem Object.

Description

Accessor. PivotField: Returns a Range object that represents the cell (or cells) that contain the field label. PivotItem: Returns a Range object that represents all the PivotTable cells that contain the item. Read-only.

Example

This example selects the field button for the field named "ORDER_DATE."

Set pvtTable = Worksheets("Sheet1").Range("A3").PivotTable
Set pvtField = pvtTable.PivotFields("ORDER_DATE")
Worksheets("Sheet1").Activate
pvtField.LabelRange.Select


Labels Collection Object

Description

A collection of all the Label objects on the specified chart sheet, dialog sheet, or worksheet. Labels have no font or background formatting, but labels on dialog sheets do have an accelerator key. Labels can be positioned and sized.

Accessors

Use the Add method to create a new label and add it to the collection. The following example adds a new label to dialog sheet one. The upper-left corner of the new label is positioned 10 points from the left and 20 points from the bottom of the dialog frame.

Dim df As DialogFrame
Set df = DialogSheets(1).DialogFrame
DialogSheets(1).Labels.Add df.Left + 10, _
    df.Top + df.Height - 20, 100, 10

Use the Labels method with an argument to access a single member of the collection or without an argument to access the entire collection at once. The following example deletes all the labels on the dialog sheet named "Dialog1."

DialogSheets("dialog1").Labels.Delete

Properties

Accelerator Property, Application Property, Caption Property, Count Property, Creator Property, Enabled Property, Height Property, Left Property, Locked Property, LockedText Property, OnAction Property, Parent Property, PhoneticAccelerator Property, Placement Property, PrintObject Property, Text Property, Top Property, Visible Property, Width Property, ZOrder Property.

Methods

Add Method (Graphic Objects and Controls), BringToFront Method, Characters Method, CheckSpelling Method, Copy Method, CopyPicture Method, Cut Method, Delete Method, Duplicate Method, Group Method, Item Method, Select Method, SendToBack Method.


Labels Method

Applies To

Chart Object, DialogSheet Object, Worksheet Object.

Description

Accessor. Returns an object that represents a single label (a Label object, Syntax 1) or a collection of labels (a Labels object, Syntax 2) on the sheet.

Syntax 1

object.Labels(index)

Syntax 2

object.Labels

object

Required. The Chart, DialogSheet or Worksheet object.

index

Required for Syntax 1. Specifies the name or number of the label (can be an array to specify more than one).

Example

This example sets the text for label one on Dialog1.

DialogSheets("Sheet1").Labels(1).Text = "Search results"


LargeButtons Property

Applies To

Application Object.

Description

True if Microsoft Excel is using large toolbar buttons. False if Microsoft Excel is using standard toolbar buttons. Read-write.

See Also

ColorButtons Property.

Example

This example displays the large toolbar buttons.

Application.LargeButtons = True


LargeChange Property

Applies To

DrawingObjects Collection, ScrollBar Object, ScrollBars Collection.

Description

Returns or sets the amount that the scroll box increments or decrements for a page scroll (when the user clicks in the scroll bar body region). Read-write.

See Also

SmallChange Property.

Example

This example sets scroll bar one on Dialog1 to move two units for each line scroll and 20 units for each page scroll.

With DialogSheets("Dialog1").ScrollBars(1)
    .SmallChange = 2
    .LargeChange = 20
End With


LargeScroll Method

Applies To

Pane Object, Window Object.

Description

Scrolls the window by pages.

Syntax

object.LargeScroll(down, up, toRight, toLeft)

object

Required. The window to scroll.

down

Optional. The number of pages to scroll the window down.

up

Optional. The number of pages to scroll the window up.

toRight

Optional. The number of pages to scroll the window right.

toLeft

Optional. The number of pages to scroll the window left.

Remarks

If down and up are both specified, the window is scrolled by the difference of the arguments. For example, if down is three and up is six, the window is scrolled up three pages.

If toLeft and toRight are both specified, the window is scrolled by the difference of the arguments. For example, if toLeft is three and toRight is six, the window is scrolled right three pages.

Any of the arguments can be a negative number.

See Also

SmallScroll Method.

Example

This example scrolls the active window of Sheet1 down three pages.

Worksheets("Sheet1").Activate
ActiveWindow.LargeScroll down:=3


LBound Function

Description

Returns the smallest available subscript for the indicated dimension of an array.

Syntax

LBound(arrayname[,dimension])

The LBound statement syntax has these parts:

Part | Description
arrayname | Name of the array variable; follows standard variable naming conventions.
dimension | Whole number indicating which dimension's lower bound is returned. Use 1 for the first dimension, 2 for the second, and so on. If dimension is omitted, 1 is assumed.

Remarks

The LBound function is used with the UBound function to determine the size of an array. Use the UBound function to find the upper limit of an array dimension.

LBound returns the values listed in the table below for an array with the following dimensions:

Dim A(1 To 100, 0 To 3, -3 To 4)

Statement | Return Value
LBound(A, 1) | 1
LBound(A, 2) | 0
LBound(A, 3) | -3

The default lower bound for any dimension is either 0 or 1, depending on the setting of the Option Base statement.

Arrays for which dimensions are set using the To clause in a Dim, Private, Public, ReDim, or Static statement can have any integer value as a lower bound.

See Also

Dim Statement, Option Base Statement, Private Statement, Public Statement, ReDim Statement, Static Statement, UBound Function.

Example

This example uses the LBound function to determine the smallest available subscript for the indicated dimension of an array. Use the Option Base statement to override the default base array subscript value of 0.

Dim MyArray(1 To 10, 5 To 15, 10 To 20)     ' Declare array variables.
Dim AnyArray(10)
Lower = LBound(MyArray, 1)     ' Returns 1.
Lower = LBound(MyArray, 3)    ' Returns 10.
Lower = LBound(AnyArray)    ' Returns 0 or 1, depending on
    ' setting of Option Base.

This example writes the elements of the first custom list in column one on Sheet1.

Sub foo()
On Error GoTo err_handler
listArray = Application.GetCustomListContents(1)
For i = LBound(listArray, 1) To UBound(listArray, 1)
    Worksheets("sheet1").Cells(i, 1).Value = listArray(i)
Next i
Exit Sub

err_handler:
    MsgBox "Custom list does not exist"
End Sub

This example assumes that you used an external data source to create a PivotTable on Sheet1. The example inserts the SQL connection string and query string into a new worksheet.

Set newSheet = ActiveWorkbook.Worksheets.Add
sdArray = Worksheets("Sheet1").UsedRange.PivotTable.SourceData
For i = LBound(sdArray) To UBound(sdArray)
    newSheet.Cells(i, 1) = sdArray(i)
Next i


LCase Function

Description

Returns a string that has been converted to lowercase.

Syntax

LCase(string)

The string named argument is any valid string expression. If string contains no valid data, Null is returned.

Remarks

Only uppercase letters are converted to lowercase; all lowercase letters and nonletter characters remain unchanged.

See Also

UCase Function.

Example

This example uses the LCase function to return a lowercase version of a string.

Uppercase = "Hello World 1234"    ' String to convert.
Lowercase = LCase(UpperCase)    ' Returns "hello world 1234".


Left Function

Description

Returns a specified number of characters from the left side of a string.

Syntax

Left(string,length)

The Left function syntax has these named-argument parts:

Part | Description
string | String expression from which the leftmost characters are returned. If string contains no valid data, Null is returned.
length | Numeric expression indicating how many characters to return. If 0, a zero-length string is returned. If greater than or equal to the number of characters in string, the entire string is returned.

Remarks

To determine the number of characters in string, use the Len function.

Note

Another function (LeftB) is provided for use with the double-byte character sets (DBCS) used in some Asian locales. Instead of specifying the number of characters to return, length specifies the number of bytes. In areas where DBCS is not used, LeftB behaves the same as Left.

See Also

Len Function, Mid Function, Right Function.

Example

This example uses the Left function to return a specified number of characters from the left side of a string.

AnyString = "Hello World"    ' Define string.
MyStr = Left(AnyString, 1)    ' Returns "H".
MyStr = Left(AnyString, 7)    ' Returns "Hello W".
MyStr = Left(AnyString, 20)    ' Returns "Hello World".


Left Property

Applies To

Application Object, Arc Object, Arcs Collection, AxisTitle Object, Button Object, Buttons Collection, ChartArea Object, ChartObject Object, ChartObjects Collection, ChartTitle Object, CheckBox Object, DataLabel Object, DialogFrame Object, Drawing Object, DrawingObjects Collection, Drawings Collection, DropDown Object, DropDowns Collection, EditBox Object, EditBoxes Collection, GroupBox Object, GroupBoxes Collection, GroupObject Object, GroupObjects Collection, Label Object, Labels Collection, Legend Object, Line Object, Lines Collection, ListBox Object, ListBoxes Collection, OLEObject Object, OLEObjects Collection, OptionButton Object, OptionButtons Collection, Oval Object, Ovals Collection, Picture Object, Pictures Collection, PlotArea Object, Range Object, Rectangle Object, Rectangles Collection, ScrollBar Object, ScrollBars Collection, Spinner Object, Spinners Collection, TextBox Object, TextBoxes Collection, Toolbar Object, Window Object.

Description

Returns or sets the position of the specified object, in points (1/72 inch). Read-write, except for the Range object.

Remarks

The Left property has several different meanings, depending on the object it is applied to.

Object | Meaning
Application | The distance from the left edge of the physical screen to the left edge of the main Microsoft Excel window, in points.
ClipboardWindow | Macintosh only. The left position of the window, in points, measured from the left edge of the usable area (below the menus, left-docked toolbars, and/or the formula bar).
Range | The distance from the left edge of column A to the left edge of the range, in points. If the range is discontinuous, the first area is used. If the range is more than one column wide, the leftmost column in the range is used. Read-only.
Toolbar | If the toolbar is docked (its Position property is not xlFloating), the number of points from the left edge of the toolbar to the left edge of the toolbar's docking area. If the toolbar is floating, the number of points from the left edge of the toolbar to the left edge of the Microsoft Excel workspace.
Window | The left position of the window, in points, measured from the left edge of the usable area.
Arc, AxisTitle, Button, ChartArea, ChartTitle, CheckBox, DataLabel, DialogFrame, Drawing, DrawingObjects, DropDown, EditBox, GroupObject, GroupBox, Label, Legend, Line, ListBox, OLEObject, OptionButton, Oval, Picture, PlotArea, Rectangle, ScrollBar, Spinner, TextBox | The left position of the object, in points, measured from the left edge of column A (on a worksheet) or the upper left of the chart area (on a chart).

If the window is maximized, the Application.Left property returns a negative number that varies based on the width of the window border. Setting Application.Left to zero will make the window a tiny bit smaller than it would if the application window were maximized. In other words, if Application.Left is zero, the left border of the main Microsoft Excel window will just be visible on screen.

On the Apple Macintosh, Application.Left is always zero. Setting this value to something else on the Macintosh will have no effect.

With Microsoft Windows, if the Microsoft Excel window is minimized, Application.Left controls the position of the icon.

See Also

Height Property, Top Property, Width Property.

Example

This example moves oval one on Sheet1 so that it is aligned with the left edge of column B.

Worksheets("Sheet1").Ovals(1).Left = _
    Worksheets("Sheet1").Columns("B").Left

This example aligns the left edge of every button on Sheet1 to the left edge of column B.

leftEdge = Worksheets("Sheet1").Columns("B").Left
For Each b In Worksheets("Sheet1").Buttons
    b.Left = leftEdge
Next b


LeftFooter Property

Applies To

PageSetup Object.

Description

Returns or sets the left part of the footer. Read-write.

Remarks

Special format codes can be used in the footer text.

See Also

CenterFooter Property, CenterHeader Property, LeftHeader Property, RightFooter Property, RightHeader Property.

Example

This example prints the page number in the lower-left corner of every page.

Worksheets("Sheet1").PageSetup.LeftFooter = "&P"


LeftHeader Property

Applies To

PageSetup Object.

Description

Returns or sets the left part of the header. Read-write.

Remarks

Special format codes can be used in the header text.

See Also

CenterFooter Property, CenterHeader Property, LeftFooter Property, RightFooter Property, RightHeader Property.

Example

This example prints the date in the upper-left corner of every page.

Worksheets("Sheet1").PageSetup.LeftHeader = "&D"


LeftMargin Property

Applies To

PageSetup Object.

Description

Returns or sets the size of the left margin, in points (1/72 inch). Read-write.

Remarks

Margins are set or returned in points. Use the InchesToPoints or CentimetersToPoints function to convert.

See Also

BottomMargin Property, RightMargin Property, TopMargin Property.

Example

This example sets the left margin of Sheet1 to 1.5 inches.

Worksheets("Sheet1").PageSetup.LeftMargin = _
        Application.InchesToPoints(1.5)

This example sets the left margin of Sheet1 to 2 centimeters.

Worksheets("Sheet1").PageSetup.LeftMargin = _
        Application.CentimetersToPoints(2)

This example displays the current left margin setting for Sheet1.

marginInches = Worksheets("Sheet1").PageSetup.LeftMargin / _
    Application.InchesToPoints(1)
MsgBox "The current left margin is " & marginInches & " inches"


Legend Object

Description

Represents the legend in a chart. The Legend object contains one or more LegendEntry objects; each LegendEntry object contains a LegendKey object. There is no Legends collection because each chart can have only one legend.

Accessors

The Legend property returns the chart legend. The following example sets the font for the legend in embedded chart one on worksheet one.

Worksheets(1).ChartObjects(1).Chart.Legend.Font.Bold = True

Remarks

The chart legend is not visible unless the HasLegend property is True. If this property is False, properties and methods of the Legend object will fail.

Properties

Application Property, Border Property, Creator Property, Font Property, Height Property, Interior Property, Left Property, Name Property, Parent Property, Position Property, Shadow Property, Top Property, Width Property.

Methods

Delete Method, LegendEntries Method, Select Method.


Legend Property

Applies To

Chart Object.

Description

Accessor. Returns a Legend object that represents the legend for the chart. Read-only.

See Also

HasLegend Property.

Example

This example turns on the legend for Chart1 and then sets the legend font color to blue.

Charts("Chart1").HasLegend = True
Charts("Chart1").Legend.Font.ColorIndex = 5


LegendEntries Collection Object

Description

A collection of all the LegendEntry objects in the specified chart legend. Each legend entry has two parts: the text of the entry, which is the name of the series or trendline associated with the legend entry; and an entry marker, which visually links the legend entry with its associated series or trendline in the chart. Formatting properties for the entry marker and its associated series or trendline are contained in the LegendKey object.

Accessors

Use the LegendEntries method with an argument to access a single member of the collection or without an argument to access the entire collection at once. The following example loops through the collection of legend entries and changes the color of their fonts.

With Worksheets("sheet1").ChartObjects(1).Chart.Legend
    For i = 1 To .LegendEntries.Count
        .LegendEntries(i).Font.ColorIndex = 5
    Next
End With

Properties

Application Property, Count Property, Creator Property, Parent Property.

Methods

Item Method.


LegendEntries Method

Applies To

Legend Object.

Description

Accessor. Returns an object that represents a single legend entry (a LegendEntry object, Syntax 1) or a collection of legend entries (a LegendEntries object, Syntax 2) for the legend.

Syntax 1

object.LegendEntries(index)

Syntax 2

object.LegendEntries

object

Required. The Legend object.

index

Required for Syntax 1. Specifies the number of the legend entry.

Example

This example sets the font for legend entry one on Chart1.

Charts("Chart1").Legend.LegendEntries(1).Font.Name = "Arial"


LegendEntry Object

Description

Represents a legend entry in a chart legend.

Each legend entry has two parts: the text of the entry, which is the name of the series associated with the legend entry; and an entry marker, which visually links the legend entry with its associated series or trendline in the chart. Formatting properties for the entry marker and its associated series or trendline are contained in the LegendKey object.

The text of a legend entry cannot be changed. LegendEntry objects support font formatting, and they can be deleted. No pattern formatting is supported for legend entries. The position and size of entries is fixed.

Accessors

The LegendEntry object is a member of the LegendEntries collection. The LegendEntries collection contains all the LegendEntry objects in the legend.

To access a single member of the collection, use the LegendEntries method with the index number of the legend entry as an argument. You cannot access legend entries by name.

The index number represents the position of the legend entry in the legend. LegendEntries(1) is at the top of the legend; LegendEntries(LegendEntries.Count) is at the bottom. The following example changes the font for the text of the legend entry at the top of the legend (this is usually the legend for series one).

Worksheets("sheet1").ChartObjects(1).Chart _
    .Legend.LegendEntries(1).Font.Italic = True

Remarks

There is no direct way to access the series or trendline corresponding to the legend entry.

Once legend entries have been deleted, the only way to restore them is to remove and recreate the legend that contained them by setting the HasLegend property for the chart to False and then back to True.

Properties

Application Property, Creator Property, Font Property, Index Property, LegendKey Property, Parent Property.

Methods

Delete Method, Select Method.


LegendKey Object

Description

Represents a legend key in a chart legend. Each legend key is a graphic that visually links a legend entry with its associated series or trendline in the chart. The legend key is linked to its associated series or trendline is such a way that changing the formatting of one simultaneously changes the formatting of the other.

Accessors

The LegendKey property returns the legend key for a LegendEntry object. The following example changes the marker background color for the legend entry at the top of the legend for the embedded chart. This simultaneously changes the format of every point in the series associated with this legend entry. The associated series must support data markers.

Worksheets("sheet1").ChartObjects(1).chart _
    .Legend.LegendEntries(1).LegendKey.MarkerBackgroundColorIndex = 5

Properties

Application Property, Border Property, Creator Property, Interior Property, InvertIfNegative Property, MarkerBackgroundColor Property, MarkerBackgroundColorIndex Property, MarkerForegroundColor Property, MarkerForegroundColorIndex Property, MarkerStyle Property, Parent Property, Smooth Property.

Methods

ClearFormats Method, Delete Method, Select Method.


LegendKey Property

Applies To

LegendEntry Object.

Description

Accessor. Returns a LegendKey object that represents the legend key associated with the entry.

Example

This example sets the legend key for legend entry one on Chart1 to be a triangle. The example should be run on a 2-D line chart.

Charts("Chart1").Legend.LegendEntries(1).LegendKey.MarkerStyle = _
        xlTriangle


Len Function

Description

Returns the number of characters in a string or the number of bytes required to store a variable.

Syntax

Len(string | varname)

The Len function syntax has these parts:

Part | Description
string | Any valid string expression. If string contains no valid data, Null is returned.
varname | Any valid variable name. If varname contains no valid data, Null is returned.

Remarks

Caution

Len may not be able to determine the actual number of storage bytes required when used with user-defined data types.

Note

Another function (LenB) is provided for use with the double-byte character sets (DBCS) used in some Asian locales. Instead of returning the number of characters in a string, LenB returns the number of bytes used to represent that string. In areas where DBCS is not used, LenB behaves the same as Len.

See Also

InStr Function.

Example

This example uses the Len function to return the number of characters in a string or the number of bytes required to store a variable.

Type CustomerRecord    ' Define user-defined type.
    ID As Integer
    Name As String * 10
    Address As String * 30
End Type
Dim Customer As CustomerRecord    ' Declare variables.
Dim MyInt As Integer, MyCur As Currency
MyString = "Hello World"    ' Initialize.
MyLen = Len(MyInt)    ' Returns 2.
MyLen = Len(Customer)    ' Returns 42.
MyLen = Len(MyString)    ' Returns 11.
MyLen = Len(MyCur)    ' Returns 8.


Let Statement

Description

Assigns the value of an expression to a variable or property.

Syntax

[Let] varname = expression

The Let statement syntax has these parts:

Part | Description
varname | Name of the variable or property; follows standard variable naming conventions.
expression | Value assigned to the variable.

Remarks

In order to simplify Basic code, the optional Let keyword is most often omitted.

A value expression can be assigned to a variable only if it is of a data type that is compatible with the variable. You can't assign string expressions to numeric variables, and you can't assign numeric expressions to string variables. If you do, an error occurs at compile time.

Variant variables can be assigned either string or numeric expressions. However, the reverse is not always true. Any Variant except a Null can be assigned to a string variable, but only a Variant whose value can be interpreted as a number can be assigned to a numeric variable. Use the IsNumeric function to determine if the Variant can be converted to a number.

Caution

Assigning an expression of one numeric data type to a variable of a different numeric data type coerces the value of the expression into the data type of the resulting variable.

Let statements can be used to assign one record variable to another only when both variables are of the same user-defined type. Use the LSet statement to assign record variables of different user-defined types. Use the Set statement to assign object references to variables.

See Also

Const Statement, Data Type Summary, IsNumeric Function, LSet Statement, Set Statement, Variant Data Type.

Example

This example uses statements with and without the Let statement to assign the value of an expression to a variable.

' The following variable assignments use the Let statement.
Let MyStr = "Hello World"
Let MyInt = 5
' The following are the same assignments without the Let statement.
MyStr = "Hello World"
MyInt = 5


LibraryPath Property

Applies To

Application Object.

Description

Returns the path to the LIBRARY directory, not including the final separator. Read-only.

Example

This example opens the file OSCAR.XLA in the LIBRARY folder (the Macro Library folder on the Macintosh).

pathSep = Application.PathSeparator
f = Application.LibraryPath & pathSep & "OSCAR.XLA"
Workbooks.Open filename:=f


Like Operator

Description

Used to compare two strings.

Syntax

result = string Like pattern

The Like operator syntax has these parts:

Part | Description
result | Any numeric variable.
string | Any string expression.
pattern | Any string expression conforming to the pattern-matching conventions described in the following section.

Remarks

If string matches pattern, result is True; if there is no match, result is False; and if either string or pattern is a Null, result is also a Null.

The behavior of the Like operator depends on the Option Compare statement. Unless otherwise specified, the default string-comparison method for each module is Option Compare Binary.

Option Compare Binary results in string comparisons based on a sort order derived from the internal binary representations of the characters. In Microsoft Windows, sort order is determined by the code page. On the Macintosh, sort order is determined by the character set. In the following example, a typical binary sort order is shown:

A < B < E < Z < a < b < e < z < À < Ê < Ø < à < ê < ø

Option Compare Text results in string comparisons based on a case-insensitive textual sort order determined by your system's locale. The same characters shown above, when sorted using Option Compare Text, produce the following text sort order:

(A=a) < ( À=à) < (B=b) < (E=e) < (Ê=ê) < (Z=z) < (Ø=ø)

Built-in pattern matching provides a versatile tool for string comparisons. The pattern-matching features allow you to use wildcard characters, character lists, or character ranges, in any combination, to match strings. The following table shows the characters allowed in pattern and what they match:

Character(s) in pattern | Matches in string
? | Any single character.
* | Zero or more characters.
# | Any single digit (0-9).
[charlist] | Any single character in charlist.
[!charlist] | Any single character not in charlist.

A group of one or more characters (charlist) enclosed in brackets ([ ]) can be used to match any single character in string and can include almost any character code, including digits.

Note

The special characters left bracket ([), question mark (?), number sign (#), and asterisk (*) can be used to match themselves directly only by enclosing them in brackets. The right bracket (]) can't be used within a group to match itself, but it can be used outside a group as an individual character.

In addition to a simple list of characters enclosed in brackets, charlist can specify a range of characters by using a hyphen (-) to separate the upper and lower bounds of the range. For example, [A-Z] in pattern results in a match if the corresponding character position in string contains any of the uppercase letters in the range A through Z. Multiple ranges are included within the brackets without any delimiters.

The meaning of a specified range depends on the character ordering valid at run time (as determined by Option Compare and the locale setting of the system the code is running on). Using the same example shown above with Option Compare Binary, the range [A-E] matches A, B and E. With Option Compare Text, [A-E] matches A, a, À, à, B, b, E, e. Note that it does not match Ê or ê because accented characters fall after unaccented characters in the sort order.

Other important rules for pattern matching include the following:

  • An exclamation point (!) at the beginning of charlist means that a match is made if any character except the ones in charlist are found in string. When used outside brackets, the exclamation point matches itself.
  • The hyphen (-) can appear either at the beginning (after an exclamation mark if one is used) or at the end of charlist to match itself. In any other location, the hyphen is used to identify a range of characters.
  • When a range of characters is specified, they must appear in ascending sort order (from lowest to highest). [A-Z] is a valid pattern, but [Z-A] is not.
  • The character sequence [] is ignored; it is considered a zero-length string.

See Also

Comparison Operators, InStr Function, Operator Precedence, Option Compare Statement, StrComp Function.

Example

This example uses the Like operator to compare a string to a pattern.

MyCheck = "aBBBa" Like "a*a"    ' Returns True.
MyCheck = "F" Like "[A-Z]"    ' Returns True.
MyCheck = "F" Like "[!A-Z]"    ' Returns False.
MyCheck = "a2a" Like "a#a"    ' Returns True.
MyCheck = "aM5b" Like "a[L-P]#[!c-e]"    ' Returns True.
MyCheck = "BAT123khg" Like "B?T*"    ' Returns True.
MyCheck = "CAT123khg" Like "B?T*"    ' Returns False.

This example deletes every defined name that contains "temp" in the name. The Option Compare Text statement must be included at the top of any module that contains this example.

For Each nm In ActiveWorkbook.Names
    If nm.Name Like "*temp*" Then
        nm.Delete
    End If
Next nm

This example adds an arrowhead to every graphic object on Sheet1 that has the word "Line" in its name.

For Each d In Worksheets("Sheet1").DrawingObjects
    If d.Name Like "*Line*" Then
        d.ArrowHeadLength = xlLong
        d.ArrowHeadStyle = xlOpen
        d.ArrowHeadWidth = xlNarrow
    End If
Next


Line Input # Statement

Description

Reads a line from an open sequential file and assigns it to a string variable.

Syntax

Line Input #filenumber,varname

The Line Input # statement syntax has these parts:

Part | Description
filenumber | Any valid file number.
varname | Valid string variable name.

Remarks

The Line Input # statement reads from a file one character at a time until it encounters a carriage return (Chr(13)) or carriage return-linefeed sequence. Carriage return-linefeed sequences are skipped rather than appended to the character string.

See Also

Input # Statement.

Example

This example uses the Line Input # statement to read a line from a sequential file and assign it to a variable. For purposes of this example, assume that TESTFILE is a text file with a few lines of sample data.

Open "TESTFILE" For Input As #1    ' Open file.
Do While Not EOF(1)    ' Loop until end of file.
    Line Input #1, TextLine    ' Read line into variable.
    Debug.Print TextLine    ' Print to Debug window.
Loop
Close #1    ' Close file.


Line Object

Description

Represents a line graphic object on a chart sheet, dialog sheet, or worksheet. An arrow is a line with its ArrowHeadStyle property set to something other than xlNone.

Accessors

The Line object is a member of the Lines collection. The Lines collection contains all the Line objects on a single sheet. Use the Add method to create a new line and add it to the collection. To access a single member of the collection, use the Lines method with the index number or name of the line as an argument.

The following example sets the line color for line one on the worksheet named "Sheet1."

Worksheets("sheet1").Lines(1).Border.Color = RGB(0, 255, 0)

The line name is shown in the Name Box when the line is selected. Use the Name property to set or return the name of the line. The following example adds an open arrowhead to the end of the line named "Line 1."

Worksheets("sheet1").Lines("line 1").ArrowHeadStyle = xlOpen

Properties

Application Property, ArrowHeadLength Property, ArrowHeadStyle Property, ArrowHeadWidth Property, Border Property, BottomRightCell Property, Creator Property, Enabled Property, Height Property, Index Property, Left Property, Locked Property, Name Property, OnAction Property, Parent Property, Placement Property, PrintObject Property, Top Property, TopLeftCell Property, Visible Property, Width Property, ZOrder Property.

Methods

BringToFront Method, Copy Method, CopyPicture Method, Cut Method, Delete Method, Duplicate Method, Select Method, SendToBack Method.


Line3DGroup Property

Applies To

Chart Object.

Description

Accessor. Returns a ChartGroup object that represents the line chart group on a 3-D chart. Read-only.

See Also

LineGroups Method.

Example

This example changes the 3-D line group in Chart1 to an area group. The example should be run on a 3-D chart.

Charts("Chart1").Line3DGroup.Type = xl3DArea


LineGroups Method

Applies To

Chart Object.

Description

Accessor. On a 2-D chart, returns an object that represents a single line chart group (a ChartGroup object, Syntax 1), or a collection of the line chart groups (a ChartGroups collection, Syntax 2).

Syntax 1

object.LineGroups(index)

Syntax 2

object.LineGroups

object

Required. The Chart object.

index

Required for Syntax 1. Specifies the chart group.

See Also

Line3DGroup Property.

Example

This example sets the subtype for line group one in Chart1. The example should be run on a 2-D chart.

Charts("Chart1").LineGroups(1).SubType = 2


Lines Collection Object

Description

A collection of all the Line objects on the specified chart sheet, dialog sheet, or worksheet.

Accessors

Use the Add method to create a new line and add it to the collection. The following example creates a new line on worksheet one. The new line starts at the upper-left corner of cell B10 and ends at the upper-left corner of cell C20.

Dim rStart As Range, rEnd As Range
Set rStart = Worksheets(1).Range("b10")
Set rEnd = Worksheets(1).Range("c20")
Worksheets(1).Lines.Add rStart.Left, rStart.Top, _
    rEnd.Left, rEnd.Top

Use the Lines method with an argument to access a single member of the collection or without an argument to access the entire collection at once. The following example sets the arrowhead style for all of the lines on worksheet one in the active workbook.

Worksheets(1).Lines.ArrowHeadStyle = xlClosed

Properties

Application Property, ArrowHeadLength Property, ArrowHeadStyle Property, ArrowHeadWidth Property, Border Property, Count Property, Creator Property, Enabled Property, Height Property, Left Property, Locked Property, OnAction Property, Parent Property, Placement Property, PrintObject Property, Top Property, Visible Property, Width Property, ZOrder Property.

Methods

Add Method (Arcs and Lines), BringToFront Method, Copy Method, CopyPicture Method, Cut Method, Delete Method, Duplicate Method, Group Method, Item Method, Select Method, SendToBack Method.


Lines Method

Applies To

Chart Object, DialogSheet Object, Worksheet Object.

Description

Accessor. Returns an object that represents a single line (a Line object, Syntax 1) or a collection of lines (a Lines object, Syntax 2) on the sheet. Read-only.

Syntax 1

object.Lines(index)

Syntax 2

object.Lines

object

Required. The object to which this method applies.

index

Required for Syntax 1. The name or number of the line.

Remarks

This property returns both lines and arrows. The only difference between a line and an arrow is the ArrowHeadStyle property.

Example

This example deletes line three on Sheet1.

Worksheets("Sheet1").Lines(3).Delete

This example formats every line on Sheet1 as red.

For Each l In Worksheets("Sheet1").Lines
    l.Border.ColorIndex = 3
Next l


LineStyle Property

Applies To

Border Object, Borders Collection.

Description

Returns or sets the line style of the border. Read-write.

For Range object borders, this property can have one of the following values: xlContinuous, xlDash, xlDot, xlDouble, xlNone.

For drawing object borders, this property can have one of the following values: xlAutomatic, xlContinuous, xlDash, xlDashDot, xlDashDotDot, xlDot, xlGray25, xlGray50, xlGray75, xlNone.

Example

This example sets the line style of oval one on Sheet1 to 50 percent gray.

Worksheets("Sheet1").Ovals(1).Border.LineStyle = xlGray50

This example creates a rectangle on Sheet1 and then gives the rectangle a dashed border.

Set myRect = Worksheets("Sheet1").Rectangles.Add(Left:=72, _
            Top:=72, Width:=144, Height:=36)
myRect.Border.LineStyle = xlDash


LinkCombo Method

Applies To

DrawingObjects Collection.

Description

Creates a combination list-edit box from a list box and an edit box. The edit box and list box to be linked must be the only two objects in the DrawingObjects collection.

Syntax

object.LinkCombo(link)

object

Required. The DrawingObjects collection.

link

Optional. If omitted or True, the objects are linked so that the edit box text is always updated to the current selection in the list box whenever the user selects a new list box item. If False, the link between the objects is broken.

Remarks

This function is only useful on a dialog sheet, because edit boxes are not allowed on a worksheet or chart. To see how to use the LinkCombo method, use the macro recorder to record creating a Combination List-Edit control on a dialog sheet.

See Also

DrawingObjects Method, EditBox Object, LinkedObject Property, ListBox Object.

Example

This example links list box one and edit box two on Dialog1.

DialogSheets("Dialog1").DrawingObjects( _
    Array("List Box 1", "Edit Box 2")).LinkCombo


LinkedCell Property

Applies To

CheckBox Object, DrawingObjects Collection, DropDown Object, DropDowns Collection, ListBox Object, ListBoxes Collection, OptionButton Object, OptionButtons Collection, ScrollBar Object, ScrollBars Collection, Spinner Object, Spinners Collection.

Description

Returns or sets the cell or cells (as a string reference) linked to the control's value. When a value is placed in the cell, the control takes this value. Likewise, if the value of the control changes, that value is also placed in the cell.

Remarks

This property cannot be used with multi-select list boxes.

Example

This example sets the fill range and the cell link for list box one on Sheet1.

Worksheets("Sheet1").ListBoxes(1).ListFillRange = "Sheet1!A1:A8"
Worksheets("Sheet1").ListBoxes(1).LinkedCell = "Sheet1!B1"


LinkedObject Property

Applies To

DropDown Object, EditBox Object, ListBox Object.

Description

Returns the name of the object linked to an edit box, list box, or drop-down control. For a DropDown object, returns the name of the drop-down control if it can be edited, or False if it is not editable. Read-only.

See Also

LinkCombo Method.

Example

This example displays the name of the list box that is linked to edit box one on dialog sheet one. The example should be run on a dialog sheet that contains a combination list-edit control.

MsgBox DialogSheets(1).EditBoxes(1).LinkedObject


LinkInfo Method

Applies To

Workbook Object.

Description

Returns information on link date and update state.

Syntax

object.LinkInfo(name, linkInfo, type, editionRef)

object

Required. The Workbook object.

name

Required. Specifies the name of the link, as returned from the LinkSources method.

linkInfo

Required. Specifies the type of information to be returned about the link (either xlUpdateState or xlEditionDate). xlEditionDate applies only to editions. For xlUpdateState, this method returns 1 if the link updates automatically, or 2 if the link must be updated manually.

type

Optional. Specifies the type of link to return. Can be one of xlOLELinks (also handles DDE links), xlPublishers, or xlSubscribers.

editionRef

Optional. If the link is an edition, this argument specifies the edition reference as a string in R1C1-style form. This argument is required if there are more than one publisher or subscriber with the same name in the workbook.

Example

This example displays a message box if the link updates automatically.

If ActiveWorkbook.LinkInfo( _
        "Word.Document.6|Document1!'!DDE_LINK1", xlUpdateState, _
        xlOLELinks) = 1 Then
    MsgBox "Link updates automatically"
End If


LinkSource Property (DocumentProperty Object)

Applies To

DocumentProperty Object.

Description

Returns or sets the source of a linked custom document property. Read-write.

To use this property, you should establish a reference to the Microsoft Office 95 Object Library by using the References command (Tools menu).

Remarks

The source of a link is defined by the container application. For Microsoft Excel, the source is the name in the workbook.

This property cannot be used with built-in document properties.

Setting the LinkSource property sets the LinkToContent property to True.

Example

This example displays the linked status of a custom document property. You must pass a DocumentProperty object to the procedure.

Sub DisplayLinkStatus(dp As DocumentProperty)
    Dim stat As String, tf As String
    If dp.LinkToContent Then
        tf = ""
    Else
        tf = "not "
    End If
    stat = "This property is " & tf & "linked"
    If dp.LinkToContent Then
        stat = stat + Chr(13) & "The link source is " & dp.LinkSource
    End If
    MsgBox stat
End Sub

This example links the custom document property named "TotalSales" to the named range "SalesNumbers" in the active workbook.

ActiveWorkbook.CustomDocumentProperties _
    .Item("TotalSales").LinkSource = "SalesNumbers"


LinkSources Method

Applies To

Workbook Object.

Description

Returns an array of links in the workbook. The names in the array are the names of the linked documents, editions, or DDE or OLE servers. Returns Empty if there are no links.

Syntax

object.LinkSources(type)

object

Required. The Workbook object.

type

Optional. Specifies the type of link to return. Can be one of xlExcelLinks, xlOLELinks (also handles DDE links), xlPublishers, or xlSubscribers.

Remarks

The format of the array is a single-dimensional array for all types but publisher and subscriber. The returned strings contain the name of the link source in the notation appropriate for the link type. For example, DDE links use the "Server|Document!Item" syntax.

For publisher and subscriber links, the returned array is two-dimensional. The first column of the array contains the names of the edition, and the second column contains the references of the editions as text.

Example

This example displays a list of OLE and DDE links in the active workbook. The example should be run on a workbook that contains one or more linked Microsoft Word objects.

aLinks = ActiveWorkbook.LinkSources(xlOLELinks)
If Not IsEmpty(aLinks) Then
    For i = 1 To UBound(aLinks)
        MsgBox "Link " & i & ":" & Chr(13) & aLinks(i)
    Next i
End If


LinkToContent Property (DocumentProperty Object)

Applies To

DocumentProperty Object.

Description

True if the value of a custom document property is linked to the content of the container document; False if the value is static. Read-write.

To use this property, you should establish a reference to the Microsoft Office 95 Object Library by using the References command (Tools menu).

Remarks

This property applies only to custom document properties. For built-in document properties, this property is always False.

Use the LinkSource property to set the source for the linked property. Setting the LinkSource property sets the LinkToContent property to True.

Example

This example displays the linked status of a custom document property. You must pass a DocumentProperty object to the procedure.

Sub DisplayLinkStatus(dp As DocumentProperty)
    Dim stat As String, tf As String
    If dp.LinkToContent Then
        tf = ""
    Else
        tf = "not "
    End If
    stat = "This property is " & tf & "linked"
    If dp.LinkToContent Then
        stat = stat + Chr(13) & "The link source is " & dp.LinkSource
    End If
    MsgBox stat
End Sub

This example displays the linked status for each custom document property as a list on worksheet one.

rw = 1
With Worksheets(1)
    For Each pro In ActiveWorkbook.CustomDocumentProperties
        .Cells(rw, 1) = pro.Name
        .Cells(rw, 2) = pro.LinkToContent
        If pro.LinkToContent Then
            .Cells(rw, 3) = pro.LinkSource
        End If
        rw = rw + 1
    Next
End With


List Property

Applies To

DrawingObjects Collection, DropDown Object, DropDowns Collection, ListBox Object, ListBoxes Collection.

Description

Returns or sets the text entries in a list box or drop-down list box, as an array of strings (Syntax 1), or returns or sets a single text entry (Syntax 2). Returns an error if there are no entries in the list. Read-write.

Syntax 1

object.List

Syntax 2

object.List(index)

Remarks

Setting this property clears any range specified by the ListFillRange property.

See Also

AddItem Method, ListCount Property, RemoveItem Method.

Example

This example sets the entries in list box one on Dialog1.

DialogSheets("Dialog1").ListBoxes(1).List = _
    Array("cogs", "widgets", "sprockets", "gizmos")

This example sets entry four in list box one on Dialog1.

DialogSheets("Dialog1").ListBoxes(1).List(4) = "gadgets"


ListBox Object

Description

Represents a scrollable list box on the specified chart sheet, dialog sheet, or worksheet. There are three list-box types: single select, simple multi-select, and extended multi-select. The list-box type specifies whether more than one item can be selected from the list, and how multiple items can be selected. For more information, see the MultiSelect property.

You can fill the list either by specifying a range of cells that contains list items (using the ListFillRange property) or by specifying each item (using the AddItem and RemoveItem methods or the List property).

Accessors

The ListBox object is a member of the ListBoxes collection. The ListBoxes collection contains all the ListBox objects on a single sheet. Use the Add method to create a new list box and add it to the collection.

To access a single member of the collection, use the ListBoxes method with the index number or name of the list box as an argument.

The following example sets the list input range for list box two on the worksheet named "Sheet2." When the dialog sheet runs, the contents of cells D1:D15 on the worksheet named "Sheet2" will appear as items in the list box.

Worksheets("sheet2").ListBoxes(2).ListFillRange = "=sheet2!d1:d15"

The list box name is shown in the Name Box when the list box is selected. Use the Name property to set or return the list box name. The following example adds an item to the list shown in the list box named "List Box 2."

Worksheets(1).ListBoxes("list box 2").AddItem "end"

Remarks

On dialog sheets, the LinkCombo method can be used to link a list box and an edit box to create a combination list edit box. For information about combination drop-down edit boxes, see the DropDown object.

Properties

Application Property, BottomRightCell Property, Creator Property, Display3DShading Property, Enabled Property, Height Property, Index Property, Left Property, LinkedCell Property, LinkedObject Property, List Property, ListCount Property, ListFillRange Property, ListIndex Property, Locked Property, MultiSelect Property, Name Property, OnAction Property, Parent Property, Placement Property, PrintObject Property, Selected Property, Top Property, TopLeftCell Property, Value Property, Visible Property, Width Property, ZOrder Property.

Methods

AddItem Method, BringToFront Method, Copy Method, CopyPicture Method, Cut Method, Delete Method, Duplicate Method, RemoveAllItems Method, RemoveItem Method, Select Method, SendToBack Method.


ListBoxes Collection Object

Description

A collection of all the ListBox objects on the specified chart sheet, dialog sheet, or worksheet. List boxes that are linked to edit boxes to form combination list edit boxes are included in the ListBoxes collection.

Accessors

Use the Add method to create a new list box and add it to the collection. The following example adds a new list box to the dialog sheet named "Dialog1." The new list box is positioned relative to the upper-left corner of the dialog frame.

Dim df As DialogFrame
Set df = DialogSheets("dialog1").DialogFrame
DialogSheets("dialog1").ListBoxes.Add df.Left + 10, _
    df.Top + 20, 100, 100

Use the ListBoxes method with an argument to access a single member of the collection or without an argument to access the entire collection at once. The following example deletes all of the list boxes on the dialog sheet named "Dialog1."

DialogSheets("dialog1").ListBoxes.Delete

Properties

Application Property, Count Property, Creator Property, Display3DShading Property, Enabled Property, Height Property, Left Property, LinkedCell Property, List Property, ListFillRange Property, ListIndex Property, Locked Property, MultiSelect Property, OnAction Property, Parent Property, Placement Property, PrintObject Property, Selected Property, Top Property, Value Property, Visible Property, Width Property, ZOrder Property.

Methods

Add Method (Graphic Objects and Controls), AddItem Method, BringToFront Method, Copy Method, CopyPicture Method, Cut Method, Delete Method, Duplicate Method, Group Method, Item Method, RemoveAllItems Method, RemoveItem Method, Select Method, SendToBack Method.


ListBoxes Method

Applies To

Chart Object, DialogSheet Object, Worksheet Object.

Description

Accessor. Returns an object that represents a single list-box control (a ListBox object, Syntax 1) or a collection of list-box controls (a ListBoxes object, Syntax 2) on the sheet.

Syntax 1

object.ListBoxes(index)

Syntax 2

object.ListBoxes

object

Required. The Chart, DialogSheet, or Worksheet object.

index

Required for Syntax 1. Specifies the name or number of the list box (can be an array to specify more than one).

Example

This example fills list box one on Dialog1 with the letters A through Z.

For i = 65 To 90
    DialogSheets("Dialog1").ListBoxes(1).AddItem Text:=Chr(i)
Next i


ListCount Property

Applies To

DropDown Object, ListBox Object.

Description

Returns the number of entries in a list box or drop-down list box. Returns zero if there are no entries in the list. Read-only.

See Also

List Property.

Example

This example displays the number of entries in list box one on Dialog1.

cEntries = DialogSheets("Dialog1").ListBoxes(1).ListCount
MsgBox "There are " & cEntries & " entries in list box one."


ListFillRange Property

Applies To

DrawingObjects Collection, DropDown Object, DropDowns Collection, ListBox Object, ListBoxes Collection.

Description

Returns or sets the worksheet range used to fill the list box, as a string. Setting this property destroys any existing list in the list box. Read-write.

Remarks

Microsoft Excel reads the contents of every cell in the range and puts it into the list box. The list will track changes in the range cells.

If the list in the list box was created with the AddItem method, this property returns an empty string ("").

See Also

AddItem Method, List Property, RemoveItem Method.

Example

This example fills list box one with the range A1:A10 on Sheet1.

DialogSheets("Dialog1").Listboxes(1).ListFillRange = _
    "Sheet1!A1:A10"


ListHeaderRows Property

Applies To

Range Object.

Description

Returns the number of header rows for the specified range. This property is available only in Microsoft Excel for Windows 95. Read-only.

Remarks

Before you use this property, use the CurrentRegion property to find the boundaries of the range.

Example

This example sets the rTbl variable to the range represented by the current region for the active cell, not including any header rows.

Set rTbl = ActiveCell.CurrentRegion
' remove the headers from the range
iHdrRows = rTbl.ListHeaderRows
If iHdrRows > 0 Then
    ' resize the range minus n rows
    Set rTbl = rTbl.Resize(rTbl.Rows.Count - iHdrRows)
    ' and then move the resized range down to
    ' get to the first non-header row
    Set rTbl = rTbl.Offset(iHdrRows)
End If


ListIndex Property

Applies To

DrawingObjects Collection, DropDown Object, DropDowns Collection, ListBox Object, ListBoxes Collection.

Description

Returns or sets the index of the currently selected item in a list box or drop-down list box. Read-write.

Remarks

This property cannot be used with multi-select list boxes. Use the Selected property instead.

See Also

MultiSelect Property, Selected Property, Value Property.

Example

This example selects item four in list box one on Dialog1.

DialogSheets("Dialog1").ListBoxes(1).ListIndex = 4


ListNames Method

Applies To

Range Object.

Description

Pastes a list of all non-hidden names on the worksheet, beginning at the first cell of the range.

Syntax

object.ListNames

object

Required. Identifies the worksheet for which to list names, and the start of the range where the names will be listed.

Remarks

Use the Names method to return a collection of all the names on a worksheet.

Example

This example pastes a list of defined names into cell A1 on Sheet1. The example pastes workbook-level names and sheet-level names defined on Sheet1.

Worksheets("Sheet1").Range("A1").ListNames


Loc Function

Description

Returns the current read/write position within an open file.

Syntax

Loc(filenumber)

The filenumber named argument is any valid file number.

Remarks

The following describes the return value for each file access mode:

File Access | Return Value
Random | Number of the last record read from or written to the file.
Sequential | Current byte position in the file divided by 128.
Binary | Position of the last byte read or written.

See Also

EOF Function, LOF Function, Open Statement.

Example

This example uses the Loc function to return the current read/write position within an open file. For purposes of this example, assume that TESTFILE is a text file with a few lines of sample data.

Open "TESTFILE" For Input As #1    ' Open file just created.
Do While Not EOF(1)    ' Loop until end of file.
    Line Input #1, MyLine    ' Read line into variable.
    MyLocation = Loc(1)    ' Get current position within file.
    ' Print to Debug window.
    Debug.Print MyLine; Tab; MyLocation
Loop


LocationInTable Property

Applies To

Range Object.

Description

Returns a constant that describes the part of the PivotTable which contains the top left corner of the specified range. Can be one of xlRowHeader, xlColumnHeader, xlPageHeader, xlDataHeader, xlRowItem, xlColumnItem, xlPageItem, xlDataItem, or xlTableBody. Read-only.

Example

This example displays a message box that describes the location of the active cell within the PivotTable.

Worksheets("Sheet1").Activate
Select Case ActiveCell.LocationInTable
Case Is = xlRowHeader
    MsgBox "Active cell is part of a row header"
Case Is = xlColumnHeader
    MsgBox "Active cell is part of a column header"
Case Is = xlPageHeader
    MsgBox "Active cell is part of a page header"
Case Is = xlDataHeader
    MsgBox "Active cell is part of a data header"
Case Is = xlRowItem
    MsgBox "Active cell is part of a row item"
Case Is = xlColumnItem
    MsgBox "Active cell is part of a column item"
Case Is = xlPageItem
    MsgBox "Active cell is part of a page item"
Case Is = xlDataItem
    MsgBox "Active cell is part of a data item"
Case Is = xlTableBody
    MsgBox "Active cell is part of the table body"
End Select


Lock...Unlock Statements

Description

Controls access by other processes to all or part of a file opened using the Open statement.

Syntax

Lock [#]filenumber[,recordrange]
. . .
Unlock [#]filenumber[,recordrange]

The Lock and Unlock statement syntax has these parts:

Part | Description
filenumber | Any valid file number.
recordrange | The range of records to lock or unlock.

The recordrange argument has the following syntax and parts:

recnumber | [start] To end

Part | Description
recnumber | Record number (Random mode files) or byte number (Binary mode files) at which locking or unlocking begins.
start | Number of the first record or byte to lock or unlock.
end | Number of the last record or byte to lock or unlock.

Remarks

The Lock and Unlock statements are used in environments where several processes might need access to the same file.

Lock and Unlock statements are always used in pairs. The arguments to Lock and Unlock must match exactly.

The first record/byte in a file is at position 1, the second record/byte is at position 2, and so on. If you specify just one record, then only that record is locked or unlocked. If you specify a range of records and omit a starting record (start), all records from the first record to the end of the range (end) are locked or unlocked. Using Lock without recnumber locks the entire file; using Unlock without recnumber unlocks the entire file.

If the file has been opened for sequential input or output, Lock and Unlock affect the entire file, regardless of the range specified by start and end.

Caution

Be sure to remove all locks with an Unlock statement before closing a file or terminating your program. Failure to remove locks produces unpredictable results.

See Also

Open Statement.

Example

This example illustrates the use of the Lock and Unlock statements. While a record is being modified, access by other processes to the record is denied. For purposes of this example, assume that TESTFILE is a file containing five records of the user-defined type Record.

Type Record    ' Define user-defined type.
    ID As Integer
    Name As String * 20
End Type
Dim MyRecord As Record    ' Declare variable.
' Open sample file for random access.
Open "TESTFILE" For Random Shared As #1 Len = Len(MyRecord)
RecordNumber = 4    ' Define record number.
Lock #1, RecordNumber    ' Lock record.
Get #1, RecordNumber, MyRecord    ' Read record.
MyRecord.ID = 234    ' Modify record.
MyRecord.Name = "John Smith"
Put #1, RecordNumber, MyRecord    ' Write modified record.
Unlock #1, RecordNumber    ' Unlock current record.
Close #1    ' Close file.


Locked Property

Applies To

Arc Object, Arcs Collection, Button Object, Buttons Collection, ChartObject Object, ChartObjects Collection, CheckBox Object, DialogFrame Object, Drawing Object, DrawingObjects Collection, Drawings Collection, DropDown Object, DropDowns Collection, EditBox Object, EditBoxes Collection, GroupBox Object, GroupBoxes Collection, GroupObject Object, GroupObjects Collection, Label Object, Labels Collection, Line Object, Lines Collection, ListBox Object, ListBoxes Collection, OLEObject Object, OLEObjects Collection, OptionButton Object, OptionButtons Collection, Oval Object, Ovals Collection, Picture Object, Pictures Collection, Range Object, Rectangle Object, Rectangles Collection, Scenario Object, ScrollBar Object, ScrollBars Collection, Spinner Object, Spinners Collection, Style Object, TextBox Object, TextBoxes Collection.

Description

False if the object can be modified when the sheet is protected. Read-write.

See Also

FormulaHidden Property, Protect Method, Unprotect Method.

Example

This example unlocks cells A1:G37 on Sheet1 so that they can be modified when the sheet is protected.

Worksheets("Sheet1").Range("A1:G37").Locked = False
Worksheets("Sheet1").Protect


LockedText Property

Applies To

Button Object, Buttons Collection, CheckBox Object, DialogFrame Object, DrawingObjects Collection, GroupBox Object, GroupBoxes Collection, Label Object, Labels Collection, OptionButton Object, OptionButtons Collection, TextBox Object, TextBoxes Collection.

Description

True if the text in the object will be locked to prevent changes when the document is protected. Read-write.

See Also

Protect Method, ProtectContents Property.

Example

This example locks the text on button one on Sheet1.

Worksheets("Sheet1").Buttons(1).LockedText = True


LOF Function

Description

Returns the size, in bytes, of a file opened using the Open statement.

Syntax

LOF(filenumber)

The filenumber named argument is any valid file number.

Remarks

To obtain the length of a file that is not open, use the FileLen function.

See Also

EOF Function, FileLen Function, Loc Function, Open Statement.

Example

This example uses the LOF function to determine the size of an open disk file. For purposes of this example, assume that TESTFILE is a text file containing sample data.

Open "TESTFILE" For Input As #1    ' Open file.
FileLength = LOF(1)    ' Get length of file.
Close #1    ' Close file.


Log Function

Description

Returns the natural logarithm of a number.

Syntax

Log(number)

The number named argument can be any valid numeric expression greater than 0.

Remarks

The natural logarithm is the logarithm to the base e. The constant e is approximately 2.718282.

You can calculate base-n logarithms for any number x by dividing the natural logarithm of x by the natural logarithm of n as follows:

Logn(x) = Log(x) / Log(n)

The following example illustrates a custom Function that calculates base-10 logarithms:

Static Function Log10(X)
    Log10 = Log(X) / Log(10#)
End Function

See Also

Derived Math Functions, Exp Function.

Example

This example uses the Log function to return the natural logarithm of a number.

' Define angle in radians.
MyAngle = 1.3
' Calculate inverse hyperbolic sine.
MyLog = Log(MyAngle + Sqr(MyAngle * MyAngle + 1))


Long Data Type

Description

Long (long integer) variables are stored as signed 32-bit (4-byte) numbers ranging in value from -2,147,483,648 to 2,147,483,647. The type-declaration character for Long is & (character code 38).

See Also

CLng Function, Data Type Summary, Def type Statements, Integer Data Type.


LSet Statement

Description

Left aligns a string within a string variable, or copies a variable of one user-defined type to another variable of a different user-defined type.

Syntax

LSet stringvar = string

LSet varname1 = varname2

The LSet statement syntax has these parts:

Part | Description
stringvar | Name of string variable.
string | String expression to be left aligned within stringvar.
varname1 | Variable name of the user-defined type being copied to.
varname2 | Variable name of the user-defined type being copied from.

Remarks

LSet replaces any leftover characters in stringvar with spaces.

If string is longer than stringvar, LSet places only the leftmost characters, up to the length of the stringvar, in stringvar.

Only user-defined types containing Integer, Long, Double, Single, String (fixed-length), or Currency types may be copied. The following example copies the contents of RecTwo (a user-defined type variable) to RecOne (a variable of another user-defined type):

Type TwoString
    StrFld As String * 2
End Type
Type ThreeString
    StrFld As String * 3
End Type
Dim RecOne As TwoString, RecTwo As ThreeString
LSet RecOne = RecTwo

Because RecOne is 2 bytes long, only 2 bytes are copied from RecTwo. LSet copies only the number of bytes in the shorter of the two user-defined type variables.

See Also

RSet Statement.

Example

This example uses the LSet statement to left align a string within a string variable and to copy a variable of one user-defined type to another variable of a different user-defined type.

MyString = "0123456789"    ' Initialize string.
LSet MyString = "<-Left"    ' MyString contains "<-Left    ".

' LSet is also used to copy a variable of one user-defined type to
' another variable of a different user-defined type.
' Module level.
Type AType    ' Define types.
    AName As String * 10
    AAdd As String * 10
End Type
Type BType
    BName As String * 5
    BAdd As String * 5
End Type

' Procedure level.
Dim AVar As AType, BVar As BType    ' Declare variables.
AVar.AName = "John Smith"    ' Define fields.
AVar.AAdd = "Rodeo Drv."
LSet BVar = AVar    ' Copy variables.
' After copying, values are truncated.
Debug.Print BVar.BName    ' Prints "John ".
Debug.Print BVar.BAdd    ' Prints "Smith".


LTrim, RTrim, and Trim Functions

Description

Returns a copy of a string without leading spaces (LTrim), trailing spaces (RTrim), or both leading and trailing spaces (Trim).

Syntax

LTrim(string)

RTrim(string)

Trim(string)

The string named argument is any valid string expression. If string contains no valid data, Null is returned.

See Also

Left Function, Right Function.

Example

This example uses the LTrim and RTrim functions to strip leading and trailing spaces from a string variable. Using the Trim function alone achieves the same result.

MyString = "  <-Trim->  "       ' Initialize.
TrimString = LTrim(MyString)    ' TrimString = "<-Trim->  ".
TrimString = RTrim(MyString)    ' TrimString = "  <-Trim->".
TrimString = LTrim(RTrim(MyString))    ' TrimString = "<-Trim->".
' Using the Trim function alone achieves the same result.
TrimString = Trim(MyString)    ' TrimString = "<-Trim->".


MacID Function

Description

Used only on the Macintosh to convert a four-character constant to a value that may be used by Dir, Kill, Shell, and AppActivate.

Syntax

MacID(constant)

The constant named argument consists of four-characters used to specify a resource type, file type, application signature, or Apple Event. For example, TEXT, OBIN, MSWD (Microsoft Word), XCEL (Microsoft Excel), and so on.

Remarks

MacID is used with Dir and Kill to specify a Macintosh file type. Since the Macintosh does not support '*' and '?' as wildcards, you can use a four-character constant instead to identify groups of files. For example, the following statement returns 'TEXT' type files from the current folder:

Dir("", MacID("TEXT"))

MacID is used with Shell and AppActivate to specify an application using the application's unique signature.

See Also

AppActivate Statement, Dir Function, Kill Statement, Shell Function.

Example

This example shows various uses of the MacID function. The MacID function is not available in Microsoft Windows.

' Return the first text file in folder HD:My Folder.
FileName = Dir("HD:My Folder:", MacID("TEXT"))

' Deletes all "TEXT" files in the current folder.
Kill MacID("TEXT")
' Run Microsoft Excel.
ReturnValue = Shell(MacID("XCEL"))

' Activate Microsoft Word.
AppActivate MacID("MSWD")


MacroOptions Method

Applies To

Application Object.

Description

Corresponds to options in the Macro Options dialog box.

Syntax

object.MacroOptions(macro, description, hasMenu, menuText, hasShortcutKey, shortcutKey, category, statusBar, helpContextID, helpFile)

object

Required. The Application object.

macro

Required. The name of the macro to set options for, as a string.

description

Optional. The description of the macro, as a string.

hasMenu

Optional. If True, then a menu item is automatically added to the Tools menu for this macro. If True, then menuText must also be specified. If False or omitted, no menu item is added for the macro. If the macro already has a menu item created for it, setting this argument to False will remove the menu item.

menuText

Required if hasMenu is True; ignored otherwise. The text of the menu item, as a string.

hasShortcutKey

Optional. If True, a shortcut key is assigned to the macro. If True, then shortcutKey must also be specified. If False or omitted, no shortcut key is assigned to the macro. If the macro already has a shortcut key, setting this argument to False will remove the shortcut key.

shortcutKey

Required if hasShortcutKey is True; ignored otherwise. The shortcut key (first character only) as a string.

category

Optional. The function category (Financial, Date & Time, User Defined, and so on) that the macro appears in, as an integer.

statusBar

Optional. The status bar text for the macro, as a string.

helpContextId

Optional. The context ID for the Help topic assigned to the macro, as an integer. The context ID also applies to any menu items and/or toolbar buttons assigned to the macro.

helpFile

Optional. The name of the Help file that contains the Help topic defined by helpContextId, as a string.


MacroType Property

Applies To

Name Object.

Description

Returns or sets what the name refers to, as shown in the following table. Read-write.

Value | Meaning
xlCommand | Name is a user-defined macro.
xlFunction | Name is a user-defined function.
xlNone | Name is not a function or macro.

See Also

Category Property.

Example

This example assumes that you created a custom function or command on a Microsoft Excel version 4.0 macro sheet. The example displays the function category, in the language of the macro. It assumes that the name of the custom function or command is the only name in the workbook.

With ActiveWorkbook.Names(1)
    If .MacroType <> xlNone Then
        MsgBox "The category for this name is " & .Category
    Else
        MsgBox "This name does not refer to" & _
            " a custom function or command."
    End If
End With


MacScript Statement

Description

Executes an AppleScript script; available on the Macintosh using System 7.0 or later.

Syntax

MacScript script

The script named argument is a string expression specifying the name of an AppleScript script.

Remarks

Multiline scripts may be created by embedding carriage return characters (Chr(13)).

See Also

MacID Function.


Mailer Object

Description

Represents the PowerTalk Mailer for a workbook. This object is available only on the Apple Macintosh with the PowerTalk system extension installed.

Accessors

The Mailer property returns the mailer for the workbook when the HasMailer property is True. The following example sets the Subject property for the mailer attached to the active workbook.

ActiveWorkbook.HasMailer = True
ActiveWorkbook.Mailer.Subject = "Here is the workbook."

Properties

Application Property, BCCRecipients Property, CCRecipients Property, Creator Property, Enclosures Property, Parent Property, Received Property, SendDateTime Property, Sender Property, Subject Property, ToRecipients Property.

See Also

SendMailer Method.


Mailer Property

Applies To

Workbook Object.

Description

Accessor. Returns a Mailer object that represents the PowerTalk mailer attached to the workbook. Available only in Microsoft Excel for the Apple Macintosh with the PowerTalk mail system extension installed. Read-only.

Remarks

The Mailer object contains the properties needed to mail workbooks with PowerTalk. To mail a workbook, turn on the mailer with the HasMailer property, set the mailer properties, and then send the workbook and mailer with the SendMailer method.

See Also

BCCRecipients Property, CCRecipients Property, Enclosures Property, HasMailer Property, Received Property, SendDateTime Property, Sender Property, SendMailer Method, Subject Property, ToRecipients Property.

Example

This example sets up the Mailer object for workbook one and then sends the workbook.

With Workbooks(1)
    .HasMailer = True
    With .Mailer
        .Subject = "Here is the workbook"
        .ToRecipients = Array("Jean")
        .CCRecipients = Array("Adam", "Bernard")
        .BCCRecipients = Array("Chris")
        .Enclosures = Array("TestFile")
    End With
    .SendMailer
End With


MailLogoff Method

Applies To

Application Object.

Description

Closes a MAPI mail session established by Microsoft Excel.

Syntax

object.MailLogoff

object

Required. The Application object.

Remarks

This method cannot be used to close or log off Microsoft Mail.

See Also

MailLogon Method, MailSession Property, SendMail Method.

Example

This example closes the established mail session if there is one.

If Not IsNull(Application.MailSession) Then Application.MailLogoff


MailLogon Method

Applies To

Application Object.

Description

Logs into MAPI Mail or Microsoft Exchange and establishes a mail session. If Microsoft Mail is not already running, you must use this method to establish a mail session before mail or document routing functions can be used.

Syntax

object.MailLogon(name, password, downloadNewMail)

object

Required. The Application object.

name

Optional. The mail account name or Microsoft Exchange profile name. If omitted, the default mail account name is used.

password

Optional. The mail account password. This argument is ignored in Microsoft Exchange.

downloadNewMail

Optional. If True, new mail is downloaded immediately.

Remarks

Mail sessions previously established by Microsoft Excel are logged off before an attempt is made to establish the new session.

Omit both the name and password parameters to piggyback on the system default mail session.

See Also

MailLogoff Method, MailSession Property, SendMail Method.

Example

This example logs into mail and downloads any new mail immediately.

If IsNull(Application.MailSession) Then
    Application.MailLogon "oscarx", "mypassword", True
End If


MailSession Property

Applies To

Application Object.

Description

Returns the MAPI mail session number as a hexadecimal string (if there is an active session), or Null if there is no session. Read-only.

Remarks

This property applies only to mail sessions created by Microsoft Excel (it does not return a mail session number for Microsoft Mail).

This property is not used on PowerTalk mail systems.

See Also

MailLogoff Method, MailLogon Method, MailSystem Property, SendMail Method.

Example

This example closes the established mail session if there is one.

If Not IsNull(Application.MailSession) Then Application.MailLogoff


MailSystem Property

Applies To

Application Object.

Description

Returns the mail system installed on the host machine (one of xlNoMailSystem, xlMAPI, or xlPowerTalk). Read-only.

See Also

MailLogoff Method, MailLogon Method, MailSession Property, SendMail Method.

Example

This example displays the name of the mail system installed on the computer.

Sub foo()
Select Case Application.MailSystem
    Case Is = xlMAPI
        MsgBox "Mail system is Microsoft Mail"
    Case Is = xlPowerTalk
        MsgBox "Mail system is PowerTalk"
    Case Is = xlNoMailSystem
        MsgBox "No mail system installed"
End Select
End Sub


MajorGridlines Property

Applies To

Axis Object.

Description

Accessor. Returns a Gridlines object that represents the major gridlines for the specified axis. Only axes in the primary axis group can have gridlines. Read-only.

See Also

AxisGroup Property, HasMajorGridlines Property, HasMinorGridlines Property, MinorGridlines Property.

Example

This example sets the color of the major gridlines for the value axis in Chart1.

With Charts("Chart1").Axes(xlValue)
    If .HasMajorGridlines Then
        .MajorGridlines.Border.ColorIndex = 5    '' 273.'set color to blue
    End If
End With


MajorTickMark Property

Applies To

Axis Object.

Description

Returns or sets the type of major tick mark for the specified axis (one of xlNone, xlInside, xlOutside, or xlCross). Read-write.

See Also

MinorTickMark Property.

Example

This example sets the major tick marks for the value axis in Chart1 to be outside the axis.

Charts("Chart1").Axes(xlValue).MajorTickMark = xlOutside


MajorUnit Property

Applies To

Axis Object.

Description

Returns or sets the major units for the value axis. Applies only to the value axis. Read-write.

Remarks

Setting this property sets the MajorUnitIsAuto property to False.

Use the TickMarkSpacing property to set tick mark spacing on the category axis.

See Also

MajorUnitIsAuto Property, MinorUnit Property, MinorUnitIsAuto Property, TickMarkSpacing Property.

Example

This example sets the major and minor units for the value axis in Chart1.

With Charts("Chart1").Axes(xlValue)
    .MajorUnit = 100
    .MinorUnit = 20
End With


MajorUnitIsAuto Property

Applies To

Axis Object.

Description

True if Microsoft Excel calculates major units for the value axis. Applies only to the value axis. Read-write.

Remarks

Setting the MajorUnit property sets this property to False.

See Also

MajorUnit Property, MinorUnit Property, MinorUnitIsAuto Property.

Example

This example automatically sets major and minor units for the value axis in Chart1.

With Charts("Chart1").Axes(xlValue)
    .MajorUnitIsAuto = True
    .MinorUnitIsAuto = True
End With


MarkerBackgroundColor Property

Applies To

LegendKey Object, Point Object, Series Object.

Description

Returns or sets the marker background color as an RGB value. Line, scatter and radar charts only. Read-write.

See Also

MarkerBackgroundColorIndex Property, MarkerForegroundColor Property, MarkerStyle Property.

Example

This example sets the marker background and foreground colors for the second point in series one in Chart1.

With Charts("Chart1").SeriesCollection(1).Points(2)
    .MarkerBackgroundColor = RGB(0,255,0)    ' green
    .MarkerForegroundColor = RGB(255,0,0)    ' red
End With


MarkerBackgroundColorIndex Property

Applies To

LegendKey Object, Point Object, Series Object.

Description

Returns or sets the marker background color as an index into the current color palette (a value from one to 56, or xlNone if there is no background color). Line, scatter and radar charts only. Read-write.

See Also

Colors Property, MarkerBackgroundColor Property, MarkerForegroundColorIndex Property, MarkerStyle Property.

Example

This example sets the marker background and foreground color for the second point in series one in Chart1.

With Charts("Chart1").SeriesCollection(1).Points(2)
    .MarkerBackgroundColorIndex = 4    'green
    .MarkerForegroundColorIndex = 3    'red
End With


MarkerForegroundColor Property

Applies To

LegendKey Object, Point Object, Series Object.

Description

Returns or sets the foreground color of the marker, specified as an RGB value. Line, scatter and radar charts only. Read-write.

See Also

MarkerBackgroundColor Property, MarkerForegroundColorIndex Property, MarkerStyle Property.

Example

This example sets the marker background and foreground colors for the second point in series one in Chart1.

With Charts("Chart1").SeriesCollection(1).Points(2)
    .MarkerBackgroundColor = RGB(0,255,0)    ' green
    .MarkerForegroundColor = RGB(255,0,0)    ' red
End With


MarkerForegroundColorIndex Property

Applies To

LegendKey Object, Point Object, Series Object.

Description

Returns or sets the marker foreground color as an index into the current color palette (a value from one to 56, or xlNone if there is no foreground color). Line, scatter and radar charts only. Read-write.

See Also

Colors Property, MarkerBackgroundColorIndex Property, MarkerForegroundColor Property, MarkerStyle Property.

Example

This example sets the marker background and foreground colors for the second point in series one in Chart1.

With Charts("Chart1").SeriesCollection(1).Points(2)
    .MarkerBackgroundColorIndex = 4    'green
    .MarkerForegroundColorIndex = 3    'red
End With


MarkerStyle Property

Applies To

LegendKey Object, Point Object, Series Object.

Description

Returns or sets the marker style for a point or series on a line chart, a scatter chart, or a radar chart. Read-write.

Remarks

This property can have one of the following values.

Value | Meaning
xlNone | No markers.
xlAutomatic | Automatic markers.
xlSquare | Square markers.
xlDiamond | Diamond-shaped markers.
xlTriangle | Triangular markers.
xlX | Square markers with an X.
xlStar | Square markers with an asterisk.
xlDot | Short bar markers.
xlDash | Long bar markers.
xlCircle | Circular markers.
xlPlus | Square markers with a plus sign.
xlPicture | Picture markers.

Example

This example sets the marker style for series one in Chart1. The example should be run on a 2-D line chart.

Charts("Chart1").SeriesCollection(1).MarkerStyle = xlCircle


MathCoprocessorAvailable Property

Applies To

Application Object.

Description

True if a math coprocessor is available. Read-only.

Example

This example displays a message box if a math coprocessor is not available.

If Not Application.MathCoprocessorAvailable Then
    MsgBox "This macro requires a math coprocessor"
End If


Max Property

Applies To

DrawingObjects Collection, ScrollBar Object, ScrollBars Collection, Spinner Object, Spinners Collection.

Description

Returns or sets the maximum value of a scroll bar or spinner range. The scroll bar or spinner will not take on values above this maximum value. Read-write.

For help about using the Max worksheet function in Visual Basic, see "Using Worksheet Functions in Visual Basic" in online Help.

Remarks

The value of the Max property must be greater than the value of the Min property.

See Also

Min Property.

Example

This example sets the minimum and maximum values for scroll bar one on Dialog1.

With DialogSheets("Dialog1").ScrollBars(1)
    .Min = 20
    .Max = 50
End With


MaxChange Property

Applies To

Application Object.

Description

Returns or sets the maximum amount of change that is used in each iteration as Microsoft Excel tries to resolve circular references. Read-write.

Remarks

The MaxIterations property sets the maximum number of iterations used when resolving circular references.

See Also

Iteration Property, MaxIterations Property.

Example

This example sets the maximum change for each iteration to 0.1.

Application.MaxChange = 0.1


MaximumScale Property

Applies To

Axis Object.

Description

Returns or sets the maximum value on the value axis. Applies only to the value axis. Read-write.

Remarks

Setting this property sets the MaximumScaleIsAuto property to False.

See Also

MaximumScaleIsAuto Property, MinimumScale Property, MinimumScaleIsAuto Property.

Example

This example sets the maximum and minimum values for the value axis in Chart1.

With Charts("Chart1").Axes(xlValue)
    .MinimumScale = 10
    .MaximumScale = 120
End With


MaximumScaleIsAuto Property

Applies To

Axis Object.

Description

True if Microsoft Excel calculates the maximum value for the value axis. Applies only to the value axis. Read-write.

Remarks

Setting the MaximumScale property sets this property to False.

See Also

MaximumScale Property, MinimumScale Property, MinimumScaleIsAuto Property.

Example

This example automatically calculates the maximum scale and minimum scale for the value axis in Chart1.

With Charts("Chart1").Axes(xlValue)
    .MinimumScaleIsAuto = True
    .MaximumScaleIsAuto = True
End With


MaxIterations Property

Applies To

Application Object.

Description

Returns or sets the maximum number of iterations that will be allowed to resolve a circular reference. Read-write.

Remarks

The MaxChange property sets the maximum amount of change used in each iteration when resolving circular references.

See Also

Iteration Property, MaxChange Property.

Example

This example sets the maximum number of iterations to 1000.

Application.MaxIterations = 1000


MemoryFree Property

Applies To

Application Object.

Description

Returns the amount of memory that is still available for Microsoft Excel to use, in bytes. Read-only.

See Also

MemoryTotal Property, MemoryUsed Property.

Example

This example displays a message box showing the number of free bytes.

MsgBox "Microsoft Excel has " & Application.MemoryFree & " bytes free"


MemoryTotal Property

Applies To

Application Object.

Description

Returns the total amount of memory that is available to Microsoft Excel, including memory already in use, in bytes. Read-only.

Remarks

MemoryTotal is equal to MemoryUsed + MemoryFree.

See Also

MemoryFree Property, MemoryUsed Property.

Example

This example displays a message box showing the total number of available bytes.

MsgBox "Microsoft Excel has " & Application.MemoryTotal & _
    " total bytes available"


MemoryUsed Property

Applies To

Application Object.

Description

Returns the amount of memory that is currently in use by Microsoft Excel, in bytes. Read-only.

See Also

MemoryFree Property, MemoryTotal Property.

Example

This example displays a message box showing the number of bytes currently being used.

MsgBox "Microsoft Excel is currently using " & _
    Application.MemoryUsed & " bytes"


Menu Object

Description

Represents a drop-down menu, shortcut menu, or submenu.

Accessors

The Menu object is a member of the Menus collection. The Menus collection contains all of the menus on a menu bar. Use the Add method to create a new menu and add it to the specified menu bar. To access a single member of the collection, use the Menus method with the menu caption or index number as an argument.

The index number indicates the position of the menu on the menu bar. The following example adds a new menu item to the bottom of the File menu on the Worksheet menu bar.

MenuBars("worksheet").Menus(1).MenuItems.Add "Search"

The menu caption is the text that appears in the menu bar. Use the Caption property to set or return the menu caption. The following example changes the caption for the Help menu on the Visual Basic Module menu bar.

MenuBars(xlModule).Menus("help").Caption = "HELP!"

The following example creates a table on worksheet one that contains the captions of all the menus on all the menu bars in the application. The column headings are the menu bar captions, and the column entries under each heading are the menu captions on that menu bar.

Sub EnumerateMenuBars()
    Worksheets(1).Activate
    c = 1
    For Each mb In MenuBars
        Cells(1, c) = mb.Caption
        i = 2
        For Each mn In mb.Menus
            Cells(i, c) = mn.Caption
            i = i + 1
        Next
        c = c + 1
    Next
End Sub

The MenuItems method returns a Menu object when the specified menu item is a submenu. The following example sets the Checked property for the mySubMenuItem submenu item on the mySubMenu submenu.

MenuBars(xlModule).Menus("myMenu").MenuItems("mySubMenu") _
    .MenuItems("mySubMenuItem").Checked = True

Remarks

You should use the menu name instead of its index number so your code will not depend on the current menu layout. Other Visual Basic procedures may change the menu layout, and the layout may change in future versions of Microsoft Excel. It is safer to use Menubars(xlWorksheet).Menus("File") than to rely on the File menu being the first menu on the menubar and use Menubars(xlWorksheet).Menus(1).

Properties

Application Property, Caption Property, Creator Property, Enabled Property, Index Property, Parent Property.

Methods

Delete Method, MenuItems Method.


MenuBar Object

Description

Represents a built-in or custom menu bar.

Accessors

The MenuBar object is a member of the MenuBars collection. The MenuBars collection contains all of the menu bars available to Microsoft Excel. Use the Add method to create a new menu bar and add it to the collection. Use the Activate method to display a menu bar. To access a single member of the collection, use the MenuBars method with the menu bar caption or index number as an argument.

Several built-in constants are available for the menu bar index number, as shown in the following list.

Constant | Description
xlWorksheet | Worksheet, macro sheet, and dialog sheet.
xlChart | Chart
xlModule | Visual Basic module
xlNoDocuments | No documents open
xlInfo | Info Window
xlWorksheetShort | Short Worksheet menu (for Microsoft Excel version 3 compatibility)
xlChartShort | Short Chart menu (for Microsoft Excel version 3 compatibility)
xlWorksheet4 | Old worksheet menu bar (for Microsoft Excel version 4 compatibility)
xlChart4 | Old chart menu bar (for Microsoft Excel version 4 compatibility)

Microsoft Excel automatically displays the built-in menu bar appropriate to the active sheet. When the active sheet type changes, Microsoft Excel changes the menu bar. If you create a custom menu bar and display it using Visual Basic code, Microsoft Excel stops changing the menu bar to fit the active sheet, and your code must activate and deactivate the menu bar (if necessary) when the sheet type changes.

The following example adds a new menu item to the bottom of the File menu on the Visual Basic Module menu bar.

MenuBars(xlModule).Menus("file").MenuItems.Add "S&earch"

The following example creates a table on worksheet one. The table contains the captions of all the menus on all the menu bars in the application. The column headings are the menu bar captions, and the column entries under each heading are the menu captions on that menu bar.

Sub EnumerateMenuBars()
    Worksheets(1).Activate
    c = 1
    For Each mb In MenuBars
        Cells(1, c) = mb.Caption
        i = 2
        For Each mn In mb.Menus
            Cells(i, c) = mn.Caption
            i = i + 1
        Next
        c = c + 1
    Next
End Sub

Properties

Application Property, BuiltIn Property, Caption Property, Creator Property, Index Property, Parent Property.

Methods

Activate Method, Delete Method, Menus Method, Reset Method.


MenuBars Collection Object

Description

A collection of all the MenuBar objects in the Microsoft Excel application. Each MenuBar object represents a built-in or custom menu bar.

Accessors

Use the Add method to add a new menu bar to the application. The following example adds a new menu bar and then activates it.

With MenuBars.Add("Stock Chart")
    With .Menus.Add("File")
        .MenuItems.Add "Update", "UpdateProc"
        .MenuItems.Add "Print", "PrintProc"
    End With
End With
MenuBars("stock chart").Activate

After running the example, you can use MenuBars(xlModule).Activate to restore the Visual Basic Module menu.

Use the MenuBars method with an argument to access a single member of the collection or without an argument to access the entire collection at once.

Properties

Application Property, Count Property, Creator Property, Parent Property.

Methods

Add Method (MenuBars Collection), Item Method.


MenuBars Method

Applies To

Application Object.

Description

Accessor. Returns an object that represents a single menu bar (a MenuBar object, Syntax 1) or a collection of the top-level menu bars (the MenuBars object, Syntax 2). Read-only.

Syntax 1

object.MenuBars(index)

Syntax 2

object.MenuBars

object

Optional. The Application object.

index

Required for Syntax 1. The name or number of the menu bar. Several predefined constants are available, as shown in the following table.

Constant

Description

xlWorksheet

Worksheet, macro sheet and dialog sheet.

xlChart

Chart

xlModule

Visual Basic module

xlNoDocuments

No documents open

xlInfo

Info Window

xlWorksheetShort

Short Worksheet menu (for Microsoft Excel version 3 compatibility)

xlChartShort

Short Chart menu (for Microsoft Excel version 3 compatibility)

xlWorksheet4

Old worksheet menu bar (for Microsoft Excel version 4 compatibility)

xlChart4

Old chart menu bar (for Microsoft Excel version 4 compatibility)

Example

This example resets all menu bars in Microsoft Excel.

For Each mb In MenuBars
    mb.Reset
Next mb

This example adds a new menu to the module menu bar.

MenuBars(xlModule).Menus.Add Caption:="&More Help"


MenuItem Object

Description

Represents an item on a menu (either a command or a separator bar).

Accessors

The MenuItem object is a member of the MenuItems collection. The MenuItems collection contains all of the menu items (the commands and command separators) on a menu. Use the Add method to create a new menu item and add it to a menu. Use the AddMenu method to add a submenu. To access a single member of the collection, use the MenuItems method with the index number or caption of the menu item as an argument.

The menu item index number indicates its position on the menu. MenuItems(1) is the item at the top of the menu; MenuItems(MenuItems.Count) is at the bottom. Remember that menu item separators (lines across the menu) are included in the collection of menu items. The following example adds a check mark to the left of menu item one on the Help menu of the Visual Basic Module menu bar.

MenuBars(xlModule).Menus("help").MenuItems(1).Checked = True

Use the Caption property to set or return the menu item caption. The following example adds a new menu item to the Help menu of the Visual Basic Module menu bar and then disables the menu item.

MenuBars(xlModule).Menus("help").MenuItems.Add "More Help"
MenuBars(xlModule).Menus("help").MenuItems("More Help").Enabled = False

The following example creates a table on worksheet one that contains the captions of all the menu items on all the menus on the Worksheet menu bar. The column headings are the menu captions, and the column entries under each heading are the menu item captions on that menu.

Sub EnumerateMenuItems()
    Worksheets(1).Activate
    c = 1
    For Each mn In MenuBars(xlWorksheet).Menus
        r = 1
        Cells(r, c) = mn.Caption
        r = r + 1
        For Each mi In mn.MenuItems
            Cells(r, c) = mi.Caption
            r = r + 1
        Next
        c = c + 1
    Next
End Sub

Properties

Application Property, Caption Property, Checked Property, Creator Property, Enabled Property, HelpContextID Property, HelpFile Property, Index Property, OnAction Property, Parent Property, StatusBar Property.

Methods

Delete Method.


MenuItems Collection Object

Description

A collection of all the MenuItem objects on the specified menu.

Accessors

Use the Add method to add a new menu item to a menu. Use the AddMenu method to add a submenu. The following example adds a new menu item to the Help menu on the Visual Basic Module menu bar.

MenuBars(xlModule).Menus("help").MenuItems.Add "More Help"

Use the MenuItems method with an argument to access a single member of the collection or without an argument to access the entire collection at once. The following example creates a list on worksheet one that contains the menu items in the File menu on the Visual Basic Module menu bar.

Sub EnumerateFileMenu()
    Worksheets(1).Activate
    For r = 1 To MenuBars(xlModule).Menus("file").MenuItems.Count
        Worksheets(1).Cells(r, 1) = MenuBars(xlModule). _
            Menus("file").MenuItems(r).Caption
    Next
End Sub

Properties

Application Property, Count Property, Creator Property, Parent Property.

Methods

Add Method (MenuItems Collection), AddMenu Method, Item Method.


MenuItems Method

Applies To

Menu Object.

Description

Accessor. Returns an object that represents a single menu item (a MenuItem object or Menu object, Syntax 1), or a collection of the menu items ( a MenuItems object, Syntax 2) on the menu. Read-only.

This method returns a MenuItem object when the menu item is a command or separator bar, and it returns a Menu object when the menu item is a submenu caption.

Syntax 1

object.MenuItems(index)

Syntax 2

object.MenuItems

object

Required. The Menu object.

index

Required for Syntax 1. The name or number of the menu item.

Remarks

You must apply the MenuItems method twice to return an item on a submenu. The following example sets the Checked property for the mySubMenuItem submenu item on the mySubMenu submenu.

MenuBars(xlModule).Menus("myMenu").MenuItems("mySubMenu") _
    .MenuItems("mySubMenuItem").Checked = True

See Also

Menus Method.

Example

This example adds a menu item to the Help menu on the active menu bar.

With ActiveMenuBar.Menus("Help")
    Set mi = .MenuItems.Add("&More Help", "my_Help_Macro")
End With

This example changes the Open command on the File menu to Open Workbook. The example makes this change to every menu bar in the product.

For Each mb In MenuBars
    mb.Menus("File").MenuItems(2).Caption = "&Open Workbook"
Next mb


Menus Collection Object

Description

A collection of all the Menu objects on the specified menu bar. Each Menu object represents a drop-down menu, shortcut menu, or submenu.

Accessors

Use the Add method to add a new menu to a menu bar. The following example adds a menu to the Visual Basic Module menu bar.

MenuBars(xlModule).Menus.Add "&Debug"

Use the Menus method with an argument to access a single member of the collection or without an argument to access the entire collection at once.

Properties

Application Property, Count Property, Creator Property, Parent Property.

Methods

Add Method (Menus Collection), Item Method.


Menus Method

Applies To

MenuBar Object.

Description

Accessor. Returns a single menu (a Menu object, Syntax 1), or a collection of the menus ( a Menus object, Syntax 2) on the menu bar. Read-only.

Syntax 1

object.Menus(index)

Syntax 2

object.Menus

object

Required. The MenuBar object.

index

Required for Syntax 1. The name of the menu as a string, or the number of the menu. For example, on the worksheet menu bar, you return the Help menu with Menus("Help") or with Menus(8).

See Also

MenuItems Method.

Example

This example adds a new menu to the active menu bar. The menu is added immediately to the left of the Help menu.

ActiveMenuBar.Menus.Add caption:="&MyMenu", before:="Help"

This example changes the Open command on the File menu to Open Workbook. The example makes this change to every menu bar in the product.

For Each mb In MenuBars
    mb.Menus("File").MenuItems(2).Caption = "&Open Workbook"
Next mb


Merge Method

Applies To

Styles Collection.

Description

Syntax 1: Merges the scenarios from another sheet into the collection of scenarios.

Syntax 2: Merges the styles from another workbook into the collection of styles.

Syntax 1

object.Merge(source)

Syntax 2

object.Merge(workbook)

object

Required. The Scenarios or Styles object.

source

Required for Syntax 1. The Worksheet object, or name of the sheet containing scenarios to merge.

workbook

Required for Syntax 2. The Workbook object containing styles to merge.

Example

This example merges the styles from the workbook TEMPLATE.XLS into the active workbook.

ActiveWorkbook.Styles.Merge Workbook:=Workbooks("TEMPLATE.XLS")


Message Property

Applies To

RoutingSlip Object.

Description

Returns or sets the message text of the routing slip. This text is used as the body text of mail messages used to route the workbook. Read-write.

See Also

Subject Property.

Example

This example sends BOOK1.XLS to three recipients, one after the other.

Workbooks("BOOK1.XLS").HasRoutingSlip = True
With Workbooks("BOOK1.XLS").RoutingSlip
    .Delivery = xlOneAfterAnother
    .Recipients = Array("Adam Bendel", "Jean Selva", "Bernard Gabor")
    .Subject = "Here is BOOK1.XLS"
    .Message = "Here is the workbook. What do you think?"
End With
Workbooks("BOOK1.XLS").Route


Mid Function

Description

Returns a specified number of characters from a string.

Syntax

Mid(string,start[,length])

The Mid function syntax has these parts:

Part | Description
string | String expression from which characters are returned. If string contains no valid data, Null is returned.
start | Character position in string at which the part to be taken begins. If start is greater than the number of characters in string, Mid returns a zero-length string.
length | Number of characters to return. If omitted or if there are fewer than length characters in the text (including the character at start), all characters from the start position to the end of the string are returned.

Remarks

To determine the number of characters in string, use the Len function.

Note

Another function (MidB) is provided for use with the double-byte character sets (DBCS) used in some Asian locales. Instead of specifying the number of characters to return, length specifies the number of bytes. In areas where DBCS is not used, MidB behaves the same as Mid.

See Also

Left Function; Len Function; LTrim, RTrim, and Trim Functions; Mid Statement; Right Function.

Example

This example uses the Mid function to return a specified number of characters from a string.

MyString = "Mid Function Demo"    ' Create text string.
FirstWord = Mid(MyString, 1, 3)    ' Returns "Mid".
LastWord = Mid(MyString, 14, 4)    ' Returns "Demo".
MidWords = Mid(MyString, 5)    ' Returns "Function Demo".


Mid Statement

Description

Replaces a specified number of characters in a string variable with characters from another string.

Syntax

Mid(stringvar,start[,length]) =string

The Mid statement syntax has these parts:

Part | Description
stringvar | Name of string variable to modify.
start | Character position in stringvar where the replacement of text begins.
length | Number of characters to replace. If omitted, all of string is used.
string | String expression that replaces part of stringvar.

Remarks

The number of characters replaced is always less than or equal to the number of characters in stringvar.

See Also

Mid Function.

Example

This example uses the Mid statement to replace a specified number of characters in a string variable with characters from another string.

MyString = "The dog jumps"    ' Initialize string.
Mid(MyString, 5, 3) = "fox"    ' MyString = "The fox jumps".
Mid(MyString, 5) = "cow"    ' MyString = "The cow jumps".
Mid(MyString, 5) = "cow jumped over"    ' MyString = "The cow jumpe".
Mid(MyString, 5, 3) = "duck"    ' MyString = "The duc jumps".


Min Property

Applies To

DrawingObjects Collection, ScrollBar Object, ScrollBars Collection, Spinner Object, Spinners Collection.

Description

Returns or sets the minimum value of a scroll bar or spinner range. The scroll bar or spinner will not take on values below this minimum value. Read-write.

For help about using the Min worksheet function in Visual Basic, see "Using Worksheet Functions in Visual Basic" in online Help.

Remarks

The value of the Min property must be less than the value of the Max property.

See Also

Max Property.

Example

This example sets the minimum and maximum values for scroll bar one on Dialog1.

With DialogSheets("Dialog1").ScrollBars(1)
    .Min = 20
    .Max = 50
End With


MinimumScale Property

Applies To

Axis Object.

Description

Returns or sets the minimum value on the value axis. Applies only to the value axis. Read-write.

Remarks

Setting this property sets the MinimumScaleIsAuto property to False.

See Also

MaximumScale Property, MaximumScaleIsAuto Property, MinimumScaleIsAuto Property.

Example

This example sets the maximum and minimum values for the value axis in Chart1.

With Charts("Chart1").Axes(xlValue)
    .MinimumScale = 10
    .MaximumScale = 120
End With


MinimumScaleIsAuto Property

Applies To

Axis Object.

Description

True if Microsoft Excel calculates the minimum value for the value axis. Applies only to the value axis. Read-write.

Remarks

Setting the MinimumScale property sets this property to False.

See Also

MaximumScale Property, MaximumScaleIsAuto Property, MinimumScale Property.

Example

This example automatically calculates the maximum scale and minimum scale for the value axis in Chart1.

With Charts("Chart1").Axes(xlValue)
    .MinimumScaleIsAuto = True
    .MaximumScaleIsAuto = True
End With


MinorGridlines Property

Applies To

Axis Object.

Description

Accessor. Returns a Gridlines object that represents the minor gridlines for the specified axis. Only axes in the primary axis group can have gridlines. Read-only.

See Also

AxisGroup Property, HasMajorGridlines Property, HasMinorGridlines Property, MajorGridlines Property.

Example

This example sets the color of the minor gridlines for the value axis in Chart1.

With Charts("Chart1").Axes(xlValue)
    If .HasMinorGridlines Then
        .MinorGridlines.Border.ColorIndex = 5    '' 273.'set color to blue
    End If
End With


MinorTickMark Property

Applies To

Axis Object.

Description

Returns or sets the type of minor tick mark for the specified axis (one of xlNone, xlInside, xlOutside, or xlCross). Read-write.

See Also

MajorTickMark Property.

Example

This example sets the minor tick marks for the value axis in Chart1 to be inside the axis.

Charts("Chart1").Axes(xlValue).MinorTickMark = xlInside


MinorUnit Property

Applies To

Axis Object.

Description

Returns or sets the minor units on the value axis. Applies only to the value axis. Read-write.

Remarks

Setting this property sets the MinorUnitIsAuto property to False.

Use the TickMarkSpacing property to set tick mark spacing on the category axis.

See Also

MajorUnit Property, MajorUnitIsAuto Property, MinorUnitIsAuto Property, TickMarkSpacing Property.

Example

This example sets the major and minor units for the value axis in Chart1.

With Charts("Chart1").Axes(xlValue)
    .MajorUnit = 100
    .MinorUnit = 20
End With


MinorUnitIsAuto Property

Applies To

Axis Object.

Description

True if Microsoft Excel calculates minor units for the value axis. Applies only to the value axis. Read-write.

Remarks

Setting the MinorUnit property sets this property to False.

See Also

MajorUnit Property, MajorUnitIsAuto Property, MinorUnit Property.

Example

This example automatically calculates major and minor units for the value axis in Chart1.

With Charts("Chart1").Axes(xlValue)
    .MajorUnitIsAuto = True
    .MinorUnitIsAuto = True
End With


Minute Function

Description

Returns a whole number between 0 and 59, inclusive, representing the minute of the hour.

Syntax

Minute(time)

The time named argument is limited to a time or numbers and strings, in any combination, that can represent a time. If time contains no valid data, Null is returned.

See Also

Day Function, Hour Function, Now Function, Second Function, Time Function, Time Statement.

Example

This example uses the Minute function to obtain the minute of the hour from a specified time.

' In the development environment, the time (date literal) will display
' in short format using the locale settings of your code.
MyTime = #4:35:17 PM#    ' Assign a time.
MyMinute = Minute(MyTime)    ' MyMinute contains 35.


MkDir Statement

Description

Creates a new directory or folder.

Syntax

MkDir path

The path named argument is a string expression that identifies the directory or folder to be created — may include drive. If no drive is specified, MkDir creates the new directory or folder on the current drive.

Remarks

In Microsoft Windows, if you use MkDir to create a directory whose name contains an embedded space, you may be able to access it with some applications, but you can't remove it using standard operating system commands. To remove such a directory, use the RmDir statement.

See Also

ChDir Statement, CurDir Function, RmDir Statement.

Example

This example uses the MkDir statement to create a directory or folder. If the drive is not specified, the new directory or folder is created on the current drive.

MkDir "MYDIR"    ' Make new directory or folder.


Mod Operator

Description

Divides two numbers and returns only the remainder.

Syntax

result = number1 Mod number2

The Mod operator syntax has these parts:

Part | Description
result | Any numeric variable.
number1 | Any numeric expression.
number2 | Any numeric expression.

Remarks

The modulus, or remainder, operator divides number1 by number2 (rounding floating-point numbers to integers) and returns only the remainder as result. For example, in the following expression, A (which is result) equals 5.

A = 19 Mod 6.7

Usually, the data type of result is an Integer, Integer variant, Long, or Variant containing a Long, regardless of whether or not result is a whole number. Any fractional portion is truncated. However, if any expression is a Null, result is also a Null. Any expression that is Empty is treated as 0.

See Also

Operator Precedence.

Example

This example uses the Mod operator to divide two numbers and return only the remainder. If either number is a floating-point number, it is first rounded to an integer.

MyResult = 10 Mod 5    ' Returns 0.
MyResult = 10 Mod 3    ' Returns 1.
MyResult = 12 Mod 4.3    ' Returns 0.
MyResult = 12.6 Mod 5    ' Returns 3.

This example sets the column width of every other column on Sheet1 to 4 points.

For Each col In Worksheets("Sheet1").Columns
    If col.Column Mod 2 = 0 Then
        col.ColumnWidth = 4
    End If
Next col

This example sets the row height of every other row on Sheet1 to 4 points.

For Each rw In Worksheets("Sheet1").Rows
    If rw.Row Mod 2 = 0 Then
        rw.RowHeight = 4
    End If
Next rw

This example selects every other item in list box one on Sheet1.

Dim items() As Boolean
Set lbox = Worksheets("Sheet1").ListBoxes(1)
ReDim items(1 To lbox.ListCount)
For i = 1 To lbox.ListCount
    If i Mod 2 = 1 Then
        items(i) = True
    Else
        items(i) = False
    End If
Next
lbox.MultiSelect = xlExtended
lbox.Selected = items


Module Object

Description

Represents a Visual Basic module in a workbook.

Accessors

The Module object is a member of the Modules collection. The Modules collection contains all the Module objects in a workbook. Use the Add method to create a new module and add it to the collection. To access a single member of the collection, use the Modules method with the index number or name of the module as an argument.

The module index number represents the position of the module on the tab bar of the workbook. Modules(1) is the first (leftmost) module in the workbook; Modules(Modules.Count) is the last. All modules are included in the index count, even if they are hidden.

The following example hides module two in the active workbook.

Modules(2).Visible = False

The module name is shown on the workbook tab for the module. Use the Name property to set or return the module name (you cannot change the name of the module where the Visual Basic code is running, however). The following example protects the Visual Basic code on the module named "Sample Code."

Modules("sample code").Protect password:="drowssap", contents:=True

The Module object is also a member of the Sheets collection. The Sheets collection contains all of the sheets in the workbook (chart sheets, dialog sheets, modules, and worksheets). To access a single member of the collection, use the Sheets method with the index number or name of the sheet as an argument.

Using ActiveSheet

When a module is the active sheet, you can use the ActiveSheet property to refer to it. The following example uses the Activate method to activate the module named "Module1" and then protects the module.

Modules("module1").Activate
ActiveSheet.Protect

Properties

Application Property, Creator Property, Index Property, Name Property, Next Property, OnDoubleClick Property, OnSheetActivate Property, OnSheetDeactivate Property, PageSetup Property, Parent Property, Previous Property, ProtectContents Property, Visible Property.

Methods

Activate Method, Copy Method, Delete Method, InsertFile Method, Move Method, PrintOut Method, Protect Method, SaveAs Method, Select Method, Unprotect Method.


Modules Collection Object

Description

A collection of all the Module objects in the specified or active workbook.

Accessors

Use the Add method to create a new module and add it to the collection. The following example adds a new module before sheet one in the active workbook.

Modules.Add before:=Sheets(1)

Use the Modules method to with an argument to access a single member of the collection or without an argument to access the entire collection at once. The following example moves all the modules in the active workbook to the end of the workbook.

Modules.Move after:=Sheets(Sheets.Count)

The Sheets collection contains all of the sheets in the workbook (chart sheets, dialog sheets, modules, and worksheets). Use the Sheets method with an argument to access a single member of the collection or without an argument to access the entire collection at once.

Properties

Application Property, Count Property, Creator Property, Parent Property, Visible Property.

Methods

Add Method (Modules Collection), Copy Method, Delete Method, Item Method, Move Method, PrintOut Method, Select Method.


Modules Method

Applies To

Application Object, Workbook Object.

Description

Accessor. Returns an object that represents a module (a Module object, Syntax 1) or a collection of all modules (a Modules object, Syntax 2) in the workbook. Read-only.

Syntax 1

object.Modules(index)

Syntax 2

object.Modules

object

Required. The Workbook object.

index

Required for Syntax 1. The name or number of the module to return.

Example

This example creates a new Visual Basic module in the active workbook and then inserts the file TESTCODE.TXT into the new module.

Set newModule = Modules.Add
newModule.InsertFile fileName:="testcode.txt"


Month Function

Description

Returns a whole number between 1 and 12, inclusive, representing the month of the year.

Syntax

Month(date)

The date named argument is limited to a date or numbers and strings, in any combination, that can represent a date. If date contains no valid data, Null is returned.

See Also

Date Function, Date Statement, Day Function, Now Function, Weekday Function, Year Function.

Example

This example uses the Month function to obtain the month from a specified date.

' In the development environment, the date literal will display in short
' format using the locale settings of your code.
MyDate = #February 12, 1969#    ' Assign a date.
MyMonth = Month(MyDate)    ' MyMonth contains 2.


MouseAvailable Property

Applies To

Application Object.

Description

True if a mouse is available (always True on the Macintosh). Read-only.

Example

This example displays a message if a mouse is not available.

If Application.MouseAvailable = False Then
    MsgBox "Your system does not have a mouse"
End If


Move Method

Applies To

Chart Object, Charts Collection, DialogSheet Object, DialogSheets Collection, Module Object, Modules Collection, Sheets Collection, ToolbarButton Object, Worksheet Object, Worksheets Collection.

Description

Syntax 1: Moves the sheet to another location in the workbook.

Syntax 2: Moves a toolbar button to another position, either on the same toolbar or to another toolbar.

Syntax 1

object.Move(before, after)

Syntax 2

object.Move(toolbar, before)

object

Required. The object to which this method applies.

before

Syntax 1: Optional. The sheet before which this sheet will be moved. You cannot specify before if you specify after.

Syntax 2: Required. Specifies the new button position as a number from 1 to the number of existing buttons + 1. Gaps count as one position. Buttons to the right of this position are moved right (or down) to make room for the moved button.

after

Optional. The sheet after which this sheet will be moved. You cannot specify after if you specify before.

toolbar

Required for Syntax 2. Specifies the toolbar object to move the button to.

Remarks

If you do not specify either before or after, Microsoft Excel creates a new workbook containing the moved sheet.

See Also

Copy Method.

Example

This example moves Sheet1 after Sheet3 in the active workbook.

Worksheets("Sheet1").Move _
    after:=Worksheets("Sheet3")


MoveAfterReturn Property

Applies To

Application Object.

Description

True if the active cell will be moved as soon as the ENTER (RETURN) key is pressed. Read-write.

Remarks

Use the MoveAfterReturnDirection property to specify the direction in which the active cell is moved.

See Also

MoveAfterReturnDirection Property.

Example

This example sets the MoveAfterReturn property to True.

Application.MoveAfterReturn = True


MoveAfterReturnDirection Property

Applies To

Application Object.

Description

Returns or sets how the active cell is moved after the user presses ENTER (one of xlToLeft, xlToRight, xlUp, or xlDown). This property is available only in Microsoft Excel for Windows 95. Read-write.

Remarks

If the MoveAfterReturn property is False, the selection doesn't move at all, regardless of how the MoveAfterReturnDirection property is set.

See Also

MoveAfterReturn Property.

Example

This example causes the active cell to move to the right when the user presses ENTER.

Application.MoveAfterReturn = True
Application.MoveAfterReturnDirection = xlToRight

Application.MoveAfterReturnDirection = xlToRight


MsgBox Function

Description

Displays a message in a dialog box, waits for the user to choose a button, and returns a value indicating which button the user has chosen.

Syntax

MsgBox(prompt[,buttons][,title][,helpfile,context])

The MsgBox function syntax has these named-argument parts:

Part | Description
prompt | String expression displayed as the message in the dialog box. The maximum length of prompt is approximately 1024 characters, depending on the width of the characters used. If prompt consists of more than one line, be sure to include a carriage return (character code 13) or carriage return linefeed (character code 10) between each line.
buttons | Numeric expression that is the sum of values specifying the number and type of buttons to display, the icon style to use, the identity of the default button, and the modality. If omitted, the default value for buttons is 0.
title | String expression displayed in the title bar of the dialog box. If you omit title, nothing is placed in the title bar.
helpfile | String expression that identifies the Help file to use to provide context-sensitive Help for the dialog box. If helpfile is provided, context must also be provided.
context | Numeric expression that is the Help context number the Help author assigned to the appropriate Help topic. If context is provided, helpfile must also be provided.

The buttons named argument has these values:

Constant | Value | Description
vbOKOnly | 0 | Display OK button only.
vbOKCancel | 1 | Display OK and Cancel buttons.
vbAbortRetryIgnore | 2 | Display Abort, Retry, and Ignore buttons.
vbYesNoCancel | 3 | Display Yes, No, and Cancel buttons.
vbYesNo | 4 | Display Yes and No buttons.
vbRetryCancel | 5 | Display Retry and Cancel buttons.
vbCritical | 16 | Display Critical Message icon.
vbQuestion | 32 | Display Warning Query icon.
vbExclamation | 48 | Display Warning Message icon.
vbInformation | 64 | Display Information Message icon.
vbDefaultButton1 | 0 | First button is default.
vbDefaultButton2 | 256 | Second button is default.
vbDefaultButton3 | 512 | Third button is default.
vbApplicationModal | 0 | Application modal; the user must respond to the message box before continuing work in the current application.
vbSystemModal | 4096 | System modal; all applications are suspended until the user responds to the message box.

The first group of values (0-5) describes the number and type of buttons displayed in the dialog box; the second group (16, 32, 48, 64) describes the icon style; the third group (0, 256, 512) determines which button is the default, and the fourth group (0, 4096) determines the modality of the message box. When adding numbers to create a final value for the argument buttons, use only one number from each group.

Note

These constants are specified by Visual Basic. As a result, the names can be used anywhere in your code in place of the actual values.

Return Values

Constant | Value | Button Selected
vbOK | 1 | OK
vbCancel | 2 | Cancel
vbAbort | 3 | Abort
vbRetry | 4 | Retry
vbIgnore | 5 | Ignore
vbYes | 6 | Yes
vbNo | 7 | No

Remarks

When both helpfile and context are provided, a Help button is automatically added to the dialog box.

If the dialog box displays a Cancel button, pressing the ESC key has the same effect as choosing Cancel. If the dialog box contains a Help button, context-sensitive Help is provided for the dialog box. However, no value is returned until one of the other buttons is chosen.

In Microsoft Excel, the prompt string cannot contain more than 256 characters.

See Also

InputBox Function.

Example

The example uses the MsgBox function to display a critical-error message in a dialog box with Yes and No buttons. The No button is specified as the default response. The value returned by the MsgBox function depends on the button chosen by the user. For purposes of this example, assume that DEMO.HLP is a Help file that contains a topic with context number equal to 1000.

Msg = "Do you want to continue ?"    ' Define message.
Style = vbYesNo + vbCritical + vbDefaultButton2    ' Define buttons.
Title = "MsgBox Demonstration"    ' Define title.
Help = "DEMO.HLP"    ' Define help file.
Ctxt = 1000    ' Define topic
    ' context.
' Display message.
Response = MsgBox(Msg, Style, Title, Help, Ctxt)
If Response = vbYES Then    ' User chose Yes
    ' button.
    MyString = "Yes"    ' Perform some action.
Else    ' User chose No
    ' button.
    MyString = "No"    ' Perform some action.
End If


MultiLine Property

Applies To

DrawingObjects Collection, EditBox Object, EditBoxes Collection.

Description

True if the edit box is multi-line enabled. Read-write.

Example

This example enables multiline input for edit box one on Dialog1.

DialogSheets("Dialog1").EditBoxes(1).MultiLine = True


MultiSelect Property

Applies To

DrawingObjects Collection, ListBox Object, ListBoxes Collection.

Description

Returns or sets the selection mode of the list box (or collection of list boxes). Can be one of xlNone, xlSimple, or xlExtended. Read-write.

Remarks

Single select (xlNone) allows only one item at a time to be selected. Any click or spacebar press deselects the currently selected item and selects the clicked-upon item.

Simple multi-select (xlSimple) toggles the selection on an item in the list when it is selected with the mouse or the spacebar is pressed when the focus is on the item. This mode is appropriate for pick lists where multiple items are often selected.

Extended multi-select (xlExtended) normally acts like a single-selection list box, so that mouse clicks on an item cancel all other selected items. When you hold down SHIFT while clicking the mouse or pressing an ARROW key, items are sequentially selected from the current item as the user navigates. When you hold down CTRL while clicking the mouse, single items are added to the list selection. This mode is appropriate when multiple items are allowed but not often used.

You can use the Value or ListIndex properties to get and set the selected item in a single-select list box. You must use the Selected property to get and set the selected items in a multi-select list box.

Multi-select list boxes cannot be linked to cells with the LinkedCell property.

See Also

ListIndex Property, Selected Property, Value Property.

Example

This example sets list box one on Dialog1 to allow extended multiple selections.

DialogSheets("Dialog1").ListBoxes(1).MultiSelect = xlExtended


MultiUserEditing Property

Applies To

Workbook Object.

Description

True if the workbook is open as a shared list. This property is available only in Microsoft Excel for Windows 95. Read-only.

Remarks

To save a workbook as a shared list, use the SaveAs method. To change the workbook from shared mode to exclusive mode, use the ExclusiveAccess method.

See Also

ExclusiveAccess Method, SaveAs Method, UserStatus Property.

Example

This example determines whether the active workbook is open as a shared list. If it is, the example notifies the user that the macros in the active workbook cannot be modified.

If ActiveWorkbook.MultiUserEditing Then
    MsgBox "Cannot modify Visual Basic modules in this workbook."
End If

This example determines whether the active workbook is open in exclusive mode. If it is, the example saves it as a shared list.

If Not ActiveWorkbook.MultiUserEditing Then
    ActiveWorkbook.SaveAs accessMode := xlShared
End If


Name Object

Description

Represents a defined name for a range of cells. Names can be built-in, such as Database, Print_Area, and Auto_Open, or they can be custom names.

Application, Workbook, and Worksheet Objects

The Name object is a member of the Names collection for the Application,Workbook, and Worksheet objects. Use the Add method to create a new name and add it to the collection. To access a single member of the collection, use the Names method with the index number or name of the defined name as an argument.

The index number indicates the position of the name within the collection. Names are placed in alphabetical order from a to z and are not case-sensitive (this is the same order as is displayed in the Define Name and Apply Names dialog boxes, accessed by clicking the Name command on the Insert menu). The following example displays the cell reference for name one in the application collection.

MsgBox Names(1).RefersTo

Use the Name property on a Name object to return or set the text of the name itself. The following example changes the name of the first Name object in the active workbook.

Names(1).Name = "stock_values"

The following example deletes the name "mySortRange" from the active workbook.

ActiveWorkbook.Names("mySortRange").Delete

Range Objects

While a Range object can have more than one name, there is no Names collection for the Range object. The Name property of the Range object returns the first name (sorted alphabetically) assigned to the range. The following sets the Visible property for the first name assigned to cells A1:B1 on worksheet one.

Worksheets(1).Range("a1:b1").Name.Visible = False

Properties

Application Property, Category Property, CategoryLocal Property, Creator Property, Index Property, MacroType Property, Name Property, NameLocal Property, Parent Property, RefersTo Property, RefersToLocal Property, RefersToR1C1 Property, RefersToR1C1Local Property, RefersToRange Property, ShortcutKey Property, Value Property, Visible Property.

Methods

Delete Method.


Name Property

Applies To

AddIn Object, Application Object, Arc Object, AxisTitle Object, Button Object, Chart Object, ChartArea Object, ChartObject Object, ChartTitle Object, CheckBox Object, Corners Object, DataLabel Object, DataLabels Collection, DialogFrame Object, DialogSheet Object, DownBars Object, Drawing Object, DropDown Object, DropLines Object, EditBox Object, ErrorBars Object, Floor Object, Font Object, Gridlines Object, GroupBox Object, GroupObject Object, HiLoLines Object, Label Object, Legend Object, Line Object, ListBox Object, Module Object, Name Object, OLEObject Object, OptionButton Object, Oval Object, Picture Object, PivotField Object, PivotItem Object, PivotTable Object, PlotArea Object, Range Object, Rectangle Object, Scenario Object, ScrollBar Object, Series Object, SeriesLines Object, Spinner Object, Style Object, TextBox Object, TickLabels Object, Toolbar Object, ToolbarButton Object, Trendline Object, UpBars Object, Walls Object, Workbook Object, Worksheet Object.

Description

Returns or sets the name of the object. See the Remarks section for details.

Remarks

The meaning of this property depends on the object, as shown in the following table. The name of a Range object is a Name object. For every other object, the name is a string.

Object | Name
AddIn | The filename of the add-in, not including its path on disk. Read-only.
Application | The name of the application. Read-only.
Chart | If the chart is a page in the workbook, this is the name of that page as shown on the tab. If the chart is an embedded object, it is the name of the object. Read-write.
Control or drawing object | The name of the control or drawing object, in the language of the macro. Read-write.
DataLabel | The name of the data label. Read-only.
DialogSheet, Module, Worksheet | The name of the sheet, as shown on the tab. Read-write.
Font | The name of the font.
Legend | The name of the legend. Read-only.
Name | The name itself. If it is one of the built-in names it will be translated to the language of the macro. Read-write.
OLEObject | The name of the object. Read-write.
PivotField | The name of the field in the PivotTable. Read-write.
PivotItem | The name of the item in the PivotTable field. Read-write.
PivotTable | The name of the PivotTable. Read-write.
Range | The name of the range (this is a Name object). Assign to this property to define a name. If the range has multiple names, returns the first one. Read-write.
Scenario | The name of the scenario. Read-write.
Series | The name of the series. Read-write.
Style | The name of the style. If the style is a built-in style, this will return the name of the style in the language of the macro. Read only.
Toolbar | The name of the toolbar, as a string. If the toolbar is built-in, returns the name in the language of the user. Read only.
ToolbarButton | The name of the button, as a string. Read-write.
Trendline | The name of the trendline as it will appear in the legend. Read-write.
Workbook | The name of the workbook, not including its path on disk. Read-only .

See Also

NameLocal Property.

Example

This example displays the name and localized name of style one in the active workbook.

With ActiveWorkbook.Styles(1)
    MsgBox "The name of the style is " & .Name
    MsgBox "The localized name of the style is " & .NameLocal
End With


Name Property (DocumentProperty Object)

Applies To

DocumentProperty Object.

Description

Returns or sets the name of the document property. Read-only for built-in document properties; read-write for custom document properties.

To use this property, you should establish a reference to the Microsoft Office 95 Object Library by using the References command (Tools menu).

For a list of valid built-in document property names, see the Item method.

Example

This example displays the name, type, and value of a document property. You must pass a DocumentProperty object to the procedure.

Sub DisplayPropertyInfo(dp As DocumentProperty)
    MsgBox "value = " & dp.Value & Chr(13) & _
        "type = " & dp.Type & Chr(13) & _
        "name = " & dp.Name
End Sub

This example displays the name of custom document property one in the active workbook.

MsgBox ActiveWorkbook.CustomDocumentProperties(1).Name


Name Statement

Description

Renames a disk file, directory, or folder.

Syntax

Name oldpathname As newpathname

The Name statement syntax has these parts:

Part | Description
oldpathname | String expression that specifies the existing file name and location — may include directory or folder, and drive.
newpathname | String expression that specifies the new file name and location — may include directory or folder, and drive. The file specified by newpathname can't already exist.

Remarks

Both newpathname and oldpathname must be on the same drive. If the path in newpathname exists and is different from the path in oldpathname, the Name statement moves the file to the new directory or folder and renames the file, if necessary. If newpathname and oldpathname have different paths and the same file name, Name moves the file to the new location and leaves the file name unchanged. Using Name, you can move a file from one directory or folder to another, but you can't move a directory or folder.

Name supports the use of '*' (multiple character) and '?' (single character) wildcards. However, on the Macintosh, these characters are treated as valid file name characters and can't be used as wildcards to specify multiple files.

Using Name on an open file produces an error. You must close an open file before renaming it.

See Also

Kill Statement.

Example

This example uses the Name statement to rename a file. For purposes of this example, assume that the directories or folders that are specified already exist.

OldName = "OLDFILE" : NewName = "NEWFILE"    ' Define file names.
Name OldName As NewName    ' Rename file.

' In Microsoft Windows.
OldName = "C:\MYDIR\OLDFILE" : NewName = "C:\YOURDIR\NEWFILE"
Name OldName As NewName    ' Move and rename file.

' On the Macintosh.
OldName = "HD:MY FOLDER:OLDFILE" : NewName = "HD:YOUR FOLDER:NEWFILE"
Name OldName As NewName    ' Move and rename file.


NameIsAuto Property

Applies To

Trendline Object.

Description

True if Microsoft Excel automatically determines the name of the trendline. Read-write.

Example

This example causes Microsoft Excel to automatically determine the name for trendline one in Chart1. The example should be run on a 2-D column chart that contains a single series with a trendline.

Charts("Chart1").SeriesCollection(1).Trendlines(1).NameIsAuto = True


NameLocal Property

Applies To

Name Object, Style Object.

Description

Returns or sets the name of the object, in the language of the user. Read-write for Name, read-only for Style.

Remarks

If the style is a built-in style, this property returns the name of the style in the language of the current locale.

See Also

Name Property.

Example

This example displays the name and localized name of style one in the active workbook.

With ActiveWorkbook.Styles(1)
    MsgBox "The name of the style is " & .Name
    MsgBox "The localized name of the style is " & .NameLocal
End With


Names Collection Object

Description

A collection of all the Name objects in the specified or active workbook. Each Name object represents a defined name for a range of cells. Names can be built-in, such as Database, Print_Area, and Auto_Open, or they can be custom names.

Accessors

Use the Names method with an argument to access a single member of the collection or without an argument to access the entire collection at once.

Use the Add method to create a name and add it to the collection. The refersTo argument must be specified in A1-style notation, including dollar signs ($) where appropriate. For example, if cell A10 is selected on sheet1, and you define a name using the refersTo argument "=sheet1!A1:B1", the new name actually refers to cells A10:B10 (because you specified a relative reference). To specify an absolute reference, use "=sheet1!$A$1:$B$1".

The following example creates a new name that refers to cells A1:C20 on the worksheet named "Sheet1."

Names.Add "test", "=sheet1!$a$1:$c$20"

Properties

Application Property, Count Property, Creator Property, Parent Property.

Methods

Add Method (Names Collection), Item Method.


Names Method

Applies To

Application Object, Workbook Object, Worksheet Object.

Description

Accessor. Returns an object that represents a single name (a Name object, Syntax 1) or a collection of names (the Names object, Syntax 2). Read-only.

Syntax 1

object.Names(index, indexLocal, refersTo)

Syntax 2

object.Names

object

Optional for Application, required for Workbook and Worksheet. Specifies the object containing names to return.

index

Optional (Syntax 1 requires one of the three arguments). The name or number of the defined name to return.

indexLocal

Optional (Syntax 1 requires one of the three arguments). The name of the defined name, in the language of the user. No names will be translated if you use this argument.

refersTo

Optional (Syntax 1 requires one of the three arguments). What the name refers to. This allows you to get a name by what it refers to.

Remarks

For Syntax 1, you must specify one (and only one) of the three arguments.

This method returns worksheet-specific names (names defined with the "WorksheetName!" prefix) for the Worksheet object.

This method returns names in the specified workbook (including all worksheet-specific names) for the Workbook object, and names in the active workbook for the Application object.

Example

This example defines the name myName for cell A1 on Sheet1.

ActiveWorkbook.Names.Add Name:="myName", RefersToR1C1:= _
    "=Sheet1!R1C1"

This example deletes every defined name that contains "temp" in the name. The Option Compare Text statement must be included at the top of any module that contains this example.

For Each nm In ActiveWorkbook.Names
    If nm.Name Like "*temp*" Then
        nm.Delete
    End If
Next nm


NavigateArrow Method

Applies To

Range Object.

Description

Navigates a tracer arrow for the specified range to the precedent, dependent, or error-causing cell or cells. Selects the precedent, dependent, or error cell and returns a Range object that represents the new selection. This method causes an error if applied to a cell without visible tracer arrows.

Syntax

object.NavigateArrow(towardPrecedent, arrowNumber, linkNumber)

object

Required. The Range object.

towardPrecedent

Required. Specifies the direction to navigate (True to navigate toward precedents or False to navigate toward dependents).

arrowNumber

Required. Specifies the arrow number to navigate, corresponding to the numbered reference in the cell's formula.

linkNumber

Optional. If the arrow is an external reference arrow, this argument indicates which external reference to follow. If this argument is omitted, the first external reference is followed.

Example

This example navigates along the first tracer arrow from cell A1 on Sheet1 toward the precedent cell. The example should be run on a worksheet containing a formula in cell A1 that uses cells D1, D2, and D3 (for example, the formula =D1*D2*D3). Before running the example, display the auditing toolbar, select cell A1, and choose the Trace Precedents button.

Worksheets("Sheet1").Activate
Range("A1").Select
ActiveCell.NavigateArrow True, 1


NetworkTemplatesPath Property

Applies To

Application Object.

Description

Returns the network path where templates are stored. If the network path doesn't exist, the property returns an empty string. This property is available only in Microsoft Excel for Windows 95. Read-only.

Example

This example displays the network path where templates are stored.

Msgbox Application.NetworkTemplatesPath


NewWindow Method

Applies To

Window Object, Workbook Object.

Description

Creates a new window for the workbook, or a copy of the specified window.

Syntax

object.NewWindow

object

Required. The Window or Workbook object.

Example

This example creates a new window for the active workbook.

ActiveWorkbook.NewWindow


Next Property

Applies To

Chart Object, DialogSheet Object, Module Object, Range Object, Worksheet Object.

Description

Accessor. Returns a Chart, DialogSheet, Module, Range or Worksheet object that represents the next sheet or cell. Read-only.

Remarks

If the object is a range, this property emulates the TAB key, although the property returns the next cell without selecting it.

On a protected sheet, this property returns the next unlocked cell. On an unprotected sheet, this property always returns the cell to the right of the specified cell.

See Also

ActivateNext Method, Previous Property.

Example

This example selects the next unlocked cell on Sheet1. If Sheet1 is unprotected, this is the cell immediately to the right of the active cell.

Worksheets("Sheet1").Activate
ActiveCell.Next.Select


NextLetter Method

Applies To

Application Object.

Description

Opens the oldest unread Microsoft Excel letter from the In Tray. Available only in Microsoft Excel for the Apple Macintosh with the PowerTalk mail system extension installed.

Syntax

object.NextLetter

object

Required. The Application object.

Remarks

This method returns a Workbook object for the newly opened workbook, or Null if there are no more workbooks to open.

This method generates an error if it is used in Microsoft Windows.

See Also

MailSystem Property, SendMail Method.

Example

This example opens the oldest unread Microsoft Excel letter from the In Tray.

If Application.MailSystem = xlPowerTalk Then _
    Application.NextLetter


Not Operator

Description

Used to perform logical negation on an expression.

Syntax

result = Not expression

The Not operator syntax has these parts:

Part | Description
result | Any numeric variable.
expression | Any expression.

Remarks

The following table illustrates how result is determined:

If expression is | Then result is
True | False
False | True
Null | Null

In addition, the Not operator inverts the bit values of any variable and sets the corresponding bit in result according to the following truth table:

Bit in expression | Bit in result
0 | 1
1 | 0

See Also

Operator Precedence.

Example

This example uses the Not operator to perform logical negation on an expression.

A = 10: B = 8: C = 6 : D = Null    ' Initialize variables.
MyCheck = Not(A > B)    ' Returns False.
MyCheck = Not(B > A)    ' Returns True.
MyCheck = Not(C > D)    ' Returns Null.
MyCheck = Not A    ' Returns -11 (bit-wise comparison).


NoteText Method

Applies To

Range Object.

Description

Returns or sets the cell note associated with the upper-left cell in this range. Read-write.

Syntax

object.NoteText(text, start, length)

object

Required. The range to which this property applies.

text

Optional. If specified, contains the text to add to the note (up to 255 characters). The text is inserted starting at position start, replacing length characters of the existing note. If this argument is omitted, this method returns the current text of the note starting at position start, for length characters.

start

Optional. Specifies the starting position for the set or returned text. If omitted, this method starts at the first character. This argument is omitted if there is no existing note. Specify a number larger than the number of characters in the existing note to append text to the note.

length

Optional. Specifies the number of characters to set or return. If this argument is omitted, Microsoft Excel sets or returns characters from the start position to the end of the note (up to 255 characters) If there are more than 255 characters from start to the end of the note, this method returns only 255 characters.

Remarks

To add a note containing more than 255 characters, use this method once to specify the first 255 characters, then append the remainder of the note 255 characters at a time.

See Also

ClearNotes Method.

Example

This example sets the cell note text for cell A1 on Sheet1.

Worksheets("Sheet1").Range("A1").NoteText "This may change!"


Now Function

Description

Returns the current date and time according to the setting of your computer's system date and time.

Syntax

Now

Remarks

Note

When displayed directly, the Now function's return value is displayed as a string using the short date and time formats you specified for your system.

See Also

Date Function, Date Statement, Day Function, Hour Function, Minute Function, Month Function, Second Function, Time Function, Time Statement, Weekday Function, Year Function.

Example

This example uses the Now function to return the current system date and time.

Today = Now    ' Get current system date and time.


NumberFormat Property

Applies To

DataLabel Object, DataLabels Collection, PivotField Object, Range Object, Style Object, TickLabels Object.

Description

Returns or sets the format code for the object (as a string). Read-write.

Remarks

For the PivotField object, the NumberFormat property can be set only for a data field.

The format code is the same string as the Format Codes option in the Format Cells dialog box. The Format function uses different format code strings than the NumberFormat and NumberFormatLocal properties.

See Also

NumberFormatLinked Property, NumberFormatLocal Property.

Example

These examples set the number format for cell A17, row one, and column C on Sheet1.

Worksheets("Sheet1").Range("A17").NumberFormat = "General"
Worksheets("Sheet1").Rows(1).NumberFormat = "hh:mm:ss"
Worksheets("Sheet1").Columns("C").NumberFormat = _
    "$#,##0.00_);[Red]($#,##0.00)"


NumberFormatLinked Property

Applies To

DataLabel Object, DataLabels Collection, TickLabels Object.

Description

True if the number format is linked to the cells (so that the number format changes in the labels when it changes in the cells). Read-write.

Example

This example links the tick label number format to its cells for the value axis in Chart1.

Charts("Chart1").Axes(xlValue).TickLabels.NumberFormatLinked = True


NumberFormatLocal Property

Applies To

Range Object, Style Object.

Description

Returns or sets the format code for the object as a string, in the language of the user (not the language of the macro writer). Read-write.

Remarks

The Format function uses different format code strings than the NumberFormat and NumberFormatLocal properties.

See Also

NumberFormat Property.

Example

This example displays the number format for cell A1 on Sheet1, in the language of the user.

MsgBox "The number format for cell A1 is " & _
    Worksheets("Sheet1").Range("A1").NumberFormatLocal


Object Data Type

Description

Object variables are stored as 32-bit (4-byte) addresses that refer to objects within an application. A variable declared as an Object is one that can subsequently be assigned (using the Set statement) to refer to any object produced by the application.

See Also

Data Type Summary, Def type Statements, IsObject Function, Variant Data Type.


Object Property

Applies To

OLEObject Object.

Description

Returns the OLE Automation object associated with this OLE object. Read-only.

Example

This example inserts text at the beginning of an embedded Microsoft Word document object on Sheet1. Note that the three statements in the With control structure are WordBasic statements.

Set wordObj = Worksheets("Sheet1").OLEObjects(1)
wordObj.Activate
With wordObj.Object.Application.WordBasic
    .StartOfDocument
    .Insert "This is the beginning"
    .InsertPara
End With


Oct Function

Description

Returns a string representing the octal value of a number.

Syntax

Oct(number)

The number named argument is any valid numeric expression.

Remarks

If number is not already a whole number, it is rounded to the nearest whole number before being evaluated.

If number is | Oct returns
Null | An error.
Empty | Zero (0).
Any other number | Up to 11 octal characters.

You can represent octal numbers directly by preceding numbers in the proper range with &O. For example, &O10 is the octal notation for decimal 8.

See Also

Hex Function.

Example

This example uses the Oct function to return the octal value of a number.

MyOct = Oct(4)     ' Returns 4.
MyOct = Oct(8)    ' Returns 10.
MyOct = Oct(459)    ' Returns 713.


Offset Method

Applies To

Range Object.

Description

Accessor. Returns a Range object that represents a range at an offset to the specified range.

Syntax

object.Offset(rowOffset, columnOffset)

object

Required. Return a range offset to this one.

rowOffset

Optional. Number of rows (positive, negative, or zero) by which to offset the range. If omitted, zero is assumed.

columnOffset

Optional. Number of columns (positive, negative, or zero) by which to offset the range. If omitted, zero is assumed.

See Also

Address Method.

Example

This example activates the cell three columns to the right of and three rows down from the active cell on Sheet1.

Worksheets("Sheet1").Activate
ActiveCell.Offset(rowOffset:=3, columnOffset:=3).Activate

This example assumes that you have a table on Sheet1 that has a header row. The example selects the table, without selecting the header row. The active cell must be somewhere in the table before you run the example.

Set tbl = ActiveCell.CurrentRegion
tbl.Offset(1, 0).Resize(tbl.Rows.Count - 1, tbl.Columns.Count).Select


OLEObject Object

Description

Represents a linked or embedded OLE object on a chart sheet, dialog sheet, or worksheet. You add an OLE object to a sheet by clicking the Object command on the Insert menu or by using the Add method.

Accessors

The OLEObject object is a member of the OLEObjects collection. The OLEObjects collection contains all of the OLE objects on a single sheet. Use the Add method to create a new OLE object and add it to the collection. To access a single member of the collection, use the OLEObjects method with the index number or name of the OLE object as an argument.

The following example deletes OLE object one on the worksheet named "Sheet1."

Worksheets("sheet1").OLEObjects(1).Delete

The OLE object name is shown in the Name Box when the object is selected. Use the Name property to set or return the object name. The following example lines up the left edge of the OLE object named "Picture 8" with the left edge of column B on the worksheet named "Sheet1."

Worksheets("sheet1").OLEObjects("picture 8").Left = _
    Worksheets("sheet1").Columns("b").Left

Properties

Application Property, AutoLoad Property, AutoUpdate Property, Border Property, BottomRightCell Property, Creator Property, Enabled Property, Height Property, Index Property, Interior Property, Left Property, Locked Property, Name Property, Object Property, OLEType Property, OnAction Property, Parent Property, Placement Property, PrintObject Property, Shadow Property, Top Property, TopLeftCell Property, Visible Property, Width Property, ZOrder Property.

Methods

Activate Method, BringToFront Method, Copy Method, CopyPicture Method, Cut Method, Delete Method, Duplicate Method, Select Method, SendToBack Method, Update Method, Verb Method.


OLEObjects Collection Object

Description

A collection of all the OLEObject objects on the specified chart sheet, dialog sheet, or worksheet.

Accessors

Use the OLEObjects method with an argument to access a single member of the collection or without an argument to access the entire collection at once. Use the Add method to create a new OLE object and add it to the collection. The following example creates a new OLE object representing the bitmap file ARCADE.BMP and adds it to worksheet one.

Worksheets(1).OLEObjects.Add fileName:="arcade.bmp"

Properties

Application Property, Border Property, Count Property, Creator Property, Enabled Property, Height Property, Interior Property, Left Property, Locked Property, OnAction Property, Parent Property, Placement Property, PrintObject Property, Shadow Property, Top Property, Visible Property, Width Property, ZOrder Property.

Methods

Add Method (OLEObjects Collection), BringToFront Method, Copy Method, CopyPicture Method, Cut Method, Delete Method, Duplicate Method, Group Method, Item Method, Select Method, SendToBack Method.


OLEObjects Method

Applies To

Chart Object, DialogSheet Object, Worksheet Object.

Description

Accessor. Returns an object that represents a single OLE Object (an OLEObject, Syntax 1) or a collection of all OLE objects (an OLEObjects collection, Syntax 2) on the chart or sheet. Read-only.

Syntax 1

object.OLEObjects(index)

Syntax 2

object.OLEObjects

object

Required. The Chart, DialogSheet, or Worksheet object.

index

Required for Syntax 1. The name or number of the OLE object.

See Also

Charts Method, OLEType Property.

Example

This example creates a list of link types for OLE objects on Sheet1. The list appears on a new worksheet created by the example.

Set newSheet = Worksheets.Add
i = 2
newSheet.Range("A1").Value = "Name"
newSheet.Range("B1").Value = "Link Type"
For Each obj In Worksheets("Sheet1").OLEObjects
    newSheet.Cells(i, 1).Value = obj.Name
    If obj.OLEType = xlOLELink Then
        newSheet.Cells(i, 2) = "Linked"
    Else
        newSheet.Cells(i, 2) = "Embedded"
    End If
    i = i + 1
Next


OLEType Property

Applies To

OLEObject Object.

Description

Returns xlOLELink if the object is linked (exists outside of the file), or xlOLEEmbed if the object is embedded (is entirely contained within the file). Read-only.

See Also

OLEObjects Method.

Example

This example creates a list of link types for OLE objects on Sheet1. The list appears on a new worksheet created by the example.

Set newSheet = Worksheets.Add
i = 2
newSheet.Range("A1").Value = "Name"
newSheet.Range("B1").Value = "Link Type"
For Each obj In Worksheets("Sheet1").OLEObjects
    newSheet.Cells(i, 1).Value = obj.Name
    If obj.OLEType = xlOLELink Then
        newSheet.Cells(i, 2) = "Linked"
    Else
        newSheet.Cells(i, 2) = "Embedded"
    End If
    i = i + 1
Next


On...GoSub, On...GoTo Statements

Description

Branch to one of several specified lines, depending on the value of an expression.

Syntax

On expression GoSub destinationlist

On expression GoTo destinationlist

The On...GoSub and On...GoTo statement syntax has these parts:

Part | Description
expression | Any numeric expression that evaluates to a whole number between 0 and 255, inclusive. If expression is any number other than a whole number, it is rounded before it is evaluated.
destinationlist | List of line numbers or line labels separated by commas.

Remarks

The value of expression determines which line in destinationlist is branched to. If the value of expression is less than 1 or greater than the number of items in the list, one of the following results occurs:

If expression is: | Then
Equal to 0 | Control drops to the statement following On...GoSub or On...GoTo.
Greater than number of items in list | Control drops to the statement following On...GoSub or On...GoTo.
Negative | An error occurs.
Greater than 255 | An error occurs.

You can mix line numbers and line labels in the same list. There is no practical limit to the number of line labels and line numbers you can use with On...GoSub and On...GoTo. However, if you use more labels or numbers than will fit on a single line, you must use the line-continuation character to continue the logical line onto the next physical line.

Tip

Select Case provides a more structured and flexible way to perform multiple branching.

See Also

GoSub...Return Statement, GoTo Statement, Select Case Statement.

Example

This example uses the On...GoSub and On...GoTo statements to branch to subroutines and line labels respectively.

Sub OnGosubGotoDemo()
    Number = 2    ' Initialize variable.
    ' Branch to Sub2.
    On Number GoSub Sub1, Sub2    ' Execution resumes here after
    ' On...GoSub.
    On Number GoTo Line1, Line2    ' Branch to Line2.
    ' Execution does not resume here after On...GoTo.
    Exit Sub
Sub1:
    MyString = "In Sub1" : Return
Sub2:
    MyString = "In Sub2" : Return
Line1:
    MyString = "In Line1"
Line2:
    MyString = "In Line2"
End Sub


OnAction Property

Applies To

Arc Object, Arcs Collection, Button Object, Buttons Collection, ChartObject Object, ChartObjects Collection, CheckBox Object, DialogFrame Object, Drawing Object, DrawingObjects Collection, Drawings Collection, DropDown Object, DropDowns Collection, EditBox Object, EditBoxes Collection, GroupBox Object, GroupBoxes Collection, GroupObject Object, GroupObjects Collection, Label Object, Labels Collection, Line Object, Lines Collection, ListBox Object, ListBoxes Collection, MenuItem Object, OLEObject Object, OLEObjects Collection, OptionButton Object, OptionButtons Collection, Oval Object, Ovals Collection, Picture Object, Pictures Collection, Rectangle Object, Rectangles Collection, ScrollBar Object, ScrollBars Collection, Spinner Object, Spinners Collection, TextBox Object, TextBoxes Collection, ToolbarButton Object.

Description

Returns or sets the name of a macro that runs when the object is clicked. Read-write.

Remarks

Setting this property for a menu item overrides any custom help information set up for the menu item with the information set up for the assigned macro.

This property cannot be used with a toolbar button that is a gap or that has a palette or list attached (such as the Font or Style buttons).

See Also

Add Method, Help Method, MacroOptions Method, StatusBar Property.

Example

This example replaces the built-in function of the Print button (button five on the Standard toolbar) with the my_Print_Macro procedure.

ToolBars("Standard").ToolbarButtons(5).OnAction = "my_Print_Macro"

This example restores the built-in function of the Print button (button five on the Standard toolbar).

ToolBars("Standard").ToolbarButtons(5).OnAction = ""


OnCalculate Property

Applies To

Application Object, Worksheet Object.

Description

Returns or sets the name of the macro that runs whenever you recalculate the worksheet. Read-write.

Remarks

Setting this property for a worksheet overrides any macro that may be set for the application.

Set this property to empty text ("") to remove the macro.

A macro set to run by the OnCalculate property is not run by actions taken by other macros. For example, a macro set by OnCalculate will not run if a macro calls the Calculate method, but will be run if you change data in a sheet set to calculate automatically or choose the Calc Now button.

Example

This example causes "my_Recalc_Macro" to run when you recalculate Sheet1.

Worksheets("Sheet1").OnCalculate = "my_Recalc_Macro"

This example disables the OnCalculate macro for Sheet1.

Worksheets("Sheet1").OnCalculate = ""


OnData Property

Applies To

Application Object, Worksheet Object.

Description

Returns or sets the name of the procedure that runs when DDE- or OLE-linked data arrives in Microsoft Excel. The specified procedure runs only when data arrives from another application. Read-write.

Remarks

Set this property to empty text ("") to remove the procedure.

Example

This example runs my_Worksheet_Data_Handler if data arrives on Sheet1.

Worksheets("Sheet1").OnData = "my_Worksheet_Data_Handler"

This example disables the OnData procedure for Sheet1.

Worksheets("Sheet1").OnData = ""


OnDoubleClick Property

Applies To

Application Object, Chart Object, DialogSheet Object, Module Object, Worksheet Object.

Description

Returns or sets the name of the macro that runs whenever you double-click anywhere on the sheet. Read-write.

Remarks

Setting this property has no effect on a module.

Setting this property for a sheet overrides any macro that may be set for the application.

On a dialog sheet, you must double-click the border of a selected drawing object or control to call the macro assigned by this property.

This property overrides normal double-click behavior in Microsoft Excel, such as editing data in a cell or displaying a formatting dialog box.

Set this property to empty text ("") to remove the macro.

See Also

DoubleClick Method.

Example

This example causes Microsoft Excel to run the macro named "my_DblClick_Macro" when you double-click anywhere on Sheet1.

Worksheets("Sheet1").OnDoubleClick = "my_DblClick_Macro"

This example removes the OnDoubleClick macro.

Worksheets("Sheet1").OnDoubleClick = ""


OnEntry Property

Applies To

Application Object, Worksheet Object.

Description

Returns or sets the name of the procedure that runs when you enter data using the formula bar or when you edit data in a cell. Read-write.

Remarks

The procedure does not run when you use edit commands or macro functions.

Set this property to empty text ("") to remove the procedure.

To determine which cell had data entered in it, use the Caller property.

Example

This example runs my_Worksheet_Entry_Procedure when data is entered on Sheet1.

Worksheets("Sheet1").OnEntry = "my_Worksheet_Entry_Procedure"

This example disables the OnEntry procedure for Sheet1.

Worksheets("Sheet1").OnEntry = ""


On Error Statement

Description

Enables an error-handling routine and specifies the location of the routine within a procedure; can also be used to disable an error-handling routine.

Syntax

On Error GoTo line

On Error Resume Next

On Error GoTo 0

The On Error statement syntax can have any of the following forms:

Statement | Description
On Error GoTo line | Enables the error-handling routine that starts at line, which is any line label or line number. Thereafter, if a run-time error occurs, control branches to line. The specified line must be in the same procedure as the On Error statement. If it isn't, a compile-time error occurs.
On Error Resume Next | Specifies that when a run-time error occurs, control goes to the statement immediately following the statement where the error occurred. In other words, execution continues.
On Error GoTo 0 | Disables any enabled error handler in the current procedure.

Remarks

If you don't use an On Error statement, any run-time error that occurs is fatal; that is, an error message is generated and execution stops.

If an error occurs while an error handler is active (between the occurrence of the error and a Resume, Exit Sub, Exit Function, or Exit Property statement), the current procedure's error handler can't handle the error. If the calling procedure has an enabled error handler, control is returned to the calling procedure and its error handler is activated to handle the error. If the calling procedure's error handler is also active, control is passed back through any previous calling procedures until an inactive error handler is found. If no inactive error handler is found, the error is fatal at the point at which it actually occurred. Each time the error handler passes control back to the calling procedure, that procedure becomes the current procedure. Once an error is handled by an error handler in any procedure, execution resumes in the current procedure at the point designated by the Resume statement.

Notice that an error-handling routine is not a Sub or Function procedure. It is a block of code marked by a line label or line number.

Error-handling routines rely on the value in Err to determine the cause of the error. The error-handling routine should test or save this value before any other error can occur or before a procedure that could cause an error is called. The value in Err reflects only the most recent error. You can use the Error function to return the error message associated with any given run-time error number returned by Err.

On Error Resume Next causes execution to continue with the statement immediately following the statement that caused the run-time error, or with the statement immediately following the most recent call out of the procedure containing the error-handling routine. This allows execution to continue despite a run-time error. You can then build the error-handling routine in line with the procedure rather than transferring control to another location within the procedure.

On Error GoTo 0 disables error handling in the current procedure. It doesn't specify line 0 as the start of the error-handling code, even if the procedure contains a line numbered 0. Without an On Error GoTo 0 statement, an error handler is automatically disabled when a procedure is exited.

To prevent error-handling code from running when no error has occurred, place an Exit Sub, Exit Function, or Exit Property statement, as appropriate, immediately ahead of the error-handling routine, as in the following example:

Sub InitializeMatrix(Var1, Var2, Var3, Var4)
    On Error GoTo ErrorHandler
    . . .
    Exit Sub
ErrorHandler:
    . . .
    Resume Next
End Sub

Here, the error-handling code follows the Exit Sub statement and precedes the End Sub statement to separate it from the normal procedure flow. This is only one possible solution; error-handling code can be placed anywhere in a procedure.

See Also

Err Function, Error Function, Resume Statement.

Example

This example uses the On Error GoTo statement to specify the location of an error-handling routine within a procedure. Attempting to delete an open file generates error number 55. The error is handled in the error-handling routine and control is then returned to the statement that caused it.

Sub OnErrorStatementDemo()
    On Error GoTo ErrorHandler    ' Enable error-handling routine.
    Open "TESTFILE" For Output as #1    ' Open file for output.
    Kill "TESTFILE"    ' Attempt to delete open file.
    Exit Sub    ' Exit Sub before error handler.
ErrorHandler:    ' Error-handling routine.
    Select Case Err    ' Evaluate Error Number.
        Case 55    ' "File already open" error.
            Close #1    ' Close open file.
        Case Else
            ' Handle other situations here...
    End Select
    Resume    ' Resume execution at same line
                ' that caused the error.
End Sub


OnKey Method

Applies To

Application Object.

Description

Runs a specified procedure when a particular key or key combination is pressed.

Syntax

object.OnKey(key, procedure)

object

Required. The Application object.

key

Required. A string indicating the keystroke.

procedure

Optional. A string indicating the name of the procedure. If procedure is "" (empty text), nothing happens when key is pressed. This form of OnKey disables the normal meaning of keystrokes in Microsoft Excel. If procedure is omitted, key reverts to its normal meaning in Microsoft Excel, and any special key assignments made with previous OnKey methods are cleared.

Remarks

The key argument can specify any single key; any key combined with ALT, CTRL, or SHIFT, or any combination of those keys (in Windows); or COMMAND, CTRL, OPTION, or SHIFT, or any combination of those keys (on the Macintosh). Each key is represented by one or more characters, such as "a" for the character a, or "{ENTER}" for the ENTER key.

To specify characters that aren't displayed when you press the key, such as ENTER or TAB, use the codes shown in the following table. Each code in the table represents one key on the keyboard.

Key | Code
BACKSPACE | "{BACKSPACE}" or "{BS}"
BREAK | "{BREAK}"
CAPS LOCK | "{CAPSLOCK}"
CLEAR | "{CLEAR}"
DELETE or DEL | "{DELETE}" or "{DEL}"
DOWN arrow | "{DOWN}"
END | "{END}"
ENTER (numeric keypad) | "{ENTER}"
ENTER | "~" (tilde)
ESC | "{ESCAPE} or {ESC}"
HELP | "{HELP}"
HOME | "{HOME}"
INS | "{INSERT}"
LEFT arrow | "{LEFT}"
NUM LOCK | "{NUMLOCK}"
PAGE DOWN | "{PGDN}"
PAGE UP | "{PGUP}"
RETURN | "{RETURN}"
RIGHT arrow | "{RIGHT}"
SCROLL LOCK | "{SCROLLLOCK}"
TAB | "{TAB}"
UP arrow | "{UP}"
F1 through F15 | "{F1}" through "{F15}"

In Windows, you can also specify keys combined with SHIFT and/or CTRL and/or ALT. On the Macintosh, you can also specify keys combined with SHIFT and/or CTRL and/or OPTION and/or COMMAND. To specify a key combined with another key or keys, use the following table.

To combine with | Precede the key code by
SHIFT | "+" (plus sign)
CTRL | "^" (caret)
ALT or OPTION | "%" (percent sign)
COMMAND | "*" (asterisk)

To assign a procedure to one of the special characters (+, ^, %, and so on), enclose the character in braces. See the example for details.

Example

This example assigns my_InsertItem_Procedure to the key sequence CTRL+PLUS SIGN and assigns my_SpecialPrint_Procedure to the key sequence SHIFT+CTRL+RIGHT ARROW.

Application.OnKey "^{+}", "my_InsertItem_Procedure"
Application.OnKey "+^{RIGHT}", "my_SpecialPrint_Procedure"

This example returns SHIFT+CTRL+RIGHT ARROW to its normal meaning.

Application.OnKey "+^{RIGHT}"

This example disables the SHIFT+CTRL+RIGHT ARROW key sequence.

Application.OnKey "+^{RIGHT}", ""


OnRepeat Method

Applies To

Application Object.

Description

Sets the Repeat menu item and the name of the procedure that will run if you choose Repeat from the Edit menu after running the procedure that sets this property.

Syntax

object.OnRepeat(text, procedure)

object

Required. The Application object.

text

Required. Specifies the text that appears with the Repeat command ( Edit menu).

procedure

Required. Specifies the name of the procedure that will run when you choose Repeat from the Edit menu.

Remarks

If a procedure does not use the OnRepeat method, the Repeat command repeats the most recently run procedure.

The procedure must use the OnRepeat and OnUndo methods last, to prevent the repeat or undo procedures from being overwritten by subsequent actions in the procedure.

See Also

OnUndo Method, Repeat Method.

Example

This example sets the repeat and undo procedures.

Application.OnRepeat "Repeat VB Procedure", _
    "Book1.xls!My_Repeat_Sub"
Application.OnUndo "Undo VB Procedure", _
    "Book1.xls!My_Undo_Sub"


OnSave Property

Applies To

Workbook Object.

Description

Returns or sets the name of a Visual Basic procedure to run after the user invokes either the Save or Save As command but before the workbook is actually saved. This property is available only in Microsoft Excel for Windows 95. Read-write.

Remarks

The procedure you specify must take one Boolean argument.

Only Visual Basic procedures are supported. Microsoft Excel 4.0 Macro Language procedures aren't supported.

The value of this property isn't saved with the workbook; it must be reset each time the workbook is opened.

This event isn't called if the workbook is saved when a macro or mail command runs, when an embedded workbook is updated, or when an unsaved workbook is saved as part of a workbook that's being closed.

Example

This example displays a message box after the user invokes either the Save or Save As command but before the workbook is saved.

' Specifies the procedure to run when the workbook is saved
Sub SetSaveEvent()
    ActiveWorkbook.OnSave = "SaveProcedure"
End Sub

Sub SaveProcedure(s As Boolean)
    MsgBox "Excel will now save your work"
End Sub


OnSheetActivate Property

Applies To

Application Object, Chart Object, DialogSheet Object, Module Object, Workbook Object, Worksheet Object.

Description

Returns or sets the name of the macro that runs when the user activates the specified sheet (Chart, DialogSheet, Module, or Worksheet object), any sheet in the specified workbook (Workbook object), or any sheet in any open workbook (Application object). Read-write.

Remarks

To disable an OnSheetActivate macro, set the property to an empty string, as shown in the examples.

See Also

OnSheetDeactivate Property, OnWindow Property, RunAutoMacros Method.

Example

This example sets the OnSheetActivate property to the macro "my_Activate_Sub" in Module1 in the active workbook. This macro will run whenever the user activates a sheet in any workbook.

Application.OnSheetActivate = ActiveWorkbook.Name & _
    "!Module1.my_Activate_Sub"

This example removes the OnSheetActivate macro.

Application.OnSheetActivate = ""


OnSheetDeactivate Property

Applies To

Application Object, Chart Object, DialogSheet Object, Module Object, Workbook Object, Worksheet Object.

Description

Returns or sets the name of the macro that runs when the user deactivates the specified sheet (Chart, DialogSheet, Module, or Worksheet object), any sheet in the specified workbook (Workbook object), or any sheet in any open workbook (Application object). Read-write.

See Also

OnSheetActivate Property, OnWindow Property, RunAutoMacros Method.

Example

This example sets the OnSheetDeactivate property to the macro "my_Deactivate_Sub" in Module1 in the active workbook. This macro will run whenever the user deactivates a sheet in any workbook.

Application.OnSheetDeactivate = ActiveWorkbook.Name & _
    "!Module1.my_Deactivate_Sub"

This example removes the OnSheetDeactivate macro.

Application.OnSheetDeactivate = ""


OnTime Method

Applies To

Application Object.

Description

Schedules a procedure to run at a specified time in the future (either at a specific time of day or after a specific period has passed).

Syntax

object.OnTime(earliestTime, procedure, latestTime, schedule)

object

Required. The Application object.

earliestTime

Required. The time when you want this procedure to run.

procedure

Required. The name of the procedure to run.

latestTime

Optional. The latest time the procedure can be run. For example, if latestTime is set to earliestTime + 30 and Microsoft Excel is not in Ready, Copy, Cut, or Find mode at earliestTime because another procedure is running, Microsoft Excel will wait 30 seconds for the first procedure to complete. If Microsoft Excel is not in Ready mode within 30 seconds, the procedure will not run. If this argument is omitted, Microsoft Excel will wait until the procedure can be run.

schedule

Optional. False to clear a previously set OnTime procedure. True (or omitted) to schedule a new procedure.

Remarks

Use Now + TimeValue(time) to schedule something at a time after the current time. Use TimeValue(time) to schedule something at a specific time.

Example

This example runs my_Procedure 15 seconds from now.

Application.OnTime Now + TimeValue("00:00:15"), "my_Procedure"

This example runs my_Procedure at 5 P.M.

Application.OnTime TimeValue("17:00:00"), "my_Procedure"

This example cancels the OnTime setting from the previous example.

Application.OnTime TimeValue("17:00:00"), "my_Procedure",,False


OnUndo Method

Applies To

Application Object.

Description

Sets the Undo menu item and the name of the procedure that will run if you choose Undo from the Edit menu after running the procedure that sets this property.

Syntax

object.OnUndo(text, procedure)

object

Required. The Application object.

text

Required. Specifies the text that appears with the Undo command ( Edit menu).

procedure

Required. Specifies the name of the procedure that runs when you choose Undo from the Edit menu.

Remarks

If a procedure does not use the OnUndo method, the Undo command is disabled.

The procedure must use the OnRepeat and OnUndo methods last, to prevent the repeat or undo procedures from being overwritten by subsequent actions in the procedure.

See Also

OnRepeat Method, Repeat Method.

Example

This example sets the repeat and undo procedures.

Application.OnRepeat "Repeat VB Procedure", _
    "Book1.xls!My_Repeat_Sub"
Application.OnUndo "Undo VB Procedure", _
    "Book1.xls!My_Undo_Sub"


OnWindow Property

Applies To

Application Object, Window Object.

Description

Returns or sets the name of the procedure that runs whenever you switch to a window. Read-write.

Remarks

The procedure specified by this property does not run when other procedures switch to the window or when a command to switch to a window is received through a DDE channel. Instead, the procedure responds to a user's actions, such as clicking a window with the mouse, choosing the Go To command from the Edit menu, and so on.

If a worksheet or macro sheet has an Auto_Activate or Auto_Deactivate macro defined for it, those macros will be run after the procedure specified by OnWindow.

Example

This example runs my_Stock_Procedure when the user switches to the STOCKS.XLS window from another workbook window.

Application.Windows("STOCKS.XLS").OnWindow = "my_Stock_Procedure"

This example disables the OnWindow procedure for the STOCKS.XLS window.

Application.Windows("STOCKS.XLS").OnWindow = ""


Open Method

Applies To

Workbooks Collection.

Description

Opens a workbook.

Syntax

object.Open(fileName, updateLinks, readOnly, format, password, writeResPassword, ignoreReadOnlyRecommended, origin, delimiter, editable, notify, converter)

object

Required. The Workbooks object.

fileName

Required. Specifies the filename of the workbook to open.

updateLinks

Optional. Specifies how links in the file are updated. If this argument is omitted, the user is prompted to determine how to update links. Otherwise, this argument is one of the values shown in the following table.

Value

Meaning

0

No updates

1

Updates external but not remote references

2

Updates remote but not external references

3

Updates both remote and external references

If Microsoft Excel is opening a file in the WKS, WK1, or WK3 format and the updateLinks argument is 2, Microsoft Excel generates charts from the graphs attached to the file. If the argument is 0, no charts are created.

readOnly

Optional. If True, the workbook is opened in read-only mode.

format

Optional. If Microsoft Excel is opening a text file, this argument specifies the delimiter character, as shown in the following table. If this argument is omitted, the current delimiter is used.

Value

Delimiter

1

Tabs

2

Commas

3

Spaces

4

Semicolons

5

Nothing

6

Custom character, see the delimiter argument.

password

Optional. A string containing the password required to open a protected workbook. If omitted and the workbook requires a password, the user is prompted for the password.

writeResPassword

Optional. A string containing the password required to write to a write-reserved workbook. If omitted and the workbook requires a password, the user will be prompted for the password.

ignoreReadOnlyRecommended

Optional. If True and the workbook was saved with the Read-Only Recommended option, Microsoft Excel does not display the read-only recommended message.

origin

Optional. If the file is a text file, this indicates where it originated (so that code pages and CR/LF can be mapped correctly). May be one of xlMacintosh, xlWindows, or xlMSDOS. If this argument is omitted, the current operating system is used.

delimiter

Optional. If the file is a text file and the format argument is 6, this is a string that specifies the character to use as the delimiter. For example, Chr(9) for tabs, "," for commas, ";" for semicolons, or a custom character. Only the first character of the string is used.

editable

Optional. If the file is a Microsoft Excel 4.0 add-in, using True opens the add-in so that it is a visible window. If False or omitted, the add-in is opened hidden and it cannot be unhidden. This option does not apply for add-ins created in Microsoft Excel 5.0 or later. If the file is not an add-in, specifying True prevents the running of any Auto_Open macros.

notify

Optional. If the file cannot be opened in the read-write mode, specifying True adds the file to the file notification list. Microsoft Excel will open the file read-only, poll the file notification list, and then notify the user when the file becomes available. If this argument is False or omitted, no notification is requested, and attempts to open an unavailable file will fail.

converter

Optional. Specifies the index of the first file converter to try when opening the file. The specified file converter is tried first, then all other converters are tried if the specified converter does not recognize the file. The converter index is the row number of the converters returned by the FileConverters property.

Remarks

If the workbook being opened has any Auto_Open macros in it, they will not be run when you open the file from Visual Basic. If you want to run the Auto_Open macro, you must use the RunAutoMacros method.

See Also

Activate Method, Close Method, FileConverters Property, OpenText Method.

Example

This example opens the workbook ANALYSIS.XLS and then runs its Auto_Open macro.

Workbooks.Open "ANALYSIS.XLS"
ActiveWorkbook.RunAutoMacros xlAutoOpen


Open Statement

Description

Enables input/output (I/O) to a file.

Syntax

Open pathname [For mode] [Access access] [lock] As [#]filenumber [Len=reclength]

The Open statement syntax has these parts:

Part | Description
pathname | String expression that specifies a file name — may include directory or folder, and drive.
mode | Keyword specifying the file mode: Append, Binary, Input, Output, or Random.
access | Keyword specifying the operations permitted on the open file: Read, Write, or Read Write.
lock | Keyword specifying the operations permitted on the open file by other processes: Shared, Lock Read, Lock Write, Lock Read Write.
filenumber | A valid file number in the range 1 to 511, inclusive. Use the FreeFile function to obtain the next available file number.
reclength | Number less than or equal to 32,767 (bytes). For files opened for random access, this value is the record length. For sequential files, this value is the number of characters buffered.

Remarks

You must open a file before any I/O operation can be performed on it. Open allocates a buffer for I/O to the file and determines the mode of access to use with the buffer.

If the file specified by pathname doesn't exist, it is created when a file is opened for Append, Binary, Output, or Random modes.

If the file is already opened by another process and the specified type of access is not allowed, the Open operation fails and an error occurs.

The Len clause is ignored if mode is Binary.

Important

In Binary, Input, and Random modes, you can open a file using a different file number without first closing the file. In Append and Output modes, you must close a file before opening it with a different file number.

On the Macintosh, the file mode specified in the Open statement determines the initial Creator and Type property settings:

File mode | Creator | Type
Output | ???? | TEXT
Append | ???? | TEXT
Random | ???? | OBIN
Binary | ???? | OBIN
Unspecified | ???? | OBIN

See Also

Close Statement, FreeFile Function.

Example

This example illustrates various uses of the Open statement to enable input/output to a file.

' Open in sequential-input mode.
Open "TESTFILE" For Input As #1

' Open in binary-file mode for writing operations only.
Open "TESTFILE" For Binary Access Write As #1

' Open file in random-access mode. The file contains records of the
' user-defined type Record.
Type Record    ' Define user-defined type.
    ID As Integer
    Name As String * 20
End Type
Dim MyRecord As Record    ' Declare variable.
Open "TESTFILE" For Random As #1 Len = Len(MyRecord)

' Open for sequential output; any process can read/write to file.
Open "TESTFILE" For Output Shared As #1

' Open in binary-file mode for reading; other processes can't read
' file.
Open "TESTFILE" For Binary Access Read Lock Read As #1


OpenLinks Method

Applies To

Workbook Object.

Description

Opens the supporting documents for a link or links.

Syntax

object.OpenLinks(name, readOnly, type)

object

Required. The Workbook object.

name

Required. Specifies the name of the Microsoft Excel or DDE/OLE link, as returned from the LinkSources method (can be an array of names to specify more than one link).

readOnly

Optional. True if the documents are opened read-only. False if omitted.

type

Optional. Specifies the link type. Can be one of xlExcelLinks, xlOLELinks (also handles DDE links), xlPublishers, or xlSubscribers. xlExcelLinks if omitted.

Example

This example opens OLE link one in the active workbook.

linkArray = ActiveWorkbook.LinkSources(xlOLELinks)
ActiveWorkbook.OpenLinks linkArray(1)

This example opens all supporting Microsoft Excel documents for the active workbook.

ActiveWorkbook.OpenLinks _
    name:=ActiveWorkbook.LinkSources(xlExcelLinks)


OpenText Method

Applies To

Workbooks Collection.

Description

Loads and parses a text file as a new workbook with a single sheet containing the parsed text-file data.

Syntax

object.OpenText(filename, origin, startRow, dataType, textQualifier, consecutiveDelimiter, tab, semicolon, comma, space, other, otherChar, fieldInfo)

object

Required. The Workbooks object.

filename

Required. Specifies the filename of the text file to open and parse.

origin

Optional. Specifies the origin of the text file (one of xlMacintosh, xlWindows, or xlMSDOS). If this argument is omitted, the method uses the current setting in the File Origin option of the Text Import Wizard.

startRow

Optional. The row number at which to start parsing text. The first row is 1. If omitted, 1 is assumed.

dataType

Optional. Specifies the column format of the data within the file (either xlDelimited or xlFixedWidth). The default is xlDelimited.

textQualifier

Optional. Specifies the text qualifier. Can be one of xlDoubleQuote, xlSingleQuote, or xlNone. The default is xlDoubleQuote.

consecutiveDelimiter

Optional. True if consecutive delimiters should be considered as one delimiter. The default is False.

tab

Optional. True if dataType is xlDelimited and the tab character is a delimiter. The default is False.

semicolon

Optional. True if dataType is xlDelimited and the semicolon character is a delimiter. The default is False.

comma

Optional. True if dataType is xlDelimited and the comma character is a delimiter. The default is False.

space

Optional. True if dataType is xlDelimited and the space character is a delimiter. The default is False.

other

Optional. True if dataType is xlDelimited and the character specified by the otherChar argument is a delimiter. The default is False.

otherChar

Optional (required if other is True). Specifies the delimiter character when other is True. If more than one character is specified, only the first character of the string is used, remaining characters are ignored.

fieldInfo

Optional. An array containing parse information for the individual columns of data. The interpretation depends on the value of dataType.

When the data is delimited, this argument is an array of two-element arrays, with each two-element array specifying the conversion options for a particular column. The first element is the column number (one based), and the second element is one of the following numbers specifying how the column in parsed:

1 General

2 Text

3 MDY date

4 DMY date

5 YMD date

6 MYD date

7 DYM date

8 YDM date

9 Skip the column

The column specifiers may be in any order. If a column specifier is not present for a particular column in the input data, the column is parsed using the General setting. This example causes the third column to be skipped, the first column to be parsed as text, and the remaining columns in the source data to be parsed with the General setting.

Array(Array(3, 9), Array(1, 2))

If the source data has fixed-width columns, the first element of each two-element array specifies the starting character position in the column (as an integer; character zero is the first character). The second element of the two-element array specifies the parse option for the column as a number from one through nine, as listed above.

The following example parses two columns from a fixed-width text file. The first column includes characters 1 through 10. Characters 11, 12, 13, 14, and 15 are skipped. The second column includes characters 16 through the last character in the line.

Array(Array(0, 1), Array(10, 9), Array(15, 1))

See Also

Close Method, Open Method, TextToColumns Method.

Example

This example opens the file DATA.TXT and uses tab delimiters to parse the text file into a worksheet.

Workbooks.OpenText filename:="DATA.TXT", _
    dataType:=xlDelimited, tab:=True


OperatingSystem Property

Applies To

Application Object.

Description

Returns the name and version number of the current operating system. For example, "Windows 3.10" or "Macintosh 7.00". Read-only.

Example

This example displays the name of the operating system.

MsgBox "Microsoft Excel is using " & Application.OperatingSystem


Operator Precedence

When several operations occur in an expression, each part is evaluated and resolved in a predetermined order. That order is known as operator precedence. Parentheses can be used to override the order of precedence and force some parts of an expression to be evaluated before others. Operations within parentheses are always performed before those outside. Within parentheses, however, normal operator precedence is maintained.

When expressions contain operators from more than one category, arithmetic operators are evaluated first, comparison operators are evaluated next, and logical operators are evaluated last. Comparison operators all have equal precedence; that is, they are evaluated in the left to right order in which they appear. Arithmetic and logical operators are evaluated in the following order of precedence:

Arithmetic | Comparison | Logical
Exponentiation (^) | Equality (=) | Not
Negation (-) | Inequality (<>) | And
Multiplication and division (*,/) | Less than (<) | Or
Integer division (\) | Greater than (>) | Xor
Modulo arithmetic (Mod) | Less than or Equal to (<=) | Eqv
Addition and subtraction (+,-) | Greater than or Equal to (>=) | Imp
String concatenation (&) | Like | Is

When multiplication and division occur together in an expression, each operation is evaluated as it occurs from left to right. Likewise, when addition and subtraction occur together in an expression, each operation is evaluated in order of appearance from left to right.

The string concatenation operator (&) is not really an arithmetic operator, but in precedence it does fall after all arithmetic operators and before all comparison operators. Similarly, the Like operator, while equal in precedence to all comparison operators, is actually a pattern-matching operator. The Is operator is an object reference comparison operator. It does not compare objects or their values; it checks only to determine if two object references refer to the same object.

Arithmetic Operators

^ Operator

* Operator

/ Operator

\ Operator

Mod Operator

+ Operator

- Operator

Concatenation Operators

& Operator

+ Operator

Logical Operators

And Operator

Eqv Operator

Imp Operator

Not Operator

Or Operator

Xor Operator


Option Base Statement

Description

Used at module level to declare the default lower bound for array subscripts.

Syntax

Option Base {0 | 1}

Remarks

If used, the Option Base statement must appear in a module before any statements that declare variables or define constants.

Since the default base is 0, the Option Base statement is never required. However, if used, it can appear only once in a module and must precede array declarations that include dimensions.

The Option Base statement has no effect on arrays within user-defined types for which the lower bound is always 0.

Tip

The To clause in the Dim, Private, Public, ReDim, and Static statements provides a more flexible way to control the range of an array's subscripts. However, if you don't explicitly set the lower bound with a To clause, you can use Option Base to change the default lower bound to 1.

The Option Base statement only affects the lower bound of arrays in the module where the statement is located.

See Also

Dim Statement, LBound Function, Option Compare Statement, Option Explicit Statement, Option Private Statement, Private Statement, Public Statement, ReDim Statement, Static Statement.

Example

This example uses the Option Base statement to override the default base array subscript value of 0. The LBound function returns the smallest available subscript for the indicated dimension of an array. The Option Base statement is used at the module-level only.

' Set default array subscripts to 1.
Option Base 1

Dim MyArray(20), TwoDArray(3,4)    ' Declare array variables.
Dim ZeroArray(0 To 5)    ' Override default base subscript.
' Use LBound function to test lower bounds of arrays.
Lower = LBound(MyArray)    ' Returns 1.
Lower = LBound(TwoDArray, 2)    ' Returns 1.
Lower = LBound(ZeroArray)    ' Returns 0.


Option Compare Statement

Description

Used at module level to declare the default comparison mode to use when string data is compared.

Syntax

Option Compare {Binary | Text}

Remarks

If used, the Option Compare statement must appear in a module before any statements that declare variables or define constants.

The Option Compare statement specifies the string comparison method (Binary or Text) for a module. If a module doesn't include an Option Compare statement, the default text comparison method is Binary.

Option Compare Binary results in string comparisons based on a sort order derived from the internal binary representations of the characters. In Microsoft Windows, sort order is determined by the code page. On the Macintosh, sort order is determined by the character set. In the following example, a typical binary sort order is shown:

A < B < E < Z < a < b < e  < z < À < Ê < Ø < à < ê < ø

Option Compare Text results in string comparisons based on a case-insensitive textual sort order determined by your system's locale. The same characters shown above, when sorted using Option Compare Text, produce the following text sort order:

(A=a) < ( À=à) < (B=b) < (E=e) < (Ê=ê) < (Z=z) < (Ø=ø)

See Also

Comparison Operators, InStr Function, Option Base Statement, Option Explicit Statement, Option Private Statement, StrComp Function.

Example

This example uses the Option Compare statement to set the default string comparison mode. The Option Compare statement is used at the module-level only.

' Set the string comparison method to Binary.
Option Compare Binary     ' i.e. "AAA" less than "aaa"
' Set the string comparison method to Text.
Option Compare Text    ' i.e. "AAA" equal to "aaa".


Option Explicit Statement

Description

Used at module level to force explicit declaration of all variables in that module.

Syntax

Option Explicit

Remarks

If used, the Option Explicit statement must appear in a module before any statements that declare variables or define constants.

If you don't use the Option Explicit statement, all undeclared variables are Variant unless the default type is otherwise specified with a Def type statement.

When you use the Option Explicit statement, you must explicitly declare all variables using the Dim, Private, Public, ReDim, or Static statements. If you attempt to use an undeclared variable name, an error occurs at compile time.

Tip

Use Option Explicit to avoid incorrectly typing the name of an existing variable or to avoid risking confusion in code where the scope of the variable is not clear.

See Also

Const Statement, Deftype Statements, Dim Statement, Function Statement, Option Base Statement, Option Compare Statement, Option Private Statement, Private Statement, Public Statement, ReDim Statement, Static Statement, Sub Statement.

Example

This example uses the Option Explicit statement to force you to explicitly declare all variables. Attempting to use an undeclared variable gives you an error at compile time. The Option Explicit statement is used at the module-level only.

Option Explicit    ' Force explicit variable declaration.
Dim MyVar    ' Declare variable.
MyInt = 10    ' Undeclared variable generates error.
MyVar = 10    ' Will not generate error.


Option Private Statement

Description

Used at module level to indicate that an entire module is Private.

Syntax

Option Private Module

Remarks

If used, the Option Private statement must appear in a module before any statements that declare variables or define constants.

The public parts (variables, objects, and user-defined types declared at module level) of modules declared Private using the Option Private statement are still available within the project containing the module, but they are not available to other applications or projects.

See Also

Option Base Statement, Option Compare Statement, Option Explicit Statement, Private Statement.

Example

This Option Private statement is used at the module-level to indicate that the entire module is private.

Option Private Module    ' Indicate that module is private.


OptionButton Object

Description

Option buttons allow the user to select one of a group of options. Option buttons are usually placed within a group box control (GroupBox object). You can set the position and size of an option button. On a worksheet or chart, you can also format the border and background. The font is fixed.

Accessors

The OptionButton object is a member of the OptionButtons collection. The OptionButtons collection contains all the OptionButton objects on a single sheet. Use the Add method to create a new option button and add it to the collection.

To access a single member of the collection, use the OptionButtons method with the index number or name of the option button as an argument. The following example turns on option button one on the worksheet named "Sheet2."

Worksheets("sheet2").OptionButtons(1).Value = xlOn

The option button name is shown in the Name Box when the option button is selected. Use the Name property to set or return the option button name. The following example disables the option button named "Option Button 13" on the worksheet named "Sheet2."

Worksheets("sheet2").OptionButtons("option button 13").Enabled = False

Properties

Accelerator Property, Application Property, Border Property, BottomRightCell Property, Caption Property, Creator Property, Display3DShading Property, Enabled Property, Height Property, Index Property, Interior Property, Left Property, LinkedCell Property, Locked Property, LockedText Property, Name Property, OnAction Property, Parent Property, PhoneticAccelerator Property, Placement Property, PrintObject Property, Text Property, Top Property, TopLeftCell Property, Value Property, Visible Property, Width Property, ZOrder Property.

Methods

BringToFront Method, Characters Method, CheckSpelling Method, Copy Method, CopyPicture Method, Cut Method, Delete Method, Duplicate Method, Select Method, SendToBack Method.


OptionButtons Collection Object

Description

A collection of all the OptionButton objects on the specified chart sheet, dialog sheet, or worksheet. Option buttons allow the user to select one of a group of options. Option buttons are usually placed within a group box control (GroupBox object). You can set the position and size of an option button. On a worksheet or chart, you can also format the border and background. The font is fixed.

Accessors

The OptionButtons collection contains all of the option buttons on a single sheet. Use the Add method to create a new option button and add it to the collection. The following example adds four option buttons to the dialog sheet named "Dialog1." The new option buttons are positioned relative to the upper-left corner of the dialog frame.

Dim df As DialogFrame
Set df = DialogSheets("dialog1").DialogFrame
With DialogSheets("dialog1").OptionButtons
    .Add df.Left + 10, df.Top + 20, 100, 10
    .Add df.Left + 10, df.Top + 40, 100, 10
    .Add df.Left + 10, df.Top + 60, 100, 10
    .Add df.Left + 10, df.Top + 80, 100, 10
End With

Use the OptionButtons method with an argument to access a single member of the collection or without an argument to access the entire collection at once. The following example creates a new group box around all the option buttons on dialog sheet one by first using the Group method to create a new GroupObject object from all of the option buttons and then using the size of the GroupObject object to create the GroupBox object.

Dim op_btns As GroupObject
Set op_btns = DialogSheets(1).OptionButtons.Group
DialogSheets(1).GroupBoxes.Add op_btns.Left, _
    op_btns.Top - 10, op_btns.Width, op_btns.Height

Properties

Accelerator Property, Application Property, Border Property, Caption Property, Count Property, Creator Property, Display3DShading Property, Enabled Property, Height Property, Interior Property, Left Property, LinkedCell Property, Locked Property, LockedText Property, OnAction Property, Parent Property, PhoneticAccelerator Property, Placement Property, PrintObject Property, Text Property, Top Property, Value Property, Visible Property, Width Property, ZOrder Property.

Methods

Add Method (Graphic Objects and Controls), BringToFront Method, Characters Method, CheckSpelling Method, Copy Method, CopyPicture Method, Cut Method, Delete Method, Duplicate Method, Group Method, Item Method, Select Method, SendToBack Method.


OptionButtons Method

Applies To

Chart Object, DialogSheet Object, Worksheet Object.

Description

Accessor. Returns an object that represents a single option button control (an OptionButton object, Syntax 1) or a collection of option button controls (an OptionButtons object, Syntax 2) on the sheet.

Syntax 1

object.OptionButtons(index)

Syntax 2

object.OptionButtons

object

Required. The Chart, DialogSheet, or Worksheet object.

index

Required for Syntax 1. Specifies the name or number of the option button (can be an array to specify more than one).

Example

This example sets option button one on Dialog1.

Dialogsheets("Dialog1").OptionButtons(1).Value = xlOn


Or Operator

Description

Used to perform a logical disjunction on two expressions.

Syntax

result = expression1 Or expression2

The Or operator syntax has these parts:

Part | Description
result | Any numeric variable.
expression1 | Any expression.
expression2 | Any expression.

Remarks

If either or both expressions evaluate True, result is True. The following table illustrates how result is determined:

If expression1 is | And expression2 is | The result is
True | True | True
True | False | True
True | Null | True
False | True | True
False | False | False
False | Null | Null
Null | True | True
Null | False | Null
Null | Null | Null

The Or operator also performs a bit-wise comparison of identically positioned bits in two numeric expressions and sets the corresponding bit in result according to the following truth table:

If bit in expression1 is | And bit in expression2 is | The result is
0 | 0 | 0
0 | 1 | 1
1 | 0 | 1
1 | 1 | 1

See Also

Operator Precedence.

Example

This example uses the Or operator to perform logical disjunction on two expressions.

A = 10: B = 8: C = 6 : D = Null    ' Initialize variables.
MyCheck = A > B Or B > C    ' Returns True.
MyCheck = B > A Or B > C    ' Returns True.
MyCheck = A > B Or B > D    ' Returns True.
MyCheck = B > D Or B > A    ' Returns Null.
MyCheck = A Or B    ' Returns 10 (bit-wise comparison).


Order Property

Applies To

PageSetup Object, Trendline Object.

Description

PageSetup object: Returns or sets the order that Microsoft Excel uses to number pages when printing a large worksheet (either xlDownThenOver or xlOverThenDown). Read-write.

Trendline object: Returns or sets the trendline order (an integer greater than one) when the trendline Type is xlPolynomial. Read-write.

Remarks

For the PageSetup object, this property applies only to worksheets.

Example

This example breaks Sheet1 into pages when the worksheet is printed. Numbering and printing proceed from the first page to the pages to the right, and then move down and continue printing across the sheet.

Worksheets("Sheet1").PageSetup.Order = xlOverThenDown


OrganizationName Property

Applies To

Application Object.

Description

Returns the registered organization name (as a string). Read-only.

See Also

UserName Property.

Example

This example displays the registered organization name.

MsgBox "The registered organization is " & Application.OrganizationName


Orientation Property

Applies To

AxisTitle Object, Button Object, Buttons Collection, ChartTitle Object, DataLabel Object, DataLabels Collection, DrawingObjects Collection, GroupObject Object, GroupObjects Collection, PageSetup Object, PivotField Object, Range Object, Style Object, TextBox Object, TextBoxes Collection, TickLabels Object.

Description

Returns or sets the object's orientation, as shown in the following table.

Object | Orientation
PageSetup | Portrait or landscape printing mode. One of xlPortrait or xlLandscape.
PivotField | Location of the field in the PivotTable. One of xlHidden, xlRowField, xlColumnField, xlPageField, or xlDataField.
AxisTitle, Button, ChartTitle, DataLabel, DrawingObjects, GroupObject, RadarAxisLabels, Range, Style, TextBox, TickLabels | The text orientation. One of xlHorizontal, xlVertical, xlUpward, or xlDownward. Can also be xlAutomatic for TickLabels only.

Example

This example displays the orientation for the field named "ORDER_DATE."

Set pvtTable = Worksheets("Sheet1").Range("A3").PivotTable
Set pvtField = pvtTable.PivotFields("ORDER_DATE")
Select Case pvtField.Orientation
    Case xlHidden
        MsgBox "Hidden field"
    Case xlRowField
        MsgBox "Row field"
    Case xlColumnField
        MsgBox "Column field"
    Case xlPageField
        MsgBox "Page field"
    Case xlDataField
        MsgBox "Data field"
End Select

This example sets Sheet1 to print in landscape orientation.

Worksheets("Sheet1").PageSetup.Orientation = xlLandscape


Outline Object

Description

An outline on a worksheet.

Accessors

The Outline property returns the outline for a worksheet. The following example sets the outline on the worksheet named "Sheet4" to show only the first outline level.

Worksheets("sheet4").Outline.ShowLevels 1

Use the following properties and methods to create and control outlines: ApplyOutlineStyles Method, AutoOutline Method, ClearOutline Method, DisplayOutline Property, Group Method, OutlineLevel Property, ShowDetail Property, Ungroup Method.

Properties

Application Property, AutomaticStyles Property, Creator Property, Parent Property, SummaryColumn Property, SummaryRow Property.

Methods

ShowLevels Method.


Outline Property

Applies To

Worksheet Object.

Description

Accessor. Returns an Outline object that represents the outline for the specified worksheet.

Example

This example sets the outline on Sheet1 to use automatic styles.

Worksheets("Sheet1").Outline.AutomaticStyles = True


OutlineFont Property

Applies To

Font Object.

Description

True if the font is an outline font. Read-write.

Remarks

This property has no effect in Microsoft Windows, but its value is retained (it can be set and returned).

Example

This example sets the font for cell A1 on Sheet1 to an outline font.

Worksheets("Sheet1").Range("A1").Font.OutlineFont = True


OutlineLevel Property

Applies To

Range Object.

Description

Returns or sets the current row or column outline level of the specified row or column. Read-write.

Remarks

Level one is the outermost summary level.

See Also

EntireColumn Property, EntireRow Property.

Example

This example sets the outline level for row two on Sheet1.

Worksheets("Sheet1").Rows(2).OutlineLevel = 1


Oval Object

Description

Represents an oval graphic object on a chart sheet, dialog sheet, or worksheet.

Accessors

The Oval object is a member of the Ovals collection. The Ovals collection contains all the Oval objects on a single sheet. Use the Add method (or click the Ellipse or Filled Ellipse button on the Drawing toolbar) to create a new oval and add it to the collection. To access a single member of the collection, use the Ovals method with the index number or name of the oval as an argument.

The following example sets the border color for oval one.

Worksheets("Sheet1").Activate
ActiveSheet.Ovals(1).Border.Color = RGB(0, 255, 255)

The oval name is shown in the Name Box when the oval is selected. Use the Name property to set and return the oval name.

The following example selects the oval named "Oval 1" on the active sheet and then sets the oval interior color.

Worksheets("sheet1").Activate
ActiveSheet.Ovals("oval 1").Select
Selection.Interior.Color = RGB(255, 0, 0)

Properties

Application Property, Border Property, BottomRightCell Property, Creator Property, Enabled Property, Height Property, Index Property, Interior Property, Left Property, Locked Property, Name Property, OnAction Property, Parent Property, Placement Property, PrintObject Property, Shadow Property, Top Property, TopLeftCell Property, Visible Property, Width Property, ZOrder Property.

Methods

BringToFront Method, Copy Method, CopyPicture Method, Cut Method, Delete Method, Duplicate Method, Select Method, SendToBack Method.


Ovals Collection Object

Description

A collection of all the Oval objects on the specified chart sheet, dialog sheet, or worksheet.

Accessors

Use the Add method to create a new oval and add it to the collection. The following example creates a new oval aligned with the left and top edges of cell C5 on the worksheet named "Sheet1." The new oval is twice as long and high as the cell, and its interior has a grid pattern.

Set r = Worksheets("sheet1").Range("c5")
Set o = Worksheets("sheet1").Ovals.Add(r.Left, _
    r.Top, 2 * r.Width, 2 * r.Height)
o.Interior.Pattern = xlGrid

Use the Ovals method with an argument to access a single member of the collection or without an argument to access the entire collection at once. The following example sets the interior color for all the ovals on the worksheet named "Sheet1."

Worksheets("sheet1").Ovals.Interior.ColorIndex = 3

Properties

Application Property, Border Property, Count Property, Creator Property, Enabled Property, Height Property, Interior Property, Left Property, Locked Property, OnAction Property, Parent Property, Placement Property, PrintObject Property, Shadow Property, Top Property, Visible Property, Width Property, ZOrder Property.

Methods

Add Method (Graphic Objects and Controls), BringToFront Method, Copy Method, CopyPicture Method, Cut Method, Delete Method, Duplicate Method, Group Method, Item Method, Select Method, SendToBack Method.


Ovals Method

Applies To

Chart Object, DialogSheet Object, Worksheet Object.

Description

Accessor. Returns an object that represents a single oval (an Oval object, Syntax 1) or a collection of ovals (an Ovals object, Syntax 2) on the sheet. Read-only.

Syntax 1

object.Ovals(index)

Syntax 2

object.Ovals

object

Required. The object containing the ovals.

index

Required for Syntax 1. The name or number of the oval.

Example

This example deletes every oval on Sheet1.

Worksheets("Sheet1").Ovals.Delete

This example changes the color of oval one on Sheet1 to red.

Worksheets("Sheet1").Ovals(1).Border.ColorIndex = 3


Overlap Property

Applies To

ChartGroup Object.

Description

Specifies how bars and columns are positioned. Can be a value from -100 to 100. Applies only to 2-D bar and 2-D column charts. Read-write.

Remarks

If this property is set to -100, bars are positioned so that there is one bar width between them. With zero overlap, there is no space between bars (one bar starts immediately after the preceding bar). At 100 overlap, bars are positioned on top of each other.

See Also

GapWidth Property.

Example

This example sets the overlap for chart group one to -50. The example should be run on a 2-D column chart that has two or more series.

Charts("Chart1").ChartGroups(1).Overlap = -50


PageBreak Property

Applies To

Range Object.

Description

Returns or sets the location of a page break (one of xlNone, xlManual, or xlAutomatic). Read-write.

Remarks

This property can return the location of either automatic or manual page breaks, but it can only set the location of manual breaks (it can only be set to xlManual or xlNone).

To remove all manual page breaks on a worksheet, set Cells.PageBreak to xlNone.

Example

This example sets a manual page break above row 25 on Sheet1.

Worksheets("Sheet1").Rows(25).PageBreak = xlManual

This example sets a manual page break to the left of column J on Sheet1.

Worksheets("Sheet1").Columns("J").PageBreak = xlManual

This example deletes the two page breaks that were set in the previous examples.

Worksheets("Sheet1").Rows(25).PageBreak = xlNone
Worksheets("Sheet1").Columns("J").PageBreak = xlNone


PageFields Method

Applies To

PivotTable Object.

Description

Accessor. Returns an object that represents a single pivot field (a PivotField object, Syntax 1) or a collection of the pivot fields (a PivotFields object, Syntax 2) that are currently showing as page fields. Read-only.

Syntax 1

object.PageFields(index)

Syntax 2

object.PageFields

object

Required. The PivotTable object.

index

Required for Syntax 1. The name or number of the pivot field to return (can be an array to specify more than one).

See Also

ColumnFields Method, DataFields Method, HiddenFields Method, PivotFields Method, RowFields Method, VisibleFields Method.

Example

This example adds the page field names to a list box. The list box appears on Sheet1.

Set pvtTable = Worksheets("Sheet1").Range("A3").PivotTable
Set newListBox = Worksheets("Sheet1").ListBoxes.Add _
    (Left:=10, Top:=72, Width:=144, Height:=144)
For Each hdnField In pvtTable.PageFields
    newListBox.AddItem (hdnField.Name)
Next hdnField
Worksheets("Sheet1").Activate


PageRange Property

Applies To

PivotTable Object.

Description

Accessor. Returns a Range object that represents the range that contains the PivotTable page area. Read-only.

See Also

ColumnRange Property, DataBodyRange Property, DataLabelRange Property, RowRange Property.

Example

This example selects the PivotTable page headers.

Worksheets("Sheet1").Activate
Range("A3").Select
ActiveCell.PivotTable.PageRange.Select


PageSetup Object

Description

Represents the page setup description. The PageSetup object contains all page setup attributes (left margin, bottom margin, paper size, and so on) as properties.

Accessors

The PageSetup property returns the PageSetup object for a sheet or window. The following example sets the orientation to landscape mode for the module named "Module1" and then prints the module.

Modules("module1").PageSetup.Orientation = xlLandscape
Modules("module1").PrintOut

The With statement makes it easier and faster to set several properties at once. The following example sets all the margins for worksheet one.

With Worksheets(1).PageSetup
    .LeftMargin = Application.InchesToPoints(0.5)
    .RightMargin = Application.InchesToPoints(0.75)
    .TopMargin = Application.InchesToPoints(1.5)
    .BottomMargin = Application.InchesToPoints(1)
    .HeaderMargin = Application.InchesToPoints(0.5)
    .FooterMargin = Application.InchesToPoints(0.5)
End With

Properties

Application Property, BlackAndWhite Property, BottomMargin Property, CenterFooter Property, CenterHeader Property, CenterHorizontally Property, CenterVertically Property, ChartSize Property, Creator Property, Draft Property, FirstPageNumber Property, FitToPagesTall Property, FitToPagesWide Property, FooterMargin Property, HeaderMargin Property, LeftFooter Property, LeftHeader Property, LeftMargin Property, Order Property, Orientation Property, PaperSize Property, Parent Property, PrintArea Property, PrintGridlines Property, PrintHeadings Property, PrintNotes Property, PrintQuality Property, PrintTitleColumns Property, PrintTitleRows Property, RightFooter Property, RightHeader Property, RightMargin Property, TopMargin Property, Zoom Property.


PageSetup Property

Applies To

Chart Object, DialogSheet Object, Module Object, Window Object, Worksheet Object.

Description

Accessor. Returns a PageSetup object that contains all of the page setup settings for the specified object. Read-only.

Example

This example sets the center header text for Chart1.

Charts("Chart1").PageSetup.CenterHeader = "December Sales"


Pane Object

Description

Represents a pane of a window. Pane objects exist only for worksheets and Excel 4.0 macro sheets.

Accessors

The Pane object is a member of the Panes collection. The Panes collection contains all of the panes shown in a single Window. To access a single member of the collection, use the Panes method with the pane index number as an argument. The following example splits the window showing worksheet one and then scrolls the pane in the lower-left corner to position row five at the top.

Worksheets(1).Activate
ActiveWindow.Split = True
ActiveWindow.Panes(3).ScrollRow = 5

Properties

Application Property, Creator Property, Index Property, Parent Property, ScrollColumn Property, ScrollRow Property, VisibleRange Property.

Methods

Activate Method, LargeScroll Method, SmallScroll Method.


Panes Collection Object

Description

A collection of all the Pane objects shown in the specified window. Pane objects exist only for worksheets and Excel 4.0 macro sheets.

Accessors

Use the Panes method with an argument to access a single member of the collection or without an argument to access the entire collection at once.

The following example scrolls the upper-left pane of the window showing the worksheet named "Sheet1."

Worksheets("sheet1").Activate
Windows(1).Panes(1).LargeScroll down:=1

Properties

Application Property, Count Property, Creator Property, Parent Property.

Methods

Item Method.


Panes Method

Applies To

Window Object.

Description

Accessor. Returns an object that represents one pane (a Pane object, Syntax 1) or a collection of all the panes (a Panes object, Syntax 2) in a window. Read-only.

Syntax 1

object.Panes(index)

Syntax 2

object.Panes

object

Required. The Window object.

index

Required for Syntax 1. The name or number of the pane.

Remarks

This method is only available on a window if its Split property can be set to True.

Example

This example displays the number of panes in the active window in BOOK1.XLS.

Workbooks("BOOK1.XLS").Worksheets("Sheet1").Activate
MsgBox "There are " & ActiveWindow.Panes.Count & _
    " panes in the active window"

This example activates the upper-left pane in the active window in BOOK1.XLS.

Workbooks("BOOK1.XLS").Worksheets("Sheet1").Activate
ActiveWindow.Panes(1).Activate


PaperSize Property

Applies To

PageSetup Object.

Description

Windows only. Returns or sets the size of the paper. Read-write.

Remarks

This property may have one of the following values.

Value | Meaning
xlPaperLetter | Letter (8 1/2 x 11 in.)
xlPaperLetterSmall | Letter Small (8 1/2 x 11 in.)
xlPaperTabloid | Tabloid (11 x 17 in.)
xlPaperLedger | Ledger (17 x 11 in.)
xlPaperLegal | Legal (8 1/2 x 14 in.)
xlPaperStatement | Statement (5 1/2 x 8 1/2 in.)
xlPaperExecutive | Executive (7 1/2 x 10 1/2 in.)
xlPaperA3 | A3 (297 x 420 mm)
xlPaperA4 | A4 (210 x 297 mm)
xlPaperA4Small | A4 Small (210 x 297 mm)
xlPaperA5 | A5 (148 x 210 mm)
xlPaperB4 | B4 (250 x 354 mm)
xlPaperB5 | B5 (182 x 257 mm)
xlPaperFolio | Folio (8 1/2 x 13 in.)
xlPaperQuarto | Quarto (215 x 275 mm)
xlPaper10x14 | 10 x 14 in.
xlPaper11x17 | 11 x 17 in.
xlPaperNote | Note (8 1/2 x 11 in.)
xlPaperEnvelope9 | Envelope #9 (3 7/8 x 8 7/8 in.)
xlPaperEnvelope10 | Envelope #10 (4 1/8 x 9 1/2 in.)
xlPaperEnvelope11 | Envelope #11 (4 1/2 x 10 3/8 in.)
xlPaperEnvelope12 | Envelope #12 (4 1/2 x 11 in.)
xlPaperEnvelope14 | Envelope #14 (5 x 11 1/2 in.)
xlPaperCsheet | C size sheet
xlPaperDsheet | D size sheet
xlPaperEsheet | E size sheet
xlPaperEnvelopeDL | Envelope DL (110 x 220 mm)
xlPaperEnvelopeC3 | Envelope C3 (324 x 458 mm)
xlPaperEnvelopeC4 | Envelope C4 (229 x 324 mm)
xlPaperEnvelopeC5 | Envelope C5 (162 x 229 mm)
xlPaperEnvelopeC6 | Envelope C6 (114 x 162 mm)
xlPaperEnvelopeC65 | Envelope C65 (114 x 229 mm)
xlPaperEnvelopeB4 | Envelope B4 (250 x 353 mm)
xlPaperEnvelopeB5 | Envelope B5 (176 x 250 mm)
xlPaperEnvelopeB6 | Envelope B6 (176 x 125 mm)
xlPaperEnvelopeItaly | Envelope (110 x 230 mm)
xlPaperEnvelopeMonarch | Envelope Monarch (3 7/8 x 7 1/2 in.)
xlPaperEnvelopePersonal | Envelope (3 5/8 x 6 1/2 in.)
xlPaperFanfoldUS | U.S. Standard Fanfold (14 7/8 x 11 in.)
xlPaperFanfoldStdGerman | German Standard Fanfold (8 1/2 x 12 in.)
xlPaperFanfoldLegalGerman | German Legal Fanfold (8 1/2 x 13 in.)
xlPaperUser | User defined

Some printers may not support all paper sizes.

Example

This example sets the paper size of Sheet1 to legal.

Worksheets("Sheet1").PageSetup.PaperSize = xlPaperLegal


Parent Property

Applies To

All objects.

Description

Accessor. Returns the parent object for the specified object. Read-only.

Example

This example displays the name of the chart that contains myAxis.

Set myAxis = Charts(1).Axes(xlValue)
MsgBox myAxis.Parent.Name


Parent Property (DocumentProperty Object)

Description

Accessor. Returns the parent object for the specified object. Read-only.

To use this property, you should establish a reference to the Microsoft Office 95 Object Library by using the References command (Tools menu).

Example

This example displays the name of the parent for a document property. You must pass a DocumentProperty object to the procedure.

Sub DisplayParent(dp as DocumentProperty)
    MsgBox dp.Parent.Name
End Sub


ParentField Property

Applies To

PivotField Object.

Description

Accessor. Returns a PivotField object that represents the pivot field that is the group parent of the object. The field must be grouped and have a parent field. Read-only.

Example

This example displays the name of the field that is the group parent of the field that contains the active cell.

Worksheets("Sheet1").Activate
MsgBox "The active field is a child of the field " & _
    ActiveCell.PivotField.ParentField.Name


ParentItem Property

Applies To

PivotItem Object.

Description

Accessor. Returns a PivotItem object that represents the parent pivot item in the parent PivotField (the field must be grouped so that it has a parent). Read-only.

Example

This example displays the name of the parent item for the item that contains the active cell.

Worksheets("Sheet1").Activate
MsgBox "This item is a subitem of " & _
    ActiveCell.PivotItem.ParentItem.Name


ParentItems Method

Applies To

PivotField Object.

Description

Accessor. Returns an object that represents one pivot item (a PivotItem object, Syntax 1) or a collection of all the pivot items (a PivotItems object, Syntax 2) that are group parents in the specified field. The specified field must be a group parent of another field. Read-only.

Syntax 1

object.ParentItems(index)

Syntax 2

object.ParentItems

object

Required. The PivotField object.

index

Required for Syntax 1. The number or name of the pivot item to return (can be an array to specify more than one).

See Also

ChildItems Method, HiddenItems Method, PivotItems Method, VisibleItems Method.

Example

This example adds to a list box the names of all the items that are group parents in the field that contains the active cell. The list box appears on Sheet1.

Worksheets("Sheet1").Activate
Set newListBox = Worksheets("Sheet1").ListBoxes.Add _
    (Left:=10, Top:=72, Width:=144, Height:=144)
For Each pvtItem In ActiveCell.PivotField.ParentItems
    newListBox.AddItem (pvtItem.Name)
Next pvtItem


ParentShowDetail Property

Applies To

PivotItem Object.

Description

True if the specified item is showing because one of its parents is showing detail; False if the specified item is not showing because one of its parents is hiding detail. This property is only available if the item is grouped. Read-only.

Example

This example displays a message if the pivot item that contains the active cell is visible because its parent item is showing detail.

Worksheets("Sheet1").Activate
Set pvtItem = ActiveCell.PivotItem
If pvtItem.ParentShowDetail = True Then
    MsgBox "Parent item is showing detail"
End If


Parse Method

Applies To

Range Object.

Description

Parses a range of data and breaks it into multiple cells. Distributes the contents of the range to fill several adjacent columns; the range can be no more than one column wide.

Syntax

object.Parse(parseLine, destination)

object

Required. The range to parse.

parseLine

Optional. The parse line, as a string. This is a string containing left and right brackets to indicate where the cells should be split. For example, "[xxx][xxx]" would put the first three characters into the first column, and the next three characters into the second column of the destination range. If omitted, Microsoft Excel guesses where to split the columns based on the spacing of the top left cell in the range. If you want to use a different range to guess the parse line, use a Range as the parseLine argument. That range must be one of the cells that is being parsed. The parseLine argument cannot be longer than 255 characters, including the brackets and spaces.

destination

Optional. A range indicating the upper-left corner of the destination for the parsed data. If omitted, Microsoft Excel will parse in place.

Example

This example divides telephone numbers of the form 206-555-1212 into two columns. The first coulmn contains only the area code, and the second column contains the 7-digit telephone number with the embedded hyphen.

Worksheets("Sheet1").Columns("A").Parse _
    parseLine:="[xxx] [xxxxxxxx]", _
    destination:=Worksheets("Sheet1").Range("B1")


PasswordEdit Property

Applies To

EditBox Object, EditBoxes Collection.

Description

True if the edit box displays its contents as a series of asterisks. This property is available only in Microsoft Excel for Windows 95. Read-write.

Example

This example sets edit box one to display asterisks when the user enters data.

DialogSheets(1).EditBoxes(1).PasswordEdit = True


Paste Method (Chart Object)

Applies To

Chart Object.

Description

Pastes chart data from the Clipboard into the specified chart.

Syntax

object.Paste(type)

object

Required. The Chart object.

type

Optional. If another chart is in the Clipboard, specifies the chart information to paste (one of xlFormats, xlFormulas, or xlAll). The default is xlAll. If there is data other than a chart in the Clipboard, this parameter cannot be used.

Remarks

This method changes the current selection.

See Also

Copy Method, Cut Method, Paste Method (DialogSheet or Worksheet Object).

Example

This example pastes data from the range B1:B5 on Sheet1 into Chart1.

Worksheets("Sheet1").Range("B1:B5").Copy
Charts("Chart1").Paste


Paste Method (DialogSheet or Worksheet Object)

Applies To

DialogSheet Object, Worksheet Object.

Description

Pastes the contents of the Clipboard onto the sheet.

Syntax

object.Paste(destination, link)

object

Required. The DialogSheet or Worksheet object.

destination

Optional. A Range specifying where the Clipboard contents should be placed. If omitted, the current selection is used. This argument can only be specified if the contents of the Clipboard can be pasted into a range—it cannot be used with drawing objects. If this argument is specified, the link argument cannot be used.

link

Optional. If True, a link is established to the source of the pasted data. If this argument is specified, the destination argument cannot be used.

Remarks

If you do not specify the destination argument, you must select the destination range before you use this method.

This method may modify the sheet selection depending on the contents of the Clipboard. For example, pasted drawing objects remain selected.

See Also

Copy Method, Cut Method, Paste Method (Chart Object), PasteSpecial Method.

Example

This example copies data from cells C1:C5 on Sheet1 to cells D1:D5 on Sheet1.

Worksheets("Sheet1").Range("C1:C5").Copy
ActiveSheet.Paste destination:=Worksheets("Sheet1").Range("D1:D5")


Paste Method (Pictures Object)

Applies To

Pictures Collection.

Description

Pastes a picture from the Clipboard to a sheet or chart. The position of the new picture is determined by the current selection.

Syntax

object.Paste(link)

object

Required. The Pictures object.

link

Optional. If True, a link is established between the pasted picture and the source data. The default is False.

See Also

Copy Method, Cut Method.

Example

This example pastes a picture from the Clipboard to cell A1 on Sheet1.

Worksheets("Sheet1").Range("A1").Select
ActiveSheet.Pictures.Paste


Paste Method (Point or Series Object)

Applies To

Point Object, Series Object.

Description

Pastes a picture from the Clipboard as the marker on the selected point or series. This method can be used on column, bar, line, or radar charts, and it sets the MarkerStyle to xlPicture.

Syntax

object.Paste

object

Required. The Point or Series object.

See Also

Copy Method, Cut Method, MarkerStyle Property.

Example

This example copies a picture to the Clipboard and then pastes it into series one in Chart1.

Worksheets("Sheet1").Activate
ActiveSheet.Pictures(1).Copy
Charts("Chart1").Activate
ActiveChart.SeriesCollection(1).Paste


Paste Method (SeriesCollection Object)

Applies To

SeriesCollection Collection.

Description

Pastes data from the Clipboard to the specified series collection.

Syntax

object.Paste(rowcol, seriesLabels, categoryLabels, replace, newSeries)

object

Required. The SeriesCollection object.

rowcol

Optional. Specifies whether the values corresponding to a particular data series are in rows (xlRows) or columns (xlColumns). The default is xlColumns.

seriesLabels

Optional. If True, Microsoft Excel uses the contents of the cell in the first column of each row (or first row of each column) as the name of the data series in that row (or column). If False (or omitted), Microsoft Excel uses the contents of the cell in the first column of each row (or first row of each column) as the first data point of the data series.

categoryLabels

Optional. If True, Microsoft Excel uses the contents of the first row (or column) of the selection as the categories for the chart. If False (or omitted), Microsoft Excel uses the contents of the first row (or column) as the first data series in the chart.

replace

Optional. If True, Microsoft Excel applies categories while replacing existing categories with information from the copied cell range. If False, Microsoft Excel inserts new categories without replacing any old ones.

newSeries

Optional. Specifies whether the data is to be pasted as new series (True) or as new points on existing series (False). The default is True.

See Also

Add Method (SeriesCollection Collection), ChartWizard Method, Copy Method, Cut Method, Extend Method.

Example

This example copies data to the Clipboard from cells C1:C5 on Sheet1 and then pastes the data into Chart1 as a new series.

Worksheets("Sheet1").Range("C1:C5").Copy
Charts("Chart1").SeriesCollection.Paste


PasteFace Method

Applies To

ToolbarButton Object.

Description

Pastes a bitmap button face from the Clipboard onto the specified button.

Syntax

object.PasteFace

object

Required. The ToolbarButton object.

Remarks

This method cannot be used with a toolbar button that is a gap or that has a palette list attached (such as the Font or Style buttons).

See Also

BuiltInFace Property, CopyFace Method.

Example

This example copies the bitmap face of button one (the New Workbook button) on the Standard toolbar and pastes it onto button three (the Save button).

With Toolbars("Standard")
    .ToolbarButtons(1).CopyFace
    .ToolbarButtons(3).PasteFace
End With


PasteSpecial Method (DialogSheet or Worksheet Object)

Applies To

DialogSheet Object, Worksheet Object.

Description

Pastes the contents of the Clipboard onto the sheet using a specified format. Use this method to paste data from other applications or paste in a specific format.

Syntax

object.PasteSpecial(format, link, displayAsIcon, iconFileName, iconIndex, iconLabel)

object

Required. The DialogSheet or Worksheet object.

format

Required. Specifies the clipboard format of the data to paste (as text).

link

Optional. If True, a link is established to the source of the pasted data. If the source data is not suitable for linking or the source application doesn't support linking, this parameter is ignored. The default value is False.

displayAsIcon

Optional. If True, the pasted data is displayed as an icon. The default value is False.

iconFileName

Optional. The name of the file that contains the icon to use if displayAsIcon is True.

iconIndex

Optional. The index number of the icon within the icon file.

iconLabel

Optional. The text label of the icon.

Remarks

You must select the destination range before you use this method.

This method may modify the sheet selection depending on the contents of the Clipboard. For example, pasted drawing objects remain selected.

See Also

Copy Method, Cut Method, Paste Method (DialogSheet or WorkSheet Object), PasteSpecial Method (Range Object).

Example

This example pastes a Microsoft Word version 6.0 document object from the Clipboard to cell D1 on Sheet1.

Worksheets("Sheet1").Range("D1").Select
ActiveSheet.PasteSpecial format:="Microsoft Word 6.0 Document Object"

This example pastes the same Microsoft Word version 6.0 document object and displays it as an icon.

Worksheets("Sheet1").Range("F5").Select
ActiveSheet.PasteSpecial _
        format:="Microsoft Word 6.0 Document Object", _
        displayAsIcon:=True


PasteSpecial Method (Range Object)

Applies To

Range Object.

Description

Pastes a Range from the Clipboard to the specified range.

Syntax

object.PasteSpecial(paste, operation, skipBlanks, transpose)

object

Required. The Range object.

paste

Optional. Specifies the part of the range to be pasted (one of xlAll, xlFormulas, xlValues, xlFormats, xlNotes, or xlAllExceptBorders). If omitted, the default is xlAll.

operation

Optional. Specifies the paste operation (one of xlNone, xlAdd, xlSubtract, xlMultiply, or xlDivide). If omitted, the default is xlNone.

skipBlanks

Optional. If True, blank cells in the Range on the Clipboard will not be pasted into the destination. If omitted, the default is False.

transpose

Optional. If True, rows and columns are transposed when the Range is pasted. If omitted, the default is False.

See Also

Copy Method, Cut Method, Paste Method, PasteSpecial Method (DialogSheet or Worksheet Object).

Example

This example replaces the data in cells D1:D5 on Sheet1 with the sum of the existing contents and cells C1:C5 on Sheet1.

Worksheets("Sheet1").Range("C1:C5").Copy
Worksheets("Sheet1").Range("D1:D5").PasteSpecial operation:=xlAdd


Path Property

Applies To

AddIn Object, Application Object, Workbook Object.

Description

Returns the complete path of the object (as a string), without including the final separator and name of the object. Read-only.

Remarks

If you do not specify an object qualifier, this property returns the path to the Microsoft Excel application (it is equivalent to Application.Path).

Example

This example displays the complete path to Microsoft Excel.

MsgBox "The path is " & Application.Path


PathSeparator Property

Applies To

Application Object.

Description

Returns the character ":" on the Macintosh; "\" in Windows. Read-only.

Example

This example displays the current path separator.

MsgBox "The path separator character is " & Application.PathSeparator


Pattern Property

Applies To

Interior Object.

Description

Returns or sets the pattern of the interior. Read-write.

Remarks

This property can have one of the these values: xlAutomatic, xlChecker, xlCrissCross, xlDown, xlGray16, xlGray25, xlGray50, xlGray75, xlGray8, xlGrid, xlHorizontal, xlLightDown, xlLightHorizontal, xlLightUp, xlLightVertical, xlNone, xlSemiGray75, xlSolid, xlUp, or xlVertical.

See Also

PatternColor Property.

Example

This example adds a crisscross pattern to the interior of cell A1 on Sheet1.

Worksheets("Sheet1").Range("A1").Interior.Pattern = xlCrissCross


PatternColor Property

Applies To

Interior Object.

Description

Returns or sets the interior pattern color as an RGB value. Read-write.

See Also

Color Property, Pattern Property, PatternColorIndex Property.

Example

This example sets the interior pattern color for rectangle one on Sheet1.

With Worksheets("Sheet1").Rectangles(1).Interior
    .Pattern = xlGrid
    .PatternColor = RGB(255,0,0)
End With


PatternColorIndex Property

Applies To

Interior Object.

Description

Returns or sets the interior pattern color as an index into the current color palette (a value from 1 to 56, or xlNone if there is no background color). Read-write.

Remarks

Set this property to xlAutomatic to specify the automatic pattern for cells or the automatic fill style for drawing objects. Set this property to xlNone to specify no pattern (this is the same as setting Interior.Pattern to xlNone).

See Also

Color Property, Colors Property, Pattern Property, PatternColor Property.

Example

This example sets the interior pattern color for rectangle one on Sheet1.

With Worksheets("Sheet1").Rectangles(1).Interior
    .Pattern = xlChecker
    .PatternColorIndex = 5
End With


Period Property

Applies To

Trendline Object.

Description

Returns or sets the period of the trendline (applies only if this is a moving average trendline; its Type property must be xlMovingAvg). Read-write.

See Also

Type Property.

Example

This example sets the period for trendline one on Chart1, if the trendline is a moving-average trendline. The example should be run on a 2-D column chart with a single series that contains 10 data points and a moving-average trendline.

With Charts("Chart1").SeriesCollection(1).Trendlines(1)
    If .Type = xlMovingAvg Then .Period = 5
End With


Perspective Property

Applies To

Chart Object.

Description

Returns or sets the perspective for the 3-D chart view. Must be between 0 and 100. This property is ignored if the RightAngleAxes property is True. Read-write.

See Also

Elevation Property, RightAngleAxes Property, Rotation Property.

Example

This example sets the perspective of Chart1 to 70. The example should be run on a 3-D chart.

Charts("Chart1").RightAngleAxes = False
Charts("Chart1").Perspective = 70


PhoneticAccelerator Property

Applies To

Button Object, Buttons Collection, CheckBox Object, DrawingObjects Collection, GroupBox Object, GroupBoxes Collection, Label Object, Labels Collection, OptionButton Object, OptionButtons Collection.

Description

Returns or sets the phonetic keyboard accelerator key character for the control (this property is available only in Far East Microsoft Excel). The phonetic accelerator is used when the system accelerator mode is switched to phonetic characters (as opposed to roman characters, which use the Accelerator property). Read-write.

See Also

Accelerator Property.

Example

This example sets the accelerator and phonetic accelerator for button four on Dialog1.

With DialogSheets("Dialog1").Buttons(4)
    .Accelerator = "E"
    .PhoneticAccelerator = "l"
End With


Picture Object

Description

Represents a graphic (a bitmap, metafile, or image created from some other graphic file) or a linked or embedded OLE object attached to a sheet.

Accessors

The Picture object is a member of the Pictures collection. The Pictures collection includes all of the graphics on the sheet, as well as any linked or embedded OLE objects. Use the Insert method or the Picture command on the Insert menu to add a graphic file to a sheet as a graphic and add it to the collection. To access a single member of the collection, use the Pictures method with the index number or name of the graphic as an argument. While the Pictures collection contains OLEObject objects, it is easier to access the OLEObject objects using the OLEObjects collection and the OLEObjects method.

The following example deletes graphic one on worksheet one.

Worksheets(1).Pictures(1).Delete

The graphic name is shown in the Name Box when the graphic is selected. Use the Name property to set or return the graphic name. The following example duplicates the graphic named "Picture 13" and moves the new graphic so that its left edge lines up with the left edge of column H, and its top lines up with the top of row 10.

Set px = Worksheets(1).Pictures("picture 13").Duplicate
px.Left = Worksheets(1).Columns("H").Left
px.Top = Worksheets(1).Rows(10).Top

Properties

Application Property, Border Property, BottomRightCell Property, Creator Property, Enabled Property, Formula Property, Height Property, Index Property, Interior Property, Left Property, Locked Property, Name Property, OnAction Property, Parent Property, Placement Property, PrintObject Property, Shadow Property, Top Property, TopLeftCell Property, Visible Property, Width Property, ZOrder Property.

Methods

BringToFront Method, Copy Method, CopyPicture Method, Cut Method, Delete Method, Duplicate Method, Select Method, SendToBack Method.


Pictures Collection Object

Description

A collection of all the Picture objects on the specified chart sheet, dialog sheet, or worksheet. This collection includes graphics (bitmaps, metafiles, or images created from some other graphic file) and linked or embedded OLE objects.

Accessors

You add a graphic to a sheet by clicking the Picture command on the Insert menu or by using the Insert method. The following example adds the file ARCADE.BMP as a new graphic on worksheet one. The upper-left corner of the new graphic fits into the upper-left corner of the active cell.

Worksheets(1).Pictures.Insert "arcade.bmp"

Use the Pictures method with an argument to access a single member of the collection or without an argument to access the entire collection at once. The following example deletes all of the pictures on the worksheet named "Sheet1."

Worksheets("sheet1").Pictures.Delete

While the Pictures collection contains OLEObject objects, it is easier to access the OLEObject objects using the OLEObjects collection and the OLEObjects method.

Properties

Application Property, Border Property, Count Property, Creator Property, Enabled Property, Formula Property, Height Property, Interior Property, Left Property, Locked Property, OnAction Property, Parent Property, Placement Property, PrintObject Property, Shadow Property, Top Property, Visible Property, Width Property, ZOrder Property.

Methods

Add Method (Graphic Objects and Controls), BringToFront Method, Copy Method, CopyPicture Method, Cut Method, Delete Method, Duplicate Method, Group Method, Insert Method, Item Method, Paste Method (Pictures Object), Select Method, SendToBack Method.


Pictures Method

Applies To

Chart Object, DialogSheet Object, Worksheet Object.

Description

Accessor. Returns an object that represents a single picture (a Picture object, Syntax 1) or a collection of pictures (a Pictures object, Syntax 2) on the sheet. Read-only.

Syntax 1

object.Pictures(index)

Syntax 2

object.Pictures

object

Required. The object containing the pictures.

index

Required for Syntax 1. The name or number of the picture.

Example

This example deletes every picture on Sheet1.

Worksheets("Sheet1").Pictures.Delete

This example changes the color of the border of picture one on Sheet1 to red.

Worksheets("Sheet1").Pictures(1).Border.ColorIndex = 3


PictureType Property

Applies To

Point Object, Series Object.

Description

Returns or sets how pictures are displayed on a column or bar picture chart, as shown in the following table. Applies only to column and bar picture charts. Read-write.

Value | Meaning
xlStretch | Stretch the picture to reach the necessary value.
xlStack | Stack the pictures to reach the necessary value.
xlScale | Stack the pictures, but use the PictureUnit property to determine what unit each picture represents.

See Also

PictureUnit Property.

Example

This example sets series one in Chart1 to stretch pictures. The example should be run on a 2-D column chart with picture data markers.

Charts("Chart1").SeriesCollection(1).PictureType = xlStretch


PictureUnit Property

Applies To

Point Object, Series Object.

Description

Returns or sets the unit for each picture on a column or bar picture chart if the PictureType property is set to xlScale (if not, this property is ignored). Read-write.

See Also

PictureType Property.

Example

This example sets series one in Chart1 to stack pictures and uses each picture to represent five units. The example should be run on a 2-D column chart with picture data markers.

With Charts("Chart1").SeriesCollection(1)
    .PictureType = xlScale
    .PictureUnit = 5
End With


Pie3DGroup Property

Applies To

Chart Object.

Description

Accessor. Returns a ChartGroup object that represents the pie chart group on a 3-D chart. Read-only.

See Also

PieGroups Method.

Example

This example converts the 3-D pie group in Chart1 to a 3-D area group. The example should be run on a 3-D chart.

Charts("Chart1").Pie3DGroup.Type = xl3DArea


PieGroups Method

Applies To

Chart Object.

Description

Accessor. On a 2-D chart, returns an object that represents a single pie chart group (a ChartGroup object, Syntax 1), or a collection of the pie chart groups (a ChartGroups collection, Syntax 2).

Syntax 1

object.PieGroups(index)

Syntax 2

object.PieGroups

object

Required. The Chart object.

index

Required for Syntax 1. Specifies the chart group.

See Also

Pie3DGroup Property.

Example

This example converts pie group one in Chart1 to an area group. The example should be run on a 2-D chart.

Charts("Chart1").PieGroups(1).Type = xlArea


PivotField Object

Description

Represents a field in a pivot table.

Accessors

The PivotField object is a member of the PivotFields collection. The PivotFields collection contains all the fields objects in a PivotTable, including hidden fields.

To access a single member of the collection, use the PivotFields method with the index number or name of the pivot field as an argument.

Use the Name property to set or return the pivot field name. The following example makes the field named "year" a row field.

Worksheets("sheet3").PivotTables(1) _
    .PivotFields("year").Orientation = xlRowField

In some cases, it may be easier to use one of the methods that returns a subset of the PivotTable fields. The following accessor methods are available: ColumnFields method, DataFields method, HiddenFields method, PageFields method, RowFields method, VisibleFields method.

Properties

Application Property, BaseField Property, BaseItem Property, Calculation Property, ChildField Property, Creator Property, CurrentPage Property, DataRange Property, DataType Property, Function Property, GroupLevel Property, LabelRange Property, Name Property, NumberFormat Property, Orientation Property, Parent Property, ParentField Property, Position Property, SourceName Property, Subtotals Property, TotalLevels Property, Value Property.

Methods

ChildItems Method, HiddenItems Method, ParentItems Method, PivotItems Method, VisibleItems Method.


PivotField Property

Applies To

Range Object.

Description

Accessor. Returns a PivotField object that represents the pivot field containing the top left corner of the specified range. Read-only.

Example

This example displays the name of the pivot field containing the active cell.

Worksheets("Sheet1").Activate
MsgBox "The active cell is in the field " & _
    ActiveCell.PivotField.Name


PivotFields Collection Object

Description

A collection of all the PivotField objects in a PivotTable.

Accessors

Use the PivotFields method with an argument to access a single member of the collection or without an argument to access the entire collection at once. The following example uses the Count property of the PivotFields collection to set up a loop that enumerates the pivot field names.

With Worksheets("sheet3").PivotTables(1)
    For i = 1 To .PivotFields.Count
        MsgBox .PivotFields(i).Name
    Next
End With

In some cases, it may be easier to use one of the methods that returns a subset of the pivot fields. The following accessor methods are available: ColumnFields method, DataFields method, HiddenFields method, PageFields method, RowFields method, VisibleFields method.

Properties

Application Property, Count Property, Creator Property, Parent Property.

Methods

Item Method.


PivotFields Method

Applies To

PivotTable Object.

Description

Accessor. Returns an object that represents a single pivot field (a PivotField object, Syntax 1) or a collection of the visible and hidden pivot fields (a PivotFields object, Syntax 2) in the PivotTable. Read-only.

Syntax 1

object.PivotFields(index)

Syntax 2

object.PivotFields

object

Required. The PivotTable object.

index

Required for Syntax 1. The name or number of the pivot field to return (can be an array to specify more than one).

See Also

ColumnFields Method, DataFields Method, HiddenFields Method, PageFields Method, RowFields Method, VisibleFields Method.

Example

This example adds the PivotTable field names to a list box. The list box appears on Sheet1.

Set pvtTable = Worksheets("Sheet1").Range("A3").PivotTable
Set newListBox = Worksheets("Sheet1").ListBoxes.Add _
    (Left:=10, Top:=72, Width:=144, Height:=144)
For Each hdnField In pvtTable.PivotFields
    newListBox.AddItem (hdnField.Name)
Next hdnField
Worksheets("Sheet1").Activate


PivotItem Object

Description

Represents an item in a pivot field. The items are the individual data entries in a field category.

Accessors

The PivotItem object is a member of the PivotItems collection. The PivotItems collection contains all the items in a PivotField object.

To access a single member of the collection, use the PivotItems method with the pivot item index number or name as an argument.

Use the Name property to set or return the item name. The following example hides the entries containing the value "1998" in the year field.

Worksheets("sheet3").PivotTables(1) _
    .PivotFields("year").PivotItems("1998").Visible = False

Properties

Application Property, Creator Property, DataRange Property, LabelRange Property, Name Property, Parent Property, ParentItem Property, ParentShowDetail Property, Position Property, ShowDetail Property, SourceName Property, Value Property, Visible Property.

Methods

ChildItems Method.


PivotItem Property

Applies To

Range Object.

Description

Accessor. Returns a PivotItem object that represents the pivot item containing the top left corner of the specified range. Read-only.

Example

This example displays the name of the pivot item containing the active cell.

Worksheets("Sheet1").Activate
MsgBox "The active cell is in the item " & _
    ActiveCell.PivotItem.Name


PivotItems Collection Object

Description

A collection of all the PivotItem objects in a pivot field. The items are the individual data entries in a field category.

Accessors

Use the PivotItems method with an argument to access a single member of the collection or without an argument to access the entire collection at once. The following example creates an enumerated list of pivot field names and the items contained in those fields. It uses the Count method on the PivotItems collection to set up the item-enumeration loop.

Worksheets("sheet4").Activate
With Worksheets("sheet3").PivotTables(1)
    c = 1
    For i = 1 To .PivotFields.Count
        r = 1
        Cells(r, c) = .PivotFields(i).Name
        r = r + 1
        For x = 1 To .PivotFields(i).PivotItems.Count
            Cells(r, c) = .PivotFields(i).PivotItems(x).Name
            r = r + 1
        Next
        c = c + 1
    Next
End With

Properties

Application Property, Count Property, Creator Property, Parent Property.

Methods

Item Method.


PivotItems Method

Applies To

PivotField Object.

Description

Accessor. Returns an object that represents a single pivot item (a PivotItem object, Syntax 1) or a collection of all the visible and hidden pivot items (a PivotItems object, Syntax 2) in the specified field. Read-only.

Syntax 1

object.PivotItems(index)

Syntax 2

object.PivotItems

object

Required. The PivotField object.

index

Required for Syntax 1. The number or name of the pivot item to return (can be an array to specify more than one).

See Also

ChildItems Method, HiddenItems Method, ParentItems Method, VisibleItems Method.

Example

This example adds the names of all items in the field named "COMPANY" to a list box. The list box appears on Sheet1.

Set pvtTable = Worksheets("Sheet1").Range("A3").PivotTable
Set newListBox = Worksheets("Sheet1").ListBoxes.Add _
    (Left:=10, Top:=72, Width:=144, Height:=144)
Set pvtField = pvtTable.PivotFields("COMPANY")
For Each pvtItem In pvtField.PivotItems
    newListBox.AddItem (pvtItem.Name)
Next pvtItem
Worksheets("Sheet1").Activate


PivotTable Object

Description

Represents a PivotTable on a worksheet.

Accessors

The PivotTable object is a member of the PivotTables collection. The PivotTables collection contains all the PivotTable objects on a single worksheet. Use the PivotTableWizard method to create a new PivotTable and add it to the collection.

To access a single member of the collection, use the PivotTables method with the PivotTable index number or name as an argument.

The following example makes the field named "year" a row field in PivotTable one on the worksheet named "Sheet3."

Worksheets("sheet3").PivotTables(1) _
    .PivotFields("year").Orientation = xlRowField

Use the Name property to set or return the PivotTable name. The following example moves the field named "year" on the PivotTable named "PivotTable2."

Worksheets("sheet3").PivotTables("pivottable2") _
    .PivotFields("year").Position = 2

Because PivotTable programming can be complex, it is generally easier to record PivotTable actions by clicking the Record Macro command on the Tools menu.

Properties

Application Property, ColumnGrand Property, ColumnRange Property, Creator Property, DataBodyRange Property, DataLabelRange Property, HasAutoFormat Property, InnerDetail Property, Name Property, PageRange Property, Parent Property, RefreshDate Property, RefreshName Property, RowGrand Property, RowRange Property, SaveData Property, SourceData Property, TableRange1 Property, TableRange2 Property, Value Property.

Methods

AddFields Method, ColumnFields Method, DataFields Method, HiddenFields Method, PageFields Method, PivotFields Method, RefreshTable Method, RowFields Method, ShowPages Method, VisibleFields Method.


PivotTable Property

Applies To

Range Object.

Description

Accessor. Returns a PivotTable object that represents the PivotTable containing the top left corner of the specified range. Read-only.

Example

This example sets the current page for the PivotTable on Sheet1 to the page named "Canada."

Set pvtTable = Worksheets("Sheet1").Range("A3").PivotTable
pvtTable.PivotFields("Country").CurrentPage = "Canada"


PivotTables Collection Object

Description

A collection of all the PivotTable objects on the specified worksheet.

Accessors

Use the PivotTableWizard method to create a new PivotTable and add it to the collection.

Use the PivotTables method with an argument to access a single member of the collection or without an argument to access the entire collection at once. The following example displays the number of PivotTables on the worksheet named "Sheet3."

MsgBox Worksheets("sheet3").PivotTables.Count

Properties

Application Property, Count Property, Creator Property, Parent Property.

Methods

Item Method.


PivotTables Method

Applies To

Worksheet Object.

Description

Accessor. Returns an object that represents a single PivotTable (a PivotTable object, Syntax 1) or a collection of all the PivotTables (a PivotTables object, Syntax 2) in a worksheet. Read-only.

Syntax 1

object.PivotTables(index)

Syntax 2

object.PivotTables

object

Required. The Worksheet object.

index

Required for Syntax 1. The name or number of the PivotTable (can be an array to specify more than one).

See Also

PivotFields Method, PivotItems Method.

Example

This example sets the Sum of 1994 field in PivotTable1 to use the SUM function.

ActiveSheet.PivotTables("PivotTable1"). _
    PivotFields("Sum of 1994").Function = xlSum


PivotTableWizard Method

Applies To

Worksheet Object.

Description

Creates a PivotTable. This method does not display the PivotTable Wizard.

Syntax

object.PivotTableWizard(sourceType, sourceData, tableDestination, tableName, rowGrand, columnGrand, saveData, hasAutoFormat, autoPage)

object

Required. The Worksheet object.

sourceType

Optional. Describes the source of the PivotTable data, as shown in the following table. If you specify this argument, you must also specify sourceData.

Value

Meaning

xlConsolidation

Multiple consolidation ranges

xlDatabase

Microsoft Excel list or database

xlExternal

Data from another application

xlPivotTable

Same source as another PivotTable

If sourceType and sourceData are not specified, Microsoft Excel assumes that the source type is xlDatabase, and the source data comes from the named range Database. If the named range does not exist, Microsoft Excel uses the current region if the current selection is in a range of more than 10 cells containing data. If this is not true, this method will fail.

sourceData

Optional. The data for the new PivotTable. A Range, an array of ranges, or a text constant representing the name of another PivotTable. For an external database, this is a two-element array. The first element is the connection string specifying the ODBC source for the data. The second element is the SQL query string used to get the data. If you specify this argument, you must specify sourceType. If the active cell is inside the sourceData range, you must specify tableDestination.

tableDestination

Optional. A Range specifying where the PivotTable should be placed on the worksheet. If this argument is not specified, the PivotTable is placed at the active cell.

tableName

Optional. The name of the PivotTable to be created, given as a string.

rowGrand

Optional. If True, the new PivotTable shows row grand totals. If False, row grand totals are omitted.

columnGrand

Optional. If True, the new PivotTable shows column grand totals. If False, column grand totals are omitted.

saveData

Optional. If True, data is saved with the table. If False, only the table definition is saved.

hasAutoFormat

Optional. If True, Microsoft Excel automatically formats the PivotTable when it is refreshed or when fields are moved.

autoPage

Optional. Valid only if sourceType is xlConsolidation. If True, Microsoft Excel creates a page field for the consolidation. If False, you must create the page field or fields.

Example

This example creates a new PivotTable from a Microsoft Excel database (contained in the range A1:C100).

ActiveSheet.PivotTableWizard xlDatabase, Range("A1:C100")


Placement Property

Applies To

Arc Object, Arcs Collection, Button Object, Buttons Collection, ChartObject Object, ChartObjects Collection, CheckBox Object, Drawing Object, DrawingObjects Collection, Drawings Collection, DropDown Object, DropDowns Collection, EditBox Object, EditBoxes Collection, GroupBox Object, GroupBoxes Collection, GroupObject Object, GroupObjects Collection, Label Object, Labels Collection, Line Object, Lines Collection, ListBox Object, ListBoxes Collection, OLEObject Object, OLEObjects Collection, OptionButton Object, OptionButtons Collection, Oval Object, Ovals Collection, Picture Object, Pictures Collection, Rectangle Object, Rectangles Collection, ScrollBar Object, ScrollBars Collection, Spinner Object, Spinners Collection, TextBox Object, TextBoxes Collection.

Description

Returns or sets how the object is attached to the cells below it. Can be one of xlMoveAndSize, xlMove, or xlFreeFloating. Can be used only on objects in a worksheet. Read-write.

Example

This example sets oval one on Sheet1 to be free floating (it neither moves nor is sized with its underlying cells).

Worksheets("Sheet1").Ovals(1).Placement = xlFreeFloating


Play Method

Applies To

SoundNote Object.

Description

Plays the sound note.

Syntax

object.Play

object

Required. The SoundNote object.

Remarks

To play sounds, you must have sound hardware installed in your computer.

See Also

Record Method.

Example

This example deletes the sound note in cell A1 on Sheet1, records a new sound note for the same cell, and then plays the sound note.

With Worksheets("Sheet1").Range("A1").SoundNote
    .Delete
    .Record
    .Play
End With


PlotArea Object

Description

Represents the plot area of a chart. This is the area in which your chart data is plotted. The plot area on a 2-D chart contains the data markers, gridlines, data labels, trendlines, and optional chart items placed in the chart area. The plot area on a 3-D chart contains all the above items plus the walls, floor, axes, axis titles, and tick-mark labels in the chart.

The plot area is surrounded by the chart area. The chart area on a 2-D chart contains the axes, the chart title, axis titles, and the legend. The chart area on a 3-D chart contains the chart title and the legend. For information about formatting the chart area, see the ChartArea object.

Accessors

The PlotArea property returns the plot area for the specified chart. The following example activates the chart sheet named "Chart1," places a dashed border around the chart area for the active chart, and places a dotted border around the plot area.

Charts("Chart1").Activate
With ActiveChart
    .ChartArea.Border.LineStyle = xlDash
    .PlotArea.Border.LineStyle = xlDot
End With

Properties

Application Property, Border Property, Creator Property, Height Property, Interior Property, Left Property, Name Property, Parent Property, Top Property, Width Property.

Methods

ClearFormats Method, Select Method.


PlotArea Property

Applies To

Chart Object.

Description

Accessor. Returns a PlotArea object that represents the plot area of a chart. Read-only.

Example

This example sets the color of the plot area interior of Chart1 to cyan.

Charts("Chart1").PlotArea.Interior.ColorIndex = 8


PlotOrder Property

Applies To

Series Object.

Description

Returns or sets the plot order for this series within the chart group. Read-write.

Remarks

Plot order can only be set within a chart group (you cannot set the plot order for the entire chart if you have more than one chart type). A chart group is a collection of series with the same chart type and subtype.

Changing the plot order of one series will cause the plot orders of the other series on the chart group to adjust as necessary.

Example

This example makes series two in Chart1 appear third in the plot order. The example should be run on a 2-D column chart with three or more series.

Charts("Chart1").ChartGroups(1).SeriesCollection(2).PlotOrder = 3


PlotVisibleOnly Property

Applies To

Chart Object.

Description

True if only visible cells are plotted (False if both visible and hidden cells are plotted). Read-write.

Example

This example causes Microsoft Excel to plot only visible cells in Chart1.

Charts("Chart1").PlotVisibleOnly = True


Point Object

Description

Represents a single point in a series in a chart.

Accessors

The Point object is a member of the Points collection. The Points collection contains all of the points in one series. To access a single member of the collection, use the Points method with the point index number as an argument. Points are numbered from left to right on the series. Points(1) is the leftmost point; Points(Points.Count) is the rightmost point. The following example sets the marker style for point three in series one in embedded chart one on worksheet one. The specified series must be a 2-D line, scatter, or radar series.

Worksheets(1).ChartObjects(1).Chart. _
    SeriesCollection(1).Points(3).MarkerStyle = xlDiamond

Properties

Application Property, Border Property, Creator Property, DataLabel Property, Explosion Property, HasDataLabel Property, Interior Property, InvertIfNegative Property, MarkerBackgroundColor Property, MarkerBackgroundColorIndex Property, MarkerForegroundColor Property, MarkerForegroundColorIndex Property, MarkerStyle Property, Parent Property, PictureType Property, PictureUnit Property.

Methods

ApplyDataLabels Method, ClearFormats Method, Copy Method, Delete Method, Paste Method (Point or Series Object), Select Method.


Points Collection Object

Description

A collection of all the Point objects in the specified series in a chart.

Accessors

Use the Points method with an argument to access a single member of the collection or without an argument to access the entire collection at once. The following example adds a data label to the last point on series one.

Dim pts As Points
Set pts = Worksheets(1).ChartObjects(1).Chart. _
    SeriesCollection(1).Points
pts(pts.Count).ApplyDataLabels type:=xlShowValue

Properties

Application Property, Count Property, Creator Property, Parent Property.

Methods

Item Method.


Points Method

Applies To

Series Object.

Description

Accessor. Returns an object that represents a single point (a Point object, Syntax 1) or a collection of all of the points (a Points object, Syntax 2) in the series. Read-only.

Syntax 1

object.Points(index)

Syntax 2

object.Points

object

Required. The Series object.

index

Required for Syntax 1. The name or number of the point.

Example

This example applies a data label to point one in series one in Chart1.

Charts("Chart1").SeriesCollection(1).Points(1).ApplyDataLabels


Position Property

Applies To

Legend Object, PivotField Object, PivotItem Object, Toolbar Object.

Description

Returns or sets the position of the specified object, as shown in the following table. Read-write.

Object | Position
Legend | Position of the legend on the chart. One of xlBottom, xlCorner, xlTop, xlRight, or xlLeft.
PivotField | Position of the field (first, second, third, and so on) among all the fields in its orientation (Rows, Columns, Pages, Data).
PivotItem | Position of the item in its field, if the item is currently showing.
Toolbar | Position of the toolbar. One of xlTop, xlLeft, xlRight, xlBottom, or xlFloating.

Example

This example sets the pivot field that contains the active cell to position one.

Worksheets("Sheet1").Activate
ActiveCell.PivotField.Position = 1

This example displays the position number of the pivot item that contains the active cell.

Worksheets("Sheet1").Activate
MsgBox "The active item is in position number " & _
    ActiveCell.PivotItem.Position


Post Method

Applies To

Workbook Object.

Description

Posts the specified workbook to a public folder or a Lotus Notes database. This method is available only in Microsoft Excel for Windows 95.

Syntax

object.Post(destName)

object

Required. The workbook to post.

destName

Optional. Specifies the name of the destination public folder or Lotus Notes database. In Microsoft Excel for Windows 95, this argument is ignored. The Post method prompts the user to specify the destination for the workbook.

Example

This example posts the active workbook.

ActiveWorkbook.Post


Precedents Property

Applies To

Range Object.

Description

Accessor. Returns a Range object that represents all of the precedents of a cell. This may be a multiple selection (a union of Range objects) if there is more than one precedent. Read-only.

See Also

Dependents Property, DirectDependents Property, DirectPrecedents Property, ShowPrecedents Method.

Example

This example selects the precedents of cell A1 on Sheet1.

Worksheets("Sheet1").Activate
Range("A1").Precedents.Select


PrecisionAsDisplayed Property

Applies To

Workbook Object.

Description

True if calculations in this workbook will be done using only the precision of the numbers as they are displayed. Read-write.

Example

This example causes calculations on the active workbook to use only the precision of the numbers as they are displayed.

ActiveWorkbook.PrecisionAsDisplayed = True


PrefixCharacter Property

Applies To

Range Object.

Description

Returns the prefix character for the cell. Read-only.

Remarks

If the TransitionNavigKeys property is False, this character will be ' for a text label, or blank. If the TransitionNavigKeys property is True, this will be ' for a left-justified label, " for a right-justified label, ^ for a centered label, \ for a repeated label, or blank.

Example

This example displays the prefix character for cell A1 on Sheet1.

MsgBox "The prefix character is " & _
    Worksheets("Sheet1").Range("A1").PrefixCharacter


Previous Property

Applies To

Chart Object, DialogSheet Object, Module Object, Range Object, Worksheet Object.

Description

Accessor. Returns a Chart, DialogSheet, Module, Range or Worksheet object that represents the previous sheet or cell. Read-only.

Remarks

If the object is a range, this property emulates SHIFT+TAB, although the property returns the previous cell without selecting it.

On a protected sheet, this property returns the previous unlocked cell. On an unprotected sheet, this property always returns the cell to the left of the specified cell.

See Also

ActivatePrevious Method, Next Property.

Example

This example selects the previous unlocked cell on Sheet1. If Sheet1 is unprotected, this is the cell immediately to the left of the active cell.

Worksheets("Sheet1").Activate
ActiveCell.Previous.Select


PreviousSelections Property

Applies To

Application Object.

Description

Accessor. Returns an array of the four previous ranges or names selected. Each element in the array is a Range object. Read-only. Each time you go to a range or cell using the name box or Go To command (Edit menu), or a macro calls the Goto method, whatever range was selected before is added to this array as element number one, and the other items in the array are moved down.

Example

This example displays the cell addresses of all items in the array of previous selections. If there are no previous selections, the LBound function returns an error. This error is trapped, and a message box appears.

On Error GoTo noSelections
For i = LBound(Application.PreviousSelections) To _
            UBound(Application.PreviousSelections)
    MsgBox Application.PreviousSelections(i).Address
Next i
Exit Sub
On Error GoTo 0

noSelections:
    MsgBox "There are no previous selections"


Print # Statement

Description

Writes display-formatted data to a sequential file.

Syntax

Print #filenumber,[outputlist]

The Print # statement syntax has these parts:

Part | Description
filenumber | Any valid file number.
outputlist | Expression or list of expressions to print.

The outputlist argument has the following syntax and parts:

[{Spc(n) | Tab[(n)]}][expression][charpos]

Part | Description
Spc(n) | Used to insert space characters in the output, where n is the number of space characters to insert.
Tab(n) | Used to position the insertion point to an absolute column number, where n is the column number. Use Tab with no argument to position the insertion point at the beginning of the next print zone.
expression | Numeric or string expressions to print.
charpos | Specifies the insertion point for the next character. Use a semicolon to specify the insertion point to be immediately after the last character displayed. Use Tab(n) to position the insertion point to an absolute column number. Use Tab with no argument to position the insertion point at the beginning of the next print zone. If charpos is omitted, the next character is printed on the next line.

Remarks

If you omit outputlist and include only a list separator after filenumber, a blank line prints to the file. Multiple expressions can be separated with either a space or a semicolon. A space has the same effect as a semicolon.

All data written to the file using Print # is internationally aware; that is, the data is properly formatted (using the appropriate decimal separator) and the keywords are output in the language appropriate for the international locale specified for your system.

For Boolean data, either True or False is printed. The True and False keywords are translated, as appropriate, according to the locale setting specified for your system.

Date data is written to the file using the standard short date format recognized by your system. When either the date or the time component is missing or zero, only the provided part gets written to the file.

Nothing is written to the file if outputlist data is Empty. However, if outputlist data is Null, Null is written to the file. Again, the Null keyword is translated, as appropriate.

For error data, the output appears as Error errorcode. The Error keyword is translated, as appropriate, when written to the file.

Because Print # writes an image of the data to the file, you must delimit the data so it prints correctly. If you use Tab with no arguments to move the print position to the next print zone, Print # also writes the spaces between print fields to the file.

Note

If, at some future time, you want to read the data from a file using the Input # statement, use the Write # statement instead of the Print # statement to write the data to the file. Using Write # ensures the integrity of each separate data field by properly delimiting it, so that it can be read back in using Input #. Using Write # also ensures that it can be correctly read in any locale.

See Also

Open Statement, Print Method, Spc Function, Tab Function, Write # Statement.

Example

This example uses the Print # statement to write data to a file.

Open "TESTFILE" For Output As #1    ' Open file for output.
Print #1, "This is a test"    ' Print text to file.
Print #1,    ' Print blank line to file.
Print #1, "Zone 1"; Tab ; "Zone 2"    ' Print in two print zones.
Print #1, "Hello" ; " " ; "World"    ' Separate strings with space.
Print #1, Spc(5) ; "5 leading spaces "    ' Print 5 leading spaces.
Print #1, Tab(10) ; "Hello"    ' Print word at col 10.

' Assign Boolean, Date, Null and Error values.
MyBool = False : MyDate = #February 12, 1969# : MyNull = Null
MyError = CVErr(32767)
' True, False, Null and Error are translated using locale settings of
' your system. Date literals are written using standard short date
' format.
Print #1, MyBool ; " is a Boolean value"
Print #1, MyDate ; " is a date"
Print #1, MyNull ; " is a null value"
Print #1, MyError ; " is an error value"
Close #1    ' Close file.


Print Method

Applies To

Debug Object.

Description

Prints text in the Immediate pane of the Debug window.

Syntax

[object.]Print [outputlist]

The Print method syntax has these parts:

Part | Description
object | Object expression that evaluates to the Debug object.
outputlist | Expression or list of expressions to print. If omitted, a blank line is printed.

The outputlist argument has the following syntax and parts:

[{Spc(n) | Tab[(n)]}][expression][charpos]

Part | Description
Spc(n) | Used to insert space characters in the output, where n is the number of space characters to insert.
Tab(n) | Used to position the insertion point at an absolute column number where n is the column number. Use Tab with no argument to position the insertion point at the beginning of the next print zone.
expression | Numeric or string expressions to print.
charpos | Specifies the insertion point for the next character. Use a semicolon to specify the insertion point to immediately follow the last character displayed. Use Tab(n) to position the insertion point at an absolute column number. Use Tab with no argument to position the insertion point at the beginning of the next print zone. If charpos is omitted, the next character is printed on the next line.

Remarks

Multiple expressions can be separated with either a space or a semicolon. A space has the same effect as a semicolon.

All data printed to the Immediate pane is internationally aware; that is, the data is properly formatted (using the appropriate decimal separator) and the keywords are output in the language appropriate for the international locale specified for your system.

For Boolean data, either True or False is printed. The True and False keywords are translated, as appropriate, according to the locale setting specified for your system.

Date data is written using the standard short date format recognized by your system. When either the date or the time component is missing or zero, only the data provided gets written.

Nothing is written if outputlist data is Empty. However, if outputlist data is Null, Null is output. Again, the Null keyword is translated, as appropriate, when output.

For error data, the output appears as Error errorcode. The Error keyword is translated, as appropriate, when output.

Note

Because the Print method normally prints with proportionally-spaced characters, it is important to remember that there is no correlation between the number of characters printed and the number of fixed-width columns those characters occupy. For example, a wide letter, such as a "W", occupies more than one fixed-width column, whereas a narrow letter, such as an "i", occupies less. To account for cases where wider than average characters are used, you must ensure that your tabular columns are positioned far enough apart. Alternatively, you can print using a fixed-pitch font (such as Courier) to ensure that each character uses only one column.

See Also

Debug Object, Print # Statement, Spc Function, Tab Function.

Example

This example uses the Print method to output text to the Debug object; that is, display text in the Debug window.

For I = 11 To 20    ' Loop 10 times.
    ' Print each value on a new line.
    Debug.Print I
Next I

For I = 11 To 20    ' Loop 10 times.
    ' Print values on the same line, next to each other.
    Debug.Print I;
Next I
Debug.Print Spc(10) ; "Hello there"    ' Print 10 spaces before.
Debug.Print Tab(20) ; "This is a test"    ' Print at column 20.
Debug.Print "Hello"; Tab; Tab; "There"    ' Print 2 print zones apart.


PrintArea Property

Applies To

PageSetup Object.

Description

Returns or sets the range to print, as a string using A1-style references in the language of the macro. Read-write.

Remarks

Set this property to False or to the empty string ("") to set the print area to the entire sheet.

This property applies only to worksheet pages.

See Also

PrintOut Method.

Example

This example sets the print area to cells A1:C5 on Sheet1.

Worksheets("Sheet1").PageSetup.PrintArea = "$A$1:$C$5"

This example sets the print area to the current region on Sheet1. Note that you use the Address method to return an A1-style address.

Worksheets("Sheet1").Activate
ActiveSheet.PageSetup.PrintArea = _
        ActiveCell.CurrentRegion.Address


PrintGridlines Property

Applies To

PageSetup Object.

Description

True if cell gridlines are printed on the page. Read-write.

Remarks

This property applies only to worksheets.

See Also

DisplayGridlines Property.

Example

This example prints cell gridlines when Sheet1 is printed.

Worksheets("Sheet1").PageSetup.PrintGridlines = True


PrintHeadings Property

Applies To

PageSetup Object.

Description

True if row and column headings are printed with this page. Read-write.

Remarks

This property applies only to worksheets.

The DisplayHeadings property controls on-screen heading display.

Example

This example turns off heading printing for Sheet1.

Worksheets("Sheet1").PageSetup.PrintHeadings = False


PrintNotes Property

Applies To

PageSetup Object.

Description

True if cell notes will be printed along with the sheet. Read-write.

Remarks

This property applies only to worksheet pages.

Example

This example turns off notes printing.

Worksheets("Sheet1").PageSetup.PrintNotes = False


PrintObject Property

Applies To

Arc Object, Arcs Collection, Button Object, Buttons Collection, ChartObject Object, ChartObjects Collection, CheckBox Object, Drawing Object, DrawingObjects Collection, Drawings Collection, DropDown Object, DropDowns Collection, EditBox Object, EditBoxes Collection, GroupBox Object, GroupBoxes Collection, GroupObject Object, GroupObjects Collection, Label Object, Labels Collection, Line Object, Lines Collection, ListBox Object, ListBoxes Collection, OLEObject Object, OLEObjects Collection, OptionButton Object, OptionButtons Collection, Oval Object, Ovals Collection, Picture Object, Pictures Collection, Rectangle Object, Rectangles Collection, ScrollBar Object, ScrollBars Collection, Spinner Object, Spinners Collection, TextBox Object, TextBoxes Collection.

Description

True if the object will be printed when the document is printed. Read-write.

See Also

PrintOut Method.

Example

This example sets line one on Sheet1 to print with the worksheet.

Worksheets("Sheet1").Lines(1).PrintObject = True


PrintOut Method

Applies To

Chart Object, Charts Collection, DialogSheet Object, DialogSheets Collection, Module Object, Modules Collection, Range Object, Sheets Collection, Window Object, Workbook Object, Worksheet Object, Worksheets Collection.

Description

Prints the object.

Syntax

object.PrintOut(from, to, copies, preview, activePrinter, printToFile, collate)

object

Required. The object to print.

from

Optional. The number of the page with which to start printing. If omitted, printing starts at the beginning.

to

Optional. The number of the last page to print. If omitted, printing goes to the last page.

copies

Optional. The number of copies to print. If omitted, one copy is printed.

preview

Optional. If True, Microsoft Excel invokes print preview before printing the object. If False (or omitted) the object is printed immediately.

activePrinter

Optional. Sets the name of the active printer.

printToFile

Optional. If True, printing goes to a file. Microsoft Excel prompts the user to enter the name of the output file. There is no way to specify the output filename from Visual Basic.

collate

Optional. If True, multiple copies are collated.

Remarks

"Pages" in the descriptions of from and to refers to printed pages-not overall pages in the sheet or workbook.

This method applies to the Window object only when it is the Info window.

See Also

PrintArea Property, PrintPreview Method.

Example

This example prints the active sheet.

ActiveSheet.PrintOut


PrintPreview Method

Applies To

Chart Object, Charts Collection, DialogSheet Object, DialogSheets Collection, Range Object, Sheets Collection, Window Object, Workbook Object, Worksheet Object, Worksheets Collection.

Description

Shows a preview of the object as it would be printed.

Syntax

object.PrintPreview

object

Required. The object to preview.

See Also

PrintOut Method.

Example

This example displays a print preview of Sheet1.

Worksheets("Sheet1").PrintPreview


PrintQuality Property

Applies To

PageSetup Object.

Description

Returns or sets the print quality, as a two-element array containing both horizontal and vertical print quality. Some printers may not support vertical print quality. Read-write.

Remarks

This property always returns a two-element array, even if the printer does not support vertical print quality.

Example

This example sets print quality on a printer with nonsquare pixels. The array specifies both horizontal and vertical print quality. This example may cause an error, depending on the printer driver you are using.

Worksheets("Sheet1").PageSetup.PrintQuality = Array(240, 140)

This example displays the current horizontal print quality setting.

MsgBox "Horizontal Print Quality is " & _
    Worksheets("Sheet1").PageSetup.PrintQuality(1)


PrintTitleColumns Property

Applies To

PageSetup Object.

Description

Returns or sets the columns containing the cells to be repeated on the left of each page, as a string in A1-style notation in the language of the macro. Read-write.

Remarks

If you specify only part of a column or columns, Microsoft Excel expands the range to full columns.

Set this property to False or to the empty string ("") to turn off title columns.

This property applies only to worksheet pages.

See Also

PrintTitleRows Property.

Example

This example defines row three as the title row, and it defines columns one through three as the title columns.

Worksheets("Sheet1").Activate
ActiveSheet.PageSetup.PrintTitleRows = ActiveSheet.Rows(3).Address
ActiveSheet.PageSetup.PrintTitleColumns = _
        ActiveSheet.Columns("A:C").Address


PrintTitleRows Property

Applies To

PageSetup Object.

Description

Returns or sets the rows containing the cells to be repeated on the top of each page, as a string in A1-style notation in the language of the macro. Read-write.

Remarks

If you specify only part of a row or rows, Microsoft Excel expands the range to full rows.

Set this property to False or to the empty string ("") to turn off title rows.

This property applies only to worksheet pages.

See Also

PrintTitleColumns Property.

Example

This example defines row three as the title row, and it defines columns one through three as the title columns.

Worksheets("Sheet1").Activate
ActiveSheet.PageSetup.PrintTitleRows = ActiveSheet.Rows(3).Address
ActiveSheet.PageSetup.PrintTitleColumns = _
        ActiveSheet.Columns("A:C").Address


PromptForSummaryInfo Property

Applies To

Application Object.

Description

True if Microsoft Excel asks for summary info when files are initially saved. Read-write.

Example

This example displays a prompt that asks for summary information when files are first saved.

Application.PromptForSummaryInfo = True


Property Get Statement

Description

Declares the name, arguments, and code that form the body of a Property procedure, which gets the value of a property.

Syntax

[Public | Private][Static] Property Get name [(arglist)][As type]
[statements]
[name = expression]
[Exit Property]
[statements]
[name = expression]
End Property

The Property Get statement syntax has these parts:

Part | Description
Public | Indicates that the Property Get procedure is accessible to all other procedures in all modules. If used in a private module (one that contains an Option Private statement) the procedure is not available outside the project.
Private | Indicates that the Property Get procedure is accessible only to other procedures in the module where it is declared.
Static | Indicates that the Property Get procedure's local variables are preserved between calls. The Static attribute doesn't affect variables that are declared outside the Property Get procedure, even if they are used in the procedure.
name | Name of the Property Get procedure; follows standard variable naming conventions, except that the name can be the same as a Property Let or Property Set procedure in the same module.
arglist | List of variables representing arguments that are passed to the Property Get procedure when it is called. Multiple variables are separated by commas.
type | Data type of the value returned by the Property Get procedure; may be Boolean, Integer, Long, Currency, Single, Double, Date, String (except fixed length), Object, or Variant. Arrays of any type can't be returned, but a Variant containing an array can.
statements | Any group of statements to be executed within the body of the Property Get procedure.
expression | Value of the property returned by the procedure defined by the Property Get statement.

The arglist argument has the following syntax and parts:

[Optional][ByVal | ByRef] varname[( )][As type]

Part | Description
Optional | Indicates that an argument is not required. If used, all subsequent arguments in arglist must also be optional and declared using the Optional keyword. All Optional arguments must be Variant.
ByVal | Indicates that the argument is passed by value.
ByRef | Indicates that the argument is passed by reference.
varname | Name of the variable representing the argument; follows standard variable naming conventions.
type | Data type of the argument passed to the Property Get procedure; may be Boolean, Integer, Long, Currency, Single, Double, Date, String (variable length only), Object, Variant, a user-defined type, or an object type.

Remarks

If not explicitly specified using either Public or Private, Property procedures are Public by default. If Static is not used, the value of local variables is not preserved between calls.

All executable code must be in procedures. You can't define a Property Get procedure inside another Sub, Function, or Property procedure.

The Exit Property keywords cause an immediate exit from a Property Get procedure. Program execution continues with the statement following the statement that called the Property Get procedure. Any number of Exit Property statements can appear anywhere in a Property Get procedure.

Like a Sub and Property Let procedure, a Property Get procedure is a separate procedure that can take arguments, perform a series of statements, and change the values of its arguments. However, unlike a Sub or Property Let procedure, a Property Get procedure can be used on the right-hand side of an expression in the same way you use a Function or a property name when you want to return the value of a property.

See Also

Function Statement, Property Let Statement, Property Set Statement, Sub Statement.

Example

This example uses the Property Get Statement to define a property procedure that gets the value of a property that identifies, as a string, the current color of a pen in a drawing package:

Dim CurrentColor As Integer
Const BLACK = 0, RED = 1, GREEN = 2, BLUE = 3

' Returns the current color of the pen as a string
Property Get PenColor() As String
    Select Case CurrentColor
        Case RED
            PenColor = "Red"
        Case GREEN
            PenColor = "Green"
        Case BLUE
            PenColor = "Blue"
    End Select
End Property

' The following line gets the color of the pen
' calling the Property Get procedure.
ColorName = PenColor()


Property Let Statement

Description

Declares the name, arguments, and code that form the body of a Property Let procedure, which assigns a value to a property.

Syntax

[Public | Private][Static] Property Let name [(arglist)]
[statements]
[Exit Property]
[statements]
End Property

The Property Let statement syntax has these parts:

Part | Description
Public | Indicates that the Property Let procedure is accessible to all other procedures in all modules. If used in a private module (one that contains an Option Private statement), the procedure is not available outside the project.
Private | Indicates that the Property Let procedure is accessible only to other procedures in the module where it is declared.
Static | Indicates that the Property Let procedure's local variables are preserved between calls. The Static attribute doesn't affect variables that are declared outside the Property Let procedure, even if they are used in the procedure.
name | Name of the Property Let procedure; follows standard variable naming conventions, except that the name can be the same as a Property Get or Property Set procedure in the same module.
arglist | List of variables representing arguments that are passed to the Property Let procedure when it is called. Multiple variables are separated by commas. The last argument is the value assigned to the property on the right-hand side of an expression.
statements | Any group of statements to be executed within the body of the Property Let procedure.

The arglist argument has the following syntax and parts:

[ByVal | ByRef] varname[( )][As type]

Part | Description
ByVal | Indicates that the argument is passed by value.
ByRef | Indicates that the argument is passed by reference.
varname | Name of the variable representing the argument; follows standard variable naming conventions.
type | Data type of the argument passed to the Property Let procedure; may be Boolean, Integer, Long, Currency, Single, Double, Date, String (variable length only), Object, Variant, a user-defined type, or an object type.

Note

Every Property Let statement must define at least one argument for the procedure it defines. That argument (or the last argument if there is more than one) will contain the actual value to be assigned to the property when the procedure defined by the Property Let statement is invoked.

Remarks

If not explicitly specified using either Public or Private, Property procedures are Public by default. If Static is not used, the value of local variables is not preserved between calls.

All executable code must be in procedures. You can't define a Property Let procedure inside another Sub, Function, or Property procedure.

The Exit Property keywords cause an immediate exit from a Property Let procedure. Program execution continues with the statement following the statement that called the Property Let procedure. Any number of Exit Property statements can appear anywhere in a Property Let procedure.

Like a Function and Property Get procedure, a Property Let procedure is a separate procedure that can take arguments, perform a series of statements, and change the value of its arguments. However, unlike a Function and Property Get procedure, both of which return a value, a Property Let procedure can only be used on the left side of a property assignment expression or Let statement.

See Also

Function Statement, Let Statement, Property Get Statement, Property Set Statement, Sub Statement.

Example

This example uses the Property Let statement to define a procedure that assigns a value to a property that identifies the pen color for a drawing package.

Dim CurrentColor As Integer
Const BLACK = 0, RED = 1, GREEN = 2, BLUE = 3

' Sets the pen color property for a Drawing package.
' The module level variable 'CurrentColor' is set to
' a numeric value that identifies the color used for drawing.
Property Let PenColor(ColorName as String)
    Select Case ColorName    ' Check color name string.
        Case "Red"
            CurrentColor = RED    ' Assign value for Red.
        Case "Green"
            CurrentColor = GREEN    ' Assign value for Green.
        Case "Blue"
            CurrentColor = BLUE    ' Assign value for Blue.
        Case Else
            CurrentColor = BLACK    ' Assign default value.
    End Select
End Property

' The following line sets the PenColor property for a drawing package
' by calling the Property Let procedure.

PenColor() = "Red"


Property Set Statement

Description

Declares the name, arguments, and code that form the body of a Property procedure, which sets a reference to an object.

Syntax

[Public | Private][Static] Property Set name [(arglist)]
[statements]
[Exit Property]
[statements]
End Property

The Property Set statement syntax has these parts:

Part | Description
Public | Indicates that the Property Set procedure is accessible to all other procedures in all modules. If used in a private module (one that contains an Option Private statement), the procedure is not available outside the project.
Private | Indicates that the Property Set procedure is accessible only to other procedures in the module where it is declared.
Static | Indicates that the Property Set procedure's local variables are preserved between calls. The Static attribute doesn't affect variables that are declared outside the Property Set procedure, even if they are used in the procedure.
name | Name of the Property Set procedure; follows standard variable naming conventions, except that the name can be the same as a Property Get or Property Let procedure in the same module.
arglist | List of variables representing arguments that are passed to the Property Set procedure when it is called. Multiple variables are separated by commas. The last argument is the object reference used on the right-hand side of an object reference assignment.
statements | Any group of statements to be executed within the body of the Property procedure.

The arglist argument has the following syntax and parts:

[ByVal | ByRef] varname[( )][As type]

Part | Description
ByVal | Indicates that the argument is passed by value.
ByRef | Indicates that the argument is passed by reference.
varname | Name of the variable representing the argument; follows standard variable naming conventions.
type | Data type of the argument passed to the Property Set procedure; may be Boolean, Integer, Long, Currency, Single, Double, Date, String (variable length only), Object, Variant, a user-defined type, or an object type.

Note

Every Property Set statement must define at least one argument for the procedure it defines. That argument (or the last argument if there is more than one) will contain the actual object reference for the property when the procedure defined by the Property Set statement is invoked.

Remarks

If not explicitly specified using either Public or Private, Property procedures are Public by default. If Static is not used, the value of local variables is not preserved between calls.

All executable code must be in procedures. You can't define a Property Set procedure inside another Sub, Function, or Property procedure.

The Exit Property keywords cause an immediate exit from a Property Set procedure. Program execution continues with the statement following the statement that called the Property Set procedure. Any number of Exit Property statements can appear anywhere in a Property Set procedure.

Like a Function and Property Get procedure, a Property Set procedure is a separate procedure that can take arguments, perform a series of statements, and change the value of its arguments. However, unlike a Function and Property Get procedure, both of which return a value, a Property Set procedure can only be used on the left side of an object reference assignment (Set statement).

See Also

Function Statement, Property Get Statement, Property Let Statement, Sub Statement.

Example

This example uses the Property Set statement to declare a property procedure which sets a reference to an object.

' The Pen property may be set to different Pen implementations.
Property Set Pen(P As Object)
    Set CurrentPen = P    ' Assign Pen to object.
End Property


Protect Method

Applies To

Chart Object, DialogSheet Object, Module Object, Workbook Object, Worksheet Object.

Description

Protects a chart, dialog sheet, Visual Basic module or worksheet (Syntax 1), or a workbook (Syntax 2) so that it cannot be modified.

Syntax 1

object.Protect(password, drawingObjects, contents, scenarios, userInterfaceOnly)

Syntax 2

object.Protect(password, structure, windows)

object

Required. The Chart, DialogSheet, Module, or Worksheet (Syntax 1) or Workbook object (Syntax 2).

password

Optional. A string that specifies a case-sensitive password for the sheet or workbook. If omitted, you can unprotect the sheet or workbook without a password. If specified, you must specify the password to unprotect the sheet or workbook. If you forget the password, you cannot unprotect the sheet or workbook. It's a good idea to keep a list of your passwords and their corresponding document names in a safe place.

drawingObjects

Optional. True to protect the drawing objects on the sheet. For a dialog sheet, this protects the layout of the controls. If this argument is omitted, the drawing objects are not protected. Ignored for Visual Basic modules.

contents

Optional. True (or omitted) to protect the contents of the object. For a Visual Basic module, this protects the source code. For a chart, this protects the entire chart. For a dialog sheet, this protects the dialog layout and text of the dialog controls. For a worksheet, this protects the cells.

scenarios

Optional. True (or omitted) to protect scenarios. This argument is valid only for worksheets.

structure

Optional. True to protect the structure of the workbook (the relative position of the sheets). If this argument is omitted, the structure is not protected.

userInterfaceOnly

Optional. True to protect the user interface but not macros. If this argument is omitted, protection applies to macros and the user interface.

windows

Optional. True to protect the windows of the sheet or workbook. If omitted, the windows are not protected.

Remarks

Using the Protect method causes an error if the workbook is already protected.

See Also

Locked Property, ProtectContents Property, ProtectDrawingObjects Property, ProtectScenarios Property, ProtectStructure Property, ProtectWindows Property, Unprotect Method.

Example

This example protects the active workbook.

ActiveWorkbook.Protect password := "drowssap"


ProtectContents Property

Applies To

Chart Object, DialogSheet Object, Module Object, Worksheet Object.

Description

True if the contents of a sheet are protected. For a Visual Basic module, this protects the source code. For a chart, this protects the entire chart. For a dialog sheet, this protects the dialog layout and text of the dialog controls. For a worksheet, this protects the cells. Read-only.

See Also

Locked Property, Protect Method, ProtectWindows Property, Unprotect Method.

Example

This example displays a message box if the contents of Sheet1 are protected.

If Worksheets("Sheet1").ProtectContents = True Then
    MsgBox "The contents of Sheet1 are protected."
End If


ProtectDrawingObjects Property

Applies To

Chart Object, DialogSheet Object, Worksheet Object.

Description

True if the drawing objects of a sheet are protected. On a dialog sheet, this protects the layout of the controls. Read-only.

See Also

Locked Property, Protect Method, ProtectContents Property, Unprotect Method.

Example

This example displays a message box if the drawing objects on the active sheet are protected.

If Worksheets("Sheet1").ProtectDrawingObjects = True Then
    MsgBox "The drawing objects on Sheet1 are protected."
End If


Protection Property

Applies To

Toolbar Object.

Description

Returns or sets how the toolbar is protected from changes by the user, as shown in the following table (in order from minimum to maximum protection). This property is available only in Microsoft Excel for Windows 95. Read-write.

Value | Meaning
xlNormal | Normal toolbar behavior. The toolbar can be moved, resized, and docked. Toolbar buttons can be added, removed, and repositioned.
xlNoButtonChanges | The toolbar can be moved, resized, and docked. Toolbar buttons cannot be added, removed, or repositioned.
xlNoShapeChanges | Same as xlNoButtonChanges, but the toolbar cannot be resized. The toolbar can be moved and docked.
xlNoDockingChanges | Same as xlNoShapeChanges, but the toolbar cannot be docked or undocked. The toolbar can be moved.
xlNoChanges | Same as xlNoDockingChanges, but the toolbar cannot be moved.

Remarks

This property is saved with the toolbar configuration file and recalled for each Microsoft Excel session.

New toolbars are always created with the protection set to xlNormal.

Example

This example sets the protection for My Custom Toolbar. The toolbar can be moved, resized, and docked, but the toolbar buttons cannot be added, removed, or repositioned.

Toolbars("My Custom Toolbar").Protection = xlNoButtonChanges


ProtectionMode Property

Applies To

Worksheet Object.

Description

True if user-interface-only protection is turned on. To turn on user interface protection, use the Protect method with the userInterfaceOnly argument set to True. This property is available only in Microsoft Excel for Windows 95. Read-only.

Example

This example displays the state of the ProtectionMode property.

MsgBox ActiveSheet.ProtectionMode


ProtectScenarios Property

Applies To

Worksheet Object.

Description

True if the worksheet scenarios are protected. Read-only.

See Also

Protect Method, Unprotect Method.

Example

This example displays a message box if scenarios are protected on Sheet1.

If Worksheets("Sheet1").ProtectScenarios Then _
    MsgBox "Scenarios are protected on this worksheet."


ProtectStructure Property

Applies To

Workbook Object.

Description

True if the order of the sheets in the workbook is protected. Read-only.

See Also

Protect Method, ProtectWindows Property, Unprotect Method.

Example

This example displays a message if the structure of the active workbook is protected.

If ActiveWorkbook.ProtectStructure = True Then
    MsgBox "Remember, you cannot delete, add, or change " & Chr(13) & _
        "the location of any sheets in this workbook."
End If


ProtectWindows Property

Applies To

Workbook Object.

Description

True if the windows of the workbook are protected. Read-only.

See Also

Protect Method, ProtectStructure Property, Unprotect Method.

Example

This example displays a message if the windows in the active workbook are protected.

If ActiveWorkbook.ProtectWindows = True Then
    MsgBox "Remember, you cannot rearrange any window in this workbook."
End If


Public Statement

Description

Used at module level to declare public variables and allocate storage space.

Syntax

Public varname[([subscripts])][As type][,varname[([subscripts])][As type]] . . .

The Public statement syntax has these parts:

Part | Description
varname | Name of the variable; follows standard variable naming conventions.
subscripts | Dimensions of an array variable; up to 60 multiple dimensions may be declared. The argument subscripts uses the following syntax:
 | [lower To] upper [,[lower To] upper] . . .
type | Data type of the variable; may be Boolean, Integer, Long, Currency, Single, Double, Date, String (for variable-length strings), String * length (for fixed-length strings), Object, Variant, a user-defined type, or an object type. Use a separate As type clause for each variable being defined.

Remarks

Variables declared using the Public statement are available to all procedures in all modules in all applications unless Option Private Module is in effect; in which case, the variables are Public only within the project in which they reside.

Use the Public statement to declare the data type or object type of a variable. For example, the following statement declares a variable as an Integer:

Public NumberOfEmployees As Integer

If you do not specify a data type or object type and there is no Def type statement in the module, the variable is Variant by default.

When variables are initialized, a numeric variable is initialized to 0, a variable-length string is initialized to a zero-length string, and a fixed-length string is filled with zeros. Variant variables are initialized to Empty. Each element of a user-defined type variable is initialized as if it was a separate variable. A variable that refers to an object must be assigned an existing object using the Set statement before it can be used. Until it is assigned an object, the declared object variable has the special value Nothing, which indicates that it does not refer to any particular instance of an object.

You can also use the Public statement with empty parentheses to declare dynamic arrays. After declaring a dynamic array, use the ReDim statement within a procedure to define the number of dimensions and elements in the array. If you try to redeclare a dimension for an array variable whose size was explicitly specified in a Private, Public or Dim statement, an error occurs.

See Also

Array Function, Const Statement, Dim Statement, Option Base Statement, Option Private Statement, Private Statement, ReDim Statement, Static Statement, Type Statement.

Example

The Public statement is used at the module-level to declare variables as public; that is, they are available to all procedures in all modules in all applications unless Option Private Module is in effect.

Public Number As Integer    ' Public integer variable.
Public NameArray(1 To 5) As String    ' Public array variable.
Public MyVar, YourVar, ThisVar As Integer    ' Multiple declarations.


Pushed Property

Applies To

ToolbarButton Object.

Description

True if the button appears pressed down. Read-write.

Remarks

You cannot set this property for a built-in button. You can only set it for a custom button, and then only if the button has a procedure attached to it.

See Also

Enabled Property.

Example

This example adds a custom button to the Standard toolbar, attaches the my_Macro procedure to the button, and then makes the button appear pressed.

Set btn = Toolbars("Standard").ToolbarButtons.Add _
        (button:=220, before:=3)
btn.OnAction = "my_Macro"
btn.Pushed = True


Put Statement

Description

Writes from a variable to a disk file.

Syntax

Put [#]filenumber,[recnumber],varname

The Put statement syntax has these parts:

Part | Description
filenumber | Any valid file number.
recnumber | Record number (Random mode files) or byte number (Binary mode files) at which writing begins.
varname | Name of variable containing data to be written to disk.

Remarks

The first record/byte in a file is at position 1, the second record/byte is at position 2, and so on. If you omit recnumber, the next record or byte (the one after the last Get or Put statement or the one pointed to by the last Seek function) is written. You must include delimiting commas, for example:

Put #4,,FileBuffer

For files opened in Random mode, the following rules apply:

  • If the length of the data being written is less than the length specified in the Len clause of the Open statement, Put still writes subsequent records on record-length boundaries. The space between the end of one record and the beginning of the next record is padded with the existing contents of the file buffer. Because the amount of padding data can't be determined with any certainty, it is generally a good idea to have the record length match the length of the data being written.
  • If the variable being written is a variable-length string, Put writes a 2-byte descriptor containing the string length and then the variable. The record length specified by the Len clause in the Open statement must be at least 2 bytes greater than the actual length of the string.
  • If the variable being written is a Variant of a numeric type, Put writes 2 bytes identifying the VarType of the Variant and then the variable. For example, when writing a Variant of VarType 3, Put writes 6 bytes: 2 bytes identifying the Variant as VarType 3 (Long) and 4 bytes containing the Long data. The record length specified by the Len clause in the Open statement must be at least 2 bytes greater than the actual number of bytes required to store the variable.
  • If the variable being written is a String Variant (VarType 8), Put writes 2 bytes identifying the VarType, 2 bytes indicating the length of the string, and then the string data. The record length specified by the Len clause in the Open statement must be at least 4 bytes greater than the actual length of the string.
  • If the variable being written is any other type of variable (not a variable-length string and not a Variant), Put writes only the variable data. The record length specified by the Len clause in the Open statement must be greater than or equal to the length of the data being written.
  • Put writes elements of user-defined types as if each were written individually, except there is no padding between elements. The record length specified by the Len clause in the Open statement must be greater than or equal to the sum of all the bytes required to write the individual elements.

For files opened in Binary mode, all of the Random rules apply except that:

  • The Len clause in the Open statement has no effect. Put writes all variables to disk contiguously; that is, with no padding between records.
  • Put writes variable-length strings that are not elements of user-defined types without the 2-byte length descriptor. The number of bytes written equals the number of characters in the string. For example, the following statements write 10 bytes to file number 1:

    VarString$ = String$(10," ")
Put #1,,VarString$

See Also

Get Statement, Open Statement, VarType Function.

Example

This example uses the Put statement to write data to a disk file. Five records of the user-defined type Record are written to the file.

' Define user-defined type.
Type Record
    ID As Integer
    Name As String * 20
End Type
Dim MyRecord As Record    ' Declare variable.
' Open file for random access.
Open "TESTFILE" For Random As #1 Len = Len(MyRecord)
For RecordNumber = 1 To 5    ' Loop 5 times.
    MyRecord.ID = RecordNumber    ' Define ID.
    MyRecord.Name = "My Name" & RecordNumber    ' Create a string.
    Put #1, RecordNumber, MyRecord    ' Write record to file.
Next RecordNumber
Close #1    ' Close file.


QueryGetData Function

Description

Builds a new query.

This function is contained in the Microsoft Query add-in. Before you use the function, you must establish a reference to the add-in using the References command (Tools menu).

Syntax

QueryGetData(connectionStr, queryText, keepQueryDef, fieldNames, rowNumbers, festination, execute)

connectionStr

Required. A string that contains database connection information, such as the data source name, user ID, and passwords, necessary to make a SQL connection to an external data source. For example, "DSN=Myserver; Server=server1; UID=dbayer; PWD=buyer1; Database=nwind".

queryText

Required. A string that contains the SQL language query to be run on the data source.

keepQueryDef

Optional. If True or omitted, preserves the query definition. If False, the query definition is lost and the data from the query is no longer a data range.

fieldNames

Optional. If True or omitted, places field names from Microsoft Query into the first row of the data range. If False, the field names are discarded.

rowNumbers

Optional. If True, places row numbers from Microsoft Query into the first column in the data range. If False or omitted, the row numbers are discarded.

destination

Optional. The destination for the returned data, as a Range object. If destination is in a data range then that data range is changed to reflect the new SQL query. The default destination is the active cell or the selection.

execute

Optional. If True or omitted, the query is run immediately. If False, the query text is added to a buffer and the query is not run until a subsequent QueryGetData function call with the execute argument set to True. When this occurs, Microsoft Query runs all query text in the buffer.

See Also

QueryGetDataDialog Function, QueryRefresh Function.


QueryGetDataDialog Function

Description

Builds a new query. Equivalent to the Get External Data command (Data menu).

This function is contained in the Microsoft Query add-in. Before you use the function, you must establish a reference to the add-in using the References command (Tools menu).

Syntax

QueryGetDataDialog(connectionStr, queryText, keepQueryDef, fieldNames, rowNumbers, destination, execute)

connectionStr

Required. A string that contains database connection information, such as the data source name, user ID, and passwords, necessary to make a SQL connection to an external data source. For example, "DSN=Myserver; Server=server1; UID=dbayer; PWD=buyer1; Database=nwind".

queryText

Required. A string that contains the SQL language query to be run on the data source.

keepQueryDef

Optional. If True or omitted, preserves the query definition. If False, the query definition is lost and the data from the query is no longer a data range.

fieldNames

Optional. If True or omitted, places field names from Microsoft Query into the first row of the data range. If False, the field names are discarded.

rowNumbers

Optional. If True, places row numbers from Microsoft Query into the first column in the data range. If False or omitted, the row numbers are discarded.

destination

Optional. The destination for the returned data, as a Range object. If destination is in a data range then that data range is changed to reflect the new SQL query. The default destination is the active cell or the selection.

execute

Optional. If True or omitted, the query is run immediately. If False, the query text is added to a buffer and the query is not run until a subsequent QueryGetData function call with the execute argument set to True. When this occurs, Microsoft Query runs all query text in the buffer.

See Also

QueryGetData Function, QueryRefresh Function.


QueryRefresh Function

Description

Refreshes the data in a data range returned by Microsoft Query.

This function is contained in the Microsoft Query add-in. Before you use the function, you must establish a reference to the add-in using the References command (Tools menu).

Syntax

QueryRefresh(ref)

ref

Optional. A single cell, as a Range object, that is inside a data range. If ref is not in a data range then the function returns the #REF! error value.

See Also

QueryGetData Function, QueryGetDataDialog Function.


Quit Method

Applies To

Application Object.

Description

Quits Microsoft Excel. Does not run any Auto_Close macros before quitting.

Syntax

object.Quit

object

Required. The Application object.

Remarks

If unsaved workbooks are open when you use this method, Microsoft Excel displays a dialog box asking if you want to save the changes. You can prevent this by saving all workbooks before using the Quit method or by setting the DisplayAlerts property to False. When this property is False, Microsoft Excel does not display the dialog box when you quit with unsaved workbooks, and it quits without saving them.

If you set the Saved property for a workbook to True without saving it to the disk, Microsoft Excel will quit without asking you to save the workbook.

Example

This example saves all open workbooks and then closes Microsoft Excel.

For Each w In Application.Workbooks
    w.Save
Next w
Application.Quit


RadarAxisLabels Property

Applies To

ChartGroup Object.

Description

Accessor. Returns a TickLabels object that represents the radar axis labels for the specified chart group. Read-only.

See Also

HasRadarAxisLabels Property.

Example

This example turns on radar axis labels for chart group one in Chart1 and then sets their color. The example should be run on a radar chart.

With Charts("Chart1").ChartGroups(1)
    .HasRadarAxisLabels = True
    .RadarAxisLabels.Font.ColorIndex = 3
End With


RadarGroups Method

Applies To

Chart Object.

Description

Accessor. On a 2-D chart, returns an object that represents a single radar chart group (a ChartGroup object, Syntax 1), or a collection of the radar chart groups (a ChartGroups collection, Syntax 2).

Syntax 1

object.RadarGroups(index)

Syntax 2

object.RadarGroups

object

Required. The Chart object.

index

Required for Syntax 1. Specifies the chart group.

Example

This example sets the subtype for radar group one in Chart1. The example should be run on a 2-D chart.

Charts("Chart1").RadarGroups(1).SubType = 2


Randomize Statement

Description

Initializes the random-number generator.

Syntax

Randomize [number]

The number named argument can be any valid numeric expression.

Remarks

Randomize uses number to initialize a random-number generator, giving it a new seed value. If you omit number, the value returned by the Timer function is used as the new seed value.

If Randomize is not used, the same initial seed is always used to start the sequence.

Use the Randomize statement without an argument to provide a random seed based on the system timer to initialize the random-number generator before Rnd is called.

See Also

Rnd Function, Timer Function.

Example

This example uses the Randomize statement to initialize the random-number generator. Because the number argument has been omitted, Randomize uses the return value from the Timer function as the new seed value.

' Initialize random-number generator.
Randomize
' Generate random value between 1 and 6.
MyAngle = Int((6 * Rnd) + 1)


Range Method

Applies To

Application Object, Range Object, Worksheet Object.

Description

Accessor. Returns a Range object that represents a cell or range of cells.

Syntax 1

object.Range(cell1)

Syntax 2

object.Range(cell1, cell2)

object

Optional for Application, required for Range and Worksheet. The object to which this method applies.

cell1

Required for Syntax 1. The name of the range. This must be an A1-style reference in the language of the macro. It may include the range operator ':' (colon), the intersection operator ' ' (space), or the union operator ',' (comma). It may include dollar signs, but they are ignored. Any part of the range may use a local defined name. If you use a name, the name is assumed to be in the language of the macro.

cell1, cell2

Required for Syntax 2. The cells at the top left and bottom right of the range. Each one may be a Range containing exactly a single cell (or an entire column or entire row), or a string naming a single cell in the language of the macro.

Remarks

When used with no object qualifier, this method is a shortcut for ActiveSheet.Range (it returns a range from the active sheet; if the active sheet is not a worksheet, the method fails).

When applied to a Range object, the method is relative to the Range object. For example, if the selection is cell C3, then Selection.Range("B1") returns cell D3 because it is relative to the Range object returned by the Selection property. On the other hand, the code ActiveSheet.Range("B1") always returns cell B1.

See Also

Cells Method.

Example

This example sets the value of cell A1 on Sheet1 to 3.14159.

Worksheets("Sheet1").Range("A1").Value = 3.14159

This example creates a formula in cell A1 on Sheet1.

Worksheets("Sheet1").Range("A1").Formula = "=10*RAND()"

This example loops on cells A1:D10 on Sheet1. If one of the cells has a value less than 0.001, the code replaces the value with 0 (zero).

For Each c in Worksheets("Sheet1").Range("A1:D10")
    If c.Value < .001 Then
        c.Value = 0
    End If
Next c

This example loops on the range named "TestRange" and displays the number of empty cells in the range.

numBlanks = 0
For Each c In Range("TestRange")
    If c.Value = "" Then
        numBlanks = numBlanks + 1
    End If
Next c
MsgBox "There are " & numBlanks & " empty cells in this range"

This example sets the font in cells A1:C5 on Sheet1 to italic. The example uses Syntax 2 of the Range method.

Worksheets("Sheet1").Activate
Range(Cells(1, 1), Cells(5, 3)).Font.Italic = True


Range Object

Description

Represents a cell, a row, a column, a selection of cells containing one or more contiguous blocks of cells, or a 3-D range.

Accessors

Here are several examples of how to use the most important accessor properties and methods of the Range object.

Range Method

Use the Range method to return a single cell or range of cells. The following example places the value of cell A1 in cell A5.

Worksheets("Sheet1").Range("A5").Value = _
    Worksheets("Sheet1").Range("A1").Value

The following example fills the range A1:H8 with random numbers by setting the formula for each cell in the range. When it is used without an object qualifier (an object to the left of the period), the Range method returns a range on the active sheet. If the active sheet is not a worksheet, the method will fail. Use the Activate method to activate a worksheet before you use the Range method without an explicit object qualifier.

Worksheets("sheet1").Activate
Range("A1:H8").Formula = "=rand()"    'Range is on the active sheet

The following example clears the contents of the range named "Criteria."

Worksheets(1).Range("criteria").ClearContents

If you use a text argument for the range address, you must specify the address in A1-style notation (you cannot use R1C1-style notation).

Cells Method

Use the Cells method to return a single cell by specifying the row and column. The following example sets the value of cell A1 to 24.

Worksheets(1).Cells(1, 1).Value = 24

The following example sets the formula for cell A2.

ActiveSheet.Cells(2, 1).Formula = "=sum(b1:b5)"

Although you can also use Range("A1") to return cell A1, there may be times when the Cells method is more convenient because you can use a variable for the row or column. The following example creates column and row headings on the worksheet named "Sheet1." Notice that once the worksheet has been activated, the Cells method can be used without an explicit sheet declaration (it returns a cell on the active sheet).

Sub SetUpTable()
Worksheets("sheet1").Activate
For theYear = 1 To 5
    Cells(1, theYear + 1).Value = 1990 + theYear
Next theYear
'
For theQuarter = 1 To 4
    Cells(theQuarter + 1, 1).Value = "Q" & theQuarter
Next theQuarter
End Sub

Although you could use Visual Basic string functions to alter A1-style references, it's much easier (and much better programming practice) to use the Cells(1, 1) notation.

Cells and Range Methods

You can also use the Cells method to return part of a range by specifying the row and column relative to the upper-left corner of the range. The following example sets the formula for cell C5.

Worksheets(1).Range("c5:c10").cells(1,1).formula = "=rand()"

You can also use the Cells method inside the Range method to specify the start and end cells for the range. The following example sets the border line style for cells A1:J10.

With Worksheets(1)
    .Range(.Cells(1, 1), .Cells(10, 10)).Borders.LineStyle = xlThick
End With

Notice the period in front of each occurrence of the Cells method. The period is required to apply the result of the preceding With statement to the Cells method—in this case to indicate that the cells are on worksheet one (without the period, the Cells method would return cells on the active sheet).

Offset Method

The Offset method returns a range at a specified offset to another range. The following example selects the cell three rows down and one column to the right from the upper-left cell of the current selection. You cannot select a cell that is not on the active sheet, so you must first activate the worksheet.

Worksheets("sheet1").Activate  'can't select unless the sheet is active
Selection.Offset(3, 1).Range("a1").Select

Union Method

Use the Union method and Range method to return multi-area ranges (ranges composed of two or more contiguous blocks of cells). The following example creates an object called myMultiAreaRange, defines it as the union of ranges A1:B2 and C3:D4, and then selects it.

Dim r1, r2, myMultiAreaRange As Range
Worksheets("sheet1").Activate
Set r1 = Range("A1:B2")
Set r2 = Range("C3:D4")
Set myMultiAreaRange = Union(r1, r2)
myMultiAreaRange.Select

If you work with selections containing more than one area, the Areas method is very useful. It divides a multi-area selection into individual Range objects and then returns them as a collection. You can use the Count property on the returned collection to check for a selection containing more than one area, as shown in the following example:

Sub NoMultiAreaSelection()
    numberOfSelectedAreas = Selection.Areas.Count
    If numberOfSelectedAreas > 1 Then
        MsgBox "You cannot carry out this command " & _
            "on multi-area selections"
    End If
End Sub

Properties

AddIndent Property, Application Property, Column Property, ColumnWidth Property, Count Property, Creator Property, CurrentArray Property, CurrentRegion Property, Dependents Property, DirectDependents Property, DirectPrecedents Property, EntireColumn Property, EntireRow Property, Font Property, Formula Property, FormulaArray Property, FormulaHidden Property, FormulaLocal Property, FormulaR1C1 Property, FormulaR1C1Local Property, HasArray Property, HasFormula Property, Height Property, Hidden Property, HorizontalAlignment Property, Interior Property, Left Property, ListHeaderRows Property, LocationInTable Property, Locked Property, Name Property, Next Property, NumberFormat Property, NumberFormatLocal Property, Orientation Property, OutlineLevel Property, PageBreak Property, Parent Property, PivotField Property, PivotItem Property, PivotTable Property, Precedents Property, PrefixCharacter Property, Previous Property, Row Property, RowHeight Property, ShowDetail Property, SoundNote Property, Style Property, Summary Property, Text Property, Top Property, UseStandardHeight Property, UseStandardWidth Property, Value Property, VerticalAlignment Property, Width Property, Worksheet Property, WrapText Property.

Methods

Activate Method, Address Method, AddressLocal Method, AdvancedFilter Method, ApplyNames Method, ApplyOutlineStyles Method, Areas Method, AutoComplete Method, AutoFill Method, AutoFilter Method, AutoFit Method, AutoFormat Method (Range Object), AutoOutline Method, BorderAround Method, Borders Method, Calculate Method, Cells Method, Characters Method, CheckSpelling Method, Clear Method, ClearContents Method, ClearFormats Method, ClearNotes Method, ClearOutline Method, ColumnDifferences Method, Columns Method, Consolidate Method, Copy Method, CopyFromRecordset Method, CopyPicture Method, CreateNames Method, CreatePublisher Method, Cut Method, DataSeries Method, Delete Method, DialogBox Method, End Method, FillDown Method, FillLeft Method, FillRight Method, FillUp Method, Find Method, FindNext Method, FindPrevious Method, FunctionWizard Method, GoalSeek Method, Group Method, Insert Method, Item Method, Justify Method, ListNames Method, NavigateArrow Method, NoteText Method, Offset Method, Parse Method, PasteSpecial Method (Range Object), PrintOut Method, PrintPreview Method, Range Method, RemoveSubtotal Method, Replace Method, Resize Method, RowDifferences Method, Rows Method, Run Method, Select Method, Show Method, ShowDependents Method, ShowErrors Method, ShowPrecedents Method, Sort Method, SortSpecial Method, SpecialCells Method, SubscribeTo Method, Subtotal Method, Table Method, TextToColumns Method, Ungroup Method.


RangeSelection Property

Applies To

Window Object.

Description

Returns a Range object that represents the selected cells on the worksheet in the specified window even if a graphic object is active or selected on the worksheet. This property is available only in Microsoft Excel for Windows 95. Read-only.

Remarks

When a graphic object is selected on a worksheet, the Selection property returns the graphic object instead of a Range; the RangeSelection property returns the range of cells that was selected before the graphic object was selected.

This property and the Selection property return identical values when a range (not a graphic object) is selected on the worksheet.

If a worksheet is not the active sheet in the specified window, this property fails.

Example

This example displays the address of the selected cells on the worksheet in the active window.

MsgBox ActiveWindow.RangeSelection.Address


ReadOnly Property

Applies To

Workbook Object.

Description

True if the workbook has been opened as read-only. Read-only.

See Also

Open Method, SaveAs Method.

Example

If the active workbook is read-only, this example saves it as NEWFILE.XLS.

If ActiveWorkbook.ReadOnly Then
    ActiveWorkbook.SaveAs fileName:="NEWFILE.XLS"
End If


ReadOnlyRecommended Property

Applies To

Workbook Object.

Description

True if the workbook was saved as read-only recommended. Read-only.

Remarks

When you open a document that was saved as read-only recommended, Microsoft Excel displays a message recommending that you open the document as read-only.

Use the SaveAs method to change this property.

See Also

Open Method, SaveAs Method.

Example

This example displays a message if the active workbook is saved as read-only recommended.

If ActiveWorkbook.ReadOnlyRecommended = True Then
    MsgBox "This workbook is saved as read-only recommended"
End If


Received Property

Applies To

Mailer Object.

Description

True if the workbook mailer has been received (if it has been sent by another user to the current user) and the current user has not modified the mailer by using the Reply, ReplyAll, or ForwardMailer methods. PowerTalk requires that mailers be received before they can be forwarded or replied to. Available only in Microsoft Excel for the Apple Macintosh with the PowerTalk mail system extension installed. Read-only.

See Also

BCCRecipients Property, CCRecipients Property, Enclosures Property, ForwardMailer Method, Mailer Property, Reply Method, ReplyAll Method, SendDateTime Property, Sender Property, SendMailer Method, Subject Property, ToRecipients Property.

Example

This example displays the current state of the Received property.

With ActiveWorkbook
    If .HasMailer Then
        If .Mailer.Received Then
            state = "True"
        Else
            state = "False"
        End If
        MsgBox "Received property is " & state
    Else
        MsgBox "The workbook has no mailer"
    End If
End With


Recipients Property

Applies To

RoutingSlip Object.

Description

Returns or sets the recipients on the routing slip (as an array of strings). Read-write.

Remarks

The order of the recipient list defines the delivery order if the routing delivery option is xlOneAfterAnother. If a routing slip is in progress, only those recipients who have not already received and routed the document are returned or set.

Example

This example sends BOOK1.XLS to three recipients, one after the other.

Workbooks("BOOK1.XLS").HasRoutingSlip = True
With Workbooks("BOOK1.XLS").RoutingSlip
    .Delivery = xlOneAfterAnother
    .Recipients = Array("Adam Bendel", "Jean Selva", "Bernard Gabor")
    .Subject = "Here is BOOK1.XLS"
    .Message = "Here is the workbook. What do you think?"
    .ReturnWhenDone = True
End With
Workbooks("BOOK1.XLS").Route


Record Method

Applies To

SoundNote Object.

Description

Displays the Record dialog box so you can record a sound note.

Syntax

object.Record

object

Required. The SoundNote object.

Remarks

To record sounds, you must have sound hardware installed in your computer. You cannot record a sound note to a cell that already has one; you must delete the existing sound note before recording a new one.

See Also

Play Method.

Example

This example deletes the sound note in cell A1 on Sheet1, records a new sound note for the same cell, and then plays the sound note.

With Worksheets("Sheet1").Range("A1").SoundNote
    .Delete
    .Record
    .Play
End With


RecordMacro Method

Applies To

Application Object.

Description

Records code if the macro recorder is on.

Syntax

object.RecordMacro(basicCode, xlmCode)

object

Required. The Application object.

basicCode

Optional. A string that specifies the Visual Basic code that will be recorded if the macro recorder is recording into a Visual Basic module. The string will be recorded on one line. If the string contains a carriage return (ASCII character 10, or Chr$(10) in code), it will be recorded on more than one line.

xlmCode

Optional. A string that specifies the formula that will be recorded if the macro recorder is recording into a Microsoft Excel version 4.0 macro sheet. The string will be recorded into one cell. If the string does not begin with an equal sign, a comment is recorded.

Remarks

The RecordMacro method cannot record into the active module (the module in which the RecordMacro method exists).

If basicCode is omitted, and the application is recording into Visual Basic, Microsoft Excel will record a suitable Application.Run statement.

If xlmCode is omitted, and the application is recording into Microsoft Excel version 4.0, Microsoft Excel will record a suitable RUN macro function.

To prevent recording (for example, if the user cancels your dialog box), call this function with two empty strings.

Example

This example records either Visual Basic code or an XLM formula.

Application.RecordMacro basicCode:="Application.Run ""MySub"" ", _
    xlmCode:="=MySub()"


RecordRelative Property

Applies To

Application Object.

Description

True if macros are recorded using relative references; False if recording is absolute. Read-only.

Example

This example displays the address of the active cell on Sheet1 in A1 style if RecordRelative is False; otherwise, it displays the address in R1C1 style.

Worksheets("Sheet1").Activate
If Application.RecordRelative = False Then
    MsgBox ActiveCell.Address(ReferenceStyle:=xlA1)
Else
    MsgBox ActiveCell.Address(ReferenceStyle:=xlR1C1)
End If


Rectangle Object

Description

Represents a rectangle graphic object on a chart sheet, dialog sheet, or worksheet.

Accessors

The Rectangle object is a member of the Rectangles collection. The Rectangles collection contains all the Rectangle objects on a single sheet. Use the Add method to create a new rectangle and add it to the collection.

To access a single member of the collection, use the Rectangles method with the index number or name of the rectangle as an argument.

The following example sets the interior color for rectangle one on the worksheet named "Sheet1."

Worksheets("sheet1").Rectangles(1).Interior.ColorIndex = 5

The rectangle name is shown in the Name Box when the rectangle is selected. Use the Name property to set or return the rectangle name. The following example sets the border line style for the rectangle named "Rectangle 3."

Worksheets("sheet1").Rectangles("rectangle 3"). _
    Border.LineStyle = xlDash

Properties

Application Property, Border Property, BottomRightCell Property, Creator Property, Enabled Property, Height Property, Index Property, Interior Property, Left Property, Locked Property, Name Property, OnAction Property, Parent Property, Placement Property, PrintObject Property, RoundedCorners Property, Shadow Property, Top Property, TopLeftCell Property, Visible Property, Width Property, ZOrder Property.

Methods

BringToFront Method, Copy Method, CopyPicture Method, Cut Method, Delete Method, Duplicate Method, Select Method, SendToBack Method.


Rectangles Collection Object

Description

A collection of all the Rectangle objects on the specified chart sheet, dialog sheet, or worksheet.

Accessors

Use the Add method to create a new rectangle and add it to the collection. The following example adds a new rectangle to the worksheet named "Sheet1." The new rectangle is 200 points high and 100 points wide, and its upper-left corner is positioned at the upper-left corner of cell C5.

Set r = Worksheets("sheet1").Range("c5")
Worksheets("sheet1").Rectangles.Add r.Left, r.Top, 200, 100

Use the Rectangles method with an argument to access a single member of the collection or without an argument to access the entire collection at once. The following example deletes all of the rectangles on the worksheet named "Sheet1."

Worksheets("sheet1").Rectangles.Delete

Properties

Application Property, Border Property, Count Property, Creator Property, Enabled Property, Height Property, Interior Property, Left Property, Locked Property, OnAction Property, Parent Property, Placement Property, PrintObject Property, RoundedCorners Property, Shadow Property, Top Property, Visible Property, Width Property, ZOrder Property.

Methods

Add Method (Graphic Objects and Controls), BringToFront Method, Copy Method, CopyPicture Method, Cut Method, Delete Method, Duplicate Method, Group Method, Item Method, Select Method, SendToBack Method.


Rectangles Method

Applies To

Chart Object, DialogSheet Object, Worksheet Object.

Description

Accessor. Returns an object that represents a single rectangle (a Rectangle object, Syntax 1) or a collection of rectangles (a Rectangles object, Syntax 2) on the sheet. Read-only.

Syntax 1

object.Rectangles(index)

Syntax 2

object.Rectangles

object

Required. The object containing the rectangles.

index

Required for Syntax 1. The name or number of the rectangle.

Example

This example deletes every rectangle on Sheet1.

Worksheets("Sheet1").Rectangles.Delete

This example changes the color of rectangle one on Sheet1 to red.

Worksheets("Sheet1").Rectangles(1).Border.ColorIndex = 3


ReDim Statement

Description

Used at the procedure level to declare dynamic-array variables and allocate or reallocate storage space.

Syntax

ReDim [Preserve] varname(subscripts) [As type][,varname(subscripts) [As type]] . . .

The ReDim statement syntax has these parts:

Part | Description
Preserve | Preserves the data in an existing array when you change the size of the last dimension.
varname | Name of the variable; follows standard variable naming conventions.
subscripts | Dimensions of an array variable; up to 60 multiple dimensions may be declared. The subscripts argument uses the following syntax:
 | [lower To] upper [,[lower To] upper] . . .
type | Data type of the variable; may be Boolean, Integer, Long, Currency, Single, Double, Date, String (for variable-length strings), String * length (for fixed-length strings), Object, Variant, a user-defined type, or an object type. Use a separate As type clause for each variable being defined. For a Variant containing an array, type describes the type of each element of the array, but does not change the Variant to some other type.

Remarks

The ReDim statement is usually used to size or resize a dynamic array that has already been formally declared using a Private, Public or Dim statement with empty parentheses (without dimension subscripts).

You can use the ReDim statement repeatedly to change the number of elements and dimensions in an array. However, you can't declare an array of one data type and later use ReDim to change the array to another data type, unless the array is contained in a Variant. If the array is contained in a Variant, the type of the elements can be changed using an As type clause.

If you use the Preserve keyword, you can resize only the last array dimension and you can't change the number of dimensions at all. For example, if your array has only one dimension, you can resize that dimension because it is the last and only dimension. However, if your array has two or more dimensions you can only change the size of the last dimension and still preserve the contents of the array. The following example shows how you can increase the size of the last dimension of a dynamic array without erasing any existing data contained in the array.

ReDim X(10, 10, 10)
. . .
ReDim Preserve X(10, 10, 15)

Caution

If you make an array smaller than it was, data in the eliminated elements will be lost.

When variables are initialized, a numeric variable is initialized to 0, a variable-length string is initialized to a zero-length string, and a fixed-length string is filled with zeros. Variant variables are initialized to Empty. Each element of a user-defined type variable is initialized as if it was a separate variable. A variable that refers to an object must be assigned an existing object using the Set statement before it can be used. Until it is assigned an object, the declared object variable has the special value Nothing, which indicates that it does not refer to any particular instance of an object.

Note

In order to resize an array contained in a Variant, you must explicitly declare the Variant variable before attempting to resize its array.

See Also

Array Function, Dim Statement, Option Base Statement, Private Statement, Public Statement, Static Statement.

Example

This example uses the ReDim statement to declare dynamic-array variables and then allocate and reallocate storage space.

Dim MyArray() As Integer    ' Declare dynamic array.
ReDim MyArray(5)    ' Allocate 5 elements.
For I = 1 To 5    ' Loop 5 times.
    MyArray(I) = I    ' Initialize array.
Next I
' The next statement resizes the array and erases the elements.
ReDim MyArray(10)    ' Resize to 10 elements.
For I = 1 To 10    ' Loop 10 times.
    MyArray(I) = I    ' Initialize array.
Next I
' The next statement resizes the array but does not erase elements.
ReDim Preserve MyArray(15)    ' Resize to 15 elements.


ReferenceStyle Property

Applies To

Application Object.

Description

Returns or sets how Microsoft Excel displays cell references and row and column headings in A1 or R1C1 reference style (either xlA1 or xlR1C1). Read-write.

Example

This example displays the current reference style.

If Application.ReferenceStyle = xlR1C1 Then
    MsgBox ("Microsoft Excel is using R1C1 references")
Else
    MsgBox ("Microsoft Excel is using A1 references")
End If


RefersTo Property

Applies To

Name Object.

Description

Returns or sets a string containing the formula that the name is defined to refer to, in A1-style notation, in the language of the macro writer, beginning with an equal sign. Read-write.

See Also

Formula Property, RefersToLocal Property, RefersToR1C1 Property, RefersToR1C1Local Property, RefersToRange Property.

Example

This example creates a list of all the names in the active workbook, and it shows their formulas in A1-style notation in the language of the macro. The list appears on a new worksheet created by the example.

Set newSheet = Worksheets.Add
i = 1
For Each nm In ActiveWorkbook.Names
    newSheet.Cells(i, 1).Value = nm.Name
    newSheet.Cells(i, 2).Value = "'" & nm.RefersTo
    i = i + 1
Next
newSheet.Columns("A:B").AutoFit


RefersToLocal Property

Applies To

Name Object.

Description

Returns or sets a string containing the formula that the name is defined to refer to, in A1 notation, in the language of the user, beginning with an equal sign. Read-write.

See Also

RefersTo Property, RefersToR1C1 Property, RefersToR1C1Local Property.

Example

This example creates a new worksheet and then inserts a list of all names in the active workbook, including their formulas in A1-style notation in the language of the user.

Set newSheet = ActiveWorkbook.Worksheets.Add
i = 1
For Each nm In ActiveWorkbook.Names
    newSheet.Cells(i, 1).Value = nm.NameLocal
    newSheet.Cells(i, 2).Value = "'" & nm.RefersToLocal
    i = i + 1
Next


RefersToR1C1 Property

Applies To

Name Object.

Description

Returns or sets a string containing the formula that the name is defined to refer to, in R1C1-style notation, in the language of the macro writer, beginning with an equal sign. Read-write.

See Also

RefersTo Property, RefersToLocal Property, RefersToR1C1Local Property, RefersToRange Property.

Example

This example creates a new worksheet and then inserts a list of all names in the active workbook, including their formulas in R1C1-style notation in the language of the macro.

Set newSheet = ActiveWorkbook.Worksheets.Add
i = 1
For Each nm In ActiveWorkbook.Names
    newSheet.Cells(i, 1).Value = nm.Name
    newSheet.Cells(i, 2).Value = "'" & nm.RefersToR1C1
    i = i + 1
Next


RefersToR1C1Local Property

Applies To

Name Object.

Description

Returns or sets a string containing the formula that the name is defined to refer to, in R1C1-style notation, in the language of the user, beginning with an equal sign. Read-write.

See Also

RefersTo Property, RefersToLocal Property, RefersToR1C1 Property.

Example

This example creates a new worksheet and then inserts a list of all names in the active workbook, including their formulas in R1C1-style notation in the language of the user.

Set newSheet = ActiveWorkbook.Worksheets.Add
i = 1
For Each nm In ActiveWorkbook.Names
    newSheet.Cells(i, 1).Value = nm.NameLocal
    newSheet.Cells(i, 2).Value = "'" & nm.RefersToR1C1Local
    i = i + 1
Next


RefersToRange Property

Applies To

Name Object.

Description

Returns the Range object referred to by a Name object. This property is available only in Microsoft Excel for Windows 95. Read-only.

Remarks

If the Name object doesn't refer to a range (for example, if the Name object refers to a constant or a formula), this property fails.

To change the range that a name refers to, use the RefersTo property.

See Also

RefersTo Property, RefersToR1C1 Property.

Example

This example displays the number of rows and columns in the print area on the active worksheet.

p = Names("Print_Area").RefersToRange.Value
MsgBox "Print_Area: " & UBound(p, 1) & " rows, " & _
    UBound(p, 2) & " columns"

    UBound(p, 2) & " columns"


RefreshDate Property

Applies To

PivotTable Object.

Description

Returns the date when the PivotTable was last refreshed. Read-only.

See Also

RefreshName Property, RefreshTable Method.

Example

This example displays the date on which the PivotTable was last refreshed.

Set pvtTable = Worksheets("Sheet1").Range("A3").PivotTable
dateString = Format(pvtTable.RefreshDate, "Long Date")
MsgBox "The data was last refreshed on " & dateString


RefreshName Property

Applies To

PivotTable Object.

Description

Returns the name of the person who last refreshed the PivotTable data. Read-only.

See Also

RefreshDate Property, RefreshTable Method.

Example

This example displays the name of the person who last refreshed the PivotTable.

Set pvtTable = Worksheets("Sheet1").Range("A3").PivotTable
MsgBox "The data was last refreshed by " & pvtTable.RefreshName


RefreshTable Method

Applies To

PivotTable Object.

Description

Refreshes the PivotTable from the source data. Returns True if it is successful.

Syntax

object.RefreshTable

object

Required. The PivotTable object.

See Also

RefreshDate Property, RefreshName Property.

Example

This example refreshes the PivotTable.

Set pvtTable = Worksheets("Sheet1").Range("A3").PivotTable
pvtTable.RefreshTable


RegisteredFunctions Property

Applies To

Application Object.

Description

Returns an array containing a list of functions in dynamic-link libraries (DLLs) or code resources that were registered with the REGISTER or REGISTER.ID functions. Read-only. Each row in the array contains information about a single function, as shown in the following table.

Column | Contents
1 | The name of the DLL or code resource.
2 | The name of the procedure in the DLL or code resource.
3 | Strings specifying the data types of the return values, and the number and data types of the arguments.

Remarks

If there are no registered functions, the property returns Null. Use the IsNull function to test the return value for Null.

Example

This example creates a list of registered functions, placing one registered function in each row on Sheet1. Column A contains the full path and filename of the DLL or code resource, column B contains the function name, and column C contains the argument data type code.

theArray = Application.RegisteredFunctions
If IsNull(theArray) Then
    MsgBox "No registered functions"
Else
    For i = LBound(theArray) To UBound(theArray)
        For j = 1 To 3
            Worksheets("Sheet1").Cells(i, j).Formula = theArray(i, j)
        Next j
    Next i
End If


RegisterXLL Method

Applies To

Application Object.

Description

Loads an XLL code resource and automatically registers the functions and commands that the resource contains.

Syntax

object.RegisterXLL(filename)

object

Required. The Application object.

filename

Required. Specifies the name of the XLL to load.

Remarks

This method returns True if the code resource is successfully loaded. Otherwise, the method returns False.

See Also

RegisteredFunctions Property.

Example

This example loads an XLL file and registers the functions and commands in the file.

Application.RegisterXLL "XLMAPI.XLL"


Rem Statement

Description

Used to include explanatory remarks in a program.

Syntax 1

Rem comment

Syntax 2

' comment

The argument comment is the text of any comment you want to include. After the Rem keyword, a space before comment is required.

Remarks

If you use line numbers or line labels, you can branch from a GoTo or GoSub statement to a line containing a Rem statement. Execution continues with the first executable statement following the Rem statement.

As shown in syntax 2, you can use a single quotation mark or apostrophe (') instead of the Rem keyword. If the Rem keyword follows other statements on a line, it must be separated from the statements by a colon. However, when you use a single quotation mark, the colon is not required after other statements.

Example

This example illustrates the various forms of the Rem statement, which is used to include explanatory remarks in a program.

Rem This is the first form of the syntax.
' This is the second form of the syntax.
MyStr1 = "Hello" : Rem Comment after a statement separated by a colon.
MyStr2 = "Goodbye"     ' This is also a comment.


RemoveAllItems Method

Applies To

DrawingObjects Collection, DropDown Object, DropDowns Collection, ListBox Object, ListBoxes Collection.

Description

Removes all entries from a list box or drop-down list box.

Syntax

object.RemoveAllItems

object

Required. The object to which this method applies.

See Also

AddItem Method, List Property, RemoveItem Method.

Example

This example removes all entries from list box one on Dialog1.

DialogSheets("Dialog1").Listboxes(1).RemoveAllItems


RemoveItem Method

Applies To

DrawingObjects Collection, DropDown Object, DropDowns Collection, ListBox Object, ListBoxes Collection.

Description

Removes one or more items from a list box or drop-down list box.

Syntax

object.RemoveItem(index, count)

object

Required. The object to which this method applies.

index

Required. Specifies the number of the first item to remove. Valid values are from one to the number of items in the list (returned by the ListCount property).

count

Optional. Specifies the number of items to remove starting at item index. If this argument is omitted, one item is removed. If index + count exceeds the number of items in the list, all items from index through the end of the list are removed without an error.

Remarks

This method fails if the object has a ListFillRange defined.

See Also

AddItem Method, List Property, RemoveAllItems Method.

Example

This example removes the first entry from list box one on Dialog1.

DialogSheets("Dialog1").Listboxes(1).RemoveItem index:=1


RemoveSubtotal Method

Applies To

Range Object.

Description

Removes subtotals from a list.

Syntax

object.RemoveSubtotal

object

Required. The Range object.

See Also

Subtotal Method.

Example

This example removes subtotals for the range A1:G37 on Sheet1. The example should be run on a list that has subtotals.

Worksheets("Sheet1").Range("A1:G37").RemoveSubtotal


Repeat Method

Applies To

Application Object.

Description

Repeats the last user-interface action.

Syntax

object.Repeat

object

Required. The Application object.

Remarks

This method can only be used to repeat the last action taken by the user before running the macro, and it must be the first line in the macro. It cannot be used to repeat Visual Basic commands.

Example

This example repeats the last user interface command. The example must be the first line in a macro.

Application.Repeat


Replace Method

Applies To

Range Object.

Description

Finds and replaces characters in cells within a range. Does not change the selection or active cell.

For help about using the Replace worksheet function in Visual Basic, see "Using Worksheet Functions in Visual Basic" in online Help.

Syntax

object.Replace(what, replacement, lookAt, searchOrder, matchCase, matchByte)

object

Required. Replace characters or cells in this range.

what

Required. A string indicating the contents for which you want to search.

replacement

Required. A string indicating the text with which you want to replace what.

lookAt

Optional. If xlWhole, what must match the entire contents of a cell. If xlPart, what must contain part of the contents of a cell.

searchOrder

Optional. Specifies whether to search by rows (xlByRows) or columns (xlByColumns).

matchCase

Optional. If True, search is case sensitive.

matchByte

Optional. Used only in Far East Microsoft Excel. If True, double-byte characters match only double-byte characters. If False, double-byte characters can match their single-byte equivalents.

Remarks

The settings for lookAt, searchOrder, matchCase, and matchByte are saved each time you use this method. If you do not specify values for these arguments the next time you call the method, the saved values are used. Setting these arguments changes the settings in the Find dialog box, and changing the settings in the Find dialog box changes the saved values that are used if you omit the arguments. To avoid problems, explicitly set these arguments each time you use this method.

If the contents of the what argument are found in at least one cell of the sheet, the method returns True.

See Also

Find Method, FindNext Method.

Example

This example replaces every occurrence of the function SIN with the function COS. The replacement range is column A on Sheet1.

Worksheets("Sheet1").Columns("A").Replace _
    what:="SIN", replacement:="COS", _
    searchOrder:=xlByColumns, matchCase:=True


ReplacementList Property

Applies To

AutoCorrect Object.

Description

Returns or sets the array of AutoCorrect replacements. This property is available only in Microsoft Excel for Windows 95. Read-write.

Syntax

object.ReplacementList(index)

object

Required. The AutoCorrect object.

index

Optional. Specifies which row of the array of AutoCorrect replacements to set or return. The row is returned as a one-dimensional array with two elements: the first element is the text in column 1, and the second element is the text in column 2. If index is out of range, the property fails.

If index is omitted, this property returns a two-dimensional array. Each row in the array contains one replacement, as shown in the following table.

Column

Contents

1

The text to replace

2

The replacement text

If index is omitted when you set this property, the entire replacement array is deleted and replaced.

Remarks

Be very careful when you set this property. If you don't specify the index argument, you'll delete the entire replacement array. It may be easier and safer to change a replacement by using the AddReplacement method.

Duplicate strings in column one of the array of replacements aren't allowed. If you attempt to modify or replace the array in a way that would create this condition, an error occurs.

See Also

AddReplacement Method, DeleteReplacement Method.

Example

This example searches the replacement list for "Temperature", sets the text to replace it with to "Temp.", and then writes the new array of AutoCorrect replacements to a worksheet.

With Application.AutoCorrect
    For x = 1 To UBound(.ReplacementList)
            repl = .ReplacementList(x)
            If repl(1) = "Temperature" Then
                repl(2) = "Temp."
                .ReplacementList(x) = repl
            End If
        Worksheets(1).Cells(x, 1) = repl(1)
        Worksheets(1).Cells(x, 2) = repl(2)
    Next
End With


ReplaceText Property

Applies To

AutoCorrect Object.

Description

True if text in the AutoCorrect replacements list is replaced automatically. This property is available only in Microsoft Excel for Windows 95. Read-write.

See Also

ReplacementList Property.

Example

This example turns off automatic text replacement.

With Application.AutoCorrect
    .CapitalizeNamesOfDays = True
    .ReplaceText = False
End With


Reply Method

Applies To

Workbook Object.

Description

Replies to the workbook by creating a copy of the workbook and pre-initializing the new workbook's mailer to send to the originator of the workbook. Valid only when the workbook has a received mailer attached (you can only reply to a workbook you have received). Available only in Microsoft Excel for the Apple Macintosh with the PowerTalk mail system extension installed.

Syntax

object.Reply

object

Required. The Workbook object.

Remarks

To reply to a workbook, use this method to set up the mailer, use the Mailer property to adjust the mailer settings (if necessary), and then use the SendMailer method to send the reply.

This method generates an error if it is used in Microsoft Windows.

See Also

Mailer Property, MailSystem Property, ReplyAll Method, SendMailer Method.

Example

This example replies to the sender of the active workbook.

Set original = ActiveWorkbook
If original.HasMailer Then
    original.Reply
    original.Mailer.Subject = "Here's my reply"
    ActiveWorkbook.SendMailer
End If


ReplyAll Method

Applies To

Workbook Object.

Description

Replies to the workbook by creating a copy of the workbook and pre-initializing the new workbook's mailer to send to all recipients of the workbook. Valid only when the workbook has a received mailer attached (you can only reply to a workbook you have received). Available only in Microsoft Excel for the Apple Macintosh with the PowerTalk mail system extension installed.

Syntax

object.ReplyAll

object

Required. The Workbook object.

Remarks

To reply to all recipients of a workbook, use this method to set up the mailer, use the Mailer property to adjust the mailer settings (if necessary), and then use the SendMailer method to send the reply.

This method generates an error if it is used in Microsoft Windows.

See Also

Mailer Property, MailSystem Property, Reply Method, SendMailer Method.

Example

This example replies to all recipients of the active workbook.

Set original = ActiveWorkbook
If original.HasMailer Then
    original.ReplyAll
    original.Mailer.Subject = "Here's my reply"
    ActiveWorkbook.SendMailer
End If


Reset Method

Applies To

MenuBar Object, RoutingSlip Object, Toolbar Object, ToolbarButton Object.

Description

Restores the built-in menu bar or toolbar to its original default configuration. Resets a toolbar button to its original face.

Resets the routing slip so that a new routing can be initiated with the same slip (using the same recipient list and delivery information). The routing must be completed before you use this method. Using this method at other times causes an error.

Syntax

object.Reset

object

Required. The object to which this method applies.

Remarks

Be careful when you reset a menu bar or toolbar-other macros may have added menu items or buttons, and resetting the menu bar or toolbar will remove those as well. To avoid conflicting with other macros, remove the menu items or buttons your macro has added without resetting the menu bar or toolbar.

This method cannot be used with a toolbar button that is a gap or a toolbar button that has a palette or list attached (such as the Font or Style buttons).

Example

This example resets the routing slip for BOOK1.XLS if routing is complete.

With Workbooks("BOOK1.XLS").RoutingSlip
    If .Status = xlRoutingComplete Then
        .Reset
    Else
        MsgBox "Cannot reset routing; not yet complete"
    End If
End With


Reset Statement

Description

Closes all disk files opened using the Open statement.

Syntax

Reset

Remarks

The Reset statement syntax closes all active files opened by the Open statement and writes the contents of all file buffers to disk.

See Also

Close Statement, End Statement, Open Statement.

Example

This example uses the Reset statement to close all open files and write the contents of all file buffers to disk.

For FileNumber = 1 To 5    ' Loop 5 times.
    ' Open file for output.
    Open "TEST" & FileNumber For Output As #FileNumber
    Write #FileNumber, "Hello World"    ' Write data to file.
Next FileNumber
Reset    ' Close files and write contents
    ' to disk.


ResetTipWizard Method

Applies To

Application Object.

Description

Resets the TipWizard memory so that all tips will be shown. Normally tips that have been shown several times are disabled so that they do not become annoying.

Syntax

object.ResetTipWizard

object

Required. The Application object.

See Also

EnableTipWizard Property.

Example

This example resets the TipWizard and then enables it.

With Application
    .ResetTipWizard
    .EnableTipWizard = True
End With


Reshape Method

Applies To

Drawing Object, DrawingObjects Collection, Drawings Collection.

Description

Reshapes the drawing by inserting, moving, or deleting vertices.

Syntax

object.Reshape(vertex, insert, left, top)

object

Required. The object to which this method applies.

vertex

Required. Specifies the vertex you want to insert, move, or delete.

insert

Required. If True, Microsoft Excel inserts a vertex between the vertices vertex and vertex - 1. The number of the new vertex then becomes vertex. The number of the vertex previously identified by vertex becomes vertex + 1, and so on. If insert is False, Microsoft Excel deletes the vertex (if top and left are omitted) or moves the vertex to the position specified by the top and left arguments.

left

Optional. The left position for the new or moved vertex, in points (1/72 inch) relative to the upper-left corner of cell A1 or the upper-left corner of the chart.

top

Optional. The top position for the new or moved vertex, in points relative to the upper-left corner of cell A1 or the upper-left corner of the chart.

Remarks

You cannot delete a vertex if only two vertices remain.

See Also

AddVertex Method, Vertices Property.

Example

Assuming that drawing one on Sheet1 is a polygon with at least five vertices, this example reshapes the polygon by deleting vertex five.

Worksheets("Sheet1").Drawings(1).Reshape _
        vertex:=5, Insert:=False


Resize Method

Applies To

Range Object.

Description

Resizes the range.

Syntax

object.Resize(rowSize, columnSize)

object

Required. The Range object to resize.

rowSize

Optional. The number of rows in the new range. If omitted, the range will keep the same number of rows.

columnSize

Optional. The number of columns in the new range. If omitted, the range will keep the same number of columns.

Example

This example resizes the selection on Sheet1 to extend it by one row and one column.

Worksheets("Sheet1").Activate
numRows = Selection.Rows.Count
numColumns = Selection.Columns.Count
Selection.Resize(numRows + 1, numColumns + 1).Select

This example assumes that you have a table on Sheet1 that has a header row. The example selects the table, without selecting the header row. The active cell must be somewhere in the table before you run the example.

Set tbl = ActiveCell.CurrentRegion
tbl.Offset(1, 0).Resize(tbl.Rows.Count - 1, tbl.Columns.Count).Select


Resume Statement

Description

Resumes execution after an error-handling routine is finished.

Syntax

Resume [0]

Resume Next

Resume line

The Resume statement syntax can have any of the following forms:

Statement | Description
Resume [0] | If the error occurred in the same procedure as the error handler, execution resumes with the one that caused the error. If the error occurred in another procedure, execution resumes at the statement that last called out of the procedure containing the error-handling routine.
Resume Next | If the error occurred in the same procedure as the error handler, execution resumes with the statement immediately following the statement that caused the error. If the error occurred in another procedure, execution resumes with the statement immediately following the statement that last called out of the procedure containing the error-handling routine.
Resume line | Execution resumes at line, which is a line label or line number. The argument line must be in the same procedure as the error handler.

Remarks

If you use a Resume statement anywhere except in an error-handling routine, an error occurs.

When an error-handling routine is active and the end of the procedure (an End Sub, End Function, or End Property statement) is encountered before a Resume statement is encountered, an error occurs because a logical error is presumed to have been made inadvertently. However, if an Exit Sub, Exit Function, or Exit Property statement is encountered while an error handler is active, no error occurs because it is considered a deliberate redirection of execution.

See Also

On Error Statement.

Example

This example uses the Resume statement to end error handling in a procedure and resume execution with the statement that caused the error. Error number 55 is generated to illustrate its usage.

Sub ResumeStatementDemo()
    On Error GoTo ErrorHandler    ' Enable error-handling routine.
    Open "TESTFILE" For Output As #1    ' Open file for output.
    Kill "TESTFILE"    ' Attempt to delete open file.
    Exit Sub    ' Exit Sub before error handler.
ErrorHandler:    ' Error-handling routine.
    Select Case Err    ' Evaluate Error Number.
        Case 55    ' "File already open" error.
            Close #1    ' Close open file.
        Case Else
            ' Handle other situations here...
    End Select
    Resume    ' Resume execution at same line
    ' that caused the error.
End Sub


ReturnWhenDone Property

Applies To

RoutingSlip Object.

Description

True if the workbook is returned to the sender when the routing is finished. Read-write before routing begins; read-only when routing is in progress.

Example

This example sends BOOK1.XLS to three recipients, one after the other, and returns the workbook to the sender when routing is complete.

Workbooks("BOOK1.XLS").HasRoutingSlip = True
With Workbooks("BOOK1.XLS").RoutingSlip
    .Delivery = xlOneAfterAnother
    .Recipients = Array("Adam Bendel", "Jean Selva", "Bernard Gabor")
    .Subject = "Here is BOOK1.XLS"
    .Message = "Here is the workbook. What do you think?"
    .ReturnWhenDone = True
End With
Workbooks("BOOK1.XLS").Route


ReversePlotOrder Property

Applies To

Axis Object.

Description

True if Microsoft Excel plots points from last to first. Read-write.

Remarks

This property is not available for radar charts.

Example

This example reverses the order in which points on the value axis in Chart1 are plotted.

Charts("Chart1").Axes(xlValue).ReversePlotOrder = True


RevisionNumber Property

Applies To

Workbook Object.

Description

Returns the number of times the workbook has been saved while open as a shared list. If the workbook is open in exclusive mode, this property returns 0 (zero). This property is available only in Microsoft Excel for Windows 95. Read-only.

Remarks

The RevisionNumber property is updated only when the local copy of the workbook is saved, not when remote copies are saved.

See Also

MultiUserEditing Property, SaveAs Method.

Example

This example uses the revision number to determine whether the active workbook is open in exclusive mode. If it is, the example saves the active workbook as a shared list.

If ActiveWorkbook.RevisionNumber = 0 then
    ActiveWorkbook.SaveAs filename := ActiveWorkbook.FullName, _
        accessMode:= xlShared, conflictResolution := _
        xlOtherSessionChanges
End If

This example displays the revision number of the active workbook.

MsgBox ActiveWorkbook.RevisionNumber


RGB Function

Description

Returns a whole number representing an RGB color value.

Syntax

RGB (red, green, blue)

The RGB function syntax has these named-argument parts:

Part | Description
red | Whole number in the range 0 to 255, inclusive, that represents the red component of the color.
green | Whole number in the range 0 to 255, inclusive, that represents the green component of the color.
blue | Whole number in the range 0 to 255, inclusive, that represents the blue component of the color.

Remarks

Application methods and properties that accept a color specification expect that specification to be a whole number representing an RGB color value. An RGB color value specifies the relative intensity of red, green, and blue, which combined cause a specific color to be displayed.

The value for any argument to RGB that exceeds 255 is assumed to be 255.

The following table lists some standard colors and the red, green and blue values they include:

Color | Red Value | Green Value | Blue Value
Black | 0 | 0 | 0
Blue | 0 | 0 | 255
Green | 0 | 255 | 0
Cyan | 0 | 255 | 255
Red | 255 | 0 | 0
Magenta | 255 | 0 | 255
Yellow | 255 | 255 | 0
White | 255 | 255 | 255

Note

The RGB values returned by this function are incompatible with those used by the Macintosh operating system. They may be used within the context of Microsoft applications for the Macintosh, but should not be used when communicating color changes directly to the Macintosh operating system.

Example

This example shows how the RGB function is used to return a whole number representing an RGB color value. It is used for those application methods and properties that accept a color specification. The object MyObject and its property are used here for illustration purposes only.

Red = RGB(255, 0, 0)    ' Return the value for Red.
I = 75    ' Initialize offset.
RGBValue = RGB(I, 64 + I, 128 + I)     ' Same as RGB(75, 139, 203).
MyObject.Color = RGB(255, 0, 0)    ' Set the Color property of
    ' MyObject to Red.

This example sets the gridline color in the active window in BOOK1.XLS to red.

Workbooks("BOOK1.XLS").Worksheets("Sheet1").Activate
ActiveWindow.GridlineColor = RGB(255,0,0)

This example sets the color of the tick labels on the value axis in Chart1 to green.

Charts("Chart1").Axes(xlValue).TickLabels.Font.Color = RGB(0, 255, 0)

This example sets the marker background and foreground colors for the second point in series one in Chart1.

With Charts("Chart1").SeriesCollection(1).Points(2)
    .MarkerBackgroundColor = RGB(0,255,0)    ' green
    .MarkerForegroundColor = RGB(255,0,0)    ' red
End With

This example sets the interior pattern color for rectangle one on Sheet1 to red.

With Worksheets("Sheet1").Rectangles(1).Interior
    .Pattern = xlGrid
    .PatternColor = RGB(255,0,0)
End With


Right Function

Description

Returns a specified number of characters from the right side of a string.

Syntax

Right(string,length)

The Right function syntax has these named-argument parts:

Part | Description
string | String expression from which the rightmost characters are returned. If string contains no valid data, Null is returned.
length | Numeric expression indicating how many characters to return. If 0, a zero-length string is returned. If greater than or equal to the number of characters in string, the entire string is returned.

Remarks

To determine the number of characters in string, use the Len function.

Note

Another function (RightB) is provided for use with the double-byte character sets (DBCS) used in some Asian locales. Instead of specifying the number of characters to return, length specifies the number of bytes. In areas where DBCS is not used, RightB behaves the same as Right.

See Also

Left Function, Len Function, Mid Function.

Example

This example uses the Right function to return a specified number of characters from the right side of a string.

AnyString = "Hello World"    ' Define string.
MyStr = Right(AnyString, 1)    ' Returns "d".
MyStr = Right(AnyString, 6)    ' Returns " World".
MyStr = Right(AnyString, 20)    ' Returns "Hello World".


RightAngleAxes Property

Applies To

Chart Object.

Description

True if the chart axes are at right angles, independent of chart rotation or elevation. Applies only to 3-D line, column, and bar charts. Read-write.

Remarks

If this property is True, the Perspective property is ignored.

See Also

Elevation Property, Perspective Property, Rotation Property.

Example

This example sets the axes in Chart1 to intersect at right angles. The example should be run on a 3-D chart.

Charts("Chart1").RightAngleAxes = True


RightFooter Property

Applies To

PageSetup Object.

Description

Returns or sets the right part of the footer. Read-write.

Remarks

Special format codes can be used in the footer text.

See Also

CenterFooter Property, CenterHeader Property, LeftFooter Property, LeftHeader Property, RightHeader Property.

Example

This example prints the page number in the lower-right corner of every page.

Worksheets("Sheet1").PageSetup.RightFooter = "&P"


RightHeader Property

Applies To

PageSetup Object.

Description

Returns or sets the right part of the header. Read-write.

Remarks

Special format codes can be used in the header text.

See Also

CenterFooter Property, CenterHeader Property, LeftFooter Property, LeftHeader Property, RightFooter Property.

Example

This example prints the filename in the upper-right corner of every page.

Worksheets("Sheet1").PageSetup.RightHeader = "&F"


RightMargin Property

Applies To

PageSetup Object.

Description

Returns or sets the size of the right margin, in points (1/72 inch). Read-write.

Remarks

Margins are set or returned in points. Use the InchesToPoints or CentimetersToPoints function to convert.

Example

This example sets the right margin of Sheet1 to 1.5 inches.

Worksheets("Sheet1").PageSetup.RightMargin = _
        Application.InchesToPoints(1.5)

This example sets the right margin of Sheet1 to 2 centimeters.

Worksheets("Sheet1").PageSetup.RightMargin = _
        Application.CentimetersToPoints(2)

This example displays the current right margin setting for Sheet1.

marginInches = Worksheets("Sheet1").PageSetup.RightMargin / _
    Application.InchesToPoints(1)
MsgBox "The current right margin is " & marginInches & " inches"


RmDir Statement

Description

Removes an existing directory or folder.

Syntax

RmDir path

The path named argument is a string expression that identifies the directory or folder to be removed — may include drive. If no drive is specified, RmDir removes the directory or folder on the current drive.

Remarks

An error occurs if you try to use RmDir on a directory or folder containing files. Use the Kill statement to delete all files before attempting to remove a directory or folder.

See Also

ChDir Statement, CurDir Function, Kill Statement, MkDir Statement.

Example

This example uses the RmDir statement to remove an existing directory or folder.

' Assume that MYDIR is an empty directory or folder.
RmDir "MYDIR"    ' Remove MYDIR.


Rnd Function

Description

Returns a random number.

Syntax

Rnd[(number)]

The number named argument can be any valid numeric expression.

Remarks

The Rnd function returns a value less than 1 but greater than or equal to 0.

The value of number determines how Rnd generates a random number:

If number is: | Rnd generates:
Less than zero | The same number every time, using number as the seed.
Greater than zero | The next random number in the sequence.
Equal to zero | The most recently generated number.
Not supplied | The next random number in the sequence.

For any given initial seed, the same number sequence is generated because each successive call to the Rnd function uses the previous number as a seed for the next number in the sequence.

Use the Randomize statement without an argument to provide a random seed based on the system timer to initialize the random-number generator before Rnd is called.

To produce random integers in a given range, use this formula:

Int((upperbound - lowerbound + 1) * Rnd + lowerbound)

Here, upperbound is the highest number in the range, and lowerbound is the lowest number in the range.

See Also

Randomize Statement, Timer Function.

Example

This example uses the Rnd function to generate a random integer value from 1 to 6.

MyValue = Int((6 * Rnd) + 1)    ' Generate random value between 1 and 6.


Rotation Property

Applies To

Chart Object.

Description

Returns or sets the rotation of the 3-D chart view (the rotation of the plot area around the z-axis, in degrees). The value of this property must be between 0 and 360, except for 3-D Bar charts, where the value must be between 0 and 44. The default value is 20. Applies only to 3-D charts. Read-write.

See Also

Elevation Property, Perspective Property, RightAngleAxes Property.

Example

This example sets the rotation of Chart1 to 30 degrees. The example should be run on a 3-D chart.

Charts("Chart1").Rotation = 30


RoundedCorners Property

Applies To

ChartObject Object, ChartObjects Collection, DrawingObjects Collection, GroupObject Object, GroupObjects Collection, Rectangle Object, Rectangles Collection, TextBox Object, TextBoxes Collection.

Description

True if the drawing object has rounded corners. Read-write.

Example

This example adds rounded corners to rectangle one on Sheet1.

Worksheets("Sheet1").Rectangles(1).RoundedCorners = True


Route Method

Applies To

Workbook Object.

Description

Routes the workbook using the workbook's current routing slip.

Syntax

object.Route

object

Required. The Workbook object.

Remarks

Routing a workbook sets the Routed property to True.

See Also

Routed Property, RoutingSlip Property, SendMail Method.

Example

This example creates a routing slip for BOOK1.XLS and then sends the workbook to three recipients, one after another.

Workbooks("BOOK1.XLS").HasRoutingSlip = True
With Workbooks("BOOK1.XLS").RoutingSlip
    .Delivery = xlOneAfterAnother
    .Recipients = Array("Adam Bendel", "Jean Selva", "Bernard Gabor")
    .Subject = "Here is BOOK1.XLS"
    .Message = "Here is the workbook. What do you think?"
End With
Workbooks("BOOK1.XLS").Route


Routed Property

Applies To

Workbook Object.

Description

True if the workbook has been routed to the next recipient; False if the workbook needs to be routed. Read-only.

Remarks

If the workbook was not routed to the current recipient, this property is always False (for example, if the document has no routing slip, or a routing slip was just created).

Example

This example sends the workbook to the next recipient.

If ActiveWorkbook.HasRoutingSlip And _
    Not ActiveWorkbook.Routed Then
        ActiveWorkbook.Route
End If


RoutingSlip Object

Description

Represents the routing slip for a workbook. The routing slip is used to send a workbook through the electronic mail system.

Accessors

The RoutingSlip property returns the routing slip for the workbook. The following example sets the delivery style for the routing slip attached to the active workbook. For a more detailed example, see the RoutingSlip property.

ActiveWorkbook.HasRoutingSlip = True
ActiveWorkbook.RoutingSlip.Delivery = xlOneAfterAnother

Remarks

The RoutingSlip object does not exist and cannot be accessed unless the HasRoutingSlip property for the workbook is True.

Properties

Application Property, Creator Property, Delivery Property, Message Property, Parent Property, Recipients Property, ReturnWhenDone Property, Status Property, Subject Property, TrackStatus Property.

Methods

Reset Method.


RoutingSlip Property

Applies To

Workbook Object.

Description

This example creates a routing slip for BOOK1.XLS and then sends the workbook to three recipients, one after another.

Accessor

Returns a RoutingSlip object that represents the routing slip for the workbook. Reading this property if there is no routing slip causes an error (check the HasRoutingSlip property first). Read-only.

Example

Workbooks("BOOK1.XLS").HasRoutingSlip = True
With Workbooks("BOOK1.XLS").RoutingSlip
    .Delivery = xlOneAfterAnother
    .Recipients = Array("Adam Bendel", "Jean Selva", "Bernard Gabor")
    .Subject = "Here is BOOK1.XLS"
    .Message = "Here is the workbook. What do you think?"
End With
Workbooks("BOOK1.XLS").Route


Row Property

Applies To

Range Object.

Description

Returns the number of the first row of the first area of the range. Read-only.

See Also

Column Property, EntireColumn Property, EntireRow Property, Rows Method.

Example

This example sets the row height of every other row on Sheet1 to 4 points.

For Each rw In Worksheets("Sheet1").Rows
    If rw.Row Mod 2 = 0 Then
        rw.RowHeight = 4
    End If
Next rw


RowDifferences Method

Applies To

Range Object.

Description

Accessor. Returns a Range object representing all the cells whose contents are different than the comparison cell in each of the rows. The comparison cell is a cell in the comparison column and is equal to the comparison argument.

Syntax

object.RowDifferences(comparison)

object

Required. The object to which this method applies.

comparison

Required. A cell in the comparison column. Use the ActiveCell property if you are finding the differences between the active cell's column and all rows in the range.

See Also

ColumnDifferences Method.

Example

This example selects the cells in row one on Sheet1 whose contents are different from cell D1.

Worksheets("Sheet1").Activate
Set c1 = ActiveSheet.Rows(1).RowDifferences( _
    comparison:=ActiveSheet.Range("D1"))
c1.Select


RowFields Method

Applies To

PivotTable Object.

Description

Accessor. Returns an object that represents a single pivot field (a PivotField object, Syntax 1) or a collection of the pivot fields (a PivotFields object, Syntax 2) that are currently showing as row fields. Read-only.

Syntax 1

object.RowFields(index)

Syntax 2

object.RowFields

object

Required. The PivotTable object.

index

Required for Syntax 1. The name or number of the pivot field to return (can be an array to specify more than one).

See Also

ColumnFields Method, DataFields Method, HiddenFields Method, PageFields Method, PivotFields Method, VisibleFields Method.

Example

This example adds the PivotTable row field names to a list box. The list box appears on Sheet1.

Set pvtTable = Worksheets("Sheet1").Range("A3").PivotTable
Set newListBox = Worksheets("Sheet1").ListBoxes.Add _
    (Left:=10, Top:=72, Width:=144, Height:=144)
For Each hdnField In pvtTable.RowFields
    newListBox.AddItem (hdnField.Name)
Next hdnField
Worksheets("Sheet1").Activate


RowGrand Property

Applies To

PivotTable Object.

Description

True if the PivotTable shows row grand totals. Read-write.

See Also

ColumnGrand Property.

Example

This example sets the PivotTable to show row grand totals.

Set pvtTable = Worksheets("Sheet1").Range("A3").PivotTable
pvtTable.RowGrand = True


RowHeight Property

Applies To

Range Object.

Description

Returns the height of all of the rows in the range specified, measured in points (1/72 inch). Read-write.

Remarks

For a single row, the value of the Height property is equal to the value of RowHeight. However, you can also use the Height property to return the total height of a range of cells.

Other differences between RowHeight and Height are the following:

  • Height is read-only.
  • If you return the RowHeight of several rows, you will either get the row height of each of the rows (if they are the same), or Null if they are different. If you return the Height property of several rows, you will get the total height of all the rows.

See Also

ColumnWidth Property, Height Property, StandardHeight Property.

Example

This example doubles the height of row one on Sheet1.

With Worksheets("Sheet1").Rows(1)
    .RowHeight = .RowHeight * 2
End With


RowRange Property

Applies To

PivotTable Object.

Description

Accessor. Returns a Range object that represents the range that includes the PivotTable row area. Read-only.

See Also

ColumnRange Property, DataBodyRange Property, DataLabelRange Property, PageRange Property.

Example

This example selects the PivotTable row headers.

Worksheets("Sheet1").Activate
Range("A3").Select
ActiveCell.PivotTable.RowRange.Select


Rows Method

Applies To

Application Object, Range Object, Worksheet Object.

Description

Accessor. Returns a Range object that represents a single row (Syntax 1) or a collection of rows (Syntax 2).

Syntax 1

object.Rows(index)

Syntax 2

object.Rows

object

Optional for Application, required for Range and Worksheet. The object that contains the rows. If you specify the Application object (or omit the object qualifier), this method applies to the active sheet in the active workbook. If the active sheet is not a worksheet, this method fails.

index

Required for Syntax 1. The name or number of the row.

Remarks

When applied to a Range object that is a multiple selection, this method returns rows from the first area of the range only. For example, if the Range object is a multiple selection with two areas, A1:B2 and C3:D4, Selection.Rows.Count returns 2, not 4. To use this method on a range that may contain a multiple selection, test Areas.Count to determine if the range is a multiple selection, and if it is, then loop over each area in the range; see the second example.

See Also

Columns Method, Range Method.

Example

This example deletes row three on Sheet1.

Worksheets("Sheet1").Rows(3).Delete

This example displays the number of rows in the selection on Sheet1. If more than one area is selected, the example loops through every area.

Worksheets("Sheet1").Activate
areaCount = Selection.Areas.Count
If areaCount <= 1 Then
    MsgBox "The selection contains " & _
        Selection.Rows.Count & " rows."
Else
    i = 1
    For Each a In Selection.Areas
        MsgBox "Area " & i & " of the selection contains " & _
            a.Rows.Count & " rows."
        i = i + 1
    Next a
End If


RSet Statement

Description

Right aligns a string within a string variable.

Syntax

RSet stringvar = string

The RSet statement syntax has these parts:

Part | Description
stringvar | Name of a string variable.
string | String expression to be right aligned within stringvar.

Remarks

RSet replaces any leftover characters in stringvar with spaces, back to its beginning.

RSet can't be used with user-defined types.

See Also

LSet Statement.

Example

This example uses the RSet statement to right align a string within a string variable.

MyString = "0123456789"    ' Initialize string.
RSet MyString = "Right->"    ' MyString contains "   Right->".


Run Method

Applies To

Application Object, Range Object.

Description

Syntax 1: Runs a macro or calls a function. This can be used to run a macro written in any language (Visual Basic, the Microsoft Excel 4.0 macro language, or a function in a DLL or XLL).

Syntax 2: Runs the Microsoft Excel 4.0 macro at this location. The range must be on a macro sheet.

Syntax 1

object.Run(macro, arg1, arg2, ...)

Syntax 2

object.Run(arg1, arg2, ...)

object

Optional for Application, required for Range. The application that contains the macro, or a range on a macro sheet that contains an Microsoft Excel 4.0 macro.

macro

Required for Syntax 1 (not used with Syntax 2). The macro to run. This can be a string with the macro name, or a Range indicating where the function is, or a register ID for a registered DLL (XLL) function. If a string is used, the string will be evaluated in the context of the active sheet.

arg1, arg2, ...

Optional. The arguments that should be passed to the function.

Remarks

The Run method returns whatever the called macro returns. Objects passed as arguments to the macro are converted to values (by applying the Value property to the object). This means you cannot pass objects to macros using the Run method.

Example

This example shows how to call the function macro My_Func_Sum, which is defined on the macro sheet MYCUSTOM.XLM (the macro sheet must be open). The function takes two numeric arguments-1 and 5, in this example.

mySum = Application.Run("MYCUSTOM.XLM!My_Func_Sum", 1, 5)
MsgBox "Macro result: " & mySum


RunAutoMacros Method

Applies To

Workbook Object.

Description

Runs the Auto_Open, Auto_Close, Auto_Activate, or Auto_Deactivate macros that are attached to the workbook.

These four auto macros do not run when workbooks are opened or closed (and when sheets are activated or deactivated) by a Visual Basic program. Use this method to run auto macros.

Syntax

object.RunAutoMacros(which)

object

Required. The Workbook object.

which

Required. Specifies which macros to run, as shown in the following table.

Value

Meaning

xlAutoOpen

Auto_Open macros.

xlAutoClose

Auto_Close macros.

xlAutoActivate

Auto_Activate macros.

xlAutoDeactivate

Auto_Deactivate macros.

Remarks

The Auto_Activate and Auto_Deactivate macros are included for backward compatibility with the Microsoft Excel 4.0 macro language. Use the OnSheetActivate and OnSheetDeactivate properties when you program in Visual Basic.

Example

This example opens the workbook ANALYSIS.XLS and then runs its Auto_Open macro.

Workbooks.Open "ANALYSIS.XLS"
ActiveWorkbook.RunAutoMacros xlAutoOpen

This example runs the Auto_Close macro for the active workbook and then closes the workbook.

With ActiveWorkbook
    .RunAutoMacros xlAutoClose
    .Close
End With


Save Method

Applies To

Application Object, Workbook Object.

Description

Workbook object (Syntax 1): Saves changes to the specified workbook. Application object (Syntax 2): Saves the current workspace.

Syntax 1

object.Save

Syntax 2

object.Save(filename)

object

Required. The Workbook object (Syntax 1) or Application object (Syntax 2).

filename

Optional. Specifies the name of the saved workspace file. If this argument is omitted, a default name is used.

Remarks

To open a workbook file, use the Open method.

To mark the workbook as saved without writing it to a disk, set its Saved property to True.

The first time you save a workbook, use the SaveAs method to specify a name for the file.

See Also

Open Method, SaveAs Method, SaveCopyAs Method, Saved Property.

Example

This example saves the active workbook.

ActiveWorkbook.Save

This example saves all open workbooks and then closes Microsoft Excel.

For Each w In Application.Workbooks
    w.Save
Next w
Application.Quit


SaveAs Method

Applies To

Chart Object, DialogSheet Object, Module Object, Workbook Object, Worksheet Object.

Description

Saves changes to the sheet or workbook in a different file.

Syntax

object.SaveAs(filename, fileFormat, password, writeResPassword, readOnlyRecommended, createBackup, accessMode, conflictResolution)

object

Required. The object to which this method applies.

filename

Optional. A string indicating the name of the file to save. You can include a full path; if you do not, Microsoft Excel saves the file in the current folder.

fileFormat

Optional. The file format to use when you save the file. See the FileFormat property for a list of valid choices.

password

Optional. A case-sensitive string indicating the protection password to be given to the file. Should be no more than 15 characters.

writeResPassword

Optional. A string indicating the write-reservation password for this file. If a file is saved with the password and the password is not supplied when the file is opened, the file is opened as read-only.

readOnlyRecommended

Optional. If True, when the file is opened, Microsoft Excel displays a message recommending that you open the file as read-only.

createBackup

Optional. If True, Microsoft Excel creates a backup file; if False, no backup file is created; if omitted, the status is unchanged.

accessMode

Optional. Specifies the workbook access mode. One of xlShared (shared list), xlExclusive (exclusive mode), or xlNoChange (do not change the access mode). If this argument is omitted, the access mode is not changed. This argument is ignored if you save a shared list without changing the filename. To change the access mode, use the ExclusiveAccess method.

conflictResolution

Optional. Specifies how change conflicts are resolved if the workbook is a shared list. One of xlUserResolution (display the conflict-resolution dialog box), xlLocalSessionChanges (automatically accept the local user's changes), or xlOtherSessionChanges (accept other changes in preference to the local user's changes). If this argument is omitted, the conflict-resolution dialog box is displayed.

See Also

FileFormat Property, MultiUserEditing Property, Save Method, SaveCopyAs Method, Saved Property.

Example

This example creates a new workbook, prompts the user for a filename, and then saves the workbook.

Set NewBook = Workbooks.Add
Do
    fName = Application.GetSaveAsFilename
Loop Until fName <> False
NewBook.SaveAs Filename:=fName


SaveCopyAs Method

Applies To

Workbook Object.

Description

Saves a copy of the workbook to a file but does not modify the open workbook in memory.

Syntax

object.SaveCopyAs(filename)

object

Required. The Workbook object.

filename

Required. Specifies the filename for the copy.

See Also

Save Method, SaveAs Method.

Example

This example saves a copy of the active workbook.

ActiveWorkbook.SaveCopyAs "C:\TEMP\XXXX.XLS"

This is the same example in Microsoft Excel for the Macintosh.

ActiveWorkbook.SaveCopyAs "HD:Temporary Folder:Temporary Workbook File"


Saved Property

Applies To

Workbook Object.

Description

False if changes have been made to a workbook since it was last saved. Read-write.

Remarks

If a workbook has never been saved, its Path will return an empty string ("").

You can set this property to True if you want to close a modified workbook without saving it or being prompted to save it.

See Also

Save Method, SaveAs Method, SaveCopyAs Method.

Example

This example displays a message if the active workbook contains unsaved changes.

If Not ActiveWorkbook.Saved Then
    MsgBox "This workbook contains unsaved changes."
End If

This example closes the workbook that contains the example code and discards any changes to the workbook by setting the Saved property to True.

ThisWorkbook.Saved = True
ThisWorkbook.Close


SaveData Property

Applies To

PivotTable Object.

Description

True if data for the PivotTable is saved with the workbook; False if only the PivotTable definition is saved. Read-write.

Example

This example sets the PivotTable to save data with the workbook.

Set pvtTable = Worksheets("Sheet1").Range("A3").PivotTable
pvtTable.SaveData = True


SaveLinkValues Property

Applies To

Workbook Object.

Description

True if Microsoft Excel will save external link values with this workbook. Read-write.

Example

This example causes Microsoft Excel to save external link values with the active workbook.

ActiveWorkbook.SaveLinkValues = True


ScaleType Property

Applies To

Axis Object.

Description

Returns or sets the value axis scale type (xlLinear or xlLogarithmic). Applies only to the value axis. Read-write.

Remarks

A logarithmic scale uses base ten logarithms.

Example

This example sets the value axis in Chart1 to use a logarithmic scale.

Charts("Chart1").Axes(xlValue).ScaleType = xlLogarithmic


Scenario Object

Description

Represents a scenario on a worksheet. A scenario is a group of input values (called changing cells) that is named and saved.

Accessors

The Scenario object is a member of the Scenarios collection. The Scenarios collection contains all of the defined scenarios for a worksheet. Use the Add method to create a new scenario and add it to the collection. To access a single member of the collection, use the Scenarios method with the index number or name of the scenario as an argument.

You assign a name to a scenario when you create it. Use the Name property to set or return the scenario name. The following example shows the scenario named "Typical" on the worksheet named "Options."

Worksheets("options").Scenarios("typical").Show

Scenario names are shown in the Scenario Manager dialog box and in the Scenarios box on the Workgroup toolbar. The first scenario created is at the top of the list; the last scenario is at the bottom (they are not sorted by alphabetical order). This is also the order used for the scenario index numbers. The first scenario created is Scenarios(1); the last scenario is Scenarios(Scenarios.Count). The following example hides scenario one for the worksheet named "Options." When the worksheet is protected, this scenario will not be visible in the Scenarios box or the Scenario Manager dialog box.

Worksheets("options").Scenarios(1).Hidden = True

Properties

Application Property, ChangingCells Property, Comment Property, Creator Property, Hidden Property, Index Property, Locked Property, Name Property, Parent Property, Values Property.

Methods

ChangeScenario Method, Delete Method, Show Method.


Scenarios Collection Object

Description

A collection of all the Scenario objects on the specified worksheet. A scenario is a group of input values (called changing cells) that is named and saved.

Accessors

Use the Add method to create a new scenario and add it to the collection. The following example adds a new scenario named "Typical" to the worksheet named "Options." The new scenario has two changing cells, A2 and A12, with the respective values of 55 and 60.

Worksheets("options").Scenarios.Add name:="Typical", _
    changingCells:=Worksheets("options").Range("A2,A12"), _
    values:=Array("55", "60")

Use the Scenarios method with an argument to access a single member of the collection or without an argument to access the entire collection at once. The following example creates a summary for the scenarios on the worksheet named "Options" using cells J10 and J20 as the result cells.

Worksheets("options").Scenarios.CreateSummary _
    resultCells:=Worksheets("options").Range("j10,j20")

Properties

Application Property, Count Property, Creator Property, Parent Property.

Methods

Add Method (Scenarios Collection), CreateSummary Method, Item Method, Merge Method.


Scenarios Method

Applies To

Worksheet Object.

Description

Accessor. Returns an object that represents a single scenario (a Scenario object, Syntax 1) or a collection of scenarios (a Scenarios object, Syntax 2) on the worksheet.

Syntax 1

object.Scenarios(index)

Syntax 2

object.Scenarios

object

Required. The Worksheet object.

index

Required for Syntax 1. The name or number of the scenario (can be an array to specify more than one).

Example

This example sets the comment for the first scenario on Sheet1.

Worksheets("Sheet1").Scenarios(1).Comment = _
    "Worst-case July 1993 sales"


ScreenUpdating Property

Applies To

Application Object.

Description

True if screen updating is on. Read-write.

Remarks

Turn screen updating off to speed up your macro code. You will not be able to see what the macro is doing, but it will run faster.

Example

This example demonstrates how turning off screen updating can make your code run faster. The example hides every other column on Sheet1, while keeping track of the time it takes to do so. The first time it hides the columns, screen updating is on; the second time, screen updating is off. When you run this example, you can compare the two times that the example displays in the message box.

Dim elapsedTime(2)
Application.ScreenUpdating = True
For i = 1 To 2
    If i = 2 Then Application.ScreenUpdating = False
    startTime = Time
    Worksheets("Sheet1").Activate
    For Each c In ActiveSheet.Columns
        If c.Column Mod 2 = 0 Then
            c.Hidden = True
        End If
    Next c
    stopTime = Time
    elapsedTime(i) = (stopTime - startTime) * 24 * 60 * 60
Next i
Application.ScreenUpdating = True
MsgBox "Elapsed time, screen updating on: " & elapsedTime(1) & _
        " sec." & Chr(13) & _
        "Elapsed time, screen updating off: " & elapsedTime(2) & _
        " sec."


ScrollBar Object

Description

Represents a scroll bar control on a chart, dialogsheet, or worksheet. Window scroll bars are not ScrollBar objects. ScrollBar objects do not support border or pattern formatting.

Accessors

The ScrollBar object is a member of the ScrollBars collection. The ScrollBars collection contains all the ScrollBar objects on a single sheet. Use the Add method to create a new scroll bar and add it to the collection. Set the width argument to be greater than the height argument to create a horizontal scroll bar.

To access a single member of the collection, use the ScrollBars method with the index number or name of the scroll bar as an argument. The following example sets scroll bar one on the dialog sheet named "Dialog1" to the top or left of its range.

DialogSheets("dialog1").ScrollBars(1).Value = 0

The scroll bar name is shown in the Name Box when the scroll bar is selected. Use the Name property to set or return the scroll bar name. The following example sets the OnAction property for the scroll bar named "Scroll Bar 6." The Visual Basic procedure named "ScrollProc" is called whenever the scroll bar changes.

DialogSheets(1).ScrollBars("scroll bar 6").OnAction = "ScrollProc"

Properties

Application Property, BottomRightCell Property, Creator Property, Display3DShading Property, Enabled Property, Height Property, Index Property, LargeChange Property, Left Property, LinkedCell Property, Locked Property, Max Property, Min Property, Name Property, OnAction Property, Parent Property, Placement Property, PrintObject Property, SmallChange Property, Top Property, TopLeftCell Property, Value Property, Visible Property, Width Property, ZOrder Property.

Methods

BringToFront Method, Copy Method, CopyPicture Method, Cut Method, Delete Method, Duplicate Method, Select Method, SendToBack Method.


ScrollBars Collection Object

Description

A collection of all the ScrollBar objects on the specified chart sheet, dialog sheet, or worksheet (not including window scroll bars). ScrollBar objects do not support border or pattern formatting.

Accessors

Use the Add method to create a new scroll bar and add it to the collection. Set the width argument to be greater than the height argument to create a horizontal scroll bar. The following example adds a new scroll bar to the dialog sheet named "Dialog1." The new scroll bar is positioned relative to the upper-left corner of the dialog frame.

Dim df As DialogFrame
Set df = DialogSheets("dialog1").DialogFrame
DialogSheets("dialog1").ScrollBars.Add df.Left + 10, _
    df.Top + 20, 10, 100

Use the ScrollBars method with an argument to access a single member of the collection or without an argument to access the entire collection at once. The following example sets each of the scroll bars on the worksheet named "Sheet1" to the top or left of its range.

Properties

Application Property, Count Property, Creator Property, Display3DShading Property, Enabled Property, Height Property, LargeChange Property, Left Property, LinkedCell Property, Locked Property, Max Property, Min Property, OnAction Property, Parent Property, Placement Property, PrintObject Property, SmallChange Property, Top Property, Value Property, Visible Property, Width Property, ZOrder Property.

Methods

Add Method (Graphic Objects and Controls), BringToFront Method, Copy Method, CopyPicture Method, Cut Method, Delete Method, Duplicate Method, Group Method, Item Method, Select Method, SendToBack Method.


ScrollBars Method

Applies To

Chart Object, DialogSheet Object, Worksheet Object.

Description

Accessor. Returns an object that represents a single scroll bar control (a ScrollBar object, Syntax 1) or a collection of scroll bar controls (a ScrollBars object, Syntax 2) on the sheet.

Syntax 1

object.ScrollBars(index)

Syntax 2

object.ScrollBars

object

Required. The Chart, DialogSheet, or Worksheet object.

index

Required for Syntax 1. Specifies the name or number of the scroll bar (can be an array to specify more than one).

See Also

Max Property, Min Property.

Example

This example sets the minimum and maximum values for scroll bar one on Dialog1.

With DialogSheets("Dialog1").ScrollBars(1)
    .Min = 20
    .Max = 50
End With


ScrollColumn Property

Applies To

Pane Object, Window Object.

Description

Returns or sets the number of the column that appears at the left of the pane or window. Read-write.

Remarks

If the window is split, Window.ScrollColumn refers to the top left pane. If panes are frozen, Window.ScrollColumn excludes the frozen areas.

See Also

ScrollRow Property.

Example

This example moves column three to the left of the window.

Worksheets("Sheet1").Activate
ActiveWindow.ScrollColumn = 3


ScrollRow Property

Applies To

Pane Object, Window Object.

Description

Returns or sets the number of the row that appears at the top of the pane or window. Read-write.

Remarks

If the window is split, Window.ScrollRow refers to the top left pane. If panes are frozen, Window.ScrollRow excludes the frozen areas.

See Also

ScrollColumn Property.

Example

This example moves row 10 to the top of the window.

Worksheets("Sheet1").Activate
ActiveWindow.ScrollRow = 10


ScrollWorkbookTabs Method

Applies To

Window Object.

Description

Scrolls the workbook tabs at the bottom of the window. Does not affect the active sheet in the workbook.

Syntax

object.ScrollWorkbookTabs(sheets, position)

object

Required. The Window object.

sheets

Optional. The number of sheets to scroll. Positive means scroll forward, negative means scroll backward, zero means don't scroll. You must specify sheets if you do not specify position.

position

Optional. xlFirst to scroll to the first sheet, or xlLast to scroll to the last sheet. You must specify position if you do not specify sheets.

Example

This example scrolls the workbook tabs to the last sheet in the workbook.

ActiveWindow.ScrollWorkbookTabs position:=xlLast


Second Function

Description

Returns a whole number between 0 and 59, inclusive, representing the second of the minute.

Syntax

Second(time)

The time named argument is limited to a time or numbers and strings, in any combination, that can represent a time. If time contains no valid data, Null is returned.

See Also

Day Function, Hour Function, Minute Function, Now Function, Time Function, Time Statement.

Example

This example uses the Second function to obtain the second of the minute from a specified time.

' In the development environment, the time (date literal) will display
' in short format using the locale settings of your code.
MyTime = #4:35:17 PM#    ' Assign a time.
MySecond = Second(MyTime)    ' MySecond contains 17.


Seek Function

Description

Returns the current read/write position within a file opened using the Open statement.

Syntax

Seek(filenumber)

The filenumber named argument is any valid file number.

Remarks

Seek returns a value between 1 and 2,147,483,647 (equivalent to 2^31-1), inclusive. For files open in Random mode, Seek returns the number of the next record read or written. For files opened in Binary, Output, Append, or Input mode, Seek returns the byte position at which the next operation is to take place. The first byte in a file is at position 1, the second byte is at position 2, and so on.

See Also

Get Statement, Open Statement, Put Statement, Seek Statement.

Example

This example uses the Seek function to return the current file position.

' For files opened in random-file mode, Seek returns number of next
' record. Assume TESTFILE is a file containing records of the
' user-defined type Record.
Type Record    ' Define user-defined type.
    ID As Integer
    Name As String * 20
End Type
Dim MyRecord As Record    ' Declare variable.
' Open file in random-file mode.
Open "TESTFILE" For Random As #1 Len = Len(MyRecord)
Do While Not EOF(1)    ' Loop until end of file.
    Get #1, , MyRecord    ' Read next record.
    Debug.Print Seek(1)    ' Print record number to Debug
            ' window.
Loop
Close #1    ' Close file.

' For files opened in modes other than random mode, Seek returns the
' byte position at which the next operation will take place. Assume
' TESTFILE is a file containing a few lines of text.
Open "TESTFILE" For Input As #1    ' Open file for reading.
Do While Not EOF(1)    ' Loop until end of file.
    MyChar = Input(1,#1)    ' Read next character of data.
    Debug.Print Seek(1)    ' Print byte position to Debug
            ' window.
Loop
Close #1    ' Close file.


Seek Statement

Description

Sets the position for the next read or write within a file opened using the Open statement.

Syntax

Seek [#]filenumber,position

The Seek statement syntax has these parts:

Part | Description
filenumber | Any valid file number.
position | Number in the range 1 to 2,147,483,647, inclusive, that indicates where the next read or write should occur.

Remarks

Record numbers specified in Get and Put statements override file positioning done by Seek.

Performing a file write after doing a Seek operation beyond the end of a file extends the file. If you attempt a Seek operation to a negative or zero position, an error occurs.

See Also

Get Statement, Open Statement, Put Statement, Seek Function.

Example

This example uses the Seek statement to set the position for the next read or write within a file.

' For files opened in random-file mode, Seek sets the next
' record. Assume TESTFILE is a file containing records of the
' user-defined type Record.
Type Record    ' Define user-defined type.
    ID As Integer
    Name As String * 20
End Type
Dim MyRecord As Record    ' Declare variable.
' Open file in random-file mode.
Open "TESTFILE" For Random As #1 Len = Len(MyRecord)
MaxSize = LOF(1) \ Len(MyRecord)    ' Get number of records in file.
' The loop reads all records starting from the last.
For RecordNumber = MaxSize To 1 Step - 1
    Seek #1, RecordNumber    ' Set position.
    Get #1, , MyRecord    ' Read record.
Next RecordNumber
Close #1    ' Close file.

' For files opened in modes other than random mode, Seek sets the
' byte position at which the next operation will take place. Assume
' TESTFILE is a file containing a few lines of text.
Open "TESTFILE" For Input As #1    ' Open file for input.
MaxSize = LOF(1)    ' Get size of file in bytes.
' The loop reads all characters starting from the last.
For NextChar = MaxSize To 1 Step -1
    Seek #1, NextChar    ' Set position.
    MyChar = Input(1,#1)    ' Read character.
Next NextChar
Close #1    ' Close file.


Select Case Statement

Description

Executes one of several groups of statements, depending on the value of an expression.

Syntax

Select Case testexpression
[Case expressionlist-n
 [statements-n]] . . .
[Case Else
[elsestatements]]
End Select

The Select Case statement syntax has these parts:

Part | Description
testexpression | Any numeric or string expression.
expressionlist-n | Comma-delimited list of one or more of the following forms: expression, expression To expression, Is comparisonoperator expression. The To keyword specifies a range of values. If you use the To keyword, the smaller value must appear before To. Use the Is keyword with comparison operators (except Is and Like) to specify a range of values. If not supplied, the Is keyword is automatically inserted.
statements-n | One or more statements executed if testexpression matches any part of expressionlist-n.
elsestatements | One or more statements executed if testexpression doesn't match any of the Case clause.

Remarks

If testexpression matches any expressionlist expression associated with a Case clause, the statements following that Case clause are executed up to the next Case clause, or, for the last clause, up to the End Select. Control then passes to the statement following End Select. If testexpression matches an expressionlist expression in more than one Case clause, only the statements following the first match are executed.

The Case Else clause is used to indicate the statements to be executed if no match is found between the testexpression and an expressionlist in any of the other Case selections. When there is no Case Else statement and no expression listed in the Case clauses matches testexpression, execution continues at the statement following End Select.

Although not required, it is a good idea to have a Case Else statement in your Select Case block to handle unforeseen testexpression values.

You can use multiple expressions or ranges in each Case clause. For example, the following line is valid:

Case 1 To 4, 7 To 9, 11, 13, Is > MaxNumber

Note

The Is comparison operator is not the same as the Is keyword used in the Select Case statement.

You also can specify ranges and multiple expressions for character strings. In the following example, Case matches strings that are exactly equal to everything,strings that fall between nuts and soup in alphabetical order, and the current value of TestItem:

Case "everything", "nuts" To "soup", TestItem

Select Case statements can be nested. Each Select Case statement must have a matching End Select statement.

See Also

If...Then...Else Statement; On...GoSub, On...GoTo Statements; Option Compare Statement.

Example

This example uses the Select Case statement to evaluate the value of a variable. The second Case clause contains the value of the variable being evaluated and therefore only the statement associated with it is executed.

Number = 8    ' Initialize variable.
Select Case Number    ' Evaluate Number.
Case 1 To 5    ' Number between 1 and 5.
    MyString = "Between 1 and 5"
Case 6, 7, 8, 9, 10    ' Number between 6 and 10.
    ' This is the only Case clause that evaluates to True.
    MyString = "Between 6 and 10"
Case Else    ' Other values.
    MyString = "Not between 1 and 10"
End Select

This example displays the name of the mail system installed on the computer.

Sub foo()
Select Case Application.MailSystem
    Case Is = xlMAPI
        MsgBox "Mail system is Microsoft Mail"
    Case Is = xlPowerTalk
        MsgBox "Mail system is PowerTalk"
    Case Is = xlNoMailSystem
        MsgBox "No mail system installed"
End Select
End Sub

This example displays a message box that describes the location of the active cell in the PivotTable.

Worksheets("Sheet1").Activate
Select Case ActiveCell.LocationInTable
Case Is = xlRowHeader
    MsgBox "Active cell is part of a row header"
Case Is = xlColumnHeader
    MsgBox "Active cell is part of a column header"
Case Is = xlPageHeader
    MsgBox "Active cell is part of a page header"
Case Is = xlDataHeader
    MsgBox "Active cell is part of a data header"
Case Is = xlRowItem
    MsgBox "Active cell is part of a row item"
Case Is = xlColumnItem
    MsgBox "Active cell is part of a column item"
Case Is = xlPageItem
    MsgBox "Active cell is part of a page item"
Case Is = xlDataItem
    MsgBox "Active cell is part of a data item"
Case Is = xlTableBody
    MsgBox "Active cell is part of the table body"
End Select

This example displays a message if the active cell on Sheet1 contains a cell error value. You can use this example as a framework for a cell-error-value error handler.

Worksheets("Sheet1").Activate
If IsError(ActiveCell.Value) Then
    errval = ActiveCell.Value
    Select Case errval
        Case CVErr(xlErrDiv0)
            MsgBox "#DIV/0! error"
        Case CVErr(xlErrNA)
            MsgBox "#N/A error"
        Case CVErr(xlErrName)
            MsgBox "#NAME? error"
        Case CVErr(xlErrNull)
            MsgBox "#NULL! error"
        Case CVErr(xlErrNum)
            MsgBox "#NUM! error"
        Case CVErr(xlErrRef)
            MsgBox "#REF! error"
        Case CVErr(xlErrValue)
            MsgBox "#VALUE! error"
        Case Else
            MsgBox "This should never happen!!"
    End Select
End If


Select Method

Applies To

Arc Object, Arcs Collection, Axis Object, AxisTitle Object, Button Object, Buttons Collection, Chart Object, ChartArea Object, ChartObject Object, ChartObjects Collection, Charts Collection, ChartTitle Object, CheckBox Object, Corners Object, DataLabel Object, DataLabels Collection, DialogFrame Object, DialogSheet Object, DialogSheets Collection, DownBars Object, Drawing Object, DrawingObjects Collection, Drawings Collection, DropDown Object, DropDowns Collection, DropLines Object, EditBox Object, EditBoxes Collection, ErrorBars Object, Floor Object, Gridlines Object, GroupBox Object, GroupBoxes Collection, GroupObject Object, GroupObjects Collection, HiLoLines Object, Label Object, Labels Collection, Legend Object, LegendEntry Object, LegendKey Object, Line Object, Lines Collection, ListBox Object, ListBoxes Collection, Module Object, Modules Collection, OLEObject Object, OLEObjects Collection, OptionButton Object, OptionButtons Collection, Oval Object, Ovals Collection, Picture Object, Pictures Collection, PlotArea Object, Point Object, Range Object, Rectangle Object, Rectangles Collection, ScrollBar Object, ScrollBars Collection, Series Object, SeriesLines Object, Sheets Collection, Spinner Object, Spinners Collection, TextBox Object, TextBoxes Collection, TickLabels Object, Trendline Object, UpBars Object, Walls Object, Worksheet Object, Worksheets Collection.

Description

Selects the object.

Syntax

object.Select(replace)

object

Required. The object to be selected.

replace

Optional (used only with drawing objects and sheets). If True or omitted, the current selection is replaced with a new selection consisting of the specified object. If False, the current selection is extended to include any previously selected objects and the specified object.

Remarks

To select a cell or range of cells, use the Select method. To make a single cell the active cell, use the Activate method.

See Also

Activate Method, Goto Method.

Example

This example selects cells A1:B3 on Sheet1.

Worksheets("Sheet1").Activate
Range("A1:B3").Select


Selected Property

Applies To

DrawingObjects Collection, ListBox Object, ListBoxes Collection.

Description

Returns or sets an array of Boolean values indicating the selection state of items in the list box. Each entry in the array corresponds to an entry in the list box, and is True if the entry is selected or False if it is not selected. Use this property to obtain the selected items in a multi-select list box. Read-write.

Remarks

For single-selection list boxes, it is easier to use the Value or ListIndex properties to get and set the selection.

See Also

ListIndex Property, Selection Property, Value Property.

Example

This example selects every other item in list box one on Sheet1.

Dim items() As Boolean
Set lbox = Worksheets("Sheet1").ListBoxes(1)
ReDim items(1 To lbox.ListCount)
For i = 1 To lbox.ListCount
    If i Mod 2 = 1 Then
        items(i) = True
    Else
        items(i) = False
    End If
Next
lbox.MultiSelect = xlExtended
lbox.Selected = items


SelectedSheets Method

Applies To

Window Object.

Description

Accessor. Returns a Sheets collection that represents all the selected sheets in the specified window.

Syntax

object.SelectedSheets

object

Required. The Window object.

Example

This example displays a message if Sheet1 is selected in BOOK1.XLS.

For Each sh In Workbooks("BOOK1.XLS").Windows(1).SelectedSheets
    If sh.Name = "Sheet1" Then
        MsgBox "Sheet1 is selected"
        Exit For
    End If
Next


Selection Property

Applies To

Application Object, Window Object.

Description

Accessor. If you specify the Application object (or omit the object qualifier), this property returns the selected object in the active window. If you specify a Window object, this property returns the selected object in the specified window. Read-only.

Remarks

The object type returned by the Selection property depends on the type of selection (for example, if a text box is selected, this property returns a TextBox object.)

The Selection property returns Nothing if nothing is selected.

See Also

Activate Method, ActiveCell Property, Select Method, Selected Property.

Example

This example clears the selection on Sheet1 (assuming that the selection is a range of cells).

Worksheets("Sheet1").Activate
Selection.Clear

This example displays the Visual Basic object type of the selection. Try running this example with cells selected, with a single oval selected, and with several different graphic objects selected.

Worksheets("Sheet1").Activate
MsgBox "The selection object type is " & TypeName(Selection)


SendDateTime Property

Applies To

Mailer Object.

Description

Returns the date and time that the mailer was sent. The mailer must be sent before this property is valid. Available only in Microsoft Excel for the Apple Macintosh with the PowerTalk mail system extension installed. Read-only.

See Also

BCCRecipients Property, CCRecipients Property, Enclosures Property, Mailer Property, Received Property, Sender Property, SendMailer Method, Subject Property, ToRecipients Property.

Example

This example displays the sender of the workbook, plus the date and time it was sent.

If ActiveWorkbook.HasMailer Then
    MsgBox "This workbook was sent by " & _
        ActiveWorkbook.Mailer.Sender & " at " & _
        Format(ActiveWorkbook.Mailer.SendDateTime, "General Date")
End If


Sender Property

Applies To

Mailer Object.

Description

Returns the name of the user (as text) who sent this workbook mailer. Available only in Microsoft Excel for the Apple Macintosh with the PowerTalk mail system extension installed. Read-only.

See Also

BCCRecipients Property, CCRecipients Property, Enclosures Property, Mailer Property, Received Property, SendDateTime Property, SendMailer Method, Subject Property, ToRecipients Property.

Example

This example displays the sender of the workbook, plus the date and time it was sent.

If ActiveWorkbook.HasMailer Then
    MsgBox "This workbook was sent by " & _
        ActiveWorkbook.Mailer.Sender & " at " & _
        Format(ActiveWorkbook.Mailer.SendDateTime, "General Date")
End If


SendKeys Method

Applies To

Application Object.

Description

Sends keystrokes to the active application. This method is not available on the Apple Macintosh.

Syntax

object.SendKeys(keys, wait)

object

Optional. The Application object.

keys

Required. The key or key combination you want to send to the application, as text.

wait

Optional. If True, Microsoft Excel waits for the keys to be processed before returning control to the macro. If False or omitted, the macro continues to run without waiting for the keys to be processed.

Remarks

This method places keystrokes into a key buffer. In some cases, you must call this method before you call the method that will use the keystrokes. For example, to send a password to a dialog box, you must call the SendKeys method before you display the dialog box.

The keys argument can specify any single key, or any key combined with ALT, CTRL, or SHIFT, or any combination of those keys. Each key is represented by one or more characters, such as "a" for the character a, or "{ENTER}" for the ENTER key.

To specify characters that aren't displayed when you press the key, such as ENTER or TAB, use the codes shown in the following table. Each code in the table represents one key on the keyboard.

Key | Code
BACKSPACE | "{BACKSPACE}" or "{BS}"
BREAK | "{BREAK}"
CAPS LOCK | "{CAPSLOCK}"
CLEAR | "{CLEAR}"
DELETE or DEL | "{DELETE}" or "{DEL}"
DOWN ARROW | "
END | "{END}"
ENTER (numeric keypad) | "{ENTER}"
ENTER | "~" (tilde)
ESC | "{ESCAPE} or {ESC}"
HELP | "{HELP}"
HOME | "{HOME}"
INS | "{INSERT}"
LEFT ARROW | "{LEFT}"
NUM LOCK | "{NUMLOCK}"
PAGE DOWN | "{PGDN}"
PAGE UP | "{PGUP}"
RETURN | "{RETURN}"
RIGHT ARROW | "{RIGHT}"
SCROLL LOCK | "{SCROLLLOCK}"
TAB | "{TAB}"
UP ARROW | "{UP}"
F1 through F15 | "{F1}" through "{F15}"

You can also specify keys combined with SHIFT and/or CTRL and/or ALT. To specify a key combined with another key or keys, use the following table.

To combine with | Precede the key code by
SHIFT | "+" (plus sign)
CTRL | "^" (caret)
ALT | "%" (percent sign)

Example

This example uses the SendKeys method to quit Microsoft Excel for Windows.

Application.SendKeys("%fx")


SendKeys Statement

Description

Sends one or more keystrokes to the active window as if typed at the keyboard; not available on the Macintosh.

Syntax

SendKeys string[,wait]

The SendKeys statement syntax has these named-argument parts:

Part | Description
string | String expression specifying the keystroke(s) to send.
wait | Boolean value specifying the wait mode. If False (default), control is returned to the procedure immediately after the keys are sent. If True, keystrokes must be processed before control is returned to the procedure.

Remarks

Each key is represented by one or more characters. To specify a single keyboard character, use the character itself. For example, to represent the letter A, use "A" for string. If you want to represent more than one character, append each additional character to the one preceding it. To represent the letters A, B, and C, use "ABC" for string.

The plus sign (+), caret (^), percent sign (%), tilde (~), and parentheses ( ) have special meanings to SendKeys. To specify one of these characters, enclose it within braces. For example, to specify the plus sign, use {+}. Brackets ([ ]) have no special meaning to SendKeys, but you must enclose them in braces as well, because in other applications, brackets do have a special meaning that may be significant when dynamic data exchange (DDE) occurs. To send brace characters, use {{} and {}}.

To specify characters that aren't displayed when you press a key (such as ENTER or TAB) and keys that represent actions rather than characters, use the codes shown below:

Key | Code
BACKSPACE | {BACKSPACE}, {BS}, or {BKSP}
BREAK | {BREAK}
CAPS LOCK | {CAPSLOCK}
DEL | {DELETE} or {DEL}
DOWN ARROW | {DOWN}
END | {END}
ENTER | {ENTER}
ESC | {ESC}
HELP | {HELP}
HOME | {HOME}
INS | {INSERT}
LEFT ARROW | {LEFT}
NUM LOCK | {NUMLOCK}
PAGE DOWN | {PGDN}
PAGE UP | {PGUP}
PRINT SCREEN | {PRTSC}
RIGHT ARROW | {RIGHT}
SCROLL LOCK | {SCROLLLOCK}
TAB | {TAB}
UP ARROW | {UP}
F1 | {F1}
F2 | {F2}
F3 | {F3}
F4 | {F4}
F5 | {F5}
F6 | {F6}
F7 | {F7}
F8 | {F8}
F9 | {F9}
F10 | {F10}
F11 | {F11}
F12 | {F12}
F13 | {F13}
F14 | {F14}
F15 | {F15}
F16 | {F16}

To specify keys combined with any combination of the SHIFT, CTRL, and ALT keys, precede the regular key code with one or more of the following codes:

Key | Code
SHIFT | +
CTRL (CONTROL) | ^
ALT | %

To specify that any combination of SHIFT, CTRL, and ALT should be held down while several other keys are pressed, enclose the code for those keys in parentheses. For example, to specify to hold down SHIFT while E and C are pressed, use "+(EC)". To specify to hold down SHIFT while E is pressed, followed by C without SHIFT, use "+EC".

To specify repeating keys, use the form {key number}. You must put a space between key and number. For example, {LEFT 42} means press the LEFT ARROW key 42 times; {h 10} means press h 10 times.

Note

SendKeys can't send keystrokes to an application that is not designed to run in Microsoft Windows. Sendkeys also can't send the PRINT SCREEN (PRTSC) key to any application.

See Also

AppActivate Statement, DoEvents Statement.

Example

This example uses the Shell function to run the Calculator application included with Microsoft Windows; it then uses the SendKeys statement to send keystrokes to add some numbers and then quit the Calculator. The SendKeys statement is not available on the Macintosh.

ReturnValue = Shell("Calc.exe", 1)    ' Run Calculator.
AppActivate ReturnValue     ' Activate the Calculator.
For I = 1 To 100    ' Set up counting loop.
    SendKeys I & "{+}", True    ' Send keystrokes to Calculator
Next I    ' to add each value of I.
SendKeys "=", True    ' Get grand total.
SendKeys "%{F4}", True    ' Send Alt+F4 to close Calculator.


SendMail Method

Applies To

Workbook Object.

Description

Sends the workbook using the installed mail system.

Syntax

object.SendMail(recipients, subject, returnReceipt)

object

Required. The Workbook object.

recipients

Required. Specifies the name of the recipient as text, or an array of text strings if there are multiple recipients. At least one recipient must be specified, and all recipients are added as To recipients.

subject

Optional. Specifies the subject of the message. If omitted, the document name is used.

returnReceipt

Optional. If True, a return receipt is requested. If False or omitted, no return receipt is requested.

Remarks

Use the SendMail method on Microsoft Mail (MAPI or Microsoft Mail for the Apple Macintosh) email systems. Pass addressing information as parameters.

See Also

Mailer Object, MailSystem Property, SendMailer Method.

Example

This example sends the active workbook to a single recipient.

ActiveWorkbook.SendMail recipients:="Jean Selva"

Use the SendMailer method on PowerTalk email systems on the Apple Macintosh. The Mailer object contains the addressing information for PowerTalk.


SendMailer Method

Applies To

Workbook Object.

Description

Sends the workbook using the PowerTalk mailer. This method is available only on the Apple Macintosh with the PowerTalk system extension installed and can only be used on a workbook with a mailer attached.

Syntax

object.SendMailer(fileFormat, priority)

object

Required. The Workbook object.

fileFormat

Optional. Specifies the file format to use for the workbook that is sent. See the FileFormat property for a list of valid types.

priority

Optional. Specifies the delivery priority of the message (one of xlNormal, xlHigh, or xlLow). The default value is xlNormal.

Remarks

Use the SendMail method on Microsoft Mail (MAPI or Microsoft Mail for the Apple Macintosh) email systems. Pass addressing information as parameters.

Use the SendMailer method on PowerTalk email systems on the Apple Macintosh. The Mailer object contains the addressing information for PowerTalk.

See Also

BCCRecipients Property, CCRecipients Property, Enclosures Property, FileFormat Property, Mailer Property, Received Property, SendDateTime Property, Sender Property, SendMail Method, Subject Property, ToRecipients Property.

Example

This example sets up the Mailer object for workbook one and then sends the workbook.

With Workbooks(1)
    .HasMailer = True
    With .Mailer
        .Subject = "Here is the workbook"
        .ToRecipients = Array("Jean")
        .CCRecipients = Array("Adam", "Bernard")
        .BCCRecipients = Array("Chris")
        .Enclosures = Array("TestFile")
    End With
    .SendMailer
End With


SendToBack Method

Applies To

Arc Object, Arcs Collection, Button Object, Buttons Collection, ChartObject Object, ChartObjects Collection, CheckBox Object, Drawing Object, DrawingObjects Collection, Drawings Collection, DropDown Object, DropDowns Collection, EditBox Object, EditBoxes Collection, GroupBox Object, GroupBoxes Collection, GroupObject Object, GroupObjects Collection, Label Object, Labels Collection, Line Object, Lines Collection, ListBox Object, ListBoxes Collection, OLEObject Object, OLEObjects Collection, OptionButton Object, OptionButtons Collection, Oval Object, Ovals Collection, Picture Object, Pictures Collection, Rectangle Object, Rectangles Collection, ScrollBar Object, ScrollBars Collection, Spinner Object, Spinners Collection, TextBox Object, TextBoxes Collection.

Description

Sends the object to the back of the z-order.

Syntax

object.SendToBack

object

Required. The object to which this method applies.

See Also

BringToFront Method, ZOrder Property.

Example

This example sends rectangle one on Sheet1 to the back of the z-order.

Worksheets("Sheet1").Rectangles(1).SendToBack


Series Object

Description

Represents a series in a chart.

Accessors

The Series object is a member of the SeriesCollection collection. Use the Add method to create a new series and add it to the collection. To access a single member of the collection, use the SeriesCollection method with the index number or name of the series as an argument.

The series index number indicates the order in which the series were added to the chart. SeriesCollection(1) is the first series added to the chart; SeriesCollection(SeriesCollection.Count) is the last. The following example sets the interior color for series one in embedded chart one on the worksheet named "Sheet1."

Worksheets("sheet1").ChartObjects(1).Chart. _
    SeriesCollection(1).Interior.Color = RGB(255, 0, 0)

Use the Name property to set or return the series name. The default name given when a series is created has the form "Seriesn", where n is a number. The following example sets the chart type for the series named "Series2" in embedded chart one on the worksheet named "Sheet1."

Worksheets("sheet1").ChartObjects(1).Chart. _
    SeriesCollection("series2").Type = xlLine

Properties

Application Property, AxisGroup Property, Border Property, Creator Property, ErrorBars Property, Explosion Property, Formula Property, FormulaLocal Property, FormulaR1C1 Property, FormulaR1C1Local Property, HasDataLabels Property, HasErrorBars Property, Interior Property, InvertIfNegative Property, MarkerBackgroundColor Property, MarkerBackgroundColorIndex Property, MarkerForegroundColor Property, MarkerForegroundColorIndex Property, MarkerStyle Property, Name Property, Parent Property, PictureType Property, PictureUnit Property, PlotOrder Property, Smooth Property, Type Property, Values Property, XValues Property.

Methods

ApplyDataLabels Method, ClearFormats Method, Copy Method, DataLabels Method, Delete Method, ErrorBar Method, Paste Method (Point or Series Object), Points Method, Select Method, Trendlines Method.


SeriesCollection Collection Object

Description

A collection of all the Series objects in the specified chart or chart group.

Accessors

Use the Add method to create a new series and add it to the chart. The following example adds the data from cells A1:A19 as a new series on the chart sheet named "Chart1."

Charts("chart1").SeriesCollection.Add _
    source:=Worksheets("sheet1").Range("a1:a19")

Use the SeriesCollection method with an argument to access a single member of the collection or without an argument to access the entire collection at once. The following example adds the data in cells C1:C10 on worksheet one to an existing series in the series collection in embedded chart one.

Worksheets(1).ChartObjects(1).Chart. _
    SeriesCollection.Extend Worksheets(1).Range("c1:c10")

Properties

Application Property, Count Property, Creator Property, Parent Property.

Methods

Add Method (SeriesCollection Collection), Extend Method, Item Method, Paste Method (SeriesCollection Object).


SeriesCollection Method

Applies To

Chart Object, ChartGroup Object.

Description

Accessor. Returns an object that represents a single series (a Series object, Syntax 1) or a collection of all the series (a SeriesCollection object, Syntax 2) in the chart or chart group.

Syntax 1

object.SeriesCollection(index)

Syntax 2

object.SeriesCollection

object

Required. The Chart or ChartGroup object.

index

Required for Syntax 1. The name or number of the series.

Example

This example turns on data labels for series one in Chart1.

Charts("Chart1").SeriesCollection(1).HasDataLabels = True


SeriesLines Object

Description

Represents series lines in a chart group. Series lines connect the data values from each series. Only 2-D stacked bar or column chart groups can have series lines. There is no singular SeriesLine object; you must turn series lines on or off for all points in a chart group at once.

Accessors

The SeriesLines property returns the series lines for a chart group. The following example adds series lines to chart group one in embedded chart one on worksheet one (the chart must be a 2-D stacked bar or column chart).

With Worksheets(1).ChartObjects(1).Chart.ChartGroups(1)
    .HasSeriesLines = True
    .SeriesLines.Border.Color = RGB(0, 0, 255)
End With

Remarks

If the HasSeriesLines property is False, most properties of the SeriesLines object are disabled.

Properties

Application Property, Border Property, Creator Property, Name Property, Parent Property.

Methods

Delete Method, Select Method.


SeriesLines Property

Applies To

ChartGroup Object.

Description

Accessor. Returns a SeriesLines object that represents the series lines for a stacked bar or stacked column chart. Applies only to stacked bar and stacked column charts. Read-only.

See Also

HasSeriesLines Property.

Example

This example turns on series lines for chart group one in Chart1 and then sets their line style, weight, and color. The example should be run on a 2-D stacked column chart that has two or more series.

With Charts("Chart1").ChartGroups(1)
    .HasSeriesLines = True
    With .SeriesLines.Border
        .LineStyle = xlThin
        .Weight = xlMedium
        .ColorIndex = 3
    End With
End With


Set Statement

Description

Assigns an object reference to a variable or property.

Syntax

Set objectvar = {objectexpression | Nothing}

The Set statement syntax has these parts:

Part | Description
objectvar | Name of the variable or property; follows standard variable naming conventions.
objectexpression | Expression consisting of the name of an object, another declared variable of the same object type, or a function or method that returns an object of the same object type.
Nothing | Discontinues association of objectvar with any specific object. Assigning objectvar to Nothing releases all the resources associated with the previously referenced object when no other variable refers to it.

Remarks

To be valid, objectvar must be an object type consistent with the object being assigned to it.

The Dim, Private, Public, Redim and Static statements only declare a variable that refers to an object. No actual object is referred to until you use Set statement to assign a specific object.

Generally, when you use Set to assign an object reference to a variable, no copy of the object is created for that variable. Instead, a reference to the object is created. More than one object variable can refer to the same object. Because these variables are references to (rather than copies of) the object, any change is reflected in all variables that refer to it.

See Also

Dim Statement, Let Statement, Private Statement, Public Statement, ReDim Statement, Static Statement.

Example

This example adds a new worksheet to the active workbook and then sets the name of the worksheet.

Set newSheet = Worksheets.Add
newSheet.Name = "1995 Budget"

This example creates a new worksheet and then inserts a list of all names in the active workbook, including their formulas in A1-style notation in the language of the user.

Set newSheet = ActiveWorkbook.Worksheets.Add
i = 1
For Each nm In ActiveWorkbook.Names
    newSheet.Cells(i, 1).Value = nm.NameLocal
    newSheet.Cells(i, 2).Value = "'" & nm.RefersToLocal
    i = i + 1
Next


SetAttr Statement

Description

Sets attribute information for a file.

Syntax

SetAttr pathname,attributes

The SetAttr statement syntax has these named-argument parts:

Part | Description
pathname | String expression that specifies a file name — may include directory or folder, and drive.
attributes | Constant or numeric expression, the sum of which specifies file attributes.

Constants and values for attributes are:

Constant | Value | File Attribute
vbNormal | 0 | Normal (default).
vbReadOnly | 1 | Read-only.
vbHidden | 2 | Hidden.
vbSystem | 4 | System — not available on the Macintosh.
vbArchive | 32 | File has changed since last backup — not available on the Macintosh.

Note

These constants are specified by Visual Basic. As a result, the names can be used anywhere in your code in place of the actual values.

Remarks

A run-time error occurs if you try to set the attributes of an open file.

See Also

FileAttr Function, GetAttr Function.

Example

This example uses the SetAttr statement to set attributes for a file.

SetAttr "TESTFILE", vbHidden    ' Set hidden attribute.
SetAttr "TESTFILE", vbHidden + vbReadOnly    ' Set hidden and Read-only
    ' attributes.


SetBackgroundPicture Method

Applies To

Chart Object, Worksheet Object.

Description

Sets the background graphic for a worksheet or chart. This method is available only in Microsoft Excel for Windows 95.

Syntax

object.SetBackgroundPicture(fileName)

object

Required. The Worksheet or Chart object.

fileName

Required. The graphic file to be displayed.

Example

This example sets the background graphic for worksheet one.

Worksheets(1).SetBackgroundPicture "c:\graphics\watrmark.bmp"


SetDefaultChart Method

Applies To

Application Object.

Description

Specifies the name of the chart template that Microsoft Excel will use when creating new charts.

Syntax

object.SetDefaultChart(formatName)

object

Required. The Application object.

formatName

Required. Specifies the name of a custom autoformat. This name can be a custom autoformat, as a string, or the special constant xlBuiltIn to specify the built-in chart template.

Example

This example sets the default chart template to the custom autoformat named "Monthly Sales."

Application.SetDefaultChart formatName:="Monthly Sales"


SetInfoDisplay Method

Applies To

Window Object.

Description

Sets the information displayed in the Info window (the specified window object must be the Info window).

Syntax

object.SetInfoDisplay(cell, formula, value, format, protection, names, precedents, dependents, note)

object

Required. The Window object.

cell

Optional. True to display the cell reference text.

formula

Optional. True to display the cell formula.

value

Optional. True to display the cell value.

format

Optional. True to display cell formatting information.

protection

Optional. True to display cell protection information.

names

Optional. True to display cell name information.

precedents

Optional. Sets whether precedents are displayed (one of xlNone, xlDirect, or xlAll).

dependents

Optional. Sets whether dependents are displayed (one of xlNone, xlDirect, or xlAll).

note

Optional. True to display notes.

Remarks

If this method is applied to any window other than Info window, an error occurs.

Example

This example displays the Info window and then sets it to display cell reference text and cell name information.

Application.DisplayInfoWindow = True
ActiveWindow.SetInfoDisplay cell:=True, Names:=True


SetLinkOnData Method

Applies To

Workbook Object.

Description

Sets the name of a macro or procedure that runs whenever a link is updated.

Syntax

object.SetLinkOnData(name, procedure)

object

Required. The Workbook object.

name

Required. Specifies the name of the Microsoft Excel or DDE/OLE link, as returned from the LinkSources method.

procedure

Optional. Specifies the name of the procedure to run when the link is updated. This can be either a Microsoft Excel version 4.0 macro or a Visual Basic procedure. Set this argument to an empty string ("") to indicate that no procedure should run when the link is updated.

Remarks

Use this method to set notification for a specific link. Use the OnData property if you wish to be notified when any link is updated.

See Also

OnData Property.

Example

This example sets the name of the procedure that runs whenever the DDE link is updated.

ActiveWorkbook.SetLinkOnData "WinWord|'C:\MSGFILE.DOC'!DDE_LINK1", _
    "my_Link_Update_Macro"


Sgn Function

Description

Returns an integer indicating the sign of a number.

Syntax

Sgn(number)

The number argument can be any valid numeric expression.

Return Values

If number is | Sgn returns
Greater than zero | 1
Equal to zero | 0
Less than zero | -1

Remarks

The sign of the number argument determines the return value of the Sgn function.

See Also

Abs Function.

Example

This example uses the Sgn function to determine the sign of a number.

MyVar1 = 12: MyVar2 = -2.4: MyVar3 = 0
MySign = Sgn(MyVar1)    ' Returns 1.
MySign = Sgn(MyVar2)    ' Returns -1.
MySign = Sgn(MyVar3)    ' Returns 0.


Shadow Property

Applies To

AxisTitle Object, ChartArea Object, ChartObject Object, ChartObjects Collection, ChartTitle Object, DataLabel Object, DataLabels Collection, Drawing Object, DrawingObjects Collection, Drawings Collection, Font Object, GroupObject Object, GroupObjects Collection, Legend Object, OLEObject Object, OLEObjects Collection, Oval Object, Ovals Collection, Picture Object, Pictures Collection, Rectangle Object, Rectangles Collection, TextBox Object, TextBoxes Collection.

Description

True if the font is a shadow font or if the drawing object has a shadow. Read-write.

Remarks

For the Font object, this property has no effect in Microsoft Windows, but its value is retained (it can be set and returned).

Example

This example adds a shadow to the title of Chart1.

Charts("Chart1").ChartTitle.Shadow = True


Sheets Collection Object

Description

A collection of all the sheets in the specified or active workbook. The Sheets collection can contain Chart, DialogSheet, Module, or Worksheet objects.

The Sheets collection is useful when you want to access sheets of any type. If you need to work with sheets of only one type, see the object topic for that sheet type.

Accessors

Use the Sheets method with the sheet index number or name as an argument to access a single member of the collection or without an argument to access the entire collection at once.

The index number represents the position of the sheet on the tab bar of the workbook. Sheets(1) is the first (leftmost) sheet in the workbook; Sheets(Sheets.Count) is the last sheet. All sheets are included in the index count, even if they are hidden.

The following example hides the sheet one in the active workbook.

Sheets(1).Visible = False

The sheet name is shown on the workbook tab for the sheet. Use the Name property to set or return the sheet name (you cannot change the name of the sheet where the Visual Basic code is running, however). The following example protects the Visual Basic code on the sheet named "Sample Code."

Sheets("sample code").Protect password:="drowssap", contents:=True

You can also use an array to specify more than one sheet. The following example moves the sheets named "Module1" and "Sheet1" to the beginning of the workbook.

Sheets(Array("module1", "sheet1")).Move before:=Sheets(1)

Use the Add method to create a new sheet and add it to the collection. The following example adds two dialog sheets to the active workbook, placing them after sheet two in the workbook.

Sheets.Add type:=xlDialogSheet, count:=2, after:=Sheets(2)

Properties

Application Property, Count Property, Creator Property, Parent Property, Visible Property.

Methods

Add Method (Sheets Collection), Copy Method, Delete Method, FillAcrossSheets Method, Item Method, Move Method, PrintOut Method, PrintPreview Method, Select Method.


Sheets Method

Applies To

Application Object, Workbook Object.

Description

Accessor. Returns an object that represents a single sheet (Syntax 1) or a collection of sheets (Syntax 2) in the workbook. Read-only. A sheet can be a Chart object, DialogSheet object, Module object, or Worksheet object.

Syntax 1

object.Sheets(index)

Syntax 2

object.Sheets

object

Optional for Application, required for Workbook. The object to which this method applies.

index

Required for Syntax 1. The name or number of the sheet to return.

Remarks

Using this method with no object qualifier is equivalent to ActiveWorkbook.Sheets.

See Also

DialogSheets Method, Modules Method, Worksheets Method.

Example

This example creates a new worksheet and then places a list of the active workbook's sheet names in the first column.

Set newSheet = Sheets.Add(Type:=xlWorksheet)
For i = 1 To Sheets.Count
    newSheet.Cells(i, 1).Value = Sheets(i).Name
Next i


SheetsInNewWorkbook Property

Applies To

Application Object.

Description

Returns or sets the number of sheets Microsoft Excel automatically inserts in new workbooks. Read-write.

Example

This example displays the number of sheets automatically inserted into new workbooks.

MsgBox "Microsoft Excel inserts " & _
    Application.SheetsInNewWorkbook & _
    " sheet(s) in each new workbook"


Shell Function

Description

Runs an executable program.

Syntax

Shell(pathname[,windowstyle])

The Shell function syntax has these named-argument parts:

Part | Description
pathname | Name of the program to execute and any required arguments or command line switches; may include directory or folder and drive. May also be the name of a document that has been associated with an executable program.
 | On the Macintosh, you can use the MacID function to specify an application's signature instead of its name. The following example uses the signature for Microsoft Word:
 | Shell MacID("MSWD")
windowstyle | Number corresponding to the style of the window in which the program is to be run. In Microsoft Windows, if windowstyle is omitted, the program is started minimized with focus. On the Macintosh (System 7.0 or later), windowstyle only determines whether or not the application gets the focus when it is run.

The windowstyle named argument has these values:

Value | Window Style
1, 5, 9 | Normal with focus.
2 | Minimized with focus.
3 | Maximized with focus.
4,8 | Normal without focus.
6,7 | Minimized without focus.

Remarks

If you use the MacID function with Shell in Microsoft Windows, an error occurs.

If the Shell function successfully executes the named file, it returns the task identification (ID) of the started program. The task ID is a unique number that identifies the running program. If the Shell function can't start the named program, an error occurs.

Note

The Shell function runs other programs asynchronously. This means you can't depend on a program started with Shell to be finished executing before the statements following the Shell function in your application are executed.

See Also

AppActivate Statement, MacID Function.

Example

This example uses the Shell function to run an application specified by the user. On the Macintosh, using the MacID function ensures that the application can be launched even if the file name of the application has been changed. The Shell function is not available on the Macintosh prior to System 7.0.

' In Microsoft Windows.
' Specifying 1 as the second argument runs the application normally and
' gives it the focus.
RetVal = Shell("C:\WINDOWS\CALC.EXE", 1)    ' Run Calculator.

' On the Macintosh.
' Both statements launch Microsoft Excel.
RetVal = Shell("Microsoft Excel")    ' Specify file name.
RetVal = Shell(MacID("XCEL"))    ' Specify signature.


ShortcutKey Property

Applies To

Name Object.

Description

Returns or sets the shortcut key for a name defined as a custom Microsoft Excel version 4.0 macro command. Read-write.

Example

This example sets the shortcut key for name one in the active workbook. The example should be run on a workbook in which name one refers to a Microsoft Excel version 4.0 command macro.

ActiveWorkbook.Names(1).ShortcutKey = "K"


ShortcutMenus Method

Applies To

Application Object.

Description

Accessor. Returns a Menu object that represents a single shortcut menu. Read-only.

Syntax

object.ShortcutMenus(index)

object

Optional. The Application object.

index

Required. Specifies the shortcut menu, as shown in the following list.

Constant

Description

xlAxis

Chart Axis

xlButton

Button

xlChartSeries

Chart Series

xlChartTitles

Chart Titles

xlColumnHeader

Column

xlDebugCodePane

Debug Code Pane

xlDesktop

Desktop

xlDialogSheet

Dialog Sheet

xlDrawingObject

Drawing Object

xlEntireChart

Entire Chart

xlFloor

Chart Floor

xlGridline

Chart Gridline

xlImmediatePane

Immediate Pane

xlLegend

Chart Legend

xlMacrosheetCell

Macro Sheet Cell

xlModule

Module

xlPlotArea

Chart Plot Area

xlRowHeader

Row

xlTextBox

Text Box

xlTitleBar

Title Bar

xlToolbar

Toolbar

xlToolbarButton

Toolbar Button

xlWatchPane

Watch Pane

xlWorkbookTab

Workbook Tab

xlWorksheetCell

Worksheet Cell

Example

This example adds a new menu item to the worksheet cells shortcut menu.

ShortcutMenus(xlWorksheetCell).MenuItems.Add _
    Caption:="More..."

This example deletes the new menu item.

ShortcutMenus(xlWorksheetCell).MenuItems("More...").Delete


Show Method

Applies To

Dialog Object, DialogSheet Object, Range Object, Scenario Object.

Description

DialogSheet object (Syntax 1): Runs the dialog box. This method will not return to the calling procedure until the dialog box is closed or hidden, but event procedures assigned to the dialog box controls will run while the calling procedure is suspended.

Range object (Syntax 1): Scrolls the active window to move the range into view. The range must consist of a single cell which is a part of the currently active document

Scenario object (Syntax 1): Shows the scenario by inserting the scenario's values onto the worksheet. The affected cells are the changing cells of the scenario.

Dialog object (Syntax 2): Displays the dialog box and waits for the user to input data.

Syntax 1

object.Show

Syntax 2

object.Show(arg1, arg2, ..., arg30)

object

Required. For Syntax 1, the DialogSheet, Range, or Scenario object. For Syntax 2, the Dialog object.

arg1, arg2, ..., arg30

Optional. For built-in dialog boxes only, provides the initial arguments for the command. For more information, see the following Remarks section.

Remarks

For built in dialog boxes, this method returns True if the user clicked OK, or False if the user clicked Cancel.

A single dialog box can change many properties at once. For example, the Format Cells dialog box can change all the properties of the Font object.

For some built-in dialog boxes (Open, for example), you can set initial values using arg1, arg2, ..., arg30.

Example

This example displays the custom dialog box Dialog1, and then it displays a message if you do not press the Cancel button. Before running this example, create a new default dialog sheet by pointing to Macro on the Insert menu and then clicking Dialog.

If DialogSheets("Dialog1").Show <> False Then
    MsgBox "You must have pressed the ""OK"" button"
End If

This example displays the Open dialog box and selects the Read-Only option.

Application.Dialogs(xlDialogOpen).Show arg3:=True


ShowAllData Method

Applies To

Worksheet Object.

Description

Makes all rows visible for the currently filtered list. If the AutoFilter is in use, this method changes the arrows to "All".

Syntax

object.ShowAllData

object

Required. The Worksheet object.

See Also

AdvancedFilter Method, AutoFilter Method, FilterMode Property.

Example

This example makes all data on Sheet1 visible. The example should be run on a worksheet that contains a list that you filtered using the AutoFilter command on the Data menu.

Worksheets("Sheet1").ShowAllData


ShowConflictHistory Property

Applies To

Workbook Object.

Description

True if the Conflict History worksheet is visible in the workbook that's open as a shared list. This property is available only in Microsoft Excel for Windows 95. Read-write.

Remarks

If the specified workbook isn't open as a shared list, ShowConflictHistory fails. To determine whether a workbook is open as a shared list, use the MultiUserEditing property.

See Also

MultiUserEditing Property, SaveAs Method, ShowConflictHistory Property.

Example

This example determines whether the active workbook is open as a shared list. If it is, the example displays the Conflict History worksheet.

If ActiveWorkbook.MultiUserEditing Then
    ActiveWorkbook.ShowConflictHistory = True
End If


ShowDataForm Method

Applies To

Worksheet Object.

Description

Displays the data form associated with the worksheet.

Syntax

object.ShowDataForm

object

Required. The Worksheet object.

Remarks

The macro pauses while you use the data form. When the user closes the data form, this macro will resume at the line following the ShowDataForm method.

This method will run the custom data form, if one exists.

Example

This example displays the data form for Sheet1.

Worksheets(1).ShowDataForm


ShowDependents Method

Applies To

Range Object.

Description

Draws tracer arrows to the direct dependents of the range.

Syntax

object.ShowDependents(remove)

object

Required. The Range object. Must be a single cell.

remove

Optional. If True, removes one level of tracer arrows to direct dependents. If False or omitted, expands one level of tracer arrows.

See Also

ClearArrows Method, Dependents Property, ShowErrors Method, ShowPrecedents Method.

Example

This example draws tracer arrows to dependents of the active cell on Sheet1.

Worksheets("Sheet1").Activate
ActiveCell.ShowDependents

This example removes the tracer arrow for one level of dependents of the active cell on Sheet1.

Worksheets("Sheet1").Activate
ActiveCell.ShowDependents remove:=True


ShowDetail Property

Applies To

PivotItem Object, Range Object.

Description

True if the outline is expanded for the specified range (the detail of the column or row is visible). The specified range must be a single summary column or row in an outline. Read-write.

For the PivotItem object (or the Range object if the range is in a PivotTable), this property is True if the pivot item is showing detail.

Remarks

If the specified range is not in a PivotTable, the following comments apply:

  • The range must be in a single summary row or column.
  • This property returns False if any of the children of the row or column are hidden.
  • Setting this property to True is equivalent to unhiding all the children on the summary row or column.
  • Setting this property to False is equivalent to hiding all the children of the summary row or column.

If the specified range is in a PivotTable, it is possible to set this property for more than one cell at once if the range is contiguous. To return this property, the range must be a single cell.

Example

This example shows detail for the summary row of an outline on Sheet1. Before running this example, create a simple outline that contains a single summary row, and then collapse the outline so that only the summary row is showing. Select one of the cells in the summary row, and then run the example.

Worksheets("Sheet1").Activate
Set myRange = ActiveCell.CurrentRegion
lastRow = myRange.Rows.Count
myRange.Rows(lastRow).ShowDetail = True


ShowErrors Method

Applies To

Range Object.

Description

Draws tracer arrows through the precedents tree to the cell that is the source of the error, and returns the range that contains the source of the error.

Syntax

object.ShowErrors

object

Required. The Range object.

See Also

ClearArrows Method, ShowDependents Method, ShowPrecedents Method.

Example

This example displays a red tracer arrow if there is an error in the active cell on Sheet1.

Worksheets("Sheet1").Activate
If IsError(ActiveCell.Value) Then
    ActiveCell.ShowErrors
End If


ShowLegendKey Property

Applies To

DataLabel Object, DataLabels Collection.

Description

True if the data label legend key is visible. Read-write.

Example

This example sets the data labels for series one in Chart1 to show values and the legend key.

With Charts("Chart1").SeriesCollection(1).DataLabels
    .ShowLegendKey = True
    .Type = xlShowValue
End With


ShowLevels Method

Applies To

Outline Object.

Description

Displays the specified number of row and/or column levels of an outline.

Syntax

object.ShowLevels (rowLevels, columnLevels)

object

Required. The Outline object (ActiveSheet.Outline, for example).

rowLevels

Optional. Specifies the number of row levels of an outline to display. If the outline has fewer levels than specified, Microsoft Excel shows all levels. If omitted or zero, no action is taken on rows.

columnLevels

Optional. Specifies the number of column levels of an outline to display. If the outline has fewer levels than specified, Microsoft Excel shows all levels. If omitted or zero, no action is taken on columns.

Remarks

You must specify at least one argument.

Example

This example displays row levels one through three and column level one of the outline on Sheet1.

Worksheets("Sheet1").Outline.ShowLevels rowLevels:=3, columnLevels:=1


ShowPages Method

Applies To

PivotTable Object.

Description

Creates a new PivotTable for each item in the page field. Each new PivotTable is created on a new worksheet.

Syntax

object.ShowPages(pageField)

object

Required. The PivotTable object.

pageField

Required. A string that names a single page field in the PivotTable.

Example

This example creates a new PivotTable for each item in the page field, which is the field named "Country."

Set pvtTable = Worksheets("Sheet1").Range("A3").PivotTable
pvtTable.ShowPages "Country"


ShowPrecedents Method

Applies To

Range Object.

Description

Draws tracer arrows to the direct precedents of the range.

Syntax

object.ShowPrecedents(remove)

object

Required. The Range object. Must be a single cell.

remove

Optional. If True, removes one level of tracer arrows to direct precedents. If False or omitted, expands one level of tracer arrows.

See Also

ClearArrows Method, Precedents Property, ShowDependents Method, ShowErrors Method.

Example

This example draws tracer arrows to the precedents of the active cell on Sheet1.

Worksheets("Sheet1").Activate
ActiveCell.ShowPrecedents

This example removes the tracer arrow for one level of precedents of the active cell on Sheet1.

Worksheets("Sheet1").Activate
ActiveCell.ShowPrecedents remove:=True


ShowToolTips Property

Applies To

Application Object.

Description

True if ToolTips are turned on. Read-write.

Example

This example causes Microsoft Excel to display ToolTips.

Application.ShowToolTips = True


Sin Function

Description

Returns the sine of an angle.

Syntax

Sin(number)

The number named argument can be any valid numeric expression that expresses an angle in radians.

Remarks

The Sin function takes an angle and returns the ratio of two sides of a right triangle. The ratio is the length of the side opposite the angle divided by the length of the hypotenuse.

The result lies in the range -1 to 1.

To convert degrees to radians, multiply degrees by pi/180. To convert radians to degrees, multiply radians by 180/pi.

See Also

Atn Function, Cos Function, Derived Math Functions, Tan Function.

Example

This example uses the Sin function to return the sine of an angle.

MyAngle = 1.3    ' Define angle in radians.
MyCosecant = 1 / Sin(MyAngle)    ' Calculate cosecant.


Single Data Type

Description

Single (single-precision floating-point) variables are stored as 32-bit (4-byte) numbers, ranging in value from -3.402823E38 to -1.401298E-45 for negative values and from 1.401298E-45 to 3.402823E38 for positive values. The type-declaration character for Single is ! (character code 33).

See Also

CSng Function, Data Type Summary, Def type Statements, Double Data Type, Variant Data Type.


Size Property

Applies To

Font Object.

Description

Returns or sets the size of the font. Read-write.

Example

This example sets the font size for cells A1:D10 on Sheet1.

With Worksheets("Sheet1").Range("A1:D10")
    .Value = "Test"
    .Font.Size = 12
End With


SizeWithWindow Property

Applies To

Chart Object.

Description

True if chart resizes to match the size of the chart sheet window. False if the chart size is not attached to the window size. Applies only to charts that are sheets in a workbook, not to embedded charts. Read-write.

See Also

ChartSize Property.

Example

This example sets Chart1 to be sized to its window.

Charts("Chart1").SizeWithWindow = True


SmallChange Property

Applies To

DrawingObjects Collection, ScrollBar Object, ScrollBars Collection, Spinner Object, Spinners Collection.

Description

Returns or sets the amount that the scroll bar or spinner increments or decrements for a line scroll (when the user clicks an arrow). Read-write.

See Also

LargeChange Property.

Example

This example sets scroll bar one on Dialog1 to move two units for each line scroll and 20 units for each page scroll.

With DialogSheets("Dialog1").ScrollBars(1)
    .SmallChange = 2
    .LargeChange = 20
End With


SmallScroll Method

Applies To

Pane Object, Window Object.

Description

Scrolls the window by rows or columns.

Syntax

object.SmallScroll(down, up, toRight, toLeft)

object

Required. The window to scroll.

down

Optional. The number of rows to scroll the window down.

up

Optional. The number of rows to scroll the window up.

toRight

Optional. The number of columns to scroll the window right.

toLeft

Optional. The number of columns to scroll the window left.

Remarks

If down and up are both specified, the window is scrolled by the difference of the arguments. For example, if down is three and up is six, the window is scrolled up three rows.

If toLeft and toRight are both specified, the window is scrolled by the difference of the arguments. For example, if toLeft is three and toRight is six, the window is scrolled right three columns.

Any of the arguments can be a negative number.

See Also

LargeScroll Method.

Example

This example scrolls the active window of Sheet1 down three rows.

Worksheets("Sheet1").Activate
ActiveWindow.SmallScroll down:=3


Smooth Property

Applies To

LegendKey Object, Series Object.

Description

True if the line or scatter chart has curve smoothing on. Applies only to line and scatter charts. Read-write.

Example

This example turns on curve smoothing for series one in Chart1. The example should be run on a 2-D line chart.

Charts("Chart1").SeriesCollection(1).Smooth = True


SolverAdd Function

Description

Adds a constraint to the current problem. Equivalent to clicking Solver on the Tools menu and then clicking Add in the Solver Parameters dialog box.

Before you use this function, you must establish a reference to the Solver add-in. With a Visual Basic module active, click References on the Tools menu, and then select the Solver.xla check box in the Available References box. If Solver.xla doesn't appear in the Available References box, click Browse, click Solver in the \Excel\Library\Solver folder, and then click OK.

Syntax

SolverAdd(cellRef, relation, formulaText)

cellRef

Required. Reference to a cell or a range of cells that forms the left side of a constraint.

relation

Required. Specifies the arithmetic relationship between the left and right sides of the constraint. If 4 is chosen, cellRef must contain an integer, and formulaText should not be specified.

Relation

Arithmetic relationship

1

<=

2

=

3

>=

4

Cells referenced by cellRef must contain integers.

formulaText

Optional. The right side of the constraint.

Remarks

After constraints are added, you can manipulate them with the SolverChange and SolverDelete functions.

See Also

SolverChange Function, SolverDelete Function, SolverOk Function.

Example

This example uses the Solver functions to maximize gross profit in a business problem. The SolverAdd function is used to add three constraints to the current problem.

Worksheets("Sheet1").Activate
SolverReset
SolverOptions precision:=0.001
SolverOK setCell:=Range("TotalProfit"), _
    maxMinVal:=1, _
    byChange:=Range("C4:E6")
SolverAdd cellRef:=Range("F4:F6"), _
    relation:=1, _
    formulaText:=100
SolverAdd cellRef:=Range("C4:E6"), _
    relation:=3, _
    formulaText:=0
SolverAdd cellRef:=Range("C4:E6"), _
    relation:=4
SolverSolve userFinish:=False
SolverSave saveArea:=Range("A33")


SolverChange Function

Description

Changes an existing constraint. Equivalent to clicking Solver on the Tools menu and then clicking Change in the Solver Parameters dialog box.

Before you use this function, you must establish a reference to the Solver add-in. With a Visual Basic module active, click References on the Tools menu, and then select the Solver.xla check box in the Available References box. If Solver.xla doesn't appear in the Available References box, click Browse, click Solver in the \Excel\Library\Solver folder, and then click OK.

Syntax

SolverChange(cellRef, relation, formulaText)

cellRef

Required. Reference to a cell or a range of cells that forms the left side of a constraint.

relation

Required. Specifies the arithmetic relationship between the left and right sides of the constraint. If 4 is chosen, cellRef must contain an integer, and formulaText should not be specified.

Relation

Arithmetic relationship

1

<=

2

=

3

>=

4

Cells referenced by cellRef must contain integers.

formulaText

Optional. The right side of the constraint.

Note

If cellRef and relation do not match an existing constraint, you must use the SolverDelete and SolverAdd functions to change the constraint.

See Also

SolverAdd Function, SolverOk Function.

Example

This example loads the previously calculated Solver model stored on Sheet1, changes one of the constraints, and then solves the model again.

Worksheets("Sheet1").Activate
SolverLoad loadArea:=Range("A33:A38")
SolverChange cellRef:=Range("F4:F6"), _
    relation:=1, _
    formulaText:=200
SolverSolve userFinish:=False


SolverDelete Function

Description

Deletes an existing constraint. Equivalent to clicking Solver on the Tools menu and then clicking Delete in the Solver Parameters dialog box.

Before you use this function, you must establish a reference to the Solver add-in. With a Visual Basic module active, click References on the Tools menu, and then select the Solver.xla check box in the Available References box. If Solver.xla doesn't appear in the Available References box, click Browse, click Solver in the \Excel\Library\Solver folder, and then click OK.

Syntax

SolverDelete(cellRef, relation, formulaText)

cellRef

Required. Reference to a cell or a range of cells that forms the left side of a constraint.

relation

Required. Specifies the arithmetic relationship between the left and right sides of the constraint. If 4 is chosen, cellRef must contain an integer, and formulaText should not be specified.

Relation

Arithmetic relationship

1

<=

2

=

3

>=

4

Cells referenced by cellRef must contain integers.

formulaText

Optional. The right side of the constraint.

See Also

SolverAdd Function, SolverOk Function.

Example

This example loads the previously calculated Solver model stored on Sheet1, deletes one of the constraints, and then solves the model again.

Worksheets("Sheet1").Activate
SolverLoad loadArea:=Range("A33:A38")
SolverDelete cellRef:=Range("C4:E6"), _
    relation:=4
SolverSolve userFinish:=False


SolverFinish Function

Description

Tells Microsoft Excel what to do with the results and what kind of report to create when the solution process is completed.

Before you use this function, you must establish a reference to the Solver add-in. With a Visual Basic module active, click References on the Tools menu, and then select the Solver.xla check box in Available References box. If Solver.xla doesn't appear in the Available References box, click Browse, click Solver in the \Excel\Library\Solver folder, and then click OK.

Syntax

SolverFinish(keepFinal, reportArray)

keepFinal

Optional. Can be the number 1 or 2. If keepFinal is 1 or omitted, the final solution values are kept in the changing cells, replacing any former values. If keepFinal is 2, the final solution values are discarded, and the former values are restored.

reportArray

Optional. Specifies what kind of report Microsoft Excel will create when Solver is finished: 1 creates an answer report, 2 creates a sensitivity report, and 3 creates a limit report. Use the Array function to specify the reports you want to display - for example, ReportArray:= Array(1,3).

See Also

SolverFinishDialog Function, SolverOk Function.

Example

This example loads the previously calculated Solver model stored on Sheet1, solves the model again, and then generates an answer report on a new worksheet.

Worksheets("Sheet1").Activate
SolverLoad loadArea:=Range("A33:A38")
SolverSolve userFinish:=True
SolverFinish keepFinal:=1, reportArray:=Array(1)


SolverFinishDialog Function

Description

Tells Microsoft Excel what to do with the results and what kind of report to create when the solution process is completed. Displays the Solver Results dialog box after solving a problem. Equivalent to the SolverFinish function, but also displays the Solver Results dialog box after solving a problem.

Before you use this function, you must establish a reference to the Solver add-in. With a Visual Basic module active, click References on the Tools menu, and then select the Solver.xla check box in the Available References box. If Solver.xla doesn't appear in the Available References box, click Browse, click Solver in the \Excel\Library\Solver folder, and then click OK.

Syntax

SolverFinishDialog(keepFinal, reportArray)

keepFinal

Optional. Can be the number 1 or 2. If keepFinal is 1 or omitted, the final solution values are kept in the changing cells, replacing any former values. If keepFinal is 2, the final solution values are discarded, and the former values are restored.

reportArray

Optional. Specifies what kind of report Microsoft Excel will create when Solver is finished: 1 creates an answer report, 2 creates a sensitivity report, and 3 creates a limit report. Use the Array function to specify the reports you want to display - for example, ReportArray:= Array(1,3).

See Also

SolverFinish Function, SolverOk Function.

Example

This example loads the previously calculated Solver model stored on Sheet1, solves the model again, and then displays the Finish dialog box with two preset options.

Worksheets("Sheet1").Activate
SolverLoad loadArea:=Range("A33:A38")
SolverSolve userFinish:=True
SolverFinishDialog keepFinal:=1, reportArray:=Array(1)


SolverGet Function

Description

Returns information about current settings for Solver. The settings are specified in the Solver Parameters and Solver Options dialog boxes.

Before you use this function, you must establish a reference to the Solver add-in. With a Visual Basic module active, click References on the Tools menu, and then select the Solver.xla check box in the Available References box. If Solver.xla doesn't appear in the Available References box, click Browse, click Solver in the \Excel\Library\Solver folder, and then click OK.

Syntax

SolverGet(typeNum, sheetName)

typeNum

Required. A number specifying the type of information you want. The following settings are specified in the Solver Parameters dialog box.

typeNum

Returns

1

The reference in the Set Target Cell box, or the #N/A error value if Solver hasn't been used on the active sheet.

2

A number corresponding to the Equal To option: 1 represents Max, 2 represents Min, and 3 represents Value Of.

3

The value in the Value Of box.

4

The reference (as a multiple reference, if necessary) in the By Changing Cells box.

5

The number of constraints.

6

An array of the left sides of the constraints in text form.

7

An array of numbers corresponding to the relationships between the left and right sides of the constraints: 1 represents <=, 2 represents =, 3 represents >=, and 4 represents int.

8

An array of the right sides of the constraints in text form.

The following settings are specified in the Solver Options dialog box.

typenum

Returns

9

The maximum calculation time.

10

The maximum number of iterations.

11

The precision.

12

The integer tolerance value.

13

True if the Assume Linear Model check box is selected; False if it's cleared.

14

True if the Show Iteration Results check box is selected; False if it's cleared.

15

True if the Use Automatic Scaling check box is selected; False if it's cleared.

16

A number corresponding to the type of estimates: 1 represents Tangent, and 2 represents Quadratic.

17

A number corresponding to the type of derivatives: 1 represents Forward, and 2 represents Central.

18

A number corresponding to the type of search: 1 represents Quasi-Newton, and 2 represents Conjugate Gradient.

sheetName

Optional. The name of a sheet that contains the scenario for which you want information. If sheetName is omitted, this sheet is assumed to be the active sheet.

See Also

SolverOk Function.

Example

This example displays a message if you have not used Solver on Sheet1.

Worksheets("Sheet1").Activate
state = SolverGet(typeNum:=1)
If IsError(state) Then
    MsgBox "You have not used Solver on the active sheet"
End If


SolverLoad Function

Description

Loads parameters for an existing Solver model that have been saved to the worksheet.

Before you use this function, you must establish a reference to the Solver add-in. With a Visual Basic module active, click References on the Tools menu, and then select the Solver.xla check box in the Available References box. If Solver.xla doesn't appear in the Available References box, click Browse, click Solver in the \Excel\Library\Solver folder, and then click OK.

Syntax

SolverLoad(loadArea)

loadArea

Required. A reference on the active worksheet to a range of cells from which you want to load a complete problem specification. The first cell in the loadArea contains a formula for the Set Target Cell box in the Solver Parameters dialog box; the second cell contains a formula for the By Changing Cells box; subsequent cells contain constraints in the form of logical formulas. The last cell optionally contains an array of Solver option values. For more information, see SolverOptions. The range represented by the argument loadArea can be on any worksheet, but you must specify the worksheet if it's not the active sheet. For example, SolverLoad("Sheet2!A1:A3") loads a model from Sheet2 even if it's not the active sheet.

See Also

SolverOk Function, SolverSave Function.

Example

This example loads the previously calculated Solver model stored on Sheet1, changes one of the constraints, and then solves the model again.

Worksheets("Sheet1").Activate
SolverLoad loadArea:=Range("A33:A38")
SolverChange cellRef:=Range("F4:F6"), _
    relation:=1, _
    formulaText:=200
SolverSolve userFinish:=False


SolverOk Function

Description

Defines a basic Solver model. Equivalent to clicking Solver on the Tools menu and then specifying options in the Solver Parameters dialog box.

Before you use this function, you must establish a reference to the Solver add-in. With a Visual Basic module active, click References on the Tools menu, and then select the Solver.xla check box in the Available References box. If Solver.xla doesn't appear in the Available References box, click Browse, click Solver in the \Excel\Library\Solver folder, and then click OK.

Syntax

SolverOk(setCell, maxMinVal, valueOf, byChange)

setCell

Optional. Refers to a single cell on the active worksheet. Corresponds to the Set Target Cell box in the Solver Parameters dialog box.

maxMinVal

Optional. Corresponds to the Max, Min, and Value Of options in the Solver Parameters dialog box.

maxMinVal

Specifies

1

Maximize

2

Minimize

3

Match specific value

valueOf

Optional. If MaxMinVal is 3, you must specify the value to which the target cell is matched.

byChange

Required. The cell or range of cells that will be changed in order to obtain the desired result in the target cell. Corresponds to the By Changing Cells box in the Solver Parameters dialog box.

See Also

SolverOkDialog Function.

Example

This example uses the Solver functions to maximize gross profit in a business problem. The SolverOK function defines a problem by specifying the setCell, maxMinVal, and byChange arguments.

Worksheets("Sheet1").Activate
SolverReset
SolverOptions precision:=0.001
SolverOK setCell:=Range("TotalProfit"), _
    maxMinVal:=1, _
    byChange:=Range("C4:E6")
SolverAdd cellRef:=Range("F4:F6"), _
    relation:=1, _
    formulaText:=100
SolverAdd cellRef:=Range("C4:E6"), _
    relation:=3, _
    formulaText:=0
SolverAdd cellRef:=Range("C4:E6"), _
    relation:=4
SolverSolve userFinish:=False
SolverSave saveArea:=Range("A33")


SolverOkDialog Function

Description

Same as the SolverOK function, but also displays the Solver dialog box.

Before you use this function, you must establish a reference to the Solver add-in. With a Visual Basic module active, click References on the Tools menu, and then select the Solver.xla check box in the Available References box. If Solver.xla doesn't appear in the Available References box, click Browse, click Solver in the \Excel\Library\Solver folder, and then click OK.

Syntax

SolverOkDialog(setCell, maxMinVal, valueOf, byChange)

setCell

Optional. Refers to a single cell on the active worksheet. Corresponds to the Set Target Cell box in the Solver Parameters dialog box.

maxMinVal

Optional. Corresponds to the Max, Min, and Value Of options in the Solver Parameters dialog box.

maxMinVal

Specifies

1

Maximize

2

Minimize

3

Match specific value

valueOf

Optional. If MaxMinVal is 3, you must specify the value to which the target cell is matched.

byChange

Optional. The cell or range of cells that will be changed in order to obtain the desired result in the target cell. Corresponds to the By Changing Cells box in the Solver Parameters dialog box.

See Also

SolverOk Function.

Example

This example loads the previously calculated Solver model stored on Sheet1, resets all Solver options, and then displays the Solver Parameters dialog box. From this point on, Solver can be used manually.

Worksheets("Sheet1").Activate
SolverLoad loadArea:=Range("A33:A38")
SolverReset
SolverOKDialog setCell:=Range("TotalProfit")
SolverSolve userFinish:=False


SolverOptions Function

Description

Allows you to specify advanced options for your Solver model. This function and its arguments correspond to the options in the Solver Options dialog box.

Before you use this function, you must establish a reference to the Solver add-in. With a Visual Basic module active, click References on the Tools menu, and then select the Solver.xla check box in the Available References box. If Solver.xla doesn't appear in the Available References box, click Browse, click Solver in the \Excel\Library\Solver folder, and then click OK.

Syntax

SolverOptions(maxTime, iterations, precision, assumeLinear, stepThru, estimates, derivatives, search, intTolerance, scaling)

maxTime

Optional. The maximum time (in seconds) Microsoft Excel will spend solving the problem. The value must be a positive integer. The default value 100 is adequate for most small problems, but you can enter a value as high as 32,767.

iterations

Optional. The maximum iterations Microsoft Excel will use in solving the problem. The value must be a positive integer. The default value 100 is adequate for most small problems, but you can enter a value as high as 32,767.

precision

Optional. A number between 0 and 1 that specifies the degree of precision to be used in solving the problem. The default precision is 0.000001. A lower precision is indicated if there are fewer decimal places - for example, 0.0001. In general, the higher the precision you specify (a smaller number), the more time Solver will take to reach solutions.

assumeLinear

Optional. If True, Solver assumes that the underlying model is linear. This speeds the solution process, but it should be used only if all the relationships in the model are linear. False is the default.

stepThru

Optional. If True, Solver pauses at each trial solution. You can pass Solver a macro to run at each pause by using the showRef argument of the SolverSolve function. If False, Solver doesn't pause at each trial solution. False is the default.

estimates

Optional. Specifies the approach used to obtain initial estimates of the basic variables in each one-dimensional search: 1 represents Tangent estimates, and 2 represents Quadratic estimates. Tangent uses linear extrapolation from a tangent vector. Quadratic uses quadratic extrapolation; this may improve the results on highly nonlinear problems. Tangent is the default.

derivatives

Optional. Specifies forward differencing or central differencing for estimates of partial derivatives of the objective and constraint functions: 1 represents forward differencing, and 2 represents central differencing. Central differencing requires more worksheet recalculations, but it may help with problems that generate a message saying that Solver couldn't improve the solution. With functions whose graphical representations aren't smooth and continuous, you should use the Central differencing option. Forward differencing is the default.

search

Optional. Use the Search options to specify which search algorithm will be used at each iteration to decide which direction to search in: 1 represents the Newton search method, and 2 represents the Conjugate search method. Newton, which uses a quasi-Newton method, is the default search method. This method typically requires more memory than the Conjugate search method, but it requires fewer iterations. Conjugate gradient searching requires less memory than the Newton search method, but it typically requires more iterations to reach a particular level of accuracy. You can try this method if you have a large problem and memory usage is a concern. Conjugate searching is especially useful if stepping through the iterations reveals slow progress between successive trial points.

intTolerance

Optional. A decimal number between 0 and 1 that specifies the integer tolerance. This argument applies only if integer constraints have been defined. You can adjust the Tolerance figure, which represents a percentage of error allowed in the optimal solution when an integer constraint is used on any element of the problem. A higher tolerance (allowable percentage of error) would tend to speed up the solution process.

scaling

Optional. If True, and if two or more constraints differ by several orders of magnitude, Solver scales the constraints to similar orders of magnitude during computation. This is useful when the inputs ( in the By Changing Cells box in the Solver Parameters dialog box) and outputs (in the Set Target Cell and Subject To The Constraints boxes in the Solver Parameters dialog box) have large differences in magnitude - for example, maximizing percent profit based on million-dollar investments. If False, Solver calculates without scaling the constraints. False is the default.

See Also

SolverOk Function.

Example

This example sets the Precision option to .001.

Worksheets("Sheet1").Activate
SolverReset
SolverOptions precision:=0.001
SolverOK setCell:=Range("TotalProfit"), _
    maxMinVal:=1, _
    byChange:=Range("C4:E6")
SolverAdd cellRef:=Range("F4:F6"), _
    relation:=1, _
    formulaText:=100
SolverAdd cellRef:=Range("C4:E6"), _
    relation:=3, _
    formulaText:=0
SolverAdd cellRef:=Range("C4:E6"), _
    relation:=4
SolverSolve userFinish:=False
SolverSave saveArea:=Range("A33")


SolverReset Function

Description

Resets all cell selections and constraints in the Solver Parameters dialog box and restores all the settings in the Solver Options dialog box to their defaults. Equivalent to clicking Reset All in the Solver Parameters dialog box. The SolverReset function is called automatically when you call the SolverLoad function.

Before you use this function, you must establish a reference to the Solver add-in. With a Visual Basic module active, click References on the Tools menu, and then select the Solver.xla check box in the Available References box. If Solver.xla doesn't appear in the Available References box, click Browse, click Solver in the \Excel\Library\Solver folder, and then click OK.

Syntax

SolverReset()

Example

This example resets the Solver settings to their defaults before defining a new problem.

Worksheets("Sheet1").Activate
SolverReset
SolverOptions precision:=0.001
SolverOK setCell:=Range("TotalProfit"), _
    maxMinVal:=1, _
    byChange:=Range("C4:E6")
SolverAdd cellRef:=Range("F4:F6"), _
    relation:=1, _
    formulaText:=100
SolverAdd cellRef:=Range("C4:E6"), _
    relation:=3, _
    formulaText:=0
SolverAdd cellRef:=Range("C4:E6"), _
    relation:=4
SolverSolve userFinish:=False
SolverSave saveArea:=Range("A33")


SolverSave Function

Description

Saves the Solver problem specifications on the worksheet.

Before you use this function, you must establish a reference to the Solver add-in. With a Visual Basic module active, click References on the Tools menu, and then select the Solver.xla check box in the Available References box. If Solver.xla doesn't appear in the Available References box, click Browse, click Solver in the \Excel\Library\Solver folder, and then click OK.

Syntax

SolverSave(saveArea)

saveArea

Required. The range of cells where the Solver model is to be saved. The range represented by the saveArea argument can be on any worksheet, but you must specify the worksheet if it's not the active sheet. For example, SolverSave("Sheet2!A1:A3") saves the model on Sheet2 even if Sheet2 isn't the active sheet.

See Also

SolverLoad Function.

Example

This example uses the Solver functions to maximize gross profit in a business problem. The SolverSave function saves the current problem to a range on the active worksheet.

Worksheets("Sheet1").Activate
SolverReset
SolverOptions precision:=0.001
SolverOK setCell:=Range("TotalProfit"), _
    maxMinVal:=1, _
    byChange:=Range("C4:E6")
SolverAdd cellRef:=Range("F4:F6"), _
    relation:=1, _
    formulaText:=100
SolverAdd cellRef:=Range("C4:E6"), _
    relation:=3, _
    formulaText:=0
SolverAdd cellRef:=Range("C4:E6"), _
    relation:=4
SolverSolve userFinish:=False
SolverSave saveArea:=Range("A33")


SolverSolve Function

Description

Begins a Solver solution run. The equivalent of clicking Solve in the Solver Parameters dialog box.

Before you use this function, you must establish a reference to the Solver add-in. With a Visual Basic module active, click References on the Tools menu, and then select the Solver.xla check box in the Available References box. If Solver.xla doesn't appear in the Available References box, click Browse, click Solver in the \Excel\Library\Solver folder, and then click OK.

Syntax

SolverSolve(userFinish, showRef)

userFinish

Optional. If True, returns the results without displaying the Solver Results dialog box. If False or omitted, returns the results and displays the Solver Results dialog box.

showRef

Optional. Used only if True is passed to the stepThru argument of the solverOptions function. You can pass the name of a macro (as a string) as the showRef argument. This macro is then called whenever Solver returns an intermediate solution.

See Also

SolverOk Function.

Example

This example uses the Solver functions to maximize gross profit in a business problem. The SolverSolve function begins the Solver solution run.

Worksheets("Sheet1").Activate
SolverReset
SolverOptions precision:=0.001
SolverOK setCell:=Range("TotalProfit"), _
    maxMinVal:=1, _
    byChange:=Range("C4:E6")
SolverAdd cellRef:=Range("F4:F6"), _
    relation:=1, _
    formulaText:=100
SolverAdd cellRef:=Range("C4:E6"), _
    relation:=3, _
    formulaText:=0
SolverAdd cellRef:=Range("C4:E6"), _
    relation:=4
SolverSolve userFinish:=False
SolverSave saveArea:=Range("A33")


Sort Method

Applies To

Range Object.

Description

Syntax 1: Sorts the range, or sorts the current region if the range contains only one cell.

Syntax 2: Sorts a PivotTable; see the argument list for more information.

Syntax 1

object.Sort(key1, order1, key2, order2, key3, order3, header, orderCustom, matchCase, orientation)

Syntax 2

object.Sort(key1, order1, type, orderCustom, orientation)

object

Required. The Range object.

key1

Optional. The first sort field, as text (a pivot field or range name) or a Range object ("Dept" or Cells(1, 1), for example).

order1

Optional. If xlAscending or omitted, key1 is sorted in ascending order. If xlDescending, key1 is sorted in descending order.

key2

Optional. The second sort field, as text (a pivot field or range name) or a Range object. If omitted, there is no second sort field. Not used when sorting PivotTables.

type

Optional. Only used when sorting PivotTables. Specifies which elements are sorted, either xlSortValues or xlSortLabels.

order2

Optional. Sort order for key2 (xlAscending or xlDescending); if omitted, xlAscending is assumed. Not used when sorting PivotTables.

key3

Optional. The third sort field, as text (a range name) or a Range object. If omitted, there is no third sort field. Not used when sorting PivotTables.

order3

Optional. Sort order for key3 (xlAscending or xlDescending); if omitted, xlAscending is assumed. Not used when sorting PivotTables.

header

Optional. If xlYes, the first row contains headers (it is not sorted). If xlNo or omitted, no headers exist (the entire range is sorted). If xlGuess, Microsoft Excel guesses if there is a header, and where it is if there is one. Not used when sorting PivotTables.

orderCustom

Optional. One-based integer offset into the list of custom sort orders. If omitted, one (Normal) is used.

matchCase

Optional. If True, the sort is case sensitive. If False, the sort is not case sensitive. Not used when sorting PivotTables.

orientation

Optional. If xlTopToBottom or omitted, the sort is done from top to bottom (sort rows). If xlLeftToRight, the sort is done from left to right (sort columns).

Example

This example sorts the range A1:C20 on Sheet1, using cell A1 as the first sort key and cell B1 as the second sort key. The sort is done in ascending order by row, and there are no headers.

Worksheets("Sheet1").Range("A1:C20").Sort _
    key1:=Worksheets("Sheet1").Range("A1"), _
    key2:=Worksheets("Sheet1").Range("B1")

This example sorts the current region that contains cell A1 on Sheet1, sorting by the data in the first column and automatically using a header row if one exists. The Sort method determines the current region automatically.

Worksheets("Sheet1").Range("A1").Sort _
    key1:=Worksheets("Sheet1").Columns("A"), _
    header:=xlGuess


SortSpecial Method

Applies To

Range Object.

Description

Syntax 1: Uses Far-East sorting methods to sort the range, or the current region if the range contains only one cell.

Syntax 2: Uses Far-East sorting methods to sort a PivotTable; see the argument list for more information.

Syntax 1

object.SortSpecial(sortMethod, key1, order1, key2, type, order2, key3, order3, header, orderCustom, matchCase, orientation)

Syntax 2

object.SortSpecial(sortMethod, key1, order1, type, orderCustom, orientation)

object

Required. The Range object.

sortMethod

Optional. Specifies how to sort (xlSyllabary to sort phonetically or xlCodePage to sort by code page). The default value is xlSyllabary.

key1

Optional. The first sort field, as text (a pivot field or range name) or a Range object ("Dept" or Cells(1, 1), for example).

order1

Optional. If xlAscending or omitted, key1 is sorted in ascending order. If xlDescending, key1 is sorted in descending order.

key2

Optional. The second sort field, as text (a pivot field or range name) or a Range object. If omitted, there is no second sort field. Not used when sorting PivotTables.

type

Optional. Only used when sorting PivotTables. Specifies which elements are sorted, either xlSortValues or xlSortLabels.

order2

Optional. Sort order for key2 (xlAscending or xlDescending); if omitted, xlAscending is assumed. Not used when sorting PivotTables.

key3

Optional. The third sort field, as text (a range name) or a Range object. If omitted, there is no third sort field. Not used when sorting PivotTables.

order3

Optional. Sort order for key3 (xlAscending or xlDescending); if omitted, xlAscending is assumed. Not used when sorting PivotTables.

header

Optional. If xlYes, the first row contains headers (it is not sorted). If xlNo or omitted, no headers exist (the entire range is sorted). If xlGuess, Microsoft Excel guesses if there is a header, and where it is if there is one. Not used when sorting PivotTables.

orderCustom

Optional. One-based integer offset into the list of custom sort orders. If omitted, one (Normal) is used.

matchCase

Optional. If True, the sort is case sensitive. If False, the sort is not case sensitive. Not used when sorting PivotTables.

orientation

Optional. If xlTopToBottom or omitted, the sort is done from top to bottom (sort rows). If xlLeftToRight, the sort is done from left to right (sort columns).

Example

This example sorts the range A1:G37 on Sheet1, using cell A1 as the first sort key and cell C1 as the second key. The sort is done in ascending code page order by row, and there are no headers.

Worksheets("Sheet1").Range("A1:G37").SortSpecial _
    sortMethod:=xlCodePage, _
    key1:=Range("A1"), order1:=xlAscending, _
    key2:=Range("C1"), order2:=xlAscending


SoundNote Object

Description

Represents a sound note in a cell (a cell is a Range object). Your computer may need additional hardware to play and record sound notes.

Accessors

The SoundNote property returns the sound note for a cell. The following example records a sound note if the computer is capable of recording.

If Application.CanRecordSounds Then
    With Worksheets(1).Range("a1").SoundNote
        .Delete
        .Record
    End With
Else
    MsgBox "This machine cannot record sound notes."
End If

Properties

Application Property, Creator Property, Parent Property.

Methods

Delete Method, Import Method, Play Method, Record Method.


SoundNote Property

Applies To

Range Object.

Description

Accessor. Returns a SoundNote object that represents the sound note associated with the top left cell in the specified range. Read-only.

Remarks

Your computer may require optional hardware to record and play sound notes.

See Also

Import Method, Play Method, Record Method.

Example

This example deletes the sound note in cell A1 on Sheet1, records a new sound note for the same cell, and then plays the sound note.

With Worksheets("Sheet1").Range("A1").SoundNote
    .Delete
    .Record
    .Play
End With


SourceData Property

Applies To

PivotTable Object.

Description

Returns the data source for the PivotTable, as shown in the following table.

Data Source | Return Value
Microsoft Excel list or database | The cell reference as text.
External data source | An array. Each row consists of a SQL connection string with the remaining elements as the query string broken down into 200-character segments.
Multiple Consolidation ranges | A two-dimensional array. Each row consists of a reference and associated page field items.
Another PivotTable | One of the above three kinds of information.

Example

Assume that you used an external data source to create a PivotTable on Sheet1. This example inserts the SQL connection string and query string into a new worksheet.

Set newSheet = ActiveWorkbook.Worksheets.Add
sdArray = Worksheets("Sheet1").UsedRange.PivotTable.SourceData
For i = LBound(sdArray) To UBound(sdArray)
    newSheet.Cells(i, 1) = sdArray(i)
Next i


SourceName Property

Applies To

PivotField Object, PivotItem Object.

Description

Returns the object name (a string) as it appears in the original source data for the PivotTable. This might be different from the current item name if the user renamed the item after creating the PivotTable. Read-only.

Example

This example displays the original name (the name from the source database) of the item that contains the active cell.

Worksheets("Sheet1").Activate
MsgBox("The original item name is " & _
    ActiveCell.PivotItem.SourceName)


Space Function

Description

Returns a string consisting of the specified number of spaces.

Syntax

Space(number)

The number named argument is the number of spaces you want in the string.

Remarks

The Space function is useful for formatting output and clearing data in fixed-length strings.

See Also

Spc Function, String Function.

Example

This example uses the Space function to return a string consisting of a specified number of spaces.

' Returns a string with 10 spaces.
MyString = Space(10)
' Insert 10 spaces between 2 strings.
MyString = "Hello" & Space(10) & "World"


Spc Function

Description

Used with the Print # statement or the Print method to position output.

Syntax

Spc(n)

The n argument is the number of spaces to insert before displaying or printing the next expression in a list.

Remarks

If n is less than the output-line width, the next print position immediately follows the number of spaces printed. If n is greater than the output-line width, Spc calculates the next print position using the formula:

currentprintposition + (n Mod width)

For example, if the current print position is 24, the output-line width is 80 and you specify Spc(90), the next print will start at position 34 (current print position + the remainder of 90/80). If the difference between the current print position and the output-line width is less than n (or n Mod width), the Spc function skips to the beginning of the next line and generates a number of spaces equal to n - (width - currentprintposition).

Note

Make sure your tabular columns are wide enough to accommodate wider letters.

When you use the Print method with a proportionally spaced font, the width of space characters printed using the Spc function is always an average of the width of all characters in the point size for the chosen font. However, there is no correlation between the number of characters printed and the number of fixed-width columns those characters occupy. For example, the uppercase letter W occupies more than one fixed-width column and the lowercase letter I occupies less.

See Also

Print # Statement, Print Method, Space Function, Tab Function, Width # Statement.

Example

This example uses the Spc function to position output in a file and in the Debug window.

' The Spc function can be used with the Print # statement.
Open "TESTFILE" For Output As #1    ' Open file for output.
Print #1, "10 spaces between here"; Spc(10); "and here."
Close #1    ' Close file.
' The following statement causes the text to be printed in the Debug
' window, preceded by 30 spaces.
Debug.Print Spc(30); "Thirty spaces later..."


SpecialCells Method

Applies To

Range Object.

Description

Accessor. Returns a Range object that represents all the cells that match the specified type and value.

Syntax

object.SpecialCells(type, value)

object

Required. The Range object.

type

Required. The types of cells to include, as shown in the following table.

Value

Meaning

xlNotes

Cells containing notes.

xlConstants

Cells containing constants.

xlFormulas

Cells containing formulas.

xlBlanks

Empty cells.

xlLastCell

Last cell of the used range.

xlVisible

All visible cells.

value

Optional. If type is xlConstants or xlFormulas, the value argument is used to determine which types of cells to include in the result. These values may be added together to return more than one type. The default is to select all constants or formulas, no matter what the type.

Value

Meaning

xlNumbers

Numbers

xlTextValues

Text

xlLogical

Logical values

xlErrors

Error values

Example

This example selects the last cell in the used range of Sheet1.

Worksheets("Sheet1").Activate
ActiveSheet.Cells.SpecialCells(xlLastCell).Activate


Spinner Object

Description

Represents a spinner, which is often linked to edit boxes so that the user can select a numeric value without having to type in a number. Spinners are very similar to scroll bars (ScrollBar object), but spinners do not have the LargeChange property.

Edit boxes do not have spinners by default. If you want an edit box to have a spinner, you must create a separate Spinner object and add the Visual Basic code to link the spinner value to the edit box. The following example links the value of the spinner named "spnTest" to the text displayed in the edit box named "edtTest," so that changing the value of one control simultaneously changes the value of the other.

Sub spnTest_Change()
    ActiveDialog.EditBoxes("edtTest").Text = _
        ActiveDialog.Spinners("spnTest").Value
End Sub

Sub edtTest_Change()
    ActiveDialog.Spinners("spnTest").Value = _
        ActiveDialog.EditBoxes("edtTest").Text
End Sub

Accessors

The Spinner object is a member of the Spinners collection. The Spinners collection contains all the Spinner objects on a single sheet. Use the Add method to create a new spinner and add it to the collection.

To access a single member of the collection, use the Spinners method with the index number or name of the spinner as an argument.

The following example sets the OnAction property for spinner one on the worksheet named "Sheet1." The SpinnerProc Visual Basic procedure runs when the user clicks the spinner.

Worksheets("sheet1").Spinners(1).OnAction = "SpinnerProc"

The spinner name is shown in the Name Box when the spinner is selected. Use the Name property to set or return the spinner name. The following example disables the spinner named "Spinner 5" on the worksheet named "Sheet1."

Worksheets("sheet1").Spinners("spinner 5").Enabled = False

Properties

Application Property, BottomRightCell Property, Creator Property, Display3DShading Property, Enabled Property, Height Property, Index Property, Left Property, LinkedCell Property, Locked Property, Max Property, Min Property, Name Property, OnAction Property, Parent Property, Placement Property, PrintObject Property, SmallChange Property, Top Property, TopLeftCell Property, Value Property, Visible Property, Width Property, ZOrder Property.

Methods

BringToFront Method, Copy Method, CopyPicture Method, Cut Method, Delete Method, Duplicate Method, Select Method, SendToBack Method.


Spinners Collection Object

Description

A collection of all the Spinner objects on the specified chart sheet, dialog sheet, or worksheet. Spinners are often linked to edit boxes so that the user can select a numeric value without having to type in a number. Spinners are very similar to scroll bars (ScrollBar objects), but spinners do not have the LargeChange property.

Accessors

Use the Add method to create a new spinner and add it to the collection. The following example adds a new spinner to the worksheet named "Sheet1." The new spinner is 10 points wide and is located at the left edge of cell C5.

Dim r As Range
Set r = Worksheets("sheet1").Range("c5")
Worksheets("sheet1").Spinners.Add r.Left, r.Top, 10, r.Height

Use the Spinners method with an argument to access a single member of the collection or without an argument to access the entire collection at once. The following example deletes all of the spinners on the worksheet named "Sheet1."

Worksheets("sheet1").Spinners.Delete

Properties

Application Property, Count Property, Creator Property, Display3DShading Property, Enabled Property, Height Property, Left Property, LinkedCell Property, Locked Property, Max Property, Min Property, OnAction Property, Parent Property, Placement Property, PrintObject Property, SmallChange Property, Top Property, Value Property, Visible Property, Width Property, ZOrder Property.

Methods

Add Method (Graphic Objects and Controls), BringToFront Method, Copy Method, CopyPicture Method, Cut Method, Delete Method, Duplicate Method, Group Method, Item Method, Select Method, SendToBack Method.


Spinners Method

Applies To

Chart Object, DialogSheet Object, Worksheet Object.

Description

Accessor. Returns an object that represents a single spinner control (a Spinner object, Syntax 1) or a collection of spinner controls (a Spinners object, Syntax 2) on the sheet.

Syntax 1

object.Spinners(index)

Syntax 2

object.Spinners

object

Required. The Chart, DialogSheet, or Worksheet object.

index

Required for Syntax 1. Specifies the name or number of the spinner (can be an array to specify more than one).

Example

This example displays the current value of spinner one on Dialog1. This example can be used in the event procedure for the spinner, in which case the message box appears every time you click the spinner.

MsgBox DialogSheets("Dialog1").Spinners(1).Value


Split Property

Applies To

Window Object.

Description

True if the window is split. Read-write.

Remarks

It is possible for FreezePanes to be True and Split to be False, or vice versa.

This property applies only to worksheets and macro sheets.

Example

This example splits the active window in BOOK1.XLS at cell B2, without freezing panes. This causes the Split property to return True.

Workbooks("BOOK1.XLS").Worksheets("Sheet1").Activate
With ActiveWindow
    .SplitColumn = 2
    .SplitRow = 2
End With

There are two ways to remove the split added by the previous example.

Workbooks("BOOK1.XLS").Worksheets("Sheet1").Activate
ActiveWindow.Split = False            'method one

Workbooks("BOOK1.XLS").Worksheets("Sheet1").Activate
ActiveWindow.SplitColumn = 0        'method two
ActiveWindow.SplitRow = 0

This example removes the window split. Before you can remove the split, you must set FreezePanes to False to remove frozen panes.

Workbooks("BOOK1.XLS").Worksheets("Sheet1").Activate
With ActiveWindow
    .FreezePanes = False
    .Split = False
End With


SplitColumn Property

Applies To

Window Object.

Description

Returns or sets the column number where the window is split into panes (the number of columns to the left of the split line). Read-write.

See Also

SplitHorizontal Property, SplitRow Property, SplitVertical Property.

Example

This example splits the window and leaves 1.5 columns to the left of the split line.

Workbooks("BOOK1.XLS").Worksheets("Sheet1").Activate
ActiveWindow.SplitColumn = 1.5


SplitHorizontal Property

Applies To

Window Object.

Description

Returns or sets the location of the horizontal window split, in points (1/72 inch). Read-write.

See Also

SplitColumn Property, SplitRow Property, SplitVertical Property.

Example

This example sets the horizontal split for the active window to 216 points (3 inches).

Workbooks("BOOK1.XLS").Worksheets("Sheet1").Activate
ActiveWindow.SplitHorizontal = 216


SplitRow Property

Applies To

Window Object.

Description

Returns or sets the row number where the window is split into panes (the number of rows above the split). Read-write.

See Also

SplitColumn Property, SplitHorizontal Property, SplitVertical Property.

Example

This example splits the active window so that there are 10 rows above the split line.

Workbooks("BOOK1.XLS").Worksheets("Sheet1").Activate
ActiveWindow.SplitRow = 10


SplitVertical Property

Applies To

Window Object.

Description

Returns or sets the location of the vertical window split, in points (1/72 inch). Read-write.

See Also

SplitColumn Property, SplitHorizontal Property, SplitRow Property.

Example

This example sets the vertical split for the active window to 216 points (3 inches).

Workbooks("BOOK1.XLS").Worksheets("Sheet1").Activate
ActiveWindow.SplitVertical = 216


SQLBind Function

Description

In Microsoft Excel for Windows 95, do not use SQLBind and the other ODBC functions in the XLODBC.XLA add-in; use the objects, methods, and properties in the Data Access Objects (DAO) library instead.

SQLBind specifies where results are placed when they are retrieved using SQLRetrieve or SQLRetrieveToFile. Use SQLBind to change the column order of the result set from a query, or to place the result set columns in non-adjacent worksheet columns.

This function is contained in the XLODBC.XLA add-in (ODBC Add-In on the Macintosh). Before you use the function, you must establish a reference to the add-in using the References command (Tools menu).

Syntax

SQLBind(connectionNum, column, reference)

connectionNum

Required. The unique connection ID of the data source, returned by SQLOpen, for which you want to bind results.

column

Optional. The column number of the result set that you want to bind. Columns in the result set are numbered from left to right starting with 1. If you omit column, all bindings for connectionNum are removed.

Column number 0 (zero) contains row numbers for the result set. You can return the row numbers by binding column number 0 (zero).

reference

Optional. The location of a single cell on a worksheet where you want the results bound, as a Range object. If reference is omitted, binding is removed for the column.

Return Value

This function returns an array listing the bound columns for the current connection by column number.

If SQLBind is unable to bind the column to the cell in the specified reference, it returns Error 2042.

If connectionNum is not valid or if you try to bind a cell that is not available, SQLBind returns Error 2015.

If reference refers to more than a single cell, SQLBind returns Error 2023.

If SQLRetrieve does not have a destination parameter, SQLBind places the result set in the location indicated by reference.

Remarks

SQLBind tells the ODBC Control Panel Administrator where to place results when they are received using SQLRetrieve The results are placed in the reference cell and cells immediately below it.

Use SQLBind if you want the results from different columns to be placed in disjoint worksheet locations.

Use SQLBind for each column in the result set. A binding remains valid as long as the connection specified by connectionNum is open.

Call SQLBind after calling SQLOpen and SQLExecQuery, but before calling SQLRetrieve or SQLRetrieveToFile. Calls to SQLBind do not affect results that have already been retrieved.

See Also

SQLClose Function, SQLError Function, SQLExecQuery Function, SQLGetSchema Function, SQLOpen Function, SQLRequest Function, SQLRetrieve Function, SQLRetrieveToFile Function.

Example

This example runs a query on the NWind sample database, and then it uses the SQLBind function to display only the fourth and ninth columns of the query result set (the product name and the quantity on order) on Sheet1.

If Application.OperatingSystem Like "*Win*" Then
    databaseName = "NWind"
Else        'Macintosh
    databaseName = "NorthWind"
End If
queryString = "SELECT * FROM product.dbf WHERE (product.ON_ORDER<>0)"
chan = SQLOpen("DSN=" & databaseName)
SQLExecQuery chan, queryString
Set output1 = Worksheets("Sheet1").Range("A1")
Set output2 = Worksheets("Sheet1").Range("B1")
SQLBind chan, 4, output1
SQLBind chan, 9, output2
SQLRetrieve chan
SQLClose chan


SQLClose Function

Description

In Microsoft Excel for Windows 95, do not use SQLClose and the other ODBC functions in the XLODBC.XLA add-in; use the objects, methods, and properties in the Data Access Objects (DAO) library instead.

SQLClose closes a connection to an external data source.

This function is contained in the XLODBC.XLA add-in (ODBC Add-In on the Macintosh). Before you use the function, you must establish a reference to the add-in using the References command (Tools menu).

Syntax

SQLClose(connectionNum)

connectionNum

Required. The unique connection ID of the data source from which you want to disconnect.

Return Value

If the connection is successfully closed, this function returns 0 (zero) and the connection ID is no longer valid.

If connectionNum is not valid, this function returns Error 2015.

If SQLClose is unable to disconnect from the data source, it returns Error 2042.

See Also

SQLBind Function, SQLError Function, SQLExecQuery Function, SQLGetSchema Function, SQLOpen Function, SQLRequest Function, SQLRetrieve Function, SQLRetrieveToFile Function.

Example

This example runs a query on the NWind sample database. The result of the query, displayed on Sheet1, is a list of all products that are currently on order.

If Application.OperatingSystem Like "*Win*" Then
    databaseName = "NWind"
Else        'Macintosh
    databaseName = "NorthWind"
End If
queryString = "SELECT * FROM product.dbf WHERE (product.ON_ORDER<>0)"
chan = SQLOpen("DSN=" & databaseName)
SQLExecQuery chan, queryString
Set output = Worksheets("Sheet1").Range("A1")
SQLRetrieve chan, output, , , True
SQLClose chan


SQLError Function

Description

In Microsoft Excel for Windows 95, do not use SQLError and the other ODBC functions in the XLODBC.XLA add-in; use the objects, methods, and properties in the Data Access Objects (DAO) library instead.

SQLError returns detailed error information when called after one of the other ODBC functions fails. If SQLError itself fails, it cannot return error information.

Error information is defined and stored in memory whenever an ODBC function fails. To make the error information available, call the SQLError function.

SQLError provides detailed error information only about errors that occur when an ODBC function fails. It does not provide information about Microsoft Excel errors.

This function is contained in the XLODBC.XLA add-in (ODBC Add-In on the Macintosh). Before you use the function, you must establish a reference to the add-in using the References command (Tools menu).

Syntax

SQLError()

Return Value

If there are errors, SQLError returns detailed error information in a two-dimensional array in which each row describes one error.

Each row has the following three fields for information obtained through the SQLError function call in ODBC:

A character string indicating the ODBC error class and subclass.

A numeric value indicating the data source native error code.

A text message describing the error.

If a function call generates multiple errors, SQLError creates a row for each error.

If there are no errors from a previous ODBC function call, this function returns only Error 2042.

See Also

SQLBind Function, SQLClose Function, SQLExecQuery Function, SQLGetSchema Function, SQLOpen Function, SQLRequest Function, SQLRetrieve Function, SQLRetrieveToFile Function.

Example

This example generates an intentional error by attempting to open a connection to the NWind sample database using an incorrect connection string (NWind is misspelled). The error information is displayed on Sheet1.

chan = SQLOpen("DSN=NWin")
returnArray = SQLError()
For i = LBound(returnArray, 1) To UBound(returnArray, 1)
    Worksheets("Sheet1").Cells(1, i).Formula = returnArray(i)
Next i
SQLClose chan


SQLExecQuery Function

Description

In Microsoft Excel for Windows 95, do not use SQLExecQuery and the other ODBC functions in the XLODBC.XLA add-in; use the objects, methods, and properties in the Data Access Objects (DAO) library instead.

SQLExecQuery executes a query on a data source with a connection that has been established using SQLOpen.

SQLExecQuery executes only the query. Use SQLRetrieve or SQLRetrieveToFile to get the results.

This function is contained in the XLODBC.XLA add-in (ODBC Add-In on the Macintosh). Before you use the function, you must establish a reference to the add-in using the References command (Tools menu).

Syntax

SQLExecQuery(connectionNum, queryText)

connectionNum

Required. The unique connection ID returned by SQLOpen that identifies the data source you want to query.

queryText

Required. The query to be executed on the data source. The query must follow the SQL syntax guidelines for the specific driver.

Return Value

The value returned by SQLExecQuery depends on the type of SQL statement executed, as shown in the following table.

SQL statement executed | Return Value
SELECT | The number of columns in the result set.
UPDATE, INSERT or DELETE | The number of rows affected by the statement.
Any other valid SQL statement | 0 (zero)

If SQLExecQuery is unable to execute the query on the specified data source, it returns Error 2042.

If connectionNum is not valid, SQLExecQuery returns Error 2015.

Remarks

Before calling SQLExecQuery you must establish a connection to a data source using SQLOpen The unique connection ID returned by SQLOpen is used by SQLExecQuery to send queries to the data source.

If you call SQLExecQuery using a previously used connection ID, any pending results on that connection are replaced by the new results.

See Also

SQLBind Function, SQLClose Function, SQLError Function, SQLGetSchema Function, SQLOpen Function, SQLRequest Function, SQLRetrieve Function, SQLRetrieveToFile Function.

Example

This example runs a query on the NWind sample database. The result of the query, displayed on Sheet1, is a list of all products that are currently on order.

If Application.OperatingSystem Like "*Win*" Then
    databaseName = "NWind"
Else        'Macintosh
    databaseName = "NorthWind"
End If
queryString = "SELECT * FROM product.dbf WHERE (product.ON_ORDER<>0)"
chan = SQLOpen("DSN=" & databaseName)
SQLExecQuery chan, queryString
Set output = Worksheets("Sheet1").Range("A1")
SQLRetrieve chan, output, , , True
SQLClose chan


SQLGetSchema Function

Description

In Microsoft Excel for Windows 95, do not use SQLGetSchema and the other ODBC functions in the XLODBC.XLA add-in; use the objects, methods, and properties in the Data Access Objects (DAO) library instead.

SQLGetSchema returns information about the structure of the data source on a particular connection.

This function is contained in the XLODBC.XLA add-in (ODBC Add-In on the Macintosh). Before you use the function, you must establish a reference to the add-in using the References command (Tools menu).

Syntax

SQLGetSchema(connectionNum, typeNum, qualifierText)

connectionNum

Required. The unique connection ID of the data source you connected to using SQLOpen and for which you want information.

typeNum

Required. Specifies the type of information you want returned, as shown in the following table.

Value

Meaning

1

A list of available data sources.

2

A list of databases on the current connection.

3

A list of owners in a database on the current connection.

4

A list of tables for a given owner and database on the current connection.

5

A list of columns in a particular table and their ODBC SQL data types in a two-dimensional array. The first field contains the name of the column and the second field is the ODBC SQL data type of the column.

6

The user ID of the current user.

7

The name of the current database.

8

The name of the data source defined during setup or by using the ODBC Control Panel Administrator.

9

The name of the DBMS the data source uses, for example, ORACLE or SQL Server.

10

The server name for the data source.

11

The terminology used by the data source to refer to the owners, for example "owner", "Authorization ID", or "Schema".

12

The terminology used by the data source to refer a table, for example, "table" or "file".

13

The terminology used by the data source to refer to a qualifier, for example, "database" or "directory".

14

The terminology used by the data source to refer to a procedure, for example, "database procedure", "stored procedure", or "procedure".

qualifierText

Optional. Included only for typeNum values of 3, 4 and 5. A string that qualifies the search, as shown in the following table.

typeNum

qualifierText

3

The name of the database in the current data source. SQLGetSchema returns the names of the table owners in that database.

4

Both a database name and an owner name. The syntax consists of the database name followed by the owner's name with a period separating the two; for example, "DatabaseName.OwnerName". This function returns an array of table names that are located in the given database and owned by the given owner.

5

The name of a table. SQLGetSchema returns information about the columns in the table.

Return Value

The return value from a successful call to SQLGetSchema depends on the type of information that is requested.

If SQLGetSchema cannot find the requested information, it returns Error 2042.

If connectionNum is not valid, this function returns Error 2015.

Remarks

SQLGetSchema uses the ODBC API functions SQLGetInfo and SQLTables to find the requested information.

See Also

SQLBind Function, SQLClose Function, SQLError Function, SQLExecQuery Function, SQLOpen Function, SQLRequest Function, SQLRetrieve Function, SQLRetrieveToFile Function.

Example

This example retrieves the database name and DBMS name for the NWind sample database and then displays them in a message box.

If Application.OperatingSystem Like "*Win*" Then
    databaseName = "NWind"
Else        'Macintosh
    databaseName = "NorthWind"
End If
chan = SQLOpen("DSN=" & databaseName)
dsName = SQLGetSchema(chan, 8)
dsDBMS = SQLGetSchema(chan, 9)
MsgBox "Database name is " & dsName & ", and its DBMS is " & dsDBMS
SQLClose chan


SQLOpen Function

Description

In Microsoft Excel for Windows 95, do not use SQLOpen and the other ODBC functions in the XLODBC.XLA add-in; use the objects, methods, and properties in the Data Access Objects (DAO) library instead.

SQLOpen establishes a connection to a data source.

This function is contained in the XLODBC.XLA add-in (ODBC Add-In on the Macintosh). Before you use the function, you must establish a reference to the add-in using the References command (Tools menu)..

Syntax

SQLOpen(connectionStr, outputRef, driverPrompt)

connectionStr

Required. Supplies the information required by the driver being used to connect to a data source and must follow the driver's format.

The connectionStr supplies the data source name and other information, such as user ID and passwords, that is required by the driver to make a connection.

You must define the data source name (DSN) used in connectionStr before you try to connect to it.

outputRef

Optional. A single cell, as a Range object, that contains the completed connection string.

Use outputRef when you want SQLOpen to return the completed connection string to a worksheet.

driverPrompt

Optional. Specifies when the driver dialog box is displayed and which options are available. Use one of the numbers described in the following table. If driverPrompt is omitted, SQLOpen uses 2 as the default.

Value

Meaning

1

Driver dialog box is always displayed.

2

Driver dialog box is displayed only if information provided by the connection string and the data source specification are not sufficient to complete the connection. All dialog box options are available.

3

The same as 2 except that dialog box options that are not required are dimmed and unavailable.

4

Driver dialog box is not displayed. If the connection is not successful, SQLOpen returns an error.

Return Value

If successful, SQLOpen returns a unique connection ID number. Use the connection ID number with the other ODBC functions.

If SQLOpen is unable to connect using the information you provide, it returns Error 2042. Additional error information is placed in memory for use by SQLError.

See Also

SQLBind Function, SQLClose Function, SQLError Function, SQLExecQuery Function, SQLGetSchema Function, SQLRequest Function, SQLRetrieve Function, SQLRetrieveToFile Function.

Example

This example runs a query on the NWind sample database. The result of the query, displayed on Sheet1, is a list of all products that are currently on order.

If Application.OperatingSystem Like "*Win*" Then
    databaseName = "NWind"
Else        'Macintosh
    databaseName = "NorthWind"
End If
queryString = "SELECT * FROM product.dbf WHERE (product.ON_ORDER<>0)"
chan = SQLOpen("DSN=" & databaseName)
SQLExecQuery chan, queryString
Set output = Worksheets("Sheet1").Range("A1")
SQLRetrieve chan, output, , , True
SQLClose chan


SQLRequest Function

Description

In Microsoft Excel for Windows 95, do not use SQLRequest and the other ODBC functions in the XLODBC.XLA add-in; use the objects, methods, and properties in the Data Access Objects (DAO) library instead.

SQLRequest connects to an external data source and runs a query from a worksheet, and then returns the result as an array.

This function is contained in the XLODBC.XLA add-in (ODBC Add-In on the Macintosh). Before you use the function, you must establish a reference to the add-in using the References command (Tools menu).

Syntax

SQLRequest(connectionStr, queryText, outputRef, driverPrompt, colNamesLogical)

connectionStr

Required. Supplies information, such as the data source name, user ID, and passwords, required by the driver being used to connect to a data source and must follow the driver's format.

You must define the data source name (DSN) used in connectionStr before you try to connect to it.

If SQLRequest is unable to access the data source using connectionStr, it returns Error 2042.

queryText

Required. The SQL statement that you want to execute on the data source.

If SQLRequest is unable to execute queryText on the specified data source, it returns Error 2042.

outputRef

Optional. A single worksheet cell, as a Range object, where you want the completed connection string placed.

driverPrompt

Optional. Specifies when the driver dialog box is displayed and which options are available. Use one of the numbers described in the following table. If driverPrompt is omitted, SQLRequest uses 2 as the default.

Value

Meaning

1

Driver dialog box is always displayed.

2

Driver dialog box is displayed only if information provided by the connection string and the data source specification is not sufficient to complete the connection. All dialog box options are available.

3

Driver dialog box is displayed only if information provided by the connection string and the data source specification is not sufficient to complete the connection. Dialog box options are dimmed and unavailable if they are not required.

4

Dialog box is not displayed. If the connection is not successful, it returns an error.

colNamesLogical

Optional. True if you want the column names to be returned as the first row of results. It should contain False if you do not want the column names returned. The default value, if colNamesLogical is omitted, is False.

Remarks

The arguments to the SQLRequest function are in a different order than the arguments to the SQL.REQUEST macro function.

Return Value

If this function completes all of its actions, it returns an array of query results or the number of rows affected by the query.

If SQLRequest is unable to complete all of its actions, it returns an error value and places the error information in memory for SQLError

If SQLRequest is unable to access the data source using connectionStr, it returns Error 2042.

See Also

SQLBind Function, SQLClose Function, SQLError Function, SQLExecQuery Function, SQLGetSchema Function, SQLOpen Function, SQLRetrieve Function, SQLRetrieveToFile Function.

Example

This example runs a query on the NWind sample database. The result of the query, displayed on Sheet1, is a list of all products that are currently on order. The SQLRequest function also writes the full connection string to Sheet2.

If Application.OperatingSystem Like "*Win*" Then
    databaseName = "NWind"
Else        'Macintosh
    databaseName = "NorthWind"
End If
queryString = "SELECT * FROM product.dbf WHERE (product.ON_ORDER<>0)"
returnArray = SQLRequest("DSN=" & databaseName, _
            queryString, _
            Worksheets("Sheet1").Range("A1"), _
            2, True)
For i = LBound(returnArray, 1) To UBound(returnArray, 1)
    For j = LBound(returnArray, 2) To UBound(returnArray, 2)
        Worksheets("Sheet1").Cells(i, j).Formula = returnArray(i, j)
    Next j
Next i


SQLRetrieve Function

Description

In Microsoft Excel for Windows 95, do not use SQLRetrieve and the other ODBC functions in the XLODBC.XLA add-in; use the objects, methods, and properties in the Data Access Objects (DAO) library instead.

SQLRetrieve retrieves all or part of the results from a previously executed query.

Before using SQLRetrieve, you must establish a connection with SQLOpen, execute a query with SQLExecQuery, and have the results pending.

This function is contained in the XLODBC.XLA add-in (ODBC Add-In on the Macintosh). Before you use the function, you must establish a reference to the add-in using the References command (Tools menu).

Syntax

SQLRetrieve(connectionNum, destinationRef, maxColumns, maxRows, colNamesLogical, rowNumsLogical, namedRngLogical, fetchFirstLogical)

connectionNum

Required. The unique connection ID returned by SQLOpen and for which you have pending query results generated by SQLExecQuery.

If connectionNum is not valid, SQLExecQuery returns Error 2015.

destinationRef

Optional. A Range object that specifies where the results should be placed. This function overwrites any values in the cells without confirmation.

If destinationRef refers to a single cell, SQLRetrieve returns all of the pending results in that cell and in the cells to the right and below it.

If destinationRef is omitted, the bindings established by previous calls to SQLBind are used to return results. If no bindings exist for the current connection, SQLRetrieve returns Error 2023.

If a particular result column has not been bound and destinationRef is omitted, the results are discarded.

maxColumns

Optional. The maximum number of columns returned to the worksheet starting at destinationRef.

If maxColumns specifies more columns than are available in the result, SQLRetrieve places data in the columns for which data is available and clears the additional columns.

If maxColumns specifies fewer columns than are available in the result, SQLRetrieve discards the rightmost result columns until the results fit the specified size.

The order in which the data source returns the columns determines column position.

All of the results are returned if maxColumns is omitted.

maxRows

Optional. The maximum number of rows to be returned to the worksheet starting at destinationRef.

If maxRows specifies more rows than are available in the results, SQLRetrieve places data in the rows for which data is available and clears the additional rows.

If maxRows specifies fewer rows than are available in the results, SQLRetrieve places data in the selected rows but does not discard the additional rows. Extra rows are retrieved by using SQLRetrieve again and by setting fetchFirstLogical to False.

All of the rows in the results are returned if maxRows is omitted.

colNamesLogical

Optional. True if you want the column names to be returned as the first row of results. False or omitted if you do not want the column names returned.

rowNumsLogical

Optional. Used only when destinationRef is included in the function call. If rowNumsLogical is True, the first column in the result set contains row numbers. If destinationRef is False or omitted, the row numbers are not returned. You can also retrieve row numbers by binding column number 0 (zero) with SQLBind.

namedRngLogical

Optional. True if you want each column of the results to be declared as a named range on the worksheet. The name of each range is the result column name. The named range includes only the rows that are returned with SQLRetrieve. The default is False.

fetchFirstLogical

Optional. Allows you to request results from the beginning of the result set. If fetchFirstLogical is False, SQLRetrieve can be called repeatedly to return the next set of rows until all the result rows are returned. When there are no more rows in the result set, SQLRequest returns 0 (zero). If you want to retrieve results from the beginning of the result set, set fetchFirstLogical to True. To retrieve additional rows from the result set, set fetchFirstLogical to False in subsequent calls. The default is False.

Return Value

SQLRetrieve returns the number of rows in the result set.

If SQLRetrieve is unable to retrieve the results on the specified data source or if there are no results pending, it returns Error 2042. If no data is found, it returns 0 (zero).

Remarks

Before calling SQLRetrieve, you must do the following:

1. Establish a connection with a data source using SQLOpen.

2. Use the connection ID returned in SQLOpen to send a query with SQLExecQuery.

See Also

SQLBind Function, SQLClose Function, SQLError Function, SQLExecQuery Function, SQLGetSchema Function, SQLOpen Function, SQLRequest Function, SQLRetrieveToFile Function.

Example

This example runs a query on the NWind sample database. The result of the query, displayed on Sheet1, is a list of all products that are currently on order.

If Application.OperatingSystem Like "*Win*" Then
    databaseName = "NWind"
Else        'Macintosh
    databaseName = "NorthWind"
End If
queryString = "SELECT * FROM product.dbf WHERE (product.ON_ORDER<>0)"
chan = SQLOpen("DSN=" & databaseName)
SQLExecQuery chan, queryString
Set output = Worksheets("Sheet1").Range("A1")
SQLRetrieve chan, output, , , True
SQLClose chan


SQLRetrieveToFile Function

Description

In Microsoft Excel for Windows 95, do not use SQLRetrieveToFile and the other ODBC functions in the XLODBC.XLA add-in; use the objects, methods, and properties in the Data Access Objects (DAO) library instead.

SQLRetrieveToFile retrieves all of the results from a previously executed query and places them in a file.

To use this function you must have established a connection with a data source using SQLOpen, executed a query using SQLExecQuery, and have the results of the query pending.

This function is contained in the XLODBC.XLA add-in (ODBC Add-In on the Macintosh). Before you use the function, you must establish a reference to the add-in using the References command (Tools menu).

Syntax

SQLRetrieveToFile(connectionNum, destination, colNamesLogical, columnDelimiter)

connectionNum

Required. The unique connection ID returned by SQLOpen and for which you have pending query results generated by SQLExecQuery.

If connectionNum is not valid, SQLExecQuery returns Error 2015.

destination

Required. A string that specifies the name and path of the file where you want to place the results. If the file exists, its contents are replaced with the query results. If the file does not exist, SQLRetrieveToFile creates and opens the file and fills it with the results.

The format of the data in the file is compatible with the Microsoft Excel .CSV (comma-separated value) file format.

Columns are separated by the character specified by columnDelimiter, and the individual rows are separated by a carriage return.

If the file specified by destination cannot be opened, SQLRetrieveToFile returns Error 2042.

colNamesLogical

Optional. True if you want the column names to be returned as the first row of data. False or omitted if you do not want the column names returned.

columnDelimiter

Optional. A string that specifies the character used to separate the elements in each row. For example, use "," to specify a comma delimiter or ";" to specify a semicolon delimiter. If you omit columnDelimiter, the list separator character is used.

Return Value

If successful, SQLRetrieveToFile returns the query results, writes them to a file, and then returns the number of rows that were written to the file.

If SQLRetrieveToFile is unable to retrieve the results, it returns Error 2042, and does not write the file.

If there are no pending results on the connection, SQLRetrieveToFile returns Error 2042.

Remarks

Before calling SQLRetrieveToFile, you must do the following:

1. Establish a connection with a data source using SQLOpen.

2. Use the connection ID returned by SQLOpen to send a query with SQLExecQuery.

See Also

SQLBind Function, SQLClose Function, SQLError Function, SQLExecQuery Function, SQLGetSchema Function, SQLOpen Function, SQLRequest Function, SQLRetrieve Function.

Example

This example runs a query on the NWind sample database. The result of the query, which is a list of all products that are currently on order, is written as a delimited text file, OUTPUT.TXT, in the current directory or folder.

If Application.OperatingSystem Like "*Win*" Then
    databaseName = "NWind"
Else        'Macintosh
    databaseName = "NorthWind"
End If
queryString = "SELECT * FROM product.dbf WHERE (product.ON_ORDER<>0)"
chan = SQLOpen("DSN=" & databaseName)
SQLExecQuery chan, queryString
SQLRetrieveToFile chan, "OUTPUT.TXT", True
SQLClose chan


Sqr Function

Description

Returns the square root of a number.

Syntax

Sqr(number)

The number named argument can be any valid numeric expression greater than or equal to 0.

Example

This example uses the Sqr function to calculate the square root of a number.

MySqr = Sqr(4)    ' Returns 2.
MySqr = Sqr(23)    ' Returns 4.795832.
MySqr = Sqr(0)    ' Returns 0.
MySqr = Sqr(-4)    ' Generates run-time error.


StandardFont Property

Applies To

Application Object.

Description

Returns or sets the standard font name as a string. Read-write.

Remarks

If you change the standard font using this property, the change does not take effect until you restart Microsoft Excel.

See Also

StandardFontSize Property.

Example

This example sets the standard font to Arial (in Windows) or Geneva (on the Macintosh).

If Application.OperatingSystem Like "*Macintosh*" Then
    Application.StandardFont = "Geneva"
Else
    Application.StandardFont = "Arial"
End If


StandardFontSize Property

Applies To

Application Object.

Description

Returns or sets the standard font size in points (1/72 inch). Read-write.

Remarks

If you change the standard font size using this property, the change does not take effect until you restart Microsoft Excel.

See Also

StandardFont Property.

Example

This example sets the standard font size to 12 points.

Application.StandardFontSize = 12


StandardHeight Property

Applies To

Worksheet Object.

Description

Returns the standard (default) height of all the rows in the worksheet, measured in points (1/72 inch). Read-only.

See Also

Height Property, RowHeight Property, StandardWidth Property.

Example

This example sets the height of row one on Sheet1 to the standard height.

Worksheets("Sheet1").Rows(1).RowHeight = _
    Worksheets("Sheet1").StandardHeight


StandardWidth Property

Applies To

Worksheet Object.

Description

Returns or sets the standard (default) width of all the columns in the worksheet, measured in characters of the normal font. Read-write.

Remarks

If the normal font is a proportional font, this property returns the column width measured in characters of the zero (0) character in the normal font.

See Also

ColumnWidth Property, StandardHeight Property, Width Property.

Example

This example sets the width of column one on Sheet1 to the standard width.

Worksheets("Sheet1").Columns(1).ColumnWidth = _
    Worksheets("Sheet1").StandardWidth


StartupPath Property

Applies To

Application Object.

Description

Returns the complete path of the startup directory, not including the final separator. Read-only.

Example

This example displays the full path to the Microsoft Excel startup folder.

MsgBox Application.StartupPath


Static Statement

Description

Used at the procedure level to declare variables and allocate storage space. Variables declared with the Static statement retain their value as long as the code is running.

Syntax

Static varname[([subscripts])][As type][,varname[([subscripts])][As type]] . . .

The Static statement syntax has these parts:

Part | Description
varname | Name of the variable; follows standard variable naming conventions.
subscripts | Dimensions of an array variable; up to 60 multiple dimensions may be declared. The subscripts argument uses the following syntax:
 | [lower To] upper [,[lower To] upper] . . .
type | Data type of the variable; may be Boolean, Integer, Long, Currency, Single, Double, Date, String (for variable-length strings), String * length (for fixed-length strings), Object, Variant, a user-defined type, or an object type. Use a separate As type clause for each variable being defined.

Remarks

Once the module code is running, variables declared with the Static statement retain their value until the module is reset or restarted. Use the Static statement in nonstatic procedures to explicitly declare Static variables.

Use a Static statement within a procedure to declare the data type of a Static variable. For example, the following statement declares a fixed-size array of integers:

Static EmployeeNumber(200) As Integer

If you do not specify a data type or object type, and there is no Def type statement in the module, the variable is Variant by default.

Note

The Static statement and the Static keyword affect the lifetime of variables differently. If you declare a procedure using the Static keyword (as in Static Sub CountSales ()), the storage space for all local variables within the procedure is allocated once and the value of the variables is preserved for the entire time the code is running. For nonstatic procedures, storage space for variables is allocated each time the procedure is called and released when the procedure is exited. The Static statement is used to declare variables within nonstatic procedures to preserve their value as long as the program is running.

When variables are initialized, a numeric variable is initialized to 0, a variable-length string is initialized to a zero-length string, and a fixed-length string is filled with zeros. Variant variables are initialized to Empty. Each element of a user-defined type variable is initialized as if it was a separate variable. A variable that refers to an object must be assigned an existing object using the Set statement before it can be used. Until it is assigned an object, the declared object variable has the special value Nothing, which indicates that it does not refer to any particular instance of an object.

Tip

When you use the Static statement in a procedure, it is a generally accepted programming practice to put the Static statement at the beginning of the procedure with any Dim statements.

See Also

Array Function, Dim Statement, Function Statement, Option Base Statement, Private Statement, Public Statement, ReDim Statement, Sub Statement.

Example

This example uses the Static statement to retain the value of a variable as long as module code is running.

' Function definition.
Function KeepTotal(Number)
    ' Only the variable Accumulate preserves its value between calls.
    Static Accumulate
    Accumulate = Accumulate + Number
    KeepTotal = Accumulate
End Function

' Static function definition.
Static Function MyFunction(Arg1, Arg2, Arg3)
    ' All local variables preserve value between function calls.
    Accumulate = Arg1 + Arg2 + Arg3
    Half = Accumulate / 2
    MyFunction = Half
End Function

This example uses the worksheet function Pmt to calculate a home mortgage loan payment. Note that this example uses the InputBox method instead of the InputBox function so that the method can perform type checking. The Static statements cause Visual Basic to retain the values of the three variables; these are displayed as default values the next time you run the example.

Static loanAmt
Static loanInt
Static loanTerm
loanAmt = Application.InputBox _
    (Prompt:="Loan amount (100,000 for example)", _
        Default:=loanAmt, Type:=1)
loanInt = Application.InputBox _
    (Prompt:="Annual interest rate (8.75 for example)", _
        Default:=loanInt, Type:=1)
loanTerm = Application.InputBox _
    (Prompt:="Term in years (30 for example)", _
        Default:=loanTerm, Type:=1)
payment = Application.Pmt(loanInt / 1200, loanTerm * 12, loanAmt)
MsgBox "Monthly payment is " & Format(payment, "Currency")


Status Property

Applies To

RoutingSlip Object.

Description

Indicates the status of the routing slip (one of xlNotYetRouted, xlRoutingInProgress, or xlRoutingComplete). Read-only.

Example

This example resets the routing slip for BOOK1.XLS if routing is complete.

With Workbooks("BOOK1.XLS").RoutingSlip
    If .Status = xlRoutingComplete Then
        .Reset
    Else
        MsgBox "Cannot reset routing; not yet complete."
    End If
End With


StatusBar Property

Applies To

Application Object, MenuItem Object, ToolbarButton Object.

Description

Returns or sets the text in the status bar. Read-write.

Remarks

For the Application object, this property returns False if Microsoft Excel has control of the status bar; set the property to False to restore the default status bar text. This works even if the status bar is hidden.

You can return or set the status bar text of custom menu items only, not built-in menu items.

Changing the macro assigned to a toolbar button with the OnAction property or the Assign Macro command (Tools menu) will reset the value of this property to match the status bar text of the macro.

See Also

DisplayStatusBar Property, HelpContextID Property, HelpFile Property.

Example

This example sets the status bar text to "Please be patient..." before it opens the workbook LARGE.XLS, and then it restores the text to the default.

oldStatusBar = Application.DisplayStatusBar
Application.DisplayStatusBar = True
Application.StatusBar = "Please be patient..."
Workbooks.Open filename:="LARGE.XLS"
Application.StatusBar = False
Application.DisplayStatusBar = oldStatusBar

This example adds a new menu item to the Help menu in the Visual Basic Module menu bar and then sets the status bar text, the Help filename, and the Help context ID for the new menu item (note that the HelpFile and HelpContextId properties are available only in Windows).

Set menuObj = MenuBars(xlModule).Menus("Help")
Set newMenuItem = menuObj.MenuItems.Add(Caption:="&Read Me First", _
        OnAction:="readmeMacro", _
        Before:=1)
newMenuItem.StatusBar = "Read this topic before you begin"
newMenuItem.HelpFile = "C:\xl5\vba_xl.hlp"
newMenuItem.HelpContextID = 65535


Stop Statement

Description

Suspends execution.

Syntax

Stop

Remarks

You can place Stop statements anywhere in procedures to suspend execution. Using the Stop statement is similar to setting a breakpoint in the code.

The Stop statement suspends execution, but unlike End, it doesn't close any files or clear variables.

See Also

End Statement.

Example

This example uses the Stop statement to suspend execution for each iteration through the For...Next loop.

For I = 1 To 10    ' Start For...Next loop.
    Debug.Print I    ' Print I to Debug window.
    Stop    ' Stop each time through.
Next I


Str Function

Description

Returns a string representation of a number.

Syntax

Str(number)

The number named argument is any valid numeric expression.

Remarks

When numbers are converted to strings, a leading space is always reserved for the sign of number. If number is positive, the returned string contains a leading space and the plus sign is implied.

Use the Format function to convert numeric values you want formatted as dates, times, or currency or in other user-defined formats. Unlike Str, the Format function doesn't include a leading space for the sign of number.

Note

The Str function recognizes only the period (.) as a valid decimal separator. When a possibility exists that different decimal separators may be used (for example, in international applications), you should use CStr to convert a number to a string.

See Also

Format Function.


StrComp Function

Description

Returns a value indicating the result of a string comparison.

Syntax

StrComp(string1,string2[,compare])

The StrComp function syntax has these parts:

Part | Description
string1 | Any valid string expression.
string2 | Any valid string expression.
compare | Number specifying the type of string comparison. Specify a 1 to perform a textual comparison. Specify a 0 (default) to perform a binary comparison. If compare is Null, an error occurs. If compare is omitted, the setting of Option Compare is used to determine the type of comparison.

Return Values

Value | Description
-1 | string1 is less than string2.
0 | string1 is equal to string2.
1 | string1 is greater than string2.
Null | string1 or string2 is Null.

Remarks

Note

When Option Compare Text is specified, comparisons are textual and case-insensitive. When Option Compare Binary is specified, comparisons are strictly binary.

See Also

Option Compare Statement.

Example

This example uses the StrComp function to return the results of a string comparison. If 1 is supplied as the third argument, a textual comparison is performed; whereas, if the third argument is 0 or omitted, a binary comparison is performed.

MyStr1 = "ABCD": MyStr2 = "abcd"    ' Define variables.
MyComp = StrComp(MyStr1, MyStr2, 1)    ' Returns 0.
MyComp = StrComp(MyStr1, MyStr2, 0)    ' Returns -1.
MyComp = StrComp(MyStr2, MyStr1)    ' Returns 1.


Strikethrough Property

Applies To

Font Object.

Description

True if the font is struck through. Read-write.

Example

This example sets the font in the active cell on Sheet1 to strikethrough.

Worksheets("Sheet1").Activate
ActiveCell.Font.Strikethrough = True


String Data Type

Description

There are two kinds of strings:

  • Variable-length strings, which can contain up to approximately 2 billion (2^31) characters (approximately 64K (2^16) characters for Microsoft Windows version 3.1 and earlier).
  • Fixed-length strings, which contain a declared number of characters (less than 64K).

The type-declaration character for String is $ (character code 36). The codes for String characters range from 0 to 255. The first 128 characters (0-127) of the character set correspond to the letters and symbols on a standard U.S. keyboard. These first 128 characters are the same as those defined by the ASCII character set. The second 128 characters (128-255) represent special characters, such as letters in international alphabets, accents, currency symbols, and fractions.

See Also

CStr Function, Data Type Summary, Def type Statements, String Function, Variant Data Type.


String Function

Description

Returns a repeating character string of the length specified.

Syntax

String(number,character)

The String function syntax has these named-argument parts:

Part | Description
number | Length of the returned string. If number contains no valid data, Null is returned.
character | Character code specifying the character or string expression whose first character is used to build the return string. If character contains no valid data, Null is returned.

Remarks

If you specify a number for character greater than 255, String converts the number to a valid character code using the formula:

character Mod 256

See Also

Space Function, String Data Type.

Example

This example uses the String function to return repeating character strings of the length specified.

MyString = String(5, "*")    ' Returns "*****".
MyString = String(5, 42)    ' Returns "*****".
MyString = String(10, "ABC")    ' Returns "AAAAAAAAAA".


Style Object

Description

Represents a range style description. The Style object contains all style attributes (font, number format, alignment, and so on) as properties. There are several built-in styles, including Normal, Currency, and Percent, which are listed in the Style Name box of the Style dialog box (Format menu). The Style object is a fast and efficient way to change several cell formatting properties on many cells at once.

Accessors

For a Range object, the Style property sets or returns the style used for that range. The following example applies the Percent style to cells A1:A10 on the worksheet named "Sheet1."

Worksheets("sheet1").Range("a1:a10").Style = "percent"

You can change the appearance of a cell by changing properties of the style applied to that cell. Keep in mind, however, that changing a style property will affect all cells already formatted with that style.

For the Workbook object, the Style object is a member of the Styles collection. The Styles collection contains all the defined styles for the workbook. Use the Add method to create a new style and add it to the collection. To access a single member of the collection, use the Styles method with the index number or name of the style as an argument.

Styles are sorted alphabetically by style name. The style index number represents the position of the specified style in the sorted list of style names. Styles(1) is the first style in the alphabetical list; Styles(Styles.Count) is the last. The following example creates a list of style names on worksheet one in the active workbook.

For i = 1 To ActiveWorkbook.Styles.Count
    Worksheets(1).Cells(i, 1) = ActiveWorkbook.Styles(i).Name
Next

You assign a name to a style when you create it. Use the Name property to return the style name. The following example changes the Normal style by setting its Bold property.

ActiveWorkbook.Styles("Normal").Font.Bold = True

For more information about creating and modifying a style, see the Styles object.

Properties

AddIndent Property, Application Property, Creator Property, Font Property, FormulaHidden Property, HorizontalAlignment Property, IncludeAlignment Property, IncludeBorder Property, IncludeFont Property, IncludeNumber Property, IncludePatterns Property, IncludeProtection Property, Interior Property, Locked Property, Name Property, NameLocal Property, NumberFormat Property, NumberFormatLocal Property, Orientation Property, Parent Property, Value Property, VerticalAlignment Property, WrapText Property.

Methods

Borders Method, Delete Method.


Style Property

Applies To

Range Object.

Description

Accessor. Returns a Style object that represents the style of the specified range. Read-only.

Example

This example applies the Normal style to cell A1 on Sheet1.

Worksheets("Sheet1").Range("A1").Style.Name = "Normal"

If cell B4 on Sheet1 currently has the Normal style applied, this example applies the Percent style.

If Worksheets("Sheet1").Range("B4").Style.Name = "Normal" Then
    Worksheets("Sheet1").Range("B4").Style.Name = "Percent"
End If


Styles Collection Object

Description

A collection of all the Style objects in the specified or active workbook. Each Style object represents a range style description. The Style object contains all style attributes (font, number format, alignment, and so on) as properties. There are several built-in styles, including Normal, Currency, and Percent, which are listed in the Style Name box of the Style dialog box (Format menu).

Accessors

Use the Add method to create a new style and add it to the collection. The following example creates a new style based on the Normal style, modifies the border and font, and then applies the new style to cells A25:A30.

Dim newStyle as Style
Set newStyle = ActiveWorkbook.Styles.Add(name:="bookman top border")
newStyle.Borders(xlTop).LineStyle = xlDouble
newStyle.Font.Bold = True
newStyle.Font.Name = "bookman"
Worksheets(1).Range("a25:a30").Style = "bookman top border"

Use the Styles method with an argument to access a single member of the collection or without an argument to access the entire collection at once.

Properties

Application Property, Count Property, Creator Property, Parent Property.

Methods

Add Method (Styles Collection), Item Method, Merge Method.


Styles Method

Applies To

Workbook Object.

Description

Accessor. Returns an object that represents a single style (a Style object, Syntax 1) or a collection of all the styles (a Styles object, Syntax 2) in the workbook. Read-only.

Syntax 1

object.Styles(index)

Syntax 2

object.Styles

object

Required. The Workbook object.

index

Required for Syntax 1. The name or number of the style to return.

Example

This example deletes the user-defined style "Stock Quote Style" from the active workbook.

ActiveWorkbook.Styles("Stock Quote Style").Delete


Sub Statement

Description

Declares the name, arguments, and code that form the body of a Sub procedure.

Syntax

[Private | Public][Static] Sub name [(arglist)]
[statements]
[Exit Sub]
[statements]
End Sub

The Sub statement syntax has these parts:

Part | Description
Public | Indicates that the Sub procedure is accessible to all other procedures in all modules. If used in a private module (one that contains an Option Private statement) the procedure is not available outside the project.
Private | Indicates that the Sub procedure is accessible only to other procedures in the module where it is declared.
Static | Indicates that the Sub procedure's local variables are preserved between calls. The Static attribute doesn't affect variables that are declared outside the Sub, even if they are used in the procedure.
name | Name of the Sub; follows standard variable naming conventions.
arglist | List of variables representing arguments that are passed to the Sub procedure when it is called. Multiple variables are separated by commas.
statements | Any group of statements to be executed within the body of the Sub procedure.

The arglist argument has the following syntax and parts:

[[Optional][ByVal | ByRef][ParamArray] varname[( )] As type]

Part | Description
Optional | Indicates that an argument is not required. If used, all subsequent arguments in arglist must also be optional and declared using the Optional keyword. All Optional arguments must be Variant. Optional can't be used for any argument if ParamArray is used.
ByVal | Indicates that the argument is passed by value.
ByRef | Indicates that the argument is passed by reference.
ParamArray | Used only as the last argument in arglist to indicate that the final argument is an Optional array of Variant elements. The ParamArray keyword allows you to provide an arbitrary number of arguments. May not be used with ByVal, ByRef, or Optional.
varname | Name of the variable representing the argument; follows standard variable naming conventions.
type | Data type of the argument passed to the procedure; may be Boolean, Integer, Long, Currency, Single, Double, Date, String (variable length only), Object, Variant, a user-defined type, or an object type.

Remarks

If not explicitly specified using either Public or Private, Sub procedures are Public by default. If Static is not used, the value of local variables is not preserved between calls.

All executable code must be in procedures. You can't define a Sub procedure inside another Sub, Function, or Property procedure.

The Exit Sub keyword causes an immediate exit from a Sub procedure. Program execution continues with the statement following the statement that called the Sub procedure. Any number of Exit Sub statements can appear anywhere in a Sub procedure.

Like a Function procedure, a Sub procedure is a separate procedure that can take arguments, perform a series of statements, and change the value of its arguments. However, unlike a Function procedure, which returns a value, a Sub procedure can't be used in an expression.

You call a Sub procedure using the procedure name followed by the argument list. See the Call statement for specific information on how to call Sub procedures.

Caution

Sub procedures can be recursive; that is, they can call themselves to perform a given task. However, recursion can lead to stack overflow. The Static keyword usually is not used with recursive Sub procedures.

Variables used in Sub procedures fall into two categories: those that are explicitly declared within the procedure and those that are not. Variables that are explicitly declared in a procedure (using Dim or the equivalent) are always local to the procedure. Other variables used but not explicitly declared in a procedure are also local unless they are explicitly declared at some higher level outside the procedure.

Caution

A procedure can use a variable that is not explicitly declared in the procedure, but a name conflict can occur if anything you have defined at the module level has the same name. If your procedure refers to an undeclared variable that has the same name as another procedure, constant or variable, it is assumed that your procedure is referring to that module-level name. Explicitly declare variables to avoid this kind of conflict. You can use an Option Explicit statement to force explicit declaration of variables.

Note

You can't use GoSub, GoTo, or Return to enter or exit a Sub procedure.

See Also

Call Statement, Dim Statement, Function Statement, Option Explicit Statement, Property Get Statement, Property Let Statement, Property Set Statement, Static Statement.

Example

This example uses the Sub statement to declare the name, arguments and code that form the body of a Sub procedure.

' Sub procedure definition.
Sub SubComputeArea(Length, Width)    ' Sub with two arguments.
    Dim Area As Double    ' Declare local variable.
    If Length = 0 Or Width = 0 Then    ' If either argument = 0.
        Exit Sub    ' Exit Sub immediately.
    End If
    Area = Length * Width    ' Calculate area of rectangle.
    Debug.Print Area    ' Print Area to Debug window.
End Sub


Subject Property

Applies To

AddIn Object, Mailer Object, RoutingSlip Object, Workbook Object.

Description

Returns or sets the subject for the object, as a string. Read-only for AddIn, read-write for RoutingSlip and Workbook.

Remarks

In Microsoft Excel for Windows 95, this property has been replaced by a built-in OLE document property. For more information about OLE document properties, see BuiltinDocumentProperties.

The subject for the RoutingSlip object is used as the subject of mail messages used to route the workbook. PowerTalk requires that a subject be present before the mailer can be sent.

You cannot use this property with an AddIn object that represents an XLL file or an add-in that was created with the Microsoft Excel 4.0 macro language.

See Also

Author Property, Comments Property, Keywords Property, Title Property.

Example

This example sets the subject for the active workbook.

ActiveWorkbook.Subject = "Data for my presentation in April"

This example sets the subject for a routing slip for the workbook BOOK1.XLS. To run this example, you must have Microsoft Mail for Windows or Microsoft Mail for the Macintosh installed.

Workbooks("BOOK1.XLS").HasRoutingSlip = True
With Workbooks("BOOK1.XLS").RoutingSlip
    .Delivery = xlOneAfterAnother
    .Recipients = Array("Adam Bendel", "Jean Selva", "Bernard Gabor")
    .Subject = "Here is BOOK1.XLS"
    .Message = "Here is the workbook. What do you think?"
End With
Workbooks("BOOK1.XLS").Route

This example sets the subject for a mailer in the PowerTalk mail system (Macintosh only). To run this example, you must have the PowerTalk mail system installed.

With Workbooks(1)
    .HasMailer = True
    With .Mailer
        .Subject = "Here is the workbook"
        .ToRecipients = Array("Jean")
        .CCRecipients = Array("Adam", "Bernard")
        .BCCRecipients = Array("Chris")
        .Enclosures = Array("TestFile")
    End With
    .SendMailer
End With


SubscribeTo Method

Applies To

Range Object.

Description

Apple Macintosh (running System 7 or later) only. Subscribes to a published edition.

Syntax

object.SubscribeTo(edition, format)

object

Required. The Range object.

edition

Required. The name of the edition, as a string, to which you want to subscribe.

format

Optional. xlPicture to subscribe to a picture, xlText to subscribe to text.

See Also

CreatePublisher Method.

Example

This example subscribes to the "stock data" publisher.

Worksheets("Sheet1").Range("D1").SubscribeTo "stock data"


Subscript Property

Applies To

Font Object.

Description

True if the font is subscripted. Read-write.

Remarks

This property is False by default.

See Also

Characters Object, Superscript Property.

Example

This example makes the second character in cell A1 a subscript.

Worksheets("Sheet1").Range("A1").Characters(2, 1).Font.Subscript = True


Subtotal Method

Applies To

Range Object.

Description

Creates subtotals for the range (or current region if the range is a single cell).

For help about using the Subtotal worksheet function in Visual Basic, see "Using Worksheet Functions in Visual Basic" in online Help.

Syntax

object.Subtotal(groupBy, function, totalList, replace, pageBreaks, summaryBelowData)

object

Required. The Range object.

groupBy

Required. The field to group by, as a one-based integer offset. For more information, see the example.

function

Required. The subtotal function. Can be one of xlAverage, xlCount, xlCountNums, xlMax, xlMin, xlProduct, xlStDev, xlStDevP, xlSum, xlVar, or xlVarP.

totalList

Required. An array of one-based field offsets, indicating the fields to which the subtotals are added. For more information, see the example.

replace

Optional. If True, existing subtotals are replaced. If False or omitted, existing subtotals are not replaced.

pageBreaks

Optional. True to create page breaks after each group, False or omitted if no page breaks are created.

summaryBelowData

Optional. If xlBelow or omitted, the summary goes below detail. If xlAbove, the summary goes above detail.

See Also

RemoveSubtotal Method.

Example

This example creates subtotals for the selection on Sheet1. The subtotals are sums grouped by each change in field one, with the subtotals added to fields two and three.

Worksheets("Sheet1").Activate
Selection.Subtotal groupBy:=1, function:=xlSum, _
    totalList:=Array(2, 3)


Subtotals Property

Applies To

PivotField Object.

Description

Returns or sets an array of Boolean values corresponding to the subtotals showing with the specified field. This property is valid only for non-data fields. Read-write.

Remarks

This property returns an array of Boolean values, as shown in the following table.

Array element | Meaning
1 | Automatic
2 | Sum
3 | Count
4 | Average
5 | Max
6 | Min
7 | Product
8 | Count Nums

Array element | Meaning
9 | StdDev
10 | StdDevp
11 | Var
12 | Varp

If an element is True, the field shows that subtotal. If element one (Automatic) is True, all other values are set to False.

Example

This example sets the field that contains the active cell to show Sum subtotals.

Worksheets("Sheet1").Activate
ActiveCell.PivotField.Subtotals = _
    Array(False, True, False, False, False, False, _
    False, False, False, False, False, False)


SubType Property

Applies To

Chart Object, ChartGroup Object.

Description

Returns or sets the subtype for a single chart group or for all chart groups in the chart. Read-write.

Remarks

Set the SubType property after you set the Type property. Each type supports different subtypes (for example, a column chart type can have clustered, stacked, or percent subtypes). The easiest way to obtain the number of the subtype is to record the subtype formatting using the macro recorder.

Example

This example sets the subtype for radar group one in Chart1. The example should be run on a 2-D chart.

Charts("Chart1").RadarGroups(1).SubType = 2


Summary Property

Applies To

Range Object.

Description

True if the range is an outlining summary row or column. The range should be a row or a column. Read-only.

Example

This example formats row four on Sheet1 as bold and italic if it is an outlining summary column.

With Worksheets("Sheet1").Rows(4)
    If .Summary = True Then
        .Font.Bold = True
        .Font.Italic = True
    End If
End With


SummaryColumn Property

Applies To

Outline Object.

Description

Returns or sets the location of the summary columns in the outline, as shown in the following table. Read-write.

Value | Meaning
xlLeft | The summary column will be to the left of the detail columns in the outline.
xlRight | The summary column will be to the right of the detail columns in the outline.

Example

This example creates an outline with automatic styles, the summary row above the detail rows, and the summary column to the right of the detail columns.

Worksheets("Sheet1").Activate
Selection.AutoOutline
With ActiveSheet.Outline
    .SummaryRow = xlAbove
    .SummaryColumn = xlRight
    .AutomaticStyles = True
End With


SummaryRow Property

Applies To

Outline Object.

Description

Returns or sets the location of the summary rows in the outline, as shown in the following table. Read-write.

Value | Meaning
xlAbove | The summary row will be above the detail columns in the outline.
xlBelow | The summary row will be below the detail columns in the outline.

Remarks

Set SummaryRow to xlAbove for Microsoft Word-style outlines, where category headers are above the detail. Set SummaryRow to xlBelow for accounting-style outlines, where summations are below the detailed information.

Example

This example creates an outline with automatic styles, the summary row above the detail rows, and the summary column to the right of the detail columns.

Worksheets("Sheet1").Activate
Selection.AutoOutline
With ActiveSheet.Outline
    .SummaryRow = xlAbove
    .SummaryColumn = xlRight
    .AutomaticStyles = True
End With


Superscript Property

Applies To

Font Object.

Description

True if the font is superscripted. Read-write.

Remarks

This property is False by default.

See Also

Characters Object, Subscript Property.

Example

This example makes the last character in cell A1 a superscript.

n = Worksheets("Sheet1").Range("A1").Characters.Count
Worksheets("Sheet1").Range("A1").Characters(n, 1).Font.Superscript = _
            True


SurfaceGroup Property

Applies To

Chart Object.

Description

Accessor. Returns a ChartGroup object that represents the surface chart group of a 3-D chart. Read-only.

Example

This example converts the 3-D surface group in Chart1 to a 3-D area group. The example should be run on a 3-D chart.

Charts("Chart1").SurfaceGroup.Type = xl3DArea


Tab Function

Description

Used with the Print # statement or the Print method to position output.

Syntax

Tab[(n)]

The n argument is the column number to tab to before displaying or printing the next expression in a list. If omitted, Tab moves the cursor to the beginning of the next print zone. This allows Tab to be used instead of a comma in locales where the comma is used as a decimal separator.

Remarks

If the current print position on the current line is greater than n, Tab skips to the nth column on the next output line. If n is less than 1, Tab moves the print position to column 1. If n is greater than the output-line width, Tab calculates the next print position using the formula:

n Mod width

For example, if width is 80 and you specify Tab(90), the next print will start at column 10 (the remainder of 90/80). If n is less than the current print position, printing begins on the next line at the calculated print position. If the calculated print position is greater than the current print position, printing begins at the calculated print position on the same line.

The leftmost print position on an output line is always 1. When you use the Print # statement to print to files, the rightmost print position is the current width of the output file, which you can set using the Width # statement.

Note

Make sure your tabular columns are wide enough to accommodate wider letters.

When you use the Tab function with the Print method, the print surface is divided into uniform, fixed-width columns. The width of each column is an average of the width of all characters in the point size for the chosen font. However, there is no correlation between the number of characters printed and the number of fixed-width columns those characters occupy. For example, the uppercase letter W occupies more than one fixed-width column and the lowercase letter I occupies less.

See Also

Print # Statement, Print Method, Space Function, Spc Function, Width # Statement.

Example

This example uses the Tab function to position output in a file or in the Debug window.

' The Tab function can be used with the Print # statement.
Open "TESTFILE" For Output As #1    ' Open file for output.
' The second word prints at column 20.
Print #1, "Hello"; Tab(20); "World."
' If the argument is omitted, cursor is moved to the next print zone.
Print #1, "Hello"; Tab ; "World"
Close #1    ' Close file.

' The Tab function can also be used with the Print method.
' The following statement prints text starting at column 10.
Debug.Print Tab(10); "10 columns from start."


Table Method

Applies To

Range Object.

Description

Creates a data table based on input values and formulas that you define on a worksheet.

Syntax

object.Table(rowInput, columnInput)

object

Required. The object to which this method applies.

rowInput

Optional. A single cell to use as the row input for your table.

columnInput

Optional. A single cell to use as the column input for your table.

Remarks

Use data tables to perform a what-if analysis by changing certain constant values on your worksheet to see how values in other cells are affected.

Example

This example creates a formatted multiplication table in cells A1:K11 on Sheet1.

Set dataTableRange = Worksheets("Sheet1").Range("A1:K11")
Set rowInputCell = Worksheets("Sheet1").Range("A12")
Set columnInputCell = Worksheets("Sheet1").Range("A13")

Worksheets("Sheet1").Range("A1").Formula = "=A12*A13"
For i = 2 To 11
    Worksheets("Sheet1").Cells(i, 1) = i - 1
    Worksheets("Sheet1").Cells(1, i) = i - 1
Next i
dataTableRange.Table rowInputCell, columnInputCell
With Worksheets("Sheet1").Range("A1").CurrentRegion
    .Rows(1).Font.Bold = True
    .Columns(1).Font.Bold = True
    .Columns.AutoFit
End With


TableRange1 Property

Applies To

PivotTable Object.

Description

Accessor. Returns a Range object that represents the range that contains the entire PivotTable, but does not include page fields. Read-only.

Remarks

The TableRange2 property includes page fields.

Example

This example selects the PivotTable, except that its page fields are not selected.

Worksheets("Sheet1").Activate
Range("A3").PivotTable.TableRange1.Select


TableRange2 Property

Applies To

PivotTable Object.

Description

Accessor. Returns a Range object that represents the range that includes the entire PivotTable, including page fields. Read-only.

Remarks

The TableRange1 property does not include page fields.

Example

This example selects the PivotTable, including its page fields.

Worksheets("Sheet1").Activate
Range("A3").PivotTable.TableRange2.Select


TabRatio Property

Applies To

Window Object.

Description

Returns or sets the ratio of the width of the workbook tab area to the width of the window horizontal scroll bar (as a number between 0 (zero) and 1; the default value is 0.75). Read-write.

Remarks

This property has no effect when DisplayWorkbookTabs is set to False (its value is retained, but it has no effect on the display).

See Also

DisplayHorizontalScrollBar Property, DisplayWorkbookTabs Property.

Example

This example makes the workbook tabs half the width of the horizontal scroll bar.

ActiveWindow.TabRatio = 0.5


Tan Function

Description

Returns the tangent of an angle.

Syntax

Tan(number)

The number named argument can be any valid numeric expression that expresses an angle in radians.

Remarks

Tan takes an angle and returns the ratio of two sides of a right triangle. The ratio is the length of the side opposite an angle divided by the length of the side adjacent to the angle.

To convert degrees to radians, multiply degrees by pi/180. To convert radians to degrees, multiply radians by 180/pi.

See Also

Atn Function, Cos Function, Derived Math Functions, Sin Function.

Example

This example uses the Tan function to return the tangent of an angle.

MyAngle = 1.3    ' Define angle in radians.
MyCotangent = 1 / Tan(MyAngle)    ' Calculate cotangent.


TemplatesPath Property

Applies To

Application Object.

Description

Returns the local path where templates are stored. This property is available only in Microsoft Excel for Windows 95. Read-only.

Example

This example returns the path where templates are stored.

Msgbox Application.TemplatesPath


Text Property

Applies To

AxisTitle Object, Button Object, Buttons Collection, Characters Object, ChartTitle Object, CheckBox Object, DataLabel Object, DialogFrame Object, DrawingObjects Collection, DropDown Object, DropDowns Collection, EditBox Object, EditBoxes Collection, GroupBox Object, GroupBoxes Collection, Label Object, Labels Collection, OptionButton Object, OptionButtons Collection, Range Object, TextBox Object, TextBoxes Collection.

Description

Returns or sets the text for the specified object, as shown in the following table. Read-write, except for the Range object, where this property is read-only. The Text property will not work with a drop-down, but it will work with a combination drop-down edit.

Object | Text
AxisTitle, ChartTitle | The title text.
Button | The button text.
Characters | The text of this range of characters.
Controls | The control text (check box, dialog frame, drop down, edit box, group box, label, and option button).
DataLabel | The data label text.
Range | The actual text appearing in a cell, as a string. For example, if a cell is formatted to show dollar signs, returning the text of a cell will show the dollar sign. This can be used to create readable text representations of the values on a worksheet. Read-only.
TextBox | The text in the text box.

Example

This example sets the text in text box one on Sheet1. Existing text, if any, is deleted before the new text is set.

Worksheets("Sheet1").TextBoxes(1).Text = "This is a test"

This example sets the text for the chart title of Chart1.

With Charts("Chart1")
    .HasTitle = True
    .ChartTitle.Text = "First Quarter Sales"
End With

This example sets the axis title text for the category axis in Chart1.

With Charts("Chart1").Axes(xlCategory)
    .HasTitle = True
    .AxisTitle.Text = "Month"
End With

This example replaces the text of the label named "Label 1" on the dialog sheet Dialog1 with the current date and time.

DialogSheets("Dialog1").Labels("Label 1").Text = Now()

This example erases the text on every button on Sheet1.

Worksheets("Sheet1").Buttons.Text = ""

This example illustrates the difference between the Text and Value properties of cells that contain formatted numbers.

Set c = Worksheets("Sheet1").Range("B14")
c.Value = 1198.3
c.NumberFormat = "$#,##0_);($#,##0)"
MsgBox c.Value
MsgBox c.Text

For help about using the Text worksheet function in Visual Basic, see "Using Worksheet Functions in Visual Basic" in online Help.


TextBox Object

Description

Represents a text box graphic object (a rectangle with text in it) on a chart sheet, dialog sheet, or worksheet.

Accessors

The TextBox object is a member of the TextBoxes collection. The TextBoxes collection contains all the TextBox objects on a single sheet. Use the Add method to create a new text box and add it to the collection.

To access a single member of the collection, use the TextBoxes method with the index number or name of the text box as an argument.

The following example sets the formula for text box one on the worksheet named "Sheet1." This links the text box to cell A10 on the worksheet. When the contents of cell A10 change, the new contents are placed in the text box.

Worksheets("sheet1").TextBoxes(1).Formula = "=a10"

The text box name is shown in the Name Box when the text box is selected. Use the Name property to set or return the name. The following example places a dashed border around the text box named "Text 1" on the worksheet named "Sheet1."

Worksheets("sheet1").TextBoxes("text 1").Border.LineStyle = xlDash

Properties

AddIndent Property, Application Property, AutoSize Property, Border Property, BottomRightCell Property, Caption Property, Creator Property, Enabled Property, Font Property, Formula Property, Height Property, HorizontalAlignment Property, Index Property, Interior Property, Left Property, Locked Property, LockedText Property, Name Property, OnAction Property, Orientation Property, Parent Property, Placement Property, PrintObject Property, RoundedCorners Property, Shadow Property, Text Property, Top Property, TopLeftCell Property, VerticalAlignment Property, Visible Property, Width Property, ZOrder Property.

Methods

BringToFront Method, Characters Method, CheckSpelling Method, Copy Method, CopyPicture Method, Cut Method, Delete Method, Duplicate Method, Select Method, SendToBack Method.


TextBoxes Collection Object

Description

A collection of all the TextBox objects (rectangles with text inside) on the specified chart sheet, dialog sheet, or worksheet.

Accessors

Use the Add method to create a new text box and add it to the collection. The following example creates a new text box on the worksheet named "Sheet1." The new text box is twice as wide and three times as high as cell C5; its upper-left corner is positioned at the upper-left corner of cell C5.

Dim r As Range
Set r = Worksheets("sheet1").Range("c5")
Worksheets("sheet1").TextBoxes.Add r.Left, r.Top, _
    2 * r.Width, 3 * r.Height

Use the TextBoxes method with an argument to access a single member of the collection or without an argument to access the entire collection at once. The following example deletes all of the text boxes on the worksheet named "Sheet1."

Worksheets("sheet1").TextBoxes.Delete

Properties

AddIndent Property, Application Property, AutoSize Property, Border Property, Caption Property, Count Property, Creator Property, Enabled Property, Font Property, Formula Property, Height Property, HorizontalAlignment Property, Interior Property, Left Property, Locked Property, LockedText Property, OnAction Property, Orientation Property, Parent Property, Placement Property, PrintObject Property, RoundedCorners Property, Shadow Property, Text Property, Top Property, VerticalAlignment Property, Visible Property, Width Property, ZOrder Property.

Methods

Add Method (Graphic Objects and Controls), BringToFront Method, Characters Method, CheckSpelling Method, Copy Method, CopyPicture Method, Cut Method, Delete Method, Duplicate Method, Group Method, Item Method, Select Method, SendToBack Method.


TextBoxes Method

Applies To

Chart Object, DialogSheet Object, Worksheet Object.

Description

Accessor. Returns an object that represents a single text box (a TextBox object, Syntax 1) or a collection of text boxes (a TextBoxes object, Syntax 2) on the sheet. Read-only.

Syntax 1

object.TextBoxes(index)

Syntax 2

object.TextBoxes

object

Required. The object containing the text boxes.

index

Required for Syntax 1. The name or number of the text box.

Example

This example sets the text that appears in text box one on Sheet1.

Worksheets("Sheet1").TextBoxes(1).Caption = "Text Box One"

This example deletes all text boxes on Sheet1.

Worksheets("Sheet1").TextBoxes.Delete


TextToColumns Method

Applies To

Range Object.

Description

Parses a column of cells containing text into several columns

Syntax

object.TextToColumns(destination, dataType, textQualifier, consecutiveDelimiter, tab, semicolon, comma, space, other, otherChar, fieldInfo)

object

Required. The Range object.

destination

Optional. A range that specifies where Microsoft Excel will place the results. If the range is larger than a single cell, the top leftmost cell is used.

dataType

Optional. Specifies the format of the text to split into columns. Can be either xlDelimited or xlFixedWidth. The default is xlDelimited.

textQualifier

Optional. Specifies the text qualifier. Can be one of xlDoubleQuote, xlSingleQuote, or xlNone. The default is xlDoubleQuote.

consecutiveDelimiter

Optional. True if consecutive delimiters should be considered as one delimiter. The default is False.

tab

Optional. True if dataType is xlDelimited and the tab character is a delimiter. The default is False.

semicolon

Optional. True if dataType is xlDelimited and the semicolon character is a delimiter. The default is False.

comma

Optional. True if dataType is xlDelimited and the comma character is a delimiter. The default is False.

space

Optional. True if dataType is xlDelimited and the space character is a delimiter. The default is False.

other

Optional. True if dataType is xlDelimited and the character specified by the otherChar argument is a delimiter. The default is False.

otherChar

Optional (required if other is True). Specifies the delimiter character when other is True. If more than one character is specified, only the first character of the string is used, remaining characters are ignored.

fieldInfo

Optional. An array containing parse information for the individual columns of data. The interpretation depends on the value of dataType.

When the data is delimited, this argument is an array of two-element arrays, with each two-element array specifying the conversion options for a particular column. The first element is the column number (one based), and the second element is one of the following numbers specifying how the column is parsed:

1 General

2 Text

3 MDY date

4 DMY date

5 YMD date

6 MYD date

7 DYM date

8 YDM date

9 Skip the column

The column specifiers may be in any order. If a column specifier is not present for a particular column in the input data, the column is parsed using the General setting. This example causes the third column to be skipped, the first column to be parsed as text, and the remaining columns in the source data to be parsed with the General setting.

Array(Array(3, 9), Array(1, 2))

If the source data has fixed-width columns, the first element of each two-element array specifies the starting character position in the column (as an integer; character zero is the first character). The second element of the two-element array specifies the parse option for the column as a number from one through nine, as listed above.

The following example parses two columns from a fixed-width file, with the first column starting at the beginning of the line and extending for 10 characters. The second column starts at position 15 and goes to the end of the line. To avoid including the characters between position 10 and position 15, a skipped column entry is added.

Array(Array(0, 1), Array(10, 9), Array(15, 1))

See Also

OpenText Method.

Example

This example converts the contents of the Clipboard, which contains a space-delimited text table, into separate columns on Sheet1. You can create a simple space-delimited table in Notepad or WordPad (or another text editor), copy the text table to the Clipboard, switch to Microsoft Excel, and then run this example.

Worksheets("Sheet1").Activate
ActiveSheet.Paste
Selection.TextToColumns DataType:=xlDelimited, _
    consecutiveDelimiter:=True, Space:=True


ThisWorkbook Property

Applies To

Application Object.

Description

Accessor. Returns a Workbook object that represents the workbook where the current macro code is running. Read-only.

Remarks

Use this property to refer to the workbook containing your macro code. ThisWorkbook is the only way to refer to an add-in workbook from inside the add-in itself. The ActiveWorkbook property does not return the add-in workbook (it returns the workbook calling the add-in), and the Workbooks method may fail because the workbook name probably changed when you created the add-in. ThisWorkbook always returns the workbook where the code is running.

For example, use the following code to activate a dialog sheet stored in your add-in workbook.

ThisWorkbook.DialogSheets(1).Show

This property can be used only from inside Microsoft Excel. You cannot use this property to access a workbook from another application.

Example

This example closes the workbook that contains the example code. Changes to the workbook, if any, are not saved.

ThisWorkbook.Close savechanges:=False


TickLabelPosition Property

Applies To

Axis Object.

Description

Describes the position of tick labels on the specified axis (one of xlNone, xlLow, xlHigh, or xlNextToAxis). Read-write.

See Also

MajorTickMark Property, MinorTickMark Property, TickLabels Property, TickLabelSpacing Property, TickMarkSpacing Property.

Example

This example sets tick labels on the category axis in Chart1 to the high position (above the chart).

Charts("Chart1").Axes(xlCategory).TickLabelPosition = xlHigh


TickLabels Object

Description

Represents the tick-mark labels associated with tick marks on a chart axis. There is no single TickLabel object; you must access all of the tick-mark labels at once.

Tick-mark label text for the category (x) axis comes from the name of the associated category in the chart. The default tick-mark label text for the category (x) axis is the number indicating the position of the category from the left. To change the number of unlabelled tick marks between tick-mark labels, you must change the TickLabelSpacing property for the category (x) axis.

Tick-mark label text for the value (y) axis is calculated based on the MajorUnit, MinimumScale, and MaximumScale properties of the value (y) axis. You must change the values of these properties to change the tick-mark label text for the value (y) axis.

Accessors

Use the TickLabels property to return the tick-mark labels for an axis. The following example sets the number format for the tick-mark labels on the value (y) axis in embedded chart one on the worksheet named "Sheet1."

Worksheets("sheet1").ChartObjects(1).Chart _
    .Axes(xlValue).TickLabels.NumberFormat = "0.00"

Properties

Application Property, Creator Property, Font Property, Name Property, NumberFormat Property, NumberFormatLinked Property, Orientation Property, Parent Property.

Methods

Delete Method, Select Method.


TickLabels Property

Applies To

Axis Object.

Description

Accessor. Returns a TickLabels object that represents the tick labels for the specified axis. Read-only.

See Also

MajorTickMark Property, MinorTickMark Property, TickLabelPosition Property, TickLabelSpacing Property, TickMarkSpacing Property.

Example

This example sets the color of the tick label font for the value axis in Chart1.

Charts("Chart1").Axes(xlValue).TickLabels.Font.ColorIndex = 3


TickLabelSpacing Property

Applies To

Axis Object.

Description

Returns or sets the number of categories or series between tick labels. Applies only to category and series axes. Read-write.

Remarks

This property applies to the category and series axes only. Label spacing on the value axis is always calculated by Microsoft Excel.

See Also

MajorTickMark Property, MinorTickMark Property, TickLabelPosition Property, TickLabels Property, TickMarkSpacing Property.

Example

This example sets the number of categories between tick labels on the category axis in Chart1.

Charts("Chart1").Axes(xlCategory).TickLabelSpacing = 10


TickMarkSpacing Property

Applies To

Axis Object.

Description

Returns or sets the number of categories or series between tick marks. Applies only to category and series axes. Read-write.

Remarks

This property applies to the category and series axes only. Use the MajorUnit and MinorUnit properties to set tick mark spacing on the value axis.

See Also

MajorTickMark Property, MajorUnit Property, MinorTickMark Property, MinorUnit Property, TickLabelPosition Property, TickLabels Property, TickLabelSpacing Property.

Example

This example sets the number of categories between tick marks on the category axis in Chart1.

Charts("Chart1").Axes(xlCategory).TickMarkSpacing = 10


Time Function

Description

Returns the current system time.

Syntax

Time

Remarks

To set the system time, use the Time statement.

See Also

Date Function, Date Statement, Time Statement, Timer Function.

Example

This example uses the Time function to return the current system time.

MyTime = Time    ' Return current system time.


Time Statement

Description

Sets the system time.

Syntax

Time = time

The time argument is limited to expressions that can represent a time. If time contains no valid data, Null is returned.

Remarks

If time is a string, Time attempts to convert it to a time using the time separators you specified for your system. If it can't be converted to a valid time, an error occurs.

Note

If you use the Time statement to set the time on computers using versions of MS-DOS earlier than version 3.3, the change remains in effect only until you change it again or turn off your computer. Many computers have a battery-powered CMOS RAM that retains date and time information when the computer is turned off. However, to permanently change the time on computers running earlier versions of MS-DOS, you may have to use your Setup disk or perform some equivalent action. Refer to the documentation for your particular system.

See Also

Date Function, Date Statement, Time Function.

Example

This example uses the Time statement to set the computer system time to a user-defined time.

MyTime = #4:35:17 PM#    ' Assign a time.
Time = MyTime    ' Set system time to MyTime.


Timer Function

Description

Returns the number of seconds elapsed since midnight.

Syntax

Timer

Remarks

The return value of the Timer function is automatically used with the Randomize statement to generate a seed for the Rnd (random-number) function.

See Also

Randomize Statement, Rnd Function, Time Function.

Example

This example uses the Timer function to record the number of seconds taken to print output to the Debug window.

Start = Timer    ' Set start time.
For I = 1 to 50    ' Loop 50 times.
    Debug.Print I    ' Print to Debug window.
Next I
Finish = Timer    ' Set end time.
TotalTime = Finish - Start    ' Calculate total time.


TimeSerial Function

Description

Returns a date containing the time for a specific hour, minute, and second.

Syntax

TimeSerial(hour,minute,second)

The TimeSerial function syntax has these named-argument parts:

Part | Description
hour | Number between 0 (12:00 A.M.) and 23 (11:00 P.M.), inclusive, or a numeric expression.
minute | Number between 0 and 59, inclusive, or a numeric expression.
second | Number between 0 and 59, inclusive, or a numeric expression.

Remarks

To specify a time, such as 11:59:59, the range of numbers for each TimeSerial argument should be in the normally accepted range for the unit; that is, 0-23 for hours and 0-59 for minutes and seconds. However, you can also specify relative times for each argument using any numeric expression that represents some number of hours, minutes, or seconds before or after a certain time. The following example uses expressions instead of absolute time numbers. The TimeSerial function returns a time for 15 minutes before (0 - 15) six hours before noon (12 - 6), or 5:45:00 A.M.

TimeSerial(12 - 6, 0 - 15, 0)

If the time specified by the three arguments, either directly or by expression, falls outside the acceptable range of times, an error occurs.

See Also

DateSerial Function, DateValue Function, Hour Function, Minute Function, Now Function, Second Function, TimeValue Function.

Example

This example uses the TimeSerial function to return a time for the specified hour, minute and second.

' MyTime contains the time for 4:35:17 PM
MyTime = TimeSerial(16, 35, 17)    ' Return time.


TimeValue Function

Description

Returns a time.

Syntax

TimeValue(time)

The time named argument is normally a string expression representing a time from 0:00:00 (12:00:00 A.M.) to 23:59:59 (11:59:59 P.M.), inclusive. However, time can also be any expression that represents a time in that range. If time contains no valid data, Null is returned.

Remarks

You can enter valid times using a 12- or 24-hour clock. For example, "2:24PM" and "14:24" are both valid time arguments.

If the time argument contains date information, TimeValue doesn't this information. However, if time includes invalid date information, an error occurs.

See Also

DateSerial Function, DateValue Function, Hour Function, Minute Function, Now Function, Second Function, TimeSerial Function.

Example

This example uses the TimeValue function to convert a string to a time. In general, it is bad programming practice to hard code dates/ times as strings as shown in this example. Use date literals instead.

MyTime = TimeValue("4:35:17 PM")    ' Return time.


Title Property

Applies To

AddIn Object, Workbook Object.

Description

Returns or sets the long, descriptive title for the object, as a string. Read-only for AddIn, read-write for Workbook.

See Also

Author Property, AxisTitle Property, ChartTitle Property, Comments Property, Keywords Property.

Example

This example displays the title and filename of every add-in.

For Each a In AddIns
    MsgBox a.Title & " has the filename " & a.Name
Next a

This example sets the title of the active workbook.

ActiveWorkbook.Title = "Weekly Sales Summary"

In Microsoft Excel for Windows 95, this property has been replaced by a built-in OLE document property. For more information about OLE document properties, see BuiltinDocumentProperties.


Toolbar Object

Description

Represents a toolbar, either built-in or custom.

Accessors

The Toolbar object is a member of the Toolbars collection. Use the Add method to create a new toolbar and add it to the collection. To access a single member of the collection, use the Toolbars method with the index number or name of the toolbar as an argument.

The toolbar index number represents the position of the toolbar name in the list shown in the Toolbars dialog box (Toolbars command, View menu). Toolbars(1) is at the top of the list; Toolbars(Toolbars.Count) is at the bottom. Built-in toolbars are shown first, with custom toolbars arranged alphabetically after the last built-in toolbar.

The following example moves the Standard toolbar to the bottom of the Microsoft Excel window.

Toolbars(1).Position = xlBottom

The Name property returns the toolbar name (as shown in the Toolbars dialog box). The Name property is read-only; you cannot change the name of a built-in or custom toolbar. The following example makes the Forms toolbar visible.

Toolbars("forms").Visible = True

The following example creates a table on worksheet one in the active workbook that contains the names of all the ToolbarButton objects in all the Toolbar objects in the application. The column headings are the Toolbar object names, and the column entries under each heading are the names of the ToolbarButton objects in that Toolbar object. ToolbarButton objects that represent gaps (extended spaces between buttons) have no name; their corresponding cells are therefore blank.

Sub EnumerateToolbars()
    Worksheets(1).Activate
    For col = 1 To Toolbars.Count
        Cells(1, col) = Toolbars(col).Name
        For rw = 2 To Toolbars(col).ToolbarButtons.Count + 1
            Cells(rw, col) = Toolbars(col).ToolbarButtons(rw - 1).Name
        Next
    Next
End Sub

Properties

Application Property, BuiltIn Property, Creator Property, Height Property, Left Property, Name Property, Parent Property, Position Property, Protection Property, Top Property, Visible Property, Width Property.

Methods

Delete Method, Reset Method, ToolbarButtons Method.


ToolbarButton Object

Description

Represents a button or a gap (an extended space between buttons) on a toolbar. Do not confuse the ToolbarButton object with the Button object, which is a custom button graphic object on a chart sheet, dialog sheet, or worksheet.

Accessors

The ToolbarButton object is a member of the ToolbarButtons collection. The ToolbarButtons collection contains all the ToolbarButton objects on a single toolbar. Use the Add method to create a new toolbar button and add it to the collection. For a complete list of available toolbar buttons, see "Toolbar Button ID Values" in online Help.

To access a single member of the collection, use the ToolbarButtons method with the toolbar button index number as an argument.

The index number represents the position of the toolbar button on the toolbar. ToolbarButtons(1) is the first (leftmost) button on the toolbar; ToolbarButtons(ToolbarButtons.Count) is the last. The following example deletes the last button on the Standard toolbar.

With Toolbars("standard")
    .ToolbarButtons(.ToolbarButtons.Count).Delete
End With

The following example creates a table on worksheet one in the active workbook. The table contains the names of all the ToolbarButton objects in all the Toolbar objects in the application. The column headings are the Toolbar object names, and the column entries under each heading are the names of the ToolbarButton objects in that Toolbar object. ToolbarButton objects that represent gaps (extended spaces between buttons) have no name; their corresponding cells are therefore blank.

Sub EnumerateToolbars()
    Worksheets(1).Activate
    For col = 1 To Toolbars.Count
        Cells(1, col) = Toolbars(col).Name
        For rw = 2 To Toolbars(col).ToolbarButtons.Count + 1
            Cells(rw, col) = Toolbars(col).ToolbarButtons(rw - 1).Name
        Next
    Next
End Sub

Remarks

The Name property sets or returns the toolbar button tool tip text (the text displayed when the user moves the mouse cursor over the toolbar button).

Properties

Application Property, BuiltIn Property, BuiltInFace Property, Creator Property, Enabled Property, HelpContextID Property, HelpFile Property, Id Property, IsGap Property, Name Property, OnAction Property, Parent Property, Pushed Property, StatusBar Property, Width Property.

Methods

Copy Method, CopyFace Method, Delete Method, Edit Method, Move Method, PasteFace Method, Reset Method.


ToolbarButtons Collection Object

Description

A collection of all the ToolbarButton objects on the specified toolbar. Each ToolbarButton object represents a button or a gap (an extended space between buttons) on a toolbar. Do not confuse the ToolbarButton object with the Button object, which is a custom button graphic object on a chart sheet, dialog sheet, or worksheet.

Accessors

Use the ToolbarButtons method with an argument to access a single member of the collection or without an argument to access the entire collection at once. The following example sets the cButtons variable to the number of toolbar buttons and gaps on the Standard toolbar.

cButtons = Toolbars("standard").ToolbarButtons.Count

Use the Add method to add a toolbar button to a toolbar. The following example adds the Insert Module button to the end of the Standard toolbar.

Toolbars("standard").ToolbarButtons.Add button:=190

For a complete list of available toolbar buttons, see "Toolbar Button ID Values" in online Help.

To add a gap instead of a button, omit the button argument for the Add method.

Properties

Application Property, Count Property, Creator Property, Parent Property.

Methods

Add Method (ToolbarButtons Collection), Item Method.


ToolbarButtons Method

Applies To

Toolbar Object.

Description

Accessor. Returns an object that represents a single toolbar button (a ToolbarButton object, Syntax 1) or a collection of toolbar buttons (a ToolbarButtons object, Syntax 2) on the specified toolbar.

Syntax 1

object.ToolbarButtons(index)

Syntax 2

object.ToolbarButtons

object

Required. The Toolbar object.

index

Required for Syntax 1. The number of the button.

Example

This example deletes the New Workbook button from the Standard toolbar.

Application.Toolbars("Standard").ToolbarButtons(1).Delete


Toolbars Collection Object

Description

A collection of all the Toolbar objects in the Microsoft Excel application. Each Toolbar object represents a toolbar, either built-in or custom.

Accessors

Use the Add method to create a new toolbar and add it to the collection. The following example creates a new toolbar called "small VBA," adds the Insert Module button (190) and the Run Macro button (100) to it, makes the new toolbar visible, and moves it to the top of the Microsoft Excel window.

Dim tb As Toolbar
Set tb = Toolbars.Add("small VBA")
tb.ToolbarButtons.Add 190    'Insert Module button
tb.ToolbarButtons.Add 100    'Run Macro button
tb.Visible = True
tb.Position = xlTop

Use the Toolbars method with an argument to access a single member of the collection or without an argument to access the entire collection at once. The following example displays the total number of toolbars currently available in Microsoft Excel and the number of built-in toolbars.

cToolbars = Toolbars.Count
cBuiltIn = 0
For i = 1 To cToolbars
    If Toolbars(i).BuiltIn Then cBuiltin = cBuiltin + 1
Next
MsgBox cToolbars & " toolbars, " & cBuiltin & " built in."

Properties

Application Property, Count Property, Creator Property, Parent Property.

Methods

Add Method (Toolbars Collection), Item Method.


Toolbars Method

Applies To

Application Object.

Description

Accessor. Returns an object that represents a single toolbar (a Toolbar object, Syntax 1) or a collection of toolbars (a Toolbars object, Syntax 2) in the current instance of Microsoft Excel. Read-only.

Syntax 1

object.Toolbars(index)

Syntax 2

object.Toolbars

object

Optional. The Application containing the toolbars.

index

Required for Syntax 1. The name or number of the toolbar.

Example

This example adds a new toolbar button to the first position on the Standard toolbar and then assigns the macro myNewButtonMacro to the button.

Set newButton = Toolbars("Standard").ToolbarButtons.Add _
    (Button:=210, Before:=1)
newButton.OnAction = "myNewButtonMacro"

This example resets all toolbars to their default configurations.

For Each tb In Application.Toolbars
    tb.Reset
Next tb


Top Property

Applies To

Application Object, Arc Object, Arcs Collection, AxisTitle Object, Button Object, Buttons Collection, ChartArea Object, ChartObject Object, ChartObjects Collection, ChartTitle Object, CheckBox Object, DataLabel Object, DialogFrame Object, Drawing Object, DrawingObjects Collection, Drawings Collection, DropDown Object, DropDowns Collection, EditBox Object, EditBoxes Collection, GroupBox Object, GroupBoxes Collection, GroupObject Object, GroupObjects Collection, Label Object, Labels Collection, Legend Object, Line Object, Lines Collection, ListBox Object, ListBoxes Collection, OLEObject Object, OLEObjects Collection, OptionButton Object, OptionButtons Collection, Oval Object, Ovals Collection, Picture Object, Pictures Collection, PlotArea Object, Range Object, Rectangle Object, Rectangles Collection, ScrollBar Object, ScrollBars Collection, Spinner Object, Spinners Collection, TextBox Object, TextBoxes Collection, Toolbar Object, Window Object.

Description

Returns or sets the position of the specified object, in points (1/72 inch). Read-write, except for the Range object.

Remarks

The Top property has several different meanings, depending on the object to which it is applied.

Object | Meaning
Application | The distance from the top edge of the physical screen to the top edge of the main Microsoft Excel window, in points. In Windows, if the application window is minimized, this property controls the position of the icon (anywhere on the screen). On the Apple Macintosh the value is always zero; setting the value to something else will have no effect.
Button | The top position of the object, in points, measured from the top of row 1.
Range | The distance from the top edge of row one to the top edge of the range, in points. If the range is discontinuous, the first area is used. If the range is more than one row high, the top (lowest numbered) row in the range is used. Read-only.
Toolbar | If the toolbar is docked (the Position property of the Toolbar object is not xlFloating), the number of points from the top edge of the toolbar to the top edge of the toolbar docking area. If the toolbar is floating, the number of points from the top edge of the toolbar to the top edge of the Microsoft Excel workspace.

Object | Meaning
Window | The top position of the window, in points, measured from the top edge of the usable area (below the menus, top-docked toolbars, and/or the formula bar). You cannot set this property for a maximized window. Use the WindowState property to return or set the state of the window.
Arc, AxisTitle, ChartArea, ChartTitle, CheckBox, DataLabel, DialogFrame, Drawing, DrawingObjects, DropDown, EditBox, GroupBox, GroupObject, Label, Legend, Line, ListBox, OLEObject, OptionButton, Oval, Picture, PlotArea, Rectangle, ScrollBar, Spinner, TextBox, Title | The top position of the object, in points, measured from the top of row one (on a worksheet) or the top of the chart area (on a chart).

See Also

Height Property, Left Property, Width Property.

Example

This example moves oval one on Sheet1 so that it is aligned with the top edge of row 4.

Worksheets("Sheet1").Ovals(1).Top = _
    Worksheets("Sheet1").Rows(4).Top

This example aligns the top of every button on Sheet1 with the top of row 2.

topEdge = Worksheets("Sheet1").Rows(2).Top
For Each b In Worksheets("Sheet1").Buttons
    b.Top = topEdge
Next b

This example expands the active window to the maximum size available (assuming that the window is not already maximized).

With ActiveWindow
    .WindowState = xlNormal
    .Top = 1
    .Left = 1
    .Height = Application.UsableHeight
    .Width = Application.UsableWidth
End With


TopLeftCell Property

Applies To

Arc Object, Button Object, ChartObject Object, CheckBox Object, Drawing Object, DropDown Object, EditBox Object, GroupBox Object, GroupObject Object, Label Object, Line Object, ListBox Object, OLEObject Object, OptionButton Object, Oval Object, Picture Object, Rectangle Object, ScrollBar Object, Spinner Object, TextBox Object.

Description

Accessor. Returns a Range object that represents the cell that lies under the top left corner of this object. For drawing objects, this property applies only when the drawing object is on a worksheet. Read only.

See Also

BottomRightCell Property.

Example

This example displays the address of the cell beneath the upper-left corner of rectangle one on Sheet1.

MsgBox "The top left corner is over cell " & _
    Worksheets("Sheet1").Rectangles(1).TopLeftCell.Address


TopMargin Property

Applies To

PageSetup Object.

Description

Returns or sets the size of the top margin, in points (1/72 inch). Read-write.

Remarks

Margins are set or returned in points. Use the InchesToPoints or CentimetersToPoints function to convert.

Example

These two examples set the top margin of Sheet1 to 0.5 inch (36 points).

Worksheets("Sheet1").PageSetup.TopMargin = _
        Application.InchesToPoints(0.5)

Worksheets("Sheet1").PageSetup.TopMargin = 36

This example displays the current top margin setting.

marginInches = ActiveSheet.PageSetup.TopMargin / _
    Application.InchesToPoints(1)
MsgBox "The current top margin is " & marginInches & " inches"


ToRecipients Property

Applies To

Mailer Object.

Description

Returns or sets the direct recipients of the mailer. Available only in Microsoft Excel for the Apple Macintosh with the PowerTalk mail system extension installed. Read-write.

Remarks

This property is an array of strings specifying the address, in one of the following formats:

  • A record in the Preferred Personal Catalog. These names are one level deep ("Fred" or "June").
  • A full path specifying either a record in a personal catalog ("HD:Excel Folder:My Catalog:Barney") or a plain record ("HD:Folder:Martin").
  • A relative path from the current working folder specifying either a personal catalog record ("My Catalog:Barney") or a plain record ("Martin").
  • A path in a PowerShare catalog tree of the form "CATALOG_NAME:<node>:RECORD_NAME" where <node> is a path to a PowerShare catalog. An example of a complete path is "AppleTalk:North Building Zone:George's Mac".

See Also

BCCRecipients Property, CCRecipients Property, Enclosures Property, Mailer Property, Received Property, SendDateTime Property, Sender Property, SendMailer Method, Subject Property.

Example

This example sets up the Mailer object for workbook one and then sends the workbook.

With Workbooks(1)
    .HasMailer = True
    With .Mailer
        .Subject = "Here is the workbook"
        .ToRecipients = Array("Jean")
        .CCRecipients = Array("Adam", "Bernard")
        .BCCRecipients = Array("Chris")
        .Enclosures = Array("TestFile")
    End With
    .SendMailer
End With


TotalLevels Property

Applies To

PivotField Object.

Description

Returns the total number of fields in the current field grouping. If the field is not grouped, TotalLevels returns the value 1. Read-only.

Remarks

All fields in a set of grouped fields have the same TotalLevels value.

Example

This example displays the total number of fields in the group that contains the active cell.

Worksheets("Sheet1").Activate
MsgBox "This group has " & _
    ActiveCell.PivotField.TotalLevels & " levels."


TrackStatus Property

Applies To

RoutingSlip Object.

Description

True if status tracking is enabled for the routing slip. Read-write before routing begins; read-only when routing is in progress.

Example

This example sends BOOK1.XLS to three recipients, with status tracking enabled.

Workbooks("BOOK1.XLS").HasRoutingSlip = True
With Workbooks("BOOK1.XLS").RoutingSlip
    .Delivery = xlOneAfterAnother
    .Recipients = Array("Adam Bendel", "Jean Selva", "Bernard Gabor")
    .Subject = "Here is BOOK1.XLS"
    .Message = "Here is the workbook. What do you think?"
    .ReturnWhenDone = True
    .TrackStatus = True
End With
Workbooks("BOOK1.XLS").Route


TransitionExpEval Property

Applies To

Worksheet Object.

Description

True if Microsoft Excel will use Lotus 1-2-3 expression evaluation rules for this worksheet. Read-write.

Example

This example causes Microsoft Excel to use Lotus 1-2-3 expression evaluation rules for Sheet1.

Worksheets("Sheet1").TransitionExpEval = True


TransitionFormEntry Property

Applies To

Worksheet Object.

Description

True if Microsoft Excel will use Lotus 1-2-3 formula entry rules for this worksheet. Read-write.

Remarks

This property is not available on the Apple Macintosh.

Example

This example causes Microsoft Excel to use Lotus 1-2-3 formula entry rules for Sheet1.

Worksheets("Sheet1").TransitionFormEntry = True


TransitionMenuKey Property

Applies To

Application Object.

Description

Returns or sets the alternate menu or help key, which is usually "/". Read-write.

Example

This example sets the transition menu key to "/" (which is the default).

Application.TransitionMenuKey = "/"


TransitionMenuKeyAction Property

Applies To

Application Object.

Description

Returns or sets the action taken when the alternate menu key is pressed (one of xlExcelMenus or xlLotusHelp). This property cannot be set to xlLotusHelp on the Apple Macintosh. Read-write.

See Also

TransitionMenuKey Property.

Example

This example sets the alternate menu key to run Lotus 1-2-3 Help when it is pressed. This property cannot be set to xlLotusHelp on the Macintosh.

Application.TransitionMenuKeyAction = xlLotusHelp


TransitionNavigKeys Property

Applies To

Application Object.

Description

True if alternate navigation keys are active. Read-write.

Example

This example displays the current state of the Transition Navigation Keys option.

If Application.TransitionNavigKeys Then
    keyState = "On"
Else
    keyState = "Off"
End If
MsgBox "The Transition Navigation Keys option is " & keyState


Trappable Errors

Trappable errors can occur while an application is running. Some of these can also occur during development or compile time. You can test and respond to trappable errors using the On Error statement and the Err function.

Code | Message
3 | Return without GoSub
5 | Invalid procedure call
6 | Overflow
7 | Out of memory
9 | Subscript out of range
10 | Duplicate definition
11 | Division by zero
13 | Type mismatch
14 | Out of string space
16 | String formula too complex
17 | Can't perform requested operation
18 | User interrupt occurred
20 | Resume without error
28 | Out of stack space
35 | Sub or Function not defined
48 | Error in loading DLL
49 | Bad DLL calling convention
51 | Internal error
52 | Bad file name or number
53 | File not found
54 | Bad file mode
55 | File already open
57 | Device I/O error
58 | File already exists
59 | Bad record length
61 | Disk full
62 | Input past end of file
63 | Bad record number
67 | Too many files
68 | Device unavailable
70 | Permission denied
71 | Disk not ready
74 | Can't rename with different drive
75 | Path/File access error
76 | Path not found
91 | Object variable not set
92 | For loop not initialized
93 | Invalid pattern string
94 | Invalid use of Null
95 | User-defined error
323 | Can't load module; invalid format
423 | Property or method not found
424 | Object required
430 | Class does not support OLE Automation
438 | Object doesn't support this property or method
440 | OLE Automation error
445 | Object doesn't support this action
446 | Object doesn't support named arguments
447 | Object doesn't support current locale setting
448 | Named argument not found
449 | Argument not optional
450 | Wrong number of arguments
451 | Object not a collection
452 | Invalid ordinal
453 | Specified DLL function not found
454 | Code resource not found
455 | Code resource lock error

You can also work with Microsoft Excel cell error values in Visual Basic. For more information, see Cell Error Values.

Code | Message
1000 | '[Object]' does not have '[property name]' property The property doesn't exist for this object. For more information, see the entry for the object name.
1001 | '[Object]' does not have '[method name]' method The method doesn't exist for this object. For more information, see the entry for the object name.
1002 | Missing required argument '[argument]' The method expected a required argument that wasn't specified. Add the argument to the code. To see a list of required arguments, see the entry for the method name.
1003 | Invalid number of arguments The method has the wrong number of arguments. This usually occurs when you specify arguments by position instead of by name and you have too many arguments. To see the valid arguments for the method, see the entry for the method name.
1004 | '[Method name]' method of '[object]' class failed The method cannot be used on the object. Possible reasons include the following: An argument contains a value that isn't valid. A common cause of this problem is an attempt to access an object that doesn't exist (for example, you tried to use Workbooks(5) when there were only three workbooks open). The method cannot be used in the applied context. For example, some Range object methods require that the range contain data; if the range doesn't contain data, the method fails. An external error occurred, such as a failure to read or write from a file. For more information about the method, see the entry for the method name.
1005 | Unable to set the '[property name]' property of the '[object]' class The property cannot be changed. Possible reasons include the following: The value you're using for the property isn't valid (for example, you set a property to a string value, but the property requires a Boolean value). The property is read-only. For more information about the property, see the entry for the property name.
1006 | Unable to get the '[property name]' property of the '[object]' class The property cannot be read. A possible reason is that the property cannot be used in the applied context. For example, the code ActiveChart.Legend.Font.Color = RGB(255, 0, 0) will cause this error if the active chart doesn't contain a legend. For more information about the property, see the entry for the property name.


Trendline Object

Description

Represents a trendline in a chart. A trendline shows the trend, or direction, of data in a series.

Accessors

The Trendline object is a member of the Trendlines collection. The Trendlines collection contains all the Trendline objects for a single series. Use the Add method to create a new trendline and add it to the series.

To access a single member of the collection, use the Trendlines method with the trendline index number as an argument.

The index number represents the order in which the trendlines were added to the series. Trendlines(1) is the first trendline added; Trendlines(Trendlines.Count) is the last. The following example changes the trendline type for series one in embedded chart one on worksheet one. If the series has no trendline, this example will fail.

Worksheets(1).ChartObjects(1).Chart. _
    SeriesCollection(1).Trendlines(1).Type = xlMovingAvg

Properties

Application Property, Backward Property, Border Property, Creator Property, DataLabel Property, DisplayEquation Property, DisplayRSquared Property, Forward Property, Index Property, Intercept Property, InterceptIsAuto Property, Name Property, NameIsAuto Property, Order Property, Parent Property, Period Property, Type Property.

Methods

ClearFormats Method, Delete Method, Select Method.


Trendlines Collection Object

Description

A collection of all the Trendline objects for the specified series. Each Trendline object represents a trendline in a chart. A trendline shows the trend, or direction, of data in a series.

Accessors

Use the Add method to create a new trendline and add it to the series. The following example adds a linear trendline to series one in embedded chart one on the worksheet named "Sheet1."

Worksheets("sheet1").ChartObjects(1).Chart.SeriesCollection(1) _
    .Trendlines.Add type:=xlLinear, name:="Linear Trend"

Use the Trendlines method with an argument to access a single member of the collection or without an argument to access the entire collection at once.

Properties

Application Property, Count Property, Creator Property, Parent Property.

Methods

Add Method (Trendlines Collection), Item Method.


Trendlines Method

Applies To

Series Object.

Description

Accessor. Returns an object that represents a single trendline (a Trendline object, Syntax 1) or a collection of all the trendlines (a Trendlines object, Syntax 2) for the series.

Syntax 1

object.Trendlines(index)

Syntax 2

object.Trendlines

object

Required. The Series object.

index

Required for Syntax 1. The name or number of the trendline.

Example

This example adds a linear trendline to series one in Chart1.

Charts("Chart1").SeriesCollection(1).Trendlines.Add Type:=xlLinear


TwoInitialCapitals Property

Applies To

AutoCorrect Object.

Description

True if words that begin with two initial capital letters are corrected automatically. This property is available only in Microsoft Excel for Windows 95. Read-write.

Example

This example sets Microsoft Excel to correct words that begin with two initial capital letters.

With Application.AutoCorrect
    .TwoInitialCapitals = True
    .ReplaceText = True
End With


Type Property (DocumentProperty Object)

Applies To

DocumentProperty Object.

Description

Returns or sets the document property type (can be one of offPropertyTypeBoolean, offPropertyTypeDate, offPropertyTypeFloat, offPropertyTypeNumber, or offPropertyTypeString). Read-only for built-in document properties; read-write for custom document properties.

To use this property, you should establish a reference to the Microsoft Office 95 Object Library by using the References command (Tools menu).

Example

This example displays the name, type, and value of a document property. You must pass a DocumentProperty object to the procedure.

Sub DisplayPropertyInfo(dp As DocumentProperty)
    MsgBox "value = " & dp.Value & Chr(13) & _
        "type = " & dp.Type & Chr(13) & _
        "name = " & dp.Name
End Sub

This example displays the type of custom document property one in the active workbook.

MsgBox ActiveWorkbook.CustomDocumentProperties(1).Type


Type Property

Applies To

Axis Object, Chart Object, ChartGroup Object, DataLabel Object, DataLabels Collection, Series Object, Trendline Object, Window Object, Worksheet Object.

Description

Returns the object type, as shown in the following table. Read-write except as noted.

Object | Type
Axis | Axis type. Can be one of xlCategory, xlValue, or xlSeries (only 3-D charts use xlSeries).
Chart | Chart type. Can be one of xl3DArea, xl3DBar, xl3DColumn, xl3DLine, xl3DPie, xl3DSurface, xlArea, xlBar, xlColumn, xlDoughnut, xlLine, xlPie, xlRadar, or xlXYScatter. If the chart has chart groups of more than one type, this property returns Null, but setting the property sets all the chart groups.
ChartGroup | Chart group type. Can be one of the values shown for the Chart object. If you set the chart group type to a type that is not on the chart, Microsoft Excel creates a new chart group.
DataLabel | Data label type (one of xlNone, xlShowValue, xlShowLabel, xlShowPercent, or xlShowLabelAndPercent).
Series | Series type. Can be one of the values shown for the Chart object. If you set the series type to a type that is not on the chart, Microsoft Excel creates a new chart group.
Trendline | Trendline type. Can be one of xlLinear, xlLogarithmic, xlExponential, xlPolynomial, xlMovingAvg, or xlPower.
Window | Window type. Can be one of xlChartInPlace, xlChartAsWindow, xlWorkbook, xlInfo, or xlClipboard. Read-only.
Worksheet | Worksheet type. Can be one of xlWorksheet, xlExcel4MacroSheet, or xlExcel4IntlMacroSheet. Read-only.

See Also

SubType Property.

Example

This example changes the 3-D line group in Chart1 to an area group. The example should be run on a 3-D chart.

Charts("Chart1").Line3DGroup.Type = xl3DArea


Type Statement

Description

Used at module level to define a user-defined data type containing one or more elements.

Syntax

[Private | Public] Type varname
elementname [([subscripts])] As type
[ elementname [([subscripts])] As type]
. . .
End Type

The Type statement syntax has these parts:

Part | Description
Public | Used to declare user-defined types that are available to all procedures in all modules in all projects.
Private | Used to declare user-defined types that are available only within the module where the declaration is made.
varname | Name of the user-defined type; follows standard variable naming conventions.
elementname | Name of an element of the user-defined type. Element names also follow standard variable naming conventions, except that reserved words can be used.
subscripts | Dimensions of an array element. Use only parentheses when declaring an array whose size can change.
type | Data type of the element; may be Boolean, Integer, Long, Currency, Single, Double, Date, String, String * length (for fixed-length strings), Object, Variant, another user-defined type, or an object type.

Remarks

The Type statement can be used only at module level. Once you have declared a user-defined type using the Type statement, you can declare a variable of that type anywhere within the scope of the declaration. Use Dim, Private, Public, ReDim, or Static to declare a variable of a user-defined type.

Line numbers and line labels aren't allowed in Type...End Type blocks.

User-defined types are often used with data records, which frequently consist of a number of related elements of different data types.

The following example shows the use of fixed-size arrays in a user-defined type:

Type StateData
    CityCode (1 To 100) As Integer ' Declare a static array.
    County As String * 30
End Type
Dim Washington(1 To 100) As StateData

In the preceding example, StateData includes the CityCode static array, and the record Washington has the same structure as StateData.

When you declare a fixed-size array within a user-defined type, its dimensions must be declared with numeric literals or constants rather than variables.

The setting of the Option Base statement determines the lower bound for arrays within user-defined types.

See Also

Dim Statement, Private Statement, Public Statement, ReDim Statement, Static Statement.


TypeName Function

Description

Returns a string that provides information about a variable.

Syntax

TypeName(varname)

The varname named argument can be any variable except a variable of a user-defined type.

Remarks

The string returned by TypeName can be any one of the following:

String Returned | Variable contains
objecttype | An OLE Automation object whose type is objecttype.
Integer | An integer.
Long | A long integer.
Single | A single-precision floating point number.
Double | A double-precision floating point number.
Currency | A currency value.
Date | A date.
String | A string.
Boolean | A Boolean value.
Error | An error value.
Empty | Uninitialized.
Null | No valid data.
Object | An object that doesn't support OLE Automation.
Unknown | An OLE Automation object whose type is unknown.
Nothing | An object variable that doesn't refer to an object.

If varname is an array, the returned string can be any one of the possible returned strings (or Variant) with empty parentheses appended. For example, if varname is an array of integers, TypeName returns "Integer()".

See Also

Data Type Summary, IsArray Function, IsDate Function, IsEmpty Function, IsError Function, IsMissing Function, IsNull Function, IsNumeric Function, IsObject Function, Variant Data Type, VarType Function.

Example

This example uses the TypeName function to return information about a variable.

' Declare variables.
Dim StrVar As String, IntVar As Integer, CurVar As Currency
Dim ArrayVar (1 To 5) As Integer
NullVar = Null    ' Assign Null value.
MyType = TypeName(StrVar)    ' Returns "String".
MyType = TypeName(IntVar)    ' Returns "Integer".
MyType = TypeName(CurVar)    ' Returns "Currency".
MyType = TypeName(NullVar)    ' Returns "Null".
MyType = TypeName(ArrayVar)    ' Returns "Integer()".

This example displays the Visual Basic object type of the selection. You can run this example with cells selected, with a single oval selected, or with several different graphic objects selected.

Worksheets("Sheet1").Activate
MsgBox "The selection object type is " & TypeName(Selection)


UBound Function

Description

Returns the largest available subscript for the indicated dimension of an array.

Syntax

UBound(arrayname[,dimension])

The UBound function syntax has these parts:

Part | Description
arrayname | Name of the array variable; follows standard variable naming conventions.
dimension | Whole number indicating which dimension's upper bound is returned. Use 1 for the first dimension, 2 for the second, and so on. If dimension is omitted, 1 is assumed.

Remarks

The UBound function is used with the LBound function to determine the size of an array. Use the LBound function to find the lower limit of an array dimension.

UBound returns the values listed in the table below for an array with these dimensions:

Dim A(1 To 100, 0 To 3, -3 To 4)

Statement | Return Value
UBound(A, 1) | 100
UBound(A, 2) | 3
UBound(A, 3) | 4

See Also

Dim Statement, LBound Function, Option Base Statement, Public Statement, ReDim Statement, Static Statement.

Example

This example uses the UBound function to determine the largest available subscript for the indicated dimension of an array.

Dim MyArray(1 To 10, 5 To 15, 10 To 20)    ' Declare array variables.
Dim AnyArray(10)
Upper = UBound(MyArray, 1)    ' Returns 10.
Upper = UBound(MyArray, 3)    ' Returns 20.
Upper = UBound(AnyArray)    ' Returns 10.

This example writes the elements of the first custom list in column one on Sheet1.

Sub foo()
On Error GoTo err_handler
listArray = Application.GetCustomListContents(1)
For i = LBound(listArray, 1) To UBound(listArray, 1)
    Worksheets("sheet1").Cells(i, 1).Value = listArray(i)
Next i
Exit Sub

err_handler:
    MsgBox "Custom list does not exist"
End Sub

This example assumes that you used an external data source to create a PivotTable on Sheet1. The example inserts the SQL connection string and query string into a new worksheet.

Set newSheet = ActiveWorkbook.Worksheets.Add
sdArray = Worksheets("Sheet1").UsedRange.PivotTable.SourceData
For i = LBound(sdArray) To UBound(sdArray)
    newSheet.Cells(i, 1) = sdArray(i)
Next i


UCase Function

Description

Returns a string that has been converted to uppercase.

Syntax

UCase(string)

The string named argument is any valid string expression. If string contains no valid data, Null is returned.

Remarks

Only lowercase letters are converted to uppercase; all uppercase letters and nonletter characters remain unchanged.

See Also

LCase Function.

Example

This example uses the UCase function to return an uppercase version of a string.

LowerCase = "Hello World 1234"    ' String to convert.
UpperCase = UCase(LowerCase)    ' Returns "HELLO WORLD 1234".


Underline Property

Applies To

Font Object.

Description

Returns or sets the type of underline applied to the font, as shown in the following table. Read-write.

Value | Meaning
xlNone | No underline.
xlSingle | Single underline.
xlDouble | Double underline.
xlSingleAccounting | Single accounting underline.
xlDoubleAccounting | Double accounting underline.

Example

This example sets the font in the active cell on Sheet1 to single underline.

Worksheets("Sheet1").Activate
ActiveCell.Font.Underline = xlSingle


Undo Method

Applies To

Application Object.

Description

Cancels the last user-interface action.

Syntax

object.Undo

object

Required. The Application object.

Remarks

This method can only be used to undo the last action taken by the user before running the macro, and it must be the first line in the macro. It cannot be used to undo Visual Basic commands.

Example

This example cancels the last user interface action. The example must be the first line in a macro.

Application.Undo


Ungroup Method

Applies To

DrawingObjects Collection, GroupObject Object, GroupObjects Collection, Range Object.

Description

Range object: Promotes a range in an outline level (in other words, decreases its outline level). The specified range must be a row or column, or a range of rows or columns. If the range is in a PivotTable, ungroups the items contained in the range.

GroupObject: Ungroups a group of drawing objects. Returns a DrawingObjects collection containing the objects in the group.

Syntax

object.Ungroup

object

Required. The object to which this method applies.

Remarks

If the active cell is in a field header of a parent field, all the groups in that field are ungrouped and the field is removed from the PivotTable. When the last group in a parent field is ungrouped, the entire field is removed from the PivotTable.

See Also

Group Method, OutlineLevel Property.

Example

This example ungroups drawing object group one on Sheet1.

Worksheets("Sheet1").GroupObjects(1).Ungroup

This example ungroups the field named "ORDER_DATE."

Set pvtTable = Worksheets("Sheet1").Range("A3").PivotTable
Set groupRange = pvtTable.PivotFields("ORDER_DATE").DataRange
groupRange.Cells(1).Ungroup


Union Method

Applies To

Application Object.

Description

Returns the union of two or more ranges.

Syntax

object.Union(arg1, arg2, ...)

object

Optional. The Application object.

arg1, arg2, ...

Required. Return the union of these ranges. At least two Range objects must be specified.

See Also

Intersect Method.

Example

This example fills the union of two named ranges, Range1 and Range2, with the formula =RAND().

Worksheets("Sheet1").Activate
Set bigRange = Application.Union(Range("Range1"), Range("Range2"))
bigRange.Formula = "=RAND()"


Unprotect Method

Applies To

Chart Object, DialogSheet Object, Module Object, Workbook Object, Worksheet Object.

Description

Removes protection from a sheet or workbook. This method has no effect if the sheet or workbook is not protected.

Syntax

object.Unprotect(password)

object

Required. The object to which this method applies.

password

Optional. A string giving the case-sensitive password to use to unprotect the sheet or workbook. If the sheet or workbook is not protected with a password, this argument is ignored. On a sheet, if you omit this argument and the sheet was protected with a password, you will be prompted for the password. On a workbook, if you omit this argument and the workbook was protected with a password, the method fails.

Remarks

If you forget the password, you cannot unprotect the sheet or workbook. It's a good idea to keep a list of your passwords and their corresponding document names in a safe place.

See Also

Locked Property, Protect Method, ProtectContents Property, ProtectDrawingObjects Property.

Example

This example removes protection from the active workbook.

ActiveWorkbook.Unprotect


UpBars Object

Description

Represents the up bars in a chart group. Up bars connect points on series one with higher values on the last series in the chart group (the lines go up from series one). Only 2-D line groups that contain at least two series can have up bars. There is no singular UpBar object; you must turn up bars and down bars on or off for all points in a chart group at once.

Accessors

The UpBars property returns the up bars for a chart group. The following example turns on up and down bars for chart group one in embedded chart one on the worksheet named "Sheet5." The example then sets the up bar color to blue and the down bar color to red.

With Worksheets("sheet5").ChartObjects(1).Chart.ChartGroups(1)
    .HasUpDownBars = True
    .UpBars.Interior.Color = RGB(0, 0, 255)
    .DownBars.Interior.Color = RGB(255, 0, 0)
End With

Remarks

If the HasUpDownBars property is False, most properties of the UpBars object are disabled.

See Also

DownBars Object

Properties

Application Property, Border Property, Creator Property, Interior Property, Name Property, Parent Property.

Methods

Delete Method, Select Method.


UpBars Property

Applies To

ChartGroup Object.

Description

Accessor. Returns an UpBars object that represents the up bars on a line chart. Applies only to line charts. Read-only.

See Also

DownBars Property, HasUpDownBars Property.

Example

This example turns on up and down bars for chart group one in Chart1 and then sets their colors. The example should be run on a 2-D line chart containing two series that cross each other at one or more data points.

With Charts("Chart1").ChartGroups(1)
    .HasUpDownBars = True
    .DownBars.Interior.ColorIndex = 3
    .UpBars.Interior.ColorIndex = 5
End With


Update Method

Applies To

OLEObject Object.

Description

Updates the link.

Syntax

object.Update

object

Required. The OLEObject object.

Example

This example updates the link to OLE object one on Sheet1.

Worksheets("Sheet1").OLEObjects(1).Update


UpdateFromFile Method

Applies To

Workbook Object.

Description

Updates a read-only workbook from the saved disk file version of the workbook if the disk version is more recent than the current copy of the workbook in memory. If the disk copy has not changed since the workbook was loaded, the in-memory copy of the workbook is not reloaded.

Syntax

object.UpdateFromFile

object

Required. The Workbook object.

Remarks

This method is useful when a workbook is opened as read-only by user A and read-write by user B. If user B saves a newer version of the workbook to disk while user A still has the workbook open, user A cannot get the updated copy without closing and reopening the workbook and losing view settings. The UpdateFromFile method updates the in-memory copy of the workbook from the disk file.

See Also

ChangeFileAccess Method.

Example

This example updates the active workbook.

ActiveWorkbook.UpdateFromFile


UpdateLink Method

Applies To

Workbook Object.

Description

Updates a Microsoft Excel, DDE, or OLE link (or links).

Syntax

object.UpdateLink(name, type)

object

Required. The Workbook object.

name

Required. Specifies the name of the Microsoft Excel or DDE/OLE link to update, as returned from the LinkSources method.

type

Optional. Specifies the link type. Can be either xlExcelLinks or xlOLELinks (also used for DDE links). xlExcelLinks if omitted.

Example

This example updates all links in the active workbook.

ActiveWorkbook.UpdateLink name:=ActiveWorkbook.LinkSources


UpdateRemoteReferences Property

Applies To

Workbook Object.

Description

True if remote references will be updated for the workbook. Read-write.

Example

This example causes remote references to be updated on the active workbook.

ActiveWorkbook.UpdateRemoteReferences = True


UsableHeight Property

Applies To

Application Object, Window Object.

Description

Returns the height of the space that can be used by a window in the application window area (the window is not maximized). The height is returned in points (1/72 inch). Read-only.

Remarks

Adding a toolbar reduces the usable height.

See Also

UsableWidth Property.

Example

This example expands the active window to the maximum size available (assuming that the window is not already maximized).

With ActiveWindow
    .WindowState = xlNormal
    .Top = 1
    .Left = 1
    .Height = Application.UsableHeight
    .Width = Application.UsableWidth
End With


UsableWidth Property

Applies To

Application Object, Window Object.

Description

Returns the width of the space that can be used by a window in the application window area (the window is not maximized). The width is returned in points (1/72 inch). Read-only.

See Also

UsableHeight Property.

Example

This example expands the active window to the maximum size available (assuming that the window is not already maximized).

With ActiveWindow
    .WindowState = xlNormal
    .Top = 1
    .Left = 1
    .Height = Application.UsableHeight
    .Width = Application.UsableWidth
End With


UsedRange Property

Applies To

Worksheet Object.

Description

Accessor. Returns a Range object that represents the used range on the specified worksheet. Read-only.

Example

This example selects the used range on Sheet1.

Worksheets("Sheet1").Activate
ActiveSheet.UsedRange.Select


User-Defined Data Type

Description

Any data type you define using the Type statement. User-defined data types can contain one or more elements of any data type, array, or a previously defined user-defined type. For example:

Type MyType
    MyName As String    ' String variable stores a name.
    MyBirthDate As Date    ' Date variable stores a birthdate.
    MySex as Integer    ' Integer variable stores sex (0 for
End Type    ' female, 1 for male.

See Also

Data Type Summary, Type Statement.


UserName Property

Applies To

Application Object.

Description

Returns or sets the name of the current user (as a string). Read-write.

Example

This example displays the current user name.

MsgBox "Current user is " & Application.UserName


UserStatus Property

Applies To

Workbook Object.

Description

Returns a one-based, two-dimensional array specifying information about each user who has the workbook open as a shared list. The first element of the second dimension is the name of the user; the second element is the date and time when the user opened the workbook; and the third element is a number indicating the type of list (1 indicates exclusive, and 2 indicates shared). This property is available only in Microsoft Excel for Windows 95. Read-only.

Remarks

The UserStatus property doesn't return information about users who have the specified workbook open as read-only.

See Also

MultiUserEditing Property, SaveAs Method.

Example

This example creates a new workbook and inserts information about all users who have the active workbook open as a shared list.

users = ActiveWorkbook.UserStatus
With Workbooks.Add.Sheets(1)
    For row = 1 To ubound(users, 1)
        .Cells(row, 1) = users(row, 1)
        .Cells(row, 2) = users(row, 2)
        Select Case users(row, 3)
            Case 1
                .Cells(row, 3).Value = "Exclusive"
            Case 2
                .Cells(row, 3).Value = "Shared"
        End Select
    Next
End With


UseStandardHeight Property

Applies To

Range Object.

Description

True if the row height of the Range object equals the standard height of the sheet. Read-write.

See Also

RowHeight Property, StandardHeight Property, UseStandardWidth Property.

Example

This example sets the height of row one on Sheet1 to the standard height.

Worksheets("Sheet1").Rows(1).UseStandardHeight = True


UseStandardWidth Property

Applies To

Range Object.

Description

True if the column width of the Range object equals the standard width of the sheet. Read-write.

See Also

ColumnWidth Property, StandardWidth Property, UseStandardHeight Property.

Example

This example sets the width of column A on Sheet1 to the standard width.

Worksheets("Sheet1").Columns("A").UseStandardWidth = True


Val Function

Description

Returns the numbers contained in a string.

Syntax

Val(string)

The string named argument is any valid string expression.

Remarks

The Val function stops reading the string at the first character it can't recognize as part of a number. Symbols and characters that are often considered parts of numeric values, such as dollar signs and commas, are not recognized. However, the function recognizes radix prefixes &O (for octal) and &H (for hexadecimal). Blanks, tabs, and linefeeds are stripped from the argument.

The following returns the value 1615198:

Val("    1615 198th Street N.E.")

In the code below, Val returns the decimal value -1 for the hexadecimal value shown:

Val("&HFFFF")

Note

The Val function recognizes only the period (.) as a valid decimal separator. When a possibility exists that different decimal separators may be used (for example, in international applications), you should use CDbl instead to convert a string to a number.


Value Property

Applies To

Application Object, Borders Collection, CheckBox Object, DrawingObjects Collection, DropDown Object, DropDowns Collection, ListBox Object, ListBoxes Collection, Name Object, OptionButton Object, OptionButtons Collection, PivotField Object, PivotItem Object, PivotTable Object, Range Object, ScrollBar Object, ScrollBars Collection, Spinner Object, Spinners Collection, Style Object.

Description

The meaning of the Value property depends on the object to which it is applied, as shown in the following table.

Object | Value
Application | Always returns "Microsoft Excel". Read-only.
Borders | Synonym for Borders.LineStyle.
CheckBox | Indicates check box status (xlOn, xlOff, or xlMixed).
DropDown, ListBox | Indicates the selected item in the list (the value is always between one and the number of items in the list). This method cannot be used with multi-select list boxes; use the Selected method instead.
Name | A string containing the formula that the name is defined to refer to, in A1-style notation, in the language of the macro, beginning with an equal sign. Read-only.
OptionButton | Indicates button status (one of xlOn or xlOff).
PivotField | The name of the field in the PivotTable.
PivotItem | The name of the item in the PivotTable field.

Object | Value
PivotTable | The name of the PivotTable.
Range | The value of a cell. If the cell is empty, returns the value Empty. Use the IsEmpty function to test for this case. If the Range object contains more than one cell, returns an array of values. Use the IsArray function to test for this case.
ScrollBar | The position of the scroll box.
Spinner | A value between the minimum and maximum range limit.
Style | The name of the style.

See Also

LineStyle Property, MultiSelect Property, Selected Property.

Example

This example sets the value of cell A1 on Sheet1 to 3.14159.

Worksheets("Sheet1").Range("A1").Value = 3.14159

This example loops on cells A1:D10 on Sheet1. If one of the cells has a value less than 0.001, the code replaces the value with 0 (zero).

For Each c in Worksheets("Sheet1").Range("A1:D10")
    If c.Value < .001 Then
        c.Value = 0
    End If
Next c

This example is a simple event procedure for a list box on a custom dialog box, Dialog1. The example sets the variable itemNum to the index of the selected item in the list box.

itemNum = DialogSheets("Dialog1").ListBoxes(1).Value


Value Property (DocumentProperty Object)

Applies To

DocumentProperty Object.

Description

Returns or sets the document property value. Read-write.

To use this property, you should establish a reference to the Microsoft Office 95 Object Library by using the References command (Tools menu).

Remarks

If the application doesn't define a value for one of the built-in document properties, reading the Value property for that document property causes an error.

Example

This example displays the name, type, and value of a document property. You must pass a DocumentProperty object to the procedure.

Sub DisplayPropertyInfo(dp As DocumentProperty)
    MsgBox "value = " & dp.Value & Chr(13) & _
        "type = " & dp.Type & Chr(13) & _
        "name = " & dp.Name
End Sub

This example displays the value of custom document property one in the active workbook.

MsgBox ActiveWorkbook.CustomDocumentProperties(1).Value


Values Property

Applies To

Scenario Object, Series Object.

Description

Scenario object: Returns an array containing the current values for the scenario changing cells. Read-only.

Series object: Returns or sets a collection of all the values in the series. This can be a range on a worksheet or an array of constant values (but not a combination of both). See the examples for details. Read-write.

Example

This example sets the series values from a range. The example uses the Set statement because the right-hand side of the expression is an object, not a value.

Set Charts("Chart1").SeriesCollection(1).Values = _
    Worksheets("Sheet1").Range("C5:T5")

To assign a constant value to each individual data point, you must use an array. This example does not require the Set statement.

Charts("Chart1").SeriesCollection(1).Values = _
    Array(1, 3, 5, 7, 11, 13, 17, 19)


Variant Data Type

Description

The Variant data type is the data type that all variables become if not explicitly declared as some other type (using statements such as Dim, Private, Public, or Static). The Variant data type has no type-declaration character.

The Variant is a special data type that can contain any kind of data as well as the special values Empty, Error, and Null. You can determine how the data in a Variant is treated using the VarType or TypeName function.

Numeric data can be any integer or real number value ranging from -1.797693134862315E308 to -4.94066E-324 for negative values and from 4.94066E-324 to 1.797693134862315E308 for positive values. Generally, numeric Variant data is maintained in its original data type within the Variant. For example, if you assign an Integer to a Variant, subsequent operations treat the Variant as if it were an Integer. However, if an arithmetic operation is performed on a Variant containing an Integer, a Long, or a Single, and the result exceeds the normal range for the original data type, the result is promoted within the Variant to the next larger data type. An Integer is promoted to a Long, and a Long and a Single are promoted to a Double. An error occurs when Variant variables containing Currency and Double values exceed their respective ranges.

You can use the Variant data type in place of any data type to work with data in a more flexible way. If the contents of a Variant variable are digits, they may be either the string representation of the digits or their actual value, depending on the context. For example:

Dim MyVar As Variant
MyVar = 98052

In the example shown above, MyVar contains a numeric representation — the actual value 98052. Arithmetic operators work as expected on Variant variables that contain numeric values or string data that can be interpreted as numbers. If you use the + operator to add MyVar to another Variant containing a number or to a variable of a numeric data type, the result is an arithmetic sum. See the information about addition and concatenation operators for complete information on how to use them with Variant data.

The value Empty denotes a Variant variable that hasn't been initialized (assigned an initial value). A Variant containing Empty is 0 if it is used in a numeric context and a zero-length string ("") if it is used in a string context.

Don't confuse Empty with Null. Null indicates that the Variant variable intentionally contains no valid data.

In a Variant, Error is a special value used to indicate that an error condition has occurred in a procedure. However, unlike for other kinds of errors, normal application-level error handling does not occur. This allows the programmer, or the application itself, to take some alternative based on the error value. Error values are created by converting real numbers to error values using the CVErr function.

See Also

CVar Function, CVErr Function, Data Type Summary, Def type Statements, Dim Statement, Private Statement, Public Statement, Static Statement, TypeName Function, VarType Function.


VarType Function

Description

Returns a value indicating the subtype of a variable.

Syntax

VarType(varname)

The varname named argument can be any variable except a variable of a user-defined type.

Return Values

Value Returned | Constant | Variable Type
0 | vbEmpty | Empty (uninitialized).
1 | vbNull | Null (no valid data).
2 | vbInteger | Integer.
3 | vbLong | Long integer.
4 | vbSingle | Single-precision floating point number.
5 | vbDouble | Double-precision floating point number.
6 | vbCurrency | Currency.
7 | vbDate | Date.
8 | vbString | String.
9 | vbObject | OLE Automation object.
10 | vbError | Error.
11 | vbBoolean | Boolean.
12 | vbVariant | Variant (used only with arrays of Variants).
13 | vbDataobject | Non-OLE Automation object.
8192 | vbArray | Array.

Note

These constants are specified by Visual Basic. As a result, the names can be used anywhere in your code in place of the actual values.

Remarks

The VarType function never returns the value for vbArray by itself. It is always added to some other value to indicate an array of a particular type. The constant vbVariant is only returned in conjunction with vbArray to indicate that the argument to the VarType function is an array of type Variant. For example, the value returned for an array of integers is calculated as vbInteger + vbArray, or 8194.

See Also

Data Type Summary, IsArray Function, IsDate Function, IsEmpty Function, IsError Function, IsMissing Function, IsNull Function, IsNumeric Function, IsObject Function, TypeName Function, Variant Data Type.

Example

This example uses VarType to determine the subtype of a variable.

' Initialize variables.
IntVar = 459: StrVar = "Hello World": DateVar = #2/12/69#
MyCheck = VarType(IntVar)    ' Returns 2.
MyCheck = VarType(DateVar)    ' Returns 7.
MyCheck = VarType(StrVar)    ' Returns 8.


VaryByCategories Property

Applies To

ChartGroup Object.

Description

If this property is True, Microsoft Excel assigns a different color or pattern to each data marker. The chart must contain only one series. Read-write.

Example

This example assigns a different color or pattern to each data marker in chart group one. The example should be run on a 2-D line chart that has data markers on a series.

Charts("Chart1").ChartGroups(1).VaryByCategories = True


Verb Method

Applies To

OLEObject Object.

Description

Sends a verb to the server of the specified OLE object.

Syntax

object.Verb(verb)

object

Required. The OLEObject object.

verb

Optional. The verb that the server of the OLE object should act upon. If this argument is omitted, the default verb is sent. The available verbs are determined by the object's source application. Typical verbs for an OLE object are Open and Primary (represented by the xlOpen and xlPrimary constants).

Example

This example sends the default verb to the server for OLE object one on Sheet1.

Worksheets("Sheet1").OLEObjects(1).Verb


Version Property

Applies To

Application Object.

Description

Returns the version number of Microsoft Excel. Read-only.

Example

This example displays a message box with the Microsoft Excel version number and the name of the operating system.

MsgBox "Welcome to Microsoft Excel version " & _
    Application.Version & " running on " & _
    Application.OperatingSystem & "!"


VerticalAlignment Property

Applies To

AxisTitle Object, Button Object, Buttons Collection, ChartTitle Object, DataLabel Object, DataLabels Collection, DrawingObjects Collection, GroupObject Object, GroupObjects Collection, Range Object, Style Object, TextBox Object, TextBoxes Collection.

Description

Returns or sets the vertical alignment of the object (can be one of xlBottom, xlCenter, xlDistributed, xlJustify, or xlTop). Read-write.

Remarks

The xlDistributed alignment style works only in Far East versions of Microsoft Excel.

See Also

AddIndent Property, HorizontalAlignment Property.

Example

This example sets the height of row two on Sheet1 to twice the standard height and then centers the vertical alignment.

Worksheets("Sheet1").Rows(2).RowHeight = _
    2 * Worksheets("Sheet1").StandardHeight
Worksheets("Sheet1").Rows(2).VerticalAlignment = xlCenter


Vertices Property

Applies To

Drawing Object, DrawingObjects Collection.

Description

Returns or sets the vertices of a polygon or freehand drawing, as a two-dimensional array of vertex coordinates in points (1/72 inch) relative to the upper-left corner of cell A1. The x coordinate is in column one of the array, the y coordinate is in column two. Every drawing and polygon will have at least two vertices. Read-only.

See Also

AddVertex Method, Reshape Method.

Example

This example creates a new worksheet and then inserts a list of the vertex coordinates for drawing one on Sheet1.

Set newSheet = ActiveWorkbook.Worksheets.Add
allVertices = Worksheets("Sheet1").Drawings(1).Vertices
newSheet.Range("A1:C1").Font.Bold = True
newSheet.Range("A1").Value = "Vertex"
newSheet.Range("B1").Value = "X value"
newSheet.Range("C1").Value = "Y value"
for i = LBound(allVertices, 1) to UBound(allVertices, 1)
    newSheet.Cells(i + 1, 1) = i
    newSheet.Cells(i + 1, 2) = allVertices(i, 1)
    newSheet.Cells(i + 1, 3) = allVertices(i, 2)
Next i

Assuming that drawing one on Sheet1 is a polygon with at least six vertices, this example reshapes the polygon by moving vertex five 12 points (1/6 inch) in the X direction.

With Worksheets("Sheet1").Drawings(1)
    vX = .Vertices(5, 1)
    vY = .Vertices(5, 2)
    .Reshape vertex:=5, Insert:=False, Left:=vX + 12, Top:=vY
End With


Visible Property

Applies To

Application Object, Arc Object, Arcs Collection, Button Object, Buttons Collection, Chart Object, ChartObject Object, ChartObjects Collection, Charts Collection, CheckBox Object, DialogSheet Object, DialogSheets Collection, Drawing Object, DrawingObjects Collection, Drawings Collection, DropDown Object, DropDowns Collection, EditBox Object, EditBoxes Collection, GroupBox Object, GroupBoxes Collection, GroupObject Object, GroupObjects Collection, Label Object, Labels Collection, Line Object, Lines Collection, ListBox Object, ListBoxes Collection, Module Object, Modules Collection, Name Object, OLEObject Object, OLEObjects Collection, OptionButton Object, OptionButtons Collection, Oval Object, Ovals Collection, Picture Object, Pictures Collection, PivotItem Object, Rectangle Object, Rectangles Collection, ScrollBar Object, ScrollBars Collection, Sheets Collection, Spinner Object, Spinners Collection, TextBox Object, TextBoxes Collection, Toolbar Object, Window Object, Worksheet Object, Worksheets Collection.

Description

True if the object is visible. For a chart, dialog sheet, module or worksheet, this property can be set to xlVeryHidden. This hides the object so that it can only be made visible by setting this property to True (the user cannot make the object visible). Read-write.

Remarks

The Visible property for a pivot item is True if the item is currently showing on the table.

If you set the Visible property for a name to False, the name will not appear in the Define Name dialog box.

Example

This example hides Sheet1.

Worksheets("Sheet1").Visible = False

This example makes Sheet1 visible.

Worksheets("Sheet1").Visible = True

This example makes every sheet in the active workbook visible.

For Each sh In Sheets
    sh.Visible = True
Next sh

This example creates a new worksheet and then sets its Visible property to xlVeryHidden. To refer to the sheet, use its object variable, newSheet, as shown in the last line of the example. To use the newSheet object variable in another procedure, you must declare it as a public variable (Public newSheet As Object) in the first line of the module preceding any Sub or Function procedure.

Set newSheet = Worksheets.Add
newSheet.Visible = xlVeryHidden
newSheet.Range("A1:D4").Formula = "=RAND()"


VisibleFields Method

Applies To

PivotTable Object.

Description

Accessor. Returns an object that represents a single pivot field (a PivotField object, Syntax 1) or a collection of the visible pivot fields (a PivotFields object, Syntax 2). Visible pivot fields are showing as row, column, page or data fields. Read-only.

Syntax 1

object.VisibleFields(index)

Syntax 2

object.VisibleFields

object

Required. The PivotTable object.

index

Required for Syntax 1. The name or number of the pivot field to return (can be an array to specify more than one).

See Also

ColumnFields Method, DataFields Method, HiddenFields Method, PageFields Method, PivotFields Method, RowFields Method.

Example

This example adds the visible field names to a list box. The list box appears on Sheet1.

Set pvtTable = Worksheets("Sheet1").Range("A3").PivotTable
Set newListBox = Worksheets("Sheet1").ListBoxes.Add _
    (Left:=10, Top:=72, Width:=144, Height:=144)
For Each hdnField In pvtTable.VisibleFields
    newListBox.AddItem (hdnField.Name)
Next hdnField
Worksheets("Sheet1").Activate


VisibleItems Method

Applies To

PivotField Object.

Description

Accessor. Returns an object that represents one visible pivot item (a PivotItem object, Syntax 1) or a collection of all the visible pivot items (a PivotItems object, Syntax 2) in the specified field. Read-only.

Syntax 1

object.VisibleItems(index)

Syntax 2

object.VisibleItems

object

Required. The PivotField object.

index

Required for Syntax 1. The number or name of the pivot item to return (can be an array to specify more than one).

See Also

ChildItems Method, HiddenItems Method, ParentItems Method, PivotItems Method.

Example

This example adds the names of all visible items in the field named "COMPANY" to a list box. The list box appears on Sheet1.

Set pvtTable = Worksheets("Sheet1").Range("A3").PivotTable
Set newListBox = Worksheets("Sheet1").ListBoxes.Add _
    (Left:=10, Top:=72, Width:=144, Height:=144)
Set pvtField = pvtTable.PivotFields("COMPANY")
For Each pvtItem In pvtField.VisibleItems
    newListBox.AddItem (pvtItem.Name)
Next pvtItem
Worksheets("Sheet1").Activate


VisibleRange Property

Applies To

Pane Object, Window Object.

Description

Accessor. Returns a Range object that represents the range of cells that are visible in the window or pane. If a column or row is partially visible, it is included in the range. Read-only.

Example

This example displays the number of cells visible on Sheet1.

Worksheets("Sheet1").Activate
MsgBox "There are " & Windows(1).VisibleRange.Cells.Count _
    & " cells visible"


Volatile Method

Applies To

Application Object.

Description

Marks a user-defined function as volatile. A volatile function must be recalculated whenever calculation occurs in any cells of the worksheet. A non-volatile function is recalculated only when the input variables change. This method has no effect if it is not inside a user-defined function used to calculate a worksheet cell.

Syntax

object.Volatile(volatile)

object

Required. The Application object.

volatile

Optional. If True or omitted, the function is marked as volatile. If False, the function is marked as non-volatile.

Example

This example marks the user-defined function "My_Func" as volatile. The function will be recalculated whenever calculation occurs in any cells on the worksheet where this function appears.

Function My_Func()
    Application.Volatile
    '
    '    Remainder of the function
    '
End Function


Wait Method

Applies To

Application Object.

Description

Pauses a macro that is running until a specified time is reached.

Important

The Wait method suspends all Microsoft Excel activity and may prevent you from performing other operations on your computer. Background processes, such as printing and recalculation, are continued.

Syntax

object.Wait(time)

object

Required. The Application object.

time

Required. The time you want the macro to resume, in Microsoft Excel date format.

Example

This example pauses a running macro until 6:23 P.M. today.

Application.Wait "18:23:00"

This example pauses a running macro for approximately 10 seconds.

newHour = Hour(Now())
newMinute = Minute(Now())
newSecond = Second(Now()) + 10
waitTime = TimeSerial(newHour, newMinute, newSecond)
Application.Wait waitTime


Walls Object

Description

Represents the walls of a 3-D chart. There is no singular Wall object; you must access all the walls at once.

Accessors

The Walls property returns the walls for the specified chart. The following example sets the pattern on the walls for embedded chart one on the worksheet named "Sheet1." The example will fail if the chart is not a 3-D chart.

Worksheets("Sheet1").ChartObjects(1).Chart _
    .Walls.Interior.Pattern = xlGray75

Properties

Application Property, Border Property, Creator Property, Interior Property, Name Property, Parent Property.

Methods

ClearFormats Method, Select Method.


Walls Property

Applies To

Chart Object.

Description

Accessor. Returns a Walls object that represents the walls of the 3-D chart. Read-only.

Remarks

This property does not apply to 3-D pie charts.

Example

This example sets the wall border color of Chart1 to red. The example should be run on a 3-D chart.

Charts("Chart1").Walls.Border.ColorIndex = 3


WallsAndGridlines2D Property

Applies To

Chart Object.

Description

True if gridlines are drawn in 2-D on a 3-D chart. Read-write.

Example

This example causes Microsoft Excel to draw 2-D gridlines on Chart1.

Charts("Chart1").WallsAndGridlines2D = True


Weekday Function

Description

Returns a whole number representing the day of the week.

Syntax

Weekday(date)

The date named argument is limited to numbers or strings, in any combination, that can represent a date. If date contains no valid data, Null is returned.

Return Values

Value | Description
1 | Sunday
2 | Monday
3 | Tuesday
4 | Wednesday
5 | Thursday
6 | Friday
7 | Saturday

See Also

Date Function, Date Statement, Day Function, Month Function, Now Function, Year Function.

Example

This example uses the Weekday function to obtain the day of the week from a specified date.

MyDate = #February 12, 1969#    ' Assign a date.
MyWeekDay = Weekday(MyDate)    ' MyWeekDay contains 4 since it
    ' was a Wednesday.


Weight Property

Applies To

Border Object, Borders Collection.

Description

Returns or sets the weight of the border (one of xlHairline, xlThin, xlMedium, or xlThick). Read-write.

Example

This example sets the border weight for oval one on Sheet1.

Worksheets("Sheet1").Ovals(1).Border.Weight = xlMedium


While...Wend Statement

Description

Executes a series of statements as long as a given condition is True.

Syntax

While condition
[statements]
Wend

The While...Wend statement syntax has these parts:

Part | Description
condition | Numeric or string expression that evaluates to True or False.
statements | One or more statements executed while condition is True.

Remarks

If condition is True, all statements in statements are executed until the Wend statement is encountered. Control then returns to the While statement and condition is again checked. If condition is still True, the process is repeated. If it is not True, execution resumes with the statement following the Wend statement.

While...Wend loops can be nested to any level. Each Wend matches the most recent While.

Caution

Do not branch into the body of a While...Wend loop without executing the While statement. Doing so may cause run-time errors or other problems that are difficult to locate.

Tip

The Do...Loop statement provides a more structured and flexible way to perform looping.

See Also

Do...Loop Statement, With Statement.

Example

This example uses the While...Wend statement to increment a counter variable. The statements in the loop are executed as long as the condition evaluates to True.

Counter = 0    ' Initialize variable.
While Counter < 20    ' Test value of Counter.
    Counter = Counter + 1    ' Increment Counter.
Wend
Debug.Print Counter    ' Prints 20 in Debug window.


Width Property

Applies To

Application Object, Arc Object, Arcs Collection, Button Object, Buttons Collection, ChartArea Object, ChartObject Object, ChartObjects Collection, CheckBox Object, DialogFrame Object, Drawing Object, DrawingObjects Collection, Drawings Collection, DropDown Object, DropDowns Collection, EditBox Object, EditBoxes Collection, GroupBox Object, GroupBoxes Collection, GroupObject Object, GroupObjects Collection, Label Object, Labels Collection, Legend Object, Line Object, Lines Collection, ListBox Object, ListBoxes Collection, OLEObject Object, OLEObjects Collection, OptionButton Object, OptionButtons Collection, Oval Object, Ovals Collection, Picture Object, Pictures Collection, PlotArea Object, Range Object, Rectangle Object, Rectangles Collection, ScrollBar Object, ScrollBars Collection, Spinner Object, Spinners Collection, TextBox Object, TextBoxes Collection, Toolbar Object, ToolbarButton Object, Window Object.

Description

Returns or sets an object's width in points (1/72 inch). Read-write for all objects, except Range, which is read-only.

Remarks

The Width property has several different meanings, depending on the object to which it is applied.

Object | Description
Application | The distance from the left edge of the application window to the right edge of the application window.
Range | The width of the range.
Toolbar | The width of the toolbar. When you set the width, Microsoft Excel snaps both the width and the height to match the nearest allowable size.
Window | The width of the window. Use the UsableWidth property to determine the maximum size for the window. You cannot set this property if the window is maximized or minimized. Use the WindowState property to determine the window state.
Arc, Button, ChartArea, CheckBox, DialogFrame, Drawing, DrawingObjects, DropDown, EditBox, GroupBox, GroupObject, Label, Legend, Line, ListBox, OLEObject, OptionButton, Oval, Picture, PlotArea, Rectangle, ScrollBar, Spinner, TextBox, ToolbarButton, Window | The width of the object. If you set the width for an entire collection of objects (using Ovals.Width = 100, for example), the width of each object changes in proportion to its existing width (this mimics the behavior of selecting all the objects and then dragging a handle to change the width of the selection). This means that the width of each object changes, but they are not all set to the same width. To set every object in the collection to the same width, you must iterate the collection and set the width of each individual object.

On the Apple Macintosh, Application.Width is always equal to the total width of the screen, in points. Setting this value to any other value will have no effect.

In Microsoft Windows, if the window is minimized, Application.Width is read-only and returns the width of the icon.

You can use negative numbers to set the Height and Width properties of the following drawing objects: Arc, Button, CheckBox, Drawing, DropDown, EditBox, GroupBox, GroupObject, Label, Line, ListBox, OLEObject, OptionButton, Oval, Picture, Rectangle, ScrollBar, Spinner, and TextBox. This causes the object to reflect or translate (the behavior depends on the object), after which the Top and Left properties change to describe the new position. The Height and Width properties always return positive numbers.

See Also

Top Property.

Example

This example sets the width of oval one on Sheet1 to 1 inch (72 points).

Worksheets("Sheet1").Ovals(1).Width = 72

This example sets the width of every button on Sheet1 to 36 points.

For Each b In Worksheets("Sheet1").Buttons
    b.Width = 36
Next b

This example expands the active window to the maximum size available (assuming that the window is not maximized).

With ActiveWindow
    .WindowState = xlNormal
    .Top = 1
    .Left = 1
    .Height = Application.UsableHeight
    .Width = Application.UsableWidth
End With


Width # Statement

Description

Assigns an output-line width to a file opened using the Open statement.

Syntax

Width #filenumber,width

The Width statement syntax has these parts:

Part | Description
filenumber | Any valid file number.
width | Numeric expression in the range 0 to 255, inclusive, that indicates how many characters appear on a line before a new line is started. If width equals 0, there is no limit to the length of a line. The default value for width is 0.

See Also

Open Statement, Print # Statement.

Example

This example uses the Width statement to set the output-line width for a file.

Open "TESTFILE" For Output As #1    ' Open file for output.
Width #1, 5    ' Set output-line width to 5.
For I = 0 To 9    ' Loop 10 times.
    Print #1, Chr(48 + I);    ' This prints 5 characters per line.
Next I
Close #1    ' Close file.


Window Object

Description

Represents a window. Many worksheet characteristics, such as scroll bars and gridlines, are actually properties of the window.

Accessors

The Window object is a member of the Windows collection. The Windows collection for the Application object contains all the windows in the application, whereas the Windows collection for the Workbook object contains only the windows in the specified workbook. Use the NewWindow method to create a new window and add it to the collection.

To access a single member of the collection, use the Windows method with the index number or caption of the window as an argument. Using the Windows method with no object qualifier returns the collection of windows for the application (this is equivalent to Application.Windows). The active window is always Windows(1).

The following example maximizes the active window.

Windows(1).WindowState = xlMaximized

The window caption is the text shown in the title bar at the top of the window when the window is not maximized. The caption is also shown in the list of open files on the bottom of the Windows menu. Use the Caption property to set or return the window caption. Changing the window caption does not change the name of the workbook. The following example turns off cell gridlines for the worksheet shown in the BOOK1.XLS:1 window.

Windows("book1.xls:1").DisplayGridlines = False

Properties

ActiveCell Property, ActiveChart Property, ActivePane Property, ActiveSheet Property, Application Property, Caption Property, Creator Property, DisplayFormulas Property, DisplayGridlines Property, DisplayHeadings Property, DisplayHorizontalScrollBar Property, DisplayOutline Property, DisplayRightToLeft Property, DisplayVerticalScrollBar Property, DisplayWorkbookTabs Property, DisplayZeros Property, FreezePanes Property, GridlineColor Property, GridlineColorIndex Property, Height Property, Index Property, Left Property, OnWindow Property, PageSetup Property, Parent Property, RangeSelection Property, ScrollColumn Property, ScrollRow Property, Selection Property, Split Property, SplitColumn Property, SplitHorizontal Property, SplitRow Property, SplitVertical Property, TabRatio Property, Top Property, Type Property, UsableHeight Property, UsableWidth Property, Visible Property, VisibleRange Property, Width Property, WindowNumber Property, WindowState Property, Zoom Property.

Methods

Activate Method, ActivateNext Method, ActivatePrevious Method, Close Method, LargeScroll Method, NewWindow Method, Panes Method, PrintOut Method, PrintPreview Method, ScrollWorkbookTabs Method, SelectedSheets Method, SetInfoDisplay Method, SmallScroll Method.


WindowNumber Property

Applies To

Window Object.

Description

Returns the window number. For example, a window entitled "BOOK1.XLS:2" has a window number of two. Most windows have a window number of one. Read-only.

Remarks

The window number is not the same as the window Index, which is the position of the window within the Windows collection.

See Also

Index Property.

Example

This example creates a new window of the active window and then displays the window number of the new window.

ActiveWindow.NewWindow
MsgBox ActiveWindow.WindowNumber


Windows Collection Object

Description

A collection of all the Window objects in the Microsoft Excel application. The Windows collection for the Application object contains all the windows in the application, whereas the Windows collection for the Workbook object contains only the windows in the specified workbook.

Accessors

Use the NewWindow method to create a new window and add it to the collection. The following example creates a new window for the active workbook.

ActiveWorkbook.NewWindow

Use the Windows method with an argument to access a single member of the collection or without an argument to access the entire collection at once. The following example cascades all the windows currently showing in Microsoft Excel.

Windows.Arrange arrangeStyle:=xlCascade

Properties

Application Property, Count Property, Creator Property, Parent Property.

Methods

Arrange Method, Item Method.


Windows Method

Applies To

Application Object, Workbook Object.

Description

Accessor. Returns an object that represents a single window (a Window object, Syntax 1) or a collection of windows (the Windows object, Syntax 2). Read-only.

Syntax 1

object.Windows(index)

Syntax 2

object.Windows

object

Optional for Application, required for Workbook. If Application (or omitted) this method returns a window (or windows) from any open workbook. If Workbook, this method returns a window (or windows) in the specified workbook.

index

Required for Syntax 1. The name or number of the window.

Remarks

Syntax 2 returns a collection of both visible and hidden windows.

Example

This example closes the first open or hidden window in Microsoft Excel.

Application.Windows(1).Close

This example sets the name of window one in the active workbook to Consolidated Balance Sheet. This name is then used as the index to the Windows method.

ActiveWorkbook.Windows(1).Caption = "Consolidated Balance Sheet"
ActiveWorkbook.Windows("Consolidated Balance Sheet") _
    .ActiveSheet.Calculate


WindowsForPens Property

Applies To

Application Object.

Description

True if the computer is running under Microsoft Windows for Pen Computing. Read-only.

Example

This example shows how to limit handwriting recognition to numbers and punctuation only if Microsoft Windows for Pen Computing is running.

If Application.WindowsForPens Then
    Application.ConstrainNumeric = True
End If


WindowState Property

Applies To

Application Object, Window Object.

Description

Returns or sets the state of the window, as shown in the following table. Read-write.

Value | Meaning
xlNormal | Window is not maximized or minimized.
xlMaximized | Window is maximized (Microsoft Windows only). Maximizing a window maximizes all windows on the Microsoft Excel desktop.
xlMinimized | Window is minimized (Microsoft Windows only).

Example

This example maximizes the application window in Microsoft Excel for Windows. (This property cannot be set on the Macintosh.)

Application.WindowState = xlMaximized

This example expands the active window to the maximum size available (assuming that the window is not already maximized).

With ActiveWindow
    .WindowState = xlNormal
    .Top = 1
    .Left = 1
    .Height = Application.UsableHeight
    .Width = Application.UsableWidth
End With


With Statement

Description

Executes a series of statements on a single object or a user-defined type.

Syntax

With object
[statements]
End With

The With statement syntax has these parts:

Part | Description
object | Name of an object or a user-defined type.
statements | One or more statements to be executed on object.

Remarks

The With statement allows you to perform a series of statements on a specified object without requalifying the name of the object. For example, if you have a number of different properties to change on a single object, it is more convenient to place the property assignment statements within the With control structure, referring to the object once instead of referring to it with each property assignment. The following example illustrates use of the With statement to assign values to several properties of the same object.

With MyLabel
    .Height = 2000
    .Width = 2000
    .Caption = "This is MyLabel"
End With

You can nest With statements by placing one With loop within another. Each object must be unique.

See Also

Do...Loop Statement, While...Wend Statement.

Example

This example uses the With statement to execute a series of statements on a single object. The object MyObject and its properties are generic names used for illustration purposes only.

With MyObject
    ' Same as MyObject.Height = 100
    .Height = 100
    .Caption = "Hello World"
    With .Font
        ' Same as MyObject.Font.Color = Red.
        .Color = Red
        .Bold = True
    End With
End With

The following example adds a new menu bar and then activates it. After running the example, you can use MenuBars(xlModule).Activate to restore the Visual Basic Module menu.

With MenuBars.Add("Stock Chart")
    With .Menus.Add("File")
        .MenuItems.Add "Update", "UpdateProc"
        .MenuItems.Add "Print", "PrintProc"
    End With
End With
MenuBars("Stock Chart").Activate

This example creates a formatted multiplication table in cells A1:K11 on Sheet1.

Set dataTableRange = Worksheets("Sheet1").Range("A1:K11")
Set rowInputCell = Worksheets("Sheet1").Range("A12")
Set columnInputCell = Worksheets("Sheet1").Range("A13")

Worksheets("Sheet1").Range("A1").Formula = "=A12*A13"
For i = 2 To 11
    Worksheets("Sheet1").Cells(i, 1) = i - 1
    Worksheets("Sheet1").Cells(1, i) = i - 1
Next i
dataTableRange.Table rowInputCell, columnInputCell
With Worksheets("Sheet1").Range("A1").CurrentRegion
    .Rows(1).Font.Bold = True
    .Columns(1).Font.Bold = True
    .Columns.AutoFit
End With


Workbook Object

Description

Represents a Microsoft Excel workbook.

Accessors

The Workbook object is a member of the Workbooks collection. The Workbooks collection contains all the Workbook objects currently open in Microsoft Excel. Use the Open method to open a file. Use the Add method to create a new empty workbook and add it to the collection.

To access a single member of the collection, use the Workbooks method with the index number or name of the workbook as an argument.

The index number represents the order in which the workbooks were opened or created. Workbooks(1) is the first workbook created; Workbooks(Workbooks.Count) is the last. Activating a workbook does not change its index number. All workbooks are included in the index count, even if they are hidden. The following example activates workbook one.

Workbooks(1).Activate

The Name property returns the workbook name. You cannot set the name using this property. Use the SaveAs method to save the workbook under a different name if you need to change the name. The following example activates the worksheet named "Sheet1" in the workbook named COGS.XLS (the workbook must already be open in Microsoft Excel).

Workbooks("cogs.xls").Worksheets("sheet1").Activate

Using ActiveWorkbook

The ActiveWorkbook property returns the currently active workbook. The following example sets the name of the author for the active workbook.

ActiveWorkbook.Author = "Jean Selva"

Using ThisWorkbook

The ThisWorkbook property returns the workbook where the Visual Basic code is running. In most cases, this is the same as the active workbook. However, if the Visual Basic code is part of an add-in, the ThisWorkbook property will not return the active workbook. In this case, the active workbook is the workbook calling the add-in, while the ThisWorkbook property returns the add-in workbook.

If you will be creating an add-in from your Visual Basic code, you should use the ThisWorkbook property to qualify any statement which must run on the workbook you compile into the add-in.

Properties

ActiveChart Property, ActiveSheet Property, Application Property, Author Property, BuiltinDocumentProperties Property, Colors Property, Comments Property, Container Property, CreateBackup Property, Creator Property, CustomDocumentProperties Property, Date1904 Property, DisplayDrawingObjects Property, FileFormat Property, FullName Property, HasMailer Property, HasPassword Property, HasRoutingSlip Property, Keywords Property, Mailer Property, MultiUserEditing Property, Name Property, OnSave Property, OnSheetActivate Property, OnSheetDeactivate Property, Parent Property, Path Property, PrecisionAsDisplayed Property, ProtectStructure Property, ProtectWindows Property, ReadOnly Property, ReadOnlyRecommended Property, RevisionNumber Property, Routed Property, RoutingSlip Property, Saved Property, SaveLinkValues Property, ShowConflictHistory Property, Subject Property, Title Property, UpdateRemoteReferences Property, UserStatus Property, WriteReserved Property, WriteReservedBy Property.

Methods

Activate Method, ChangeFileAccess Method, ChangeLink Method, Charts Method, Close Method, DeleteNumberFormat Method, DialogSheets Method, EditionOptions Method, Excel4IntlMacroSheets Method, Excel4MacroSheets Method, ExclusiveAccess Method, ForwardMailer Method, LinkInfo Method, LinkSources Method, Modules Method, Names Method, NewWindow Method, OpenLinks Method, Post Method, PrintOut Method, PrintPreview Method, Protect Method, Reply Method, ReplyAll Method, Route Method, RunAutoMacros Method, Save Method, SaveAs Method, SaveCopyAs Method, SendMail Method, SendMailer Method, SetLinkOnData Method, Sheets Method, Styles Method, Unprotect Method, UpdateFromFile Method, UpdateLink Method, Windows Method, Worksheets Method.


Workbooks Collection Object

Description

A collection of all the Workbook objects currently open in the Microsoft Excel application.

Accessors

Use the Open method to open a file. Use the Add method to create a new empty workbook and add it to the collection. The following example adds a new empty workbook to Microsoft Excel (this is equivalent to clicking the New command on the File menu).

Workbooks.Add

The following example opens the file ARRAY.XLS as a read-only workbook.

Workbooks.Open fileName:="array.xls", readOnly:=True

Use the Workbooks method with an argument to access a single member of the collection or without an argument to access the entire collection at once. The following example closes all open workbooks.

Workbooks.Close

Properties

Application Property, Count Property, Creator Property, Parent Property.

Methods

Add Method (Workbooks Collection), Close Method, Item Method, Open Method, OpenText Method.


Workbooks Method

Applies To

Application Object.

Description

Accessor. Returns an object that represents a single open workbook (a Workbook object, Syntax 1) or a collection of all open workbooks (the Workbooks object, Syntax 2). Read-only.

Syntax 1

object.Workbooks(index)

Syntax 2

object.Workbooks

object

Optional. The Application object.

index

Required for Syntax 1. The name or number of the workbook.

Remarks

The collection returned by syntax 2 of the Workbooks method does not include open add-ins, which are a special kind of hidden workbook.

You can, however, return a single open add-in if you know the filename. For example Workbooks("OSCAR.XLA") will return the open add-in named "OSCAR.XLA" as a Workbook object.

Example

This example activates workbook BOOK1.

Workbooks("BOOK1").Activate

This example opens the workbook LARGE.XLS.

Workbooks.Open filename:="LARGE.XLS"

This example closes and saves changes to all workbooks except the one that is running the example.

For Each w In Workbooks
    If w.Name <> ThisWorkbook.Name Then
        w.Close savechanges:=True
    End If
Next w


Worksheet Object

Description

Represents a worksheet, a Microsoft Excel version 4.0 macro sheet, or a Microsoft Excel version 4.0 international macro sheet.

Accessors

The Worksheet object is a member of the Worksheets collection. The Worksheets collection contains all the Worksheet objects in a workbook. Use the Add method to create a new worksheet and add it to the collection. To access a single member of the collection, use the Worksheets method with the index number or name of the worksheet as an argument.

The worksheet index number represents the position of the worksheet on the tab bar of the workbook. Worksheets(1) is the first (leftmost) worksheet in the workbook; Worksheets(Worksheets.Count) is the last. All worksheets are included in the index count, even if they are hidden.

The following example hides worksheet one in the active workbook.

Worksheets(1).Visible = False

The worksheet name is shown on the tab for the worksheet. Use the Name property to set or return the worksheet name. The following example protects the scenarios on the worksheet named "Sheet1."

Worksheets("sheet1").Protect password:="drowssap", scenarios:=True

The Worksheet object is also a member of the Sheets collection. The Sheets collection contains all of the sheets in the workbook (chart sheets, dialog sheets, modules, and worksheets). To access a single member of the collection, use the Sheets method with the index number or name of the sheet as an argument.

Using ActiveSheet

When a worksheet is the active sheet, you can use the ActiveSheet property to refer to it. The following example uses the Activate method to activate the worksheet named "Sheet 1," sets the page orientation to landscape mode, and then prints the worksheet.

Worksheets("sheet1").Activate
ActiveSheet.PageSetup.Orientation = xlLandscape
ActiveSheet.PrintOut

Properties

Application Property, AutoFilterMode Property, CircularReference Property, ConsolidationFunction Property, ConsolidationOptions Property, ConsolidationSources Property, Creator Property, DisplayAutomaticPageBreaks Property, EnableAutoFilter Property, EnableOutlining Property, EnablePivotTable Property, FilterMode Property, Index Property, Name Property, Next Property, OnCalculate Property, OnData Property, OnDoubleClick Property, OnEntry Property, OnSheetActivate Property, OnSheetDeactivate Property, Outline Property, PageSetup Property, Parent Property, Previous Property, ProtectContents Property, ProtectDrawingObjects Property, ProtectionMode Property, ProtectScenarios Property, StandardHeight Property, StandardWidth Property, TransitionExpEval Property, TransitionFormEntry Property, Type Property, UsedRange Property, Visible Property.

Methods

Activate Method, Arcs Method, Buttons Method, Calculate Method, Cells Method, ChartObjects Method, CheckBoxes Method, CheckSpelling Method, ClearArrows Method, Columns Method, Copy Method, Delete Method, DrawingObjects Method, Drawings Method, DropDowns Method, Evaluate Method, GroupBoxes Method, GroupObjects Method, Labels Method, Lines Method, ListBoxes Method, Move Method, Names Method, OLEObjects Method, OptionButtons Method, Ovals Method, Paste Method (DialogSheet or Worksheet Object), PasteSpecial Method (DialogSheet or Worksheet Object), Pictures Method, PivotTables Method, PivotTableWizard Method, PrintOut Method, PrintPreview Method, Protect Method, Range Method, Rectangles Method, Rows Method, SaveAs Method, Scenarios Method, ScrollBars Method, Select Method, SetBackgroundPicture Method, ShowAllData Method, ShowDataForm Method, Spinners Method, TextBoxes Method, Unprotect Method.


Worksheet Property

Applies To

Range Object.

Description

Accessor. Returns a Worksheet object that represents the worksheet containing the specified range. Read-only.

Example

This example displays the name of the worksheet containing the active cell. The example must be run from a worksheet.

MsgBox ActiveCell.Worksheet.Name

This example displays the name of the worksheet containing the range named "testRange."

MsgBox Range("testRange").Worksheet.Name


Worksheets Collection Object

Description

A collection of all the Worksheet objects in the specified or active workbook. Each Worksheet object represents a worksheet, a Microsoft Excel version 4.0 macro sheet, or a Microsoft Excel version 4.0 international macro sheet.

Use the Add method to create a new worksheet and add it to the collection. The following example adds two new worksheets before sheet one of the active workbook.

Worksheets.Add count:=2, before:=Sheets(1)

Use the Worksheets method with an argument to access a single member of the collection or without an argument to access the entire collection at once. The following example moves all the worksheets to the end of the workbook.

Worksheets.Move after:=Sheets(Sheets.Count)

The Sheets collection contains all of the sheets in the workbook (chart sheets, dialog sheets, modules, and worksheets). Use the Sheets method with an argument to access a single member of the collection or without an argument to access the entire collection at once.

Properties

Application Property, Count Property, Creator Property, Parent Property, Visible Property.

Methods

Add Method (Worksheets Collection), Copy Method, Delete Method, FillAcrossSheets Method, Item Method, Move Method, PrintOut Method, PrintPreview Method, Select Method.


Worksheets Method

Applies To

Application Object, Workbook Object.

Description

Accessor. Returns an object that represents a worksheet (a Worksheet object, Syntax 1) or a collection of all worksheets (a Worksheets object, Syntax 2) in the workbook. Read-only.

Syntax 1

object.Worksheets(index)

Syntax 2

object.Worksheets

object

Optional for Application, required for Workbook. The object that contains worksheets.

index

Required for Syntax 1. The name or number of the worksheet to return.

Remarks

This method returns worksheets with the Type property equal to xlWorksheet, not xlExcel4MacroSheet or xlExcel4IntlMacroSheet; use the Excel4MacroSheets method or the Excel4IntlMacroSheets method to return those types.

Using this method with no object qualifier is a shortcut for ActiveWorkbook.Worksheets.

Example

This example displays the value in cell A1 on Sheet1 in the active workbook.

MsgBox Worksheets("Sheet1").Range("A1").Value

This example displays the name of each worksheet in the active workbook.

For Each ws In Worksheets
    MsgBox ws.Name
Next ws

This example adds a new worksheet to the active workbook and then sets the name of the worksheet.

Set newSheet = Worksheets.Add
newSheet.Name = "1995 Budget"


WrapText Property

Applies To

Range Object, Style Object.

Description

True if Microsoft Excel wraps the text in the object. Read-write.

Remarks

Microsoft Excel will change the row height of the range, if necessary, to display the text in the range.

Example

This example formats cell B2 on Sheet1 so that the text in it wraps.

Worksheets("Sheet1").Range("B2").Value = _
    "This text should wrap in a cell."
Worksheets("Sheet1").Range("B2").WrapText = True


Write # Statement

Description

Writes raw data to a sequential file.

Syntax

Write #filenumber[,outputlist]

The Write statement syntax has these parts:

Part | Description
filenumber | Any valid file number.
outputlist | One or more comma-delimited numeric or string expressions to write to a file.

Remarks

If you omit outputlist and include a comma after filenumber, a blank line prints to the file. Multiple expressions can be separated with a space, a semicolon, or a comma. A space has the same effect as a semicolon.

When Write # is used to output data to a file, several universal assumptions are followed so the data can always be read and correctly interpreted using Input #, regardless of locale:

  • Numeric data is always output using the period (.) as the decimal separator.
  • For Boolean data, either #TRUE# or #FALSE# is printed. The True and False keywords are not translated, regardless of locale.
  • Date data is written to the file using the universal date format. When either the date or the time component is missing or zero, only the provided part gets written to the file.
  • Nothing is written to the file if outputlist data is Empty. However, for Null data, #NULL# is output.
  • For error data, the output appears as #ERROR errorcode#. The Error keyword is not translated, regardless of locale.

Unlike the Print # statement, the Write # statement inserts commas between items and quotation marks around strings as they are written to the file. You don't have to put explicit delimiters in the list. Write # inserts a newline character (carriage return or carriage return-linefeed) after it has written the final character in outputlist to the file.

See Also

Input # Statement, Open Statement, Print # Statement.

Example

This example uses the Write # statement to write raw data to a sequential file.

Open "TESTFILE" For Output As 1    ' Open file for output.
Write #1, "Hello World", 234    ' Written data is comma delimited.
Write #1,    ' Write blank line.

' Assign Boolean, Date, Null and Error values.
MyBool = False : MyDate = #February 12, 1969# : MyNull = Null
MyError = CVErr(32767)
' Boolean data is written as #TRUE# or #FALSE#. Date literals are
' written in universal date format. Null data is written as #NULL#.
' Error data is written as #ERROR errorcode#.
Write #1, MyBool ; " is a Boolean value"
Write #1, MyDate ; " is a date"
Write #1, MyNull ; " is a null value"
Write #1, MyError ; " is an error value"
Close #1    ' Close file.


WriteReserved Property

Applies To

Workbook Object.

Description

True if the workbook is write reserved. Read-only.

Remarks

Use the SaveAs method to set this property.

Example

If the active workbook is write-reserved, this example displays a message that contains the name of the user who saved the workbook as write-reserved.

With ActiveWorkbook
    If .WriteReserved = True Then
        MsgBox "Please contact " & .WriteReservedBy & Chr(13) & _
            " if you need to insert data in this workbook."
    End If
End With


WriteReservedBy Property

Applies To

Workbook Object.

Description

Returns a string that names the user with current write permission for the workbook. Read-only.

Example

If the active workbook is write-reserved, this example displays a message that contains the name of the user who saved the workbook as write-reserved.

With ActiveWorkbook
    If .WriteReserved = True Then
        MsgBox "Please contact " & .WriteReservedBy & Chr(13) & _
            " if you need to insert data in this workbook."
    End If
End With


Xor Operator

Description

Used to perform a logical exclusion on two expressions.

Syntax

result = expression1 Xor expression2

The Xor operator syntax has these parts:

Part | Description
result | Any numeric variable.
expression1 | Any expression.
expression2 | Any expression.

Remarks

If one, and only one, of the expressions evaluates True, result is True. However, if either expression is a Null, result is also a Null. When neither expression is a Null, result is determined according to the following table:

If expression1 is | And expression2 is | The result is
True | True | False
True | False | True
False | True | True
False | False | False

The Xor operator also performs a bit-wise comparison of identically positioned bits in two numeric expressions and sets the corresponding bit in result according to the following truth table:

If bit in expression1 is | And bit in expression2 is | The result is
0 | 0 | 0
0 | 1 | 1
1 | 0 | 1
1 | 1 | 0

See Also

Operator Precedence.

Example

This example uses the Xor operator to perform logical exclusion on two expressions.

A = 10: B = 8: C = 6 : D = Null    ' Initialize variables.
MyCheck = A > B Xor B > C    ' Returns False.
MyCheck = B > A Xor B > C    ' Returns True.
MyCheck = B > A Xor C > B    ' Returns False.
MyCheck = B > D Xor A > B    ' Returns Null.
MyCheck = A Xor B    ' Returns 2 (bit-wise comparison).


XValues Property

Applies To

Series Object.

Description

Returns or sets an array of x values for a chart series. The XValues property can be set to a range on a worksheet or an array of values, but it may not be a combination of both. Read-write.

Example

This example sets the x values for series one in Chart1 to the range B1:B5 on Sheet1.

Set Charts("Chart1").SeriesCollection(1).XValues = _
        Worksheets("Sheet1").Range("B1:B5")

This example uses an array to set values for the individual points in series one in Chart1.

Charts("Chart1").SeriesCollection(1).XValues = _
        Array(5.0, 6.3, 12.6, 28, 50)


XYGroups Method

Applies To

Chart Object.

Description

Accessor. On a 2-D chart, returns an object that represents a single scatter chart group (a ChartGroup object, Syntax 1), or a collection of the scatter chart groups (a ChartGroups collection, Syntax 2).

Syntax 1

object.XYGroups(index)

Syntax 2

object.XYGroups

object

Required. The Chart object.

index

Required for Syntax 1. Specifies the chart group.

Example

This example converts X-Y group (scatter group) one to an area group. The example should be run on a 2-D chart.

Charts("Chart1").XYGroups(1).Type = xlArea


Year Function

Description

Returns a whole number representing the year.

Syntax

Year(date)

The date named argument is limited to a date or numbers and strings, in any combination, that can represent a date. If date contains no valid data, Null is returned.

See Also

Date Function, Date Statement, Day Function, Month Function, Now Function, Weekday Function.

Example

This example uses the Year function to obtain the year from a specified date.

' In the development environment, the date literal will display in short
' format using the locale settings of your code.
MyDate = #February 12, 1969#    ' Assign a date.
MyYear = Year(MyDate)    ' MyYear contains 1969.


Zoom Property

Applies To

PageSetup Object, Window Object.

Description

PageSetup object:

Returns or sets a percentage to scale the worksheet for printing, between 10 and 400 percent. Read-write.

If this property is False, the FitToPagesWide and FitToPagesTall properties control how the worksheet is scaled.

Window object:

Returns or sets the display size of the window, in percent (100 means show at normal size; 200 means the window is double size, etc.).

The property can also be set to True to set the window size to fit the current selection.

Remarks

PageSetup object:

This property applies only to worksheets.

All scaling retains the aspect ratio of the original document.

Window object:

This function will only affect the sheet that is currently active in the window. To use this property on other sheets, you must first activate them.

Example

This example scales Sheet1 by 150 percent when the worksheet is printed.

Worksheets("Sheet1").PageSetup.Zoom = 150


ZOrder Property

Applies To

Arc Object, Arcs Collection, Button Object, Buttons Collection, ChartObject Object, ChartObjects Collection, CheckBox Object, Drawing Object, DrawingObjects Collection, Drawings Collection, DropDown Object, DropDowns Collection, EditBox Object, EditBoxes Collection, GroupBox Object, GroupBoxes Collection, GroupObject Object, GroupObjects Collection, Label Object, Labels Collection, Line Object, Lines Collection, ListBox Object, ListBoxes Collection, OLEObject Object, OLEObjects Collection, OptionButton Object, OptionButtons Collection, Oval Object, Ovals Collection, Picture Object, Pictures Collection, Rectangle Object, Rectangles Collection, ScrollBar Object, ScrollBars Collection, Spinner Object, Spinners Collection, TextBox Object, TextBoxes Collection.

Description

Returns the z-order position of the object. Read only.

Remarks

For any collection of objects, the object at the back of the z-order is collection(1), and the object at the front of the z-order is collection(collection.Count). For example, if there are three ovals on the active sheet, the oval at the back of the z-order is ActiveSheet.Ovals(1), and the oval at the front of the z-order is ActiveSheet.Ovals(ActiveSheet.Ovals.Count).

See Also

BringToFront Method, SendToBack Method.

Example

This example displays the z-order position of oval one on Sheet1.

MsgBox "The oval's z-order position is " & _
    Worksheets("Sheet1").Ovals(1).ZOrder


Microsoft Excel Macro Functions Contents

Alphabetical List of Macro Functions

Macro Functions Listed by Category


Alphabetical List of Macro Functions

A1.R1C1

ABSREF

ACTIVATE

ACTIVATE.NEXT

ACTIVATE.PREV

ACTIVE.CELL

ACTIVE.CELL.FONT

ADD.ARROW

ADD.BAR

ADD.CHART.AUTOFORMAT

ADD.COMMAND

ADD.LIST.ITEM

ADD.MENU

ADD.OVERLAY

ADD.TOOL

ADD.TOOLBAR

ADDIN.MANAGER

ALERT

ALIGNMENT

ANOVA1

ANOVA2

ANOVA3

APP.ACTIVATE.MICROSOFT

APP.ACTIVATE

APP.MAXIMIZE

APP.MINIMIZE

APP.MOVE

APP.RESTORE

APP.SIZE

APP.TITLE

APPLY.NAMES

APPLY.STYLE

ARGUMENT

ARRANGE.ALL

ASSIGN.TO.OBJECT

ASSIGN.TO.TOOL

ATTACH.TEXT

ATTACH.TOOLBARS

AUTO.OUTLINE

AXES

BEEP

BORDER

BREAK

BRING.TO.FRONT

CALCULATE.DOCUMENT

CALCULATE.NOW

CALCULATION

CALLER

CANCEL.COPY

CANCEL.KEY

CELL.PROTECTION

CHANGE.LINK

CHART.ADD.DATA

CHART.TREND

CHART.WIZARD

CHECK.COMMAND

CHECKBOX.PROPERTIES

CLEAR

CLEAR.OUTLINE

CLEAR.ROUTING.SLIP

CLOSE

CLOSE.ALL

COLOR.PALETTE

COLUMN.WIDTH

COMBINATION

CONSOLIDATE

CONSTRAIN.NUMERIC

COPY

COPY.CHART

COPY.PICTURE

COPY.TOOL

CREATE.NAMES

CREATE.OBJECT

CREATE.PUBLISHER

CUSTOM.REPEAT

CUSTOM.UNDO

CUT

DATA.DELETE

DATA.FIND

DATA.FIND.NEXT

DATA.FIND.PREV

DATA.FORM

DATA.LABEL

DATA.SERIES

DEFINE.NAME

DEFINE.STYLE

DELETE.ARROW

DELETE.BAR

DELETE.CHART.AUTOFORMAT

DELETE.COMMAND

DELETE.FORMAT

DELETE.MENU

DELETE.NAME

DELETE.OVERLAY

DELETE.STYLE

DELETE.TOOL

DELETE.TOOLBAR

DEMOTE

DEREF

DESCR

DIALOG.BOX

DIRECTORY

DISABLE.INPUT

DISPLAY

DOCUMENTS

DUPLICATE

ECHO

EDIT.COLOR

EDIT.DELETE

EDIT.OBJECT

EDIT.REPEAT

EDIT.SERIES

EDIT.TOOL

EDITBOX.PROPERTIES

EDITION.OPTIONS

ELSE

ELSE.IF

EMBED

ENABLE.COMMAND

ENABLE.TIPWIZARD

ENABLE.OBJECT

ENABLE.TOOL

END.IF

ENTER.DATA

ERROR

ERRORBAR.X

ERRORBAR.Y

EVALUATE

EXEC

EXECUTE

EXPON

EXTEND.POLYGON

EXTRACT

FCLOSE

FILE.DELETE

FILES

FILL.AUTO

FILL.DOWN

FILL.GROUP

FILL.LEFT

FILL.RIGHT

FILL.UP

FILTER

FILTER.ADVANCED

FILTER.SHOW.ALL

FIND.FILE

FONT

FONT.PROPERTIES

FOPEN

FOR

FOR.CELL

FORMAT.AUTO

FORMAT.CHART

FORMAT.CHARTTYPE

FORMAT.FONT

FORMAT.LEGEND

FORMAT.MAIN

FORMAT.MOVE

FORMAT.NUMBER

FORMAT.OVERLAY

FORMAT.SHAPE

FORMAT.SIZE

FORMAT.TEXT

FORMULA.ARRAY

FORMULA.CONVERT

FORMULA.FILL

FORMULA.FIND

FORMULA.FIND.NEXT

FORMULA.FIND.PREV

FORMULA.GOTO

FORMULA.REPLACE

FOURIER

FPOS

FREAD

FREADLN

FREEZE.PANES

FSIZE

FTESTV

FULL

FULL.SCREEN

FUNCTION.WIZARD

FWRITE

FWRITELN

GALLERY.3D.AREA

GALLERY.3D.BAR

GALLERY.3D.COLUMN

GALLERY.3D.LINE

GALLERY.3D.PIE

GALLERY.3D.SURFACE

GALLERY.AREA

GALLERY.BAR

GALLERY.COLUMN

GALLERY.CUSTOM

GALLERY.DOUGHNUT

GALLERY.LINE

GALLERY.PIE

GALLERY.RADAR

GALLERY.SCATTER

GET.BAR

GET.CELL

GET.CHART.ITEM

GET.DEF

GET.DOCUMENT

GET.FORMULA

GET.LINK.INFO

GET.NAME

GET.NOTE

GET.OBJECT

GET.PIVOT.FIELD

GET.PIVOT.ITEM

GET.PIVOT.TABLE

GET.TOOL

GET.TOOLBAR

GET.WINDOW

GET.WORKBOOK

GET.WORKSPACE

GOAL.SEEK

GOTO

GRIDLINES

GROUP

HALT

HELP

HIDE

HIDE.DIALOG

HIDE.OBJECT

HISTOGRAM

HLINE

HPAGE

HSCROLL

IF

INITIATE

INPUT

INSERT.OBJECT

INSERT.PICTURE

INSERT.TITLE

JUSTIFY

LABEL.PROPERTIES

LAST.ERROR

LEGEND

LINK.COMBO

LINK.FORMAT

LINKS

LIST.NAMES

LISTBOX.PROPERTIES

MACRO.OPTIONS

MAIL.ADD.MAILER

MAIL.DELETE.MAILER

MAIL.EDIT.MAILER

MAIL.FORWARD

MAIL.LOGOFF

MAIL.LOGON

MAIL.NEXT.LETTER

MAIL.REPLY

MAIL.REPLY.ALL

MAIN.CHART

MAIN.CHART.TYPE

MCORREL

MCOVAR

MENU.EDITOR

MERGE.STYLES

MESSAGE

MOVE

MOVEAVG

MOVE.TOOL

NAMES

NEW

NEW.WINDOW

NEXT

NOTE

OBJECT.PROPERTIES

OBJECT.PROTECTION

ON.DATA

ON.DOUBLECLICK

ON.ENTRY

ON.KEY

ON.RECALC

ON.SHEET

ON.TIME

ON.WINDOW

OPEN

OPEN.DIALOG

OPEN.LINKS

OPEN.MAIL

OPEN.TEXT

OPTIONS.CALCULATION

OPTIONS.CHART

OPTIONS.EDIT

OPTIONS.GENERAL

OPTIONS.LISTS.ADD

OPTIONS.LISTS.DELETE

OPTIONS.TRANSITION

OPTIONS.VIEW

OUTLINE

OVERLAY

PAGE.SETUP

PARSE

PASTE

PASTE.LINK

PASTE.PICTURE

PASTE.PICTURE.LINK

PASTE.SPECIAL

PASTE.TOOL

PATTERNS

PAUSE

PIVOT.ADD.DATA

PIVOT.ADD.FIELDS

PIVOT.FIELD

PIVOT.FIELD.GROUP

PIVOT.FIELD.PROPERTIES

PIVOT.FIELD.UNGROUP

PIVOT.ITEM.PROPERTIES

PIVOT.ITEM

PIVOT.REFRESH

PIVOT.SHOW.PAGES

PIVOT.TABLE.WIZARD

PLACEMENT

POKE

PRECISION

PREFERRED

PRESS.TOOL

PRINT

PRINT.PREVIEW

PRINTER.SETUP

PROMOTE

PROTECT.DOCUMENT

PTTESTM

PTTESTV

PUSHBUTTON.PROPERTIES

QUERY.GET.DATA

QUERY.REFRESH

QUIT

RANDOM

RANKPERC

REFTEXT

REGISTER

REGRESS

RELREF

REMOVE.LIST.ITEM

REMOVE.PAGE.BREAK

RENAME.COMMAND

RENAME.OBJECT

REPLACE.FONT

REPORT.DEFINE

REPORT.DELETE

REPORT.GET

REPORT.PRINT

REQUEST

RESET.TOOL

RESET.TOOLBAR

RESTART

RESULT

RESUME

RETURN

ROUTE.DOCUMENT

ROUTING.SLIP

ROW.HEIGHT

RUN

SAMPLE

SAVE

SAVE.DIALOG

SAVE.AS

SAVE.COPY.AS

SAVE.TOOLBAR

SAVE.WORKBOOK

SAVE.WORKSPACE

SCALE

SCENARIO.ADD

SCENARIO.CELLS

SCENARIO.DELETE

SCENARIO.EDIT

SCENARIO.GET

SCENARIO.MERGE

SCENARIO.SHOW

SCENARIO.SHOW.NEXT

SCENARIO.SUMMARY

SCROLLBAR.PROPERTIES

SELECT

SELECT.ALL

SELECT.CHART

SELECT.END

SELECT.LAST.CELL

SELECT.LIST.ITEM

SELECT.PLOT.AREA

SELECT.SPECIAL

SELECTION

SEND.KEYS

SEND.MAIL

SEND.TO.BACK

SERIES

SERIES.AXES

SERIES.ORDER

SERIES.X

SERIES.Y

SET.CONTROL.VALUE

SET.CRITERIA

SET.DATABASE

SET.DIALOG.DEFAULT

SET.DIALOG.FOCUS

SET.EXTRACT

SET.LIST.ITEM

SET.NAME

SET.PAGE.BREAK

SET.PREFERRED

SET.PRINT.AREA

SET.PRINT.TITLES

SET.UPDATE.STATUS

SET.VALUE

SHORT.MENUS

SHOW.ACTIVE.CELL

SHOW.BAR

SHOW.CLIPBOARD

SHOW.DETAIL

SHOW.DIALOG

SHOW.INFO

SHOW.LEVELS

SHOW.TOOLBAR

SIZE

SLIDE.COPY.ROW

SLIDE.CUT.ROW

SLIDE.DEFAULTS

SLIDE.DELETE.ROW

SLIDE.EDIT

SLIDE.GET

SLIDE.PASTE

SLIDE.PASTE.ROW

SLIDE.SHOW

SOLVER.ADD

SOLVER.CHANGE

SOLVER.DELETE

SOLVER.FINISH

SOLVER.GET

SOLVER.LOAD

SOLVER.OK

SOLVER.OPTIONS

SOLVER.RESET

SOLVER.SAVE

SOLVER.SOLVE

SORT

SOUND.NOTE

SOUND.PLAY

SPELLING

SPELLING.CHECK

SPLIT

SQL.BIND

SQL.CLOSE

SQL.ERROR

SQL.EXEC.QUERY

SQL.GET.SCHEMA

SQL.OPEN

SQL.RETRIEVE

SQL.RETRIEVE.TO.FILE

STANDARD.FONT

STANDARD.WIDTH

STEP

STYLE

SUBSCRIBE.TO

SUBTOTAL.CREATE

SUBTOTAL.REMOVE

SUMMARY.INFO

TAB.ORDER

TABLE

TERMINATE

TEXT.BOX

TEXT.TO.COLUMNS

TEXTREF

TRACER.CLEAR

TRACER.DISPLAY

TRACER.ERROR

TRACER.NAVIGATE

TTESTM

UNDO

UNGROUP

UNHIDE

UNLOCKED.NEXT

UNLOCKED.PREV

UNREGISTER

UPDATE.LINK

VBA.INSERT.FILE

VBA.MAKE.ADDIN

VIEW.3D

VIEW.DEFINE

VIEW.DELETE

VIEW.GET

VIEW.SHOW

VLINE

VOLATILE

VPAGE

VSCROLL

WAIT

WHILE

WINDOW.MAXIMIZE

WINDOW.MINIMIZE

WINDOW.MOVE

WINDOW.RESTORE

WINDOW.SIZE

WINDOW.TITLE

WINDOWS

WORKBOOK.ACTIVATE

WORKBOOK.ADD

WORKBOOK.COPY

WORKBOOK.DELETE

WORKBOOK.HIDE

WORKBOOK.INSERT

WORKBOOK.MOVE

WORKBOOK.NAME

WORKBOOK.NEW

WORKBOOK.NEXT

WORKBOOK.OPTIONS

WORKBOOK.PREV

WORKBOOK.PROTECT

WORKBOOK.SCROLL

WORKBOOK.SELECT

WORKBOOK.TAB.SPLIT

WORKBOOK.UNHIDE

WORKGROUP

WORKSPACE

ZOOM

ZTESTM


Macro Functions Listed by Category

Command-Equivalent

Control

Customizing

Database & List Management

DDE/External

Engineering

Information

Lookup & Reference

Statistical

Text


Command-Equivalent Macro Functions

A1.R1C1

ACTIVATE

ACTIVATE.NEXT

ACTIVATE.PREV

ACTIVE.CELL.FONT

ADD.ARROW

ADD.OVERLAY

ADDIN.MANAGER

ALIGNMENT

APP.MAXIMIZE

APP.MINIMIZE

APP.MOVE

APP.RESTORE

APP.SIZE

APPLY.NAMES

APPLY.STYLE

ARRANGE.ALL

ASSIGN.TO.OBJECT

ATTACH.TEXT

ATTACH.TOOLBARS

AUTO.OUTLINE

AXES

BORDER

BRING.TO.FRONT

CALCULATE.DOCUMENT

CALCULATE.NOW

CALCULATION

CANCEL.COPY

CELL.PROTECTION

CHANGE.LINK

CHART.ADD.DATA

CHART.WIZARD

CLEAR

CLEAR.OUTLINE

CLEAR.ROUTING.SLIP

CLOSE

CLOSE.ALL

COLOR.PALETTE

COLUMN.WIDTH

COMBINATION

CONSOLIDATE

CONSTRAIN.NUMERIC

COPY

COPY.CHART

COPY.PICTURE

CREATE.NAMES

CREATE.OBJECT

CREATE.PUBLISHER

CUT

DATA.LABEL

DATA.SERIES

DEFINE.NAME

DEFINE.STYLE

DELETE.ARROW

DELETE.FORMAT

DELETE.CHART.AUTOFORMAT

DELETE.NAME

DELETE.OVERLAY

DELETE.STYLE

DEMOTE

DISPLAY

DUPLICATE

EDIT.COLOR

EDIT.DELETE

EDIT.REPEAT

EDIT.SERIES

ENABLE.TIPWIZARD

ERRORBAR.X

ERRORBAR.Y

EXTEND.POLYGON

FILE.CLOSE

FILE.DELETE

FILL.AUTO

FILL.DOWN

FILL.GROUP

FILL.LEFT

FILL.RIGHT

FILL.UP

FILTER

FILTER.ADVANCED

FILTER.SHOW.ALL

FIND.FILE

FONT

FONT.PROPERTIES

FORMAT.AUTO

FORMAT.CHART

FORMAT.CHARTTYPE

FORMAT.FONT

FORMAT.LEGEND

FORMAT.MAIN

FORMAT.MOVE

FORMAT.NUMBER

FORMAT.OVERLAY

FORMAT.SHAPE

FORMAT.SIZE

FORMAT.TEXT

FORMULA.FILL

FORMULA.FIND

FORMULA.FIND.NEXT

FORMULA.FIND.PREV

FORMULA.GOTO

FORMULA.REPLACE

FREEZE.PANES

FULL

FULL.SCREEN

FUNCTION.WIZARD

GALLERY.3D.AREA

GALLERY.3D.BAR

GALLERY.3D.COLUMN

GALLERY.3D.LINE

GALLERY.3D.PIE

GALLERY.3D.SURFACE

GALLERY.AREA

GALLERY.BAR

GALLERY.COLUMN

GALLERY.CUSTOM

GALLERY.DOUGHNUT

GALLERY.LINE

GALLERY.PIE

GALLERY.RADAR

GALLERY.SCATTER

GOAL.SEEK

GRIDLINES

GROUP

HIDE

HIDE.OBJECT

HLINE

HPAGE

HSCROLL

INSERT

INSERT.PICTURE

INSERT.TITLE

JUSTIFY

LEGEND

LINK.FORMAT

LINKS

LIST.NAMES

INSERT

MACRO.OPTIONS

MAIL.ADD.MAILER

MAIL.DELETE.MAILER

MAIL.EDIT.MAILER

MAIL.FORWARD

MAIL.LOGOFF

MAIL.LOGON

MAIL.NEXT.LETTER

MAIL.REPLY

MAIL.REPLY.ALL

MAIN.CHART

MAIN.CHART.TYPE

MENU.EDITOR

MERGE.STYLES

MOVE

NEW

NEW.WINDOW

NOTE

OBJECT.PROPERTIES

OBJECT.PROTECTION

OPEN

OPEN.LINKS

OPEN.MAIL

OPEN.TEXT

OPTIONS.CALCULATION

OPTIONS.CHART

OPTIONS.EDIT

OPTIONS.GENERAL

OPTIONS.LISTS.ADD

OPTIONS.LISTS.DELETE

OPTIONS.TRANSITION

OPTIONS.VIEW

OUTLINE

OVERLAY

PAGE.SETUP

PARSE

PASTE

PASTE.LINK

PASTE.PICTURE

PASTE.PICTURE.LINK

PASTE.SPECIAL

PATTERNS

PIVOT.ADD.DATA

PIVOT.ADD.FIELDS

PIVOT.FIELD

PIVOT.FIELD.GROUP

PIVOT.FIELD.PROPERTIES

PIVOT.FIELD.UNGROUP

PIVOT.ITEM.PROPERTIES

PIVOT.ITEM

PIVOT.REFRESH

PIVOT.SHOW.PAGES

PIVOT.TABLE.WIZARD

PLACEMENT

PRECISION

PREFERRED

PRINT

PRINT.PREVIEW

PRINTER.SETUP

PROMOTE

PROTECT.DOCUMENT

QUERY.GET.DATA

QUERY.REFRESH

QUIT

REMOVE.PAGE.BREAK

RENAME.OBJECT

REPLACE.FONT

REPORT.DEFINE

REPORT.DELETE

REPORT.PRINT

RESUME

ROUTE.DOCUMENT

ROUTING.SLIP

ROW.HEIGHT

RUN

SAMPLE

SAVE

SAVE.AS

SAVE.COPY.AS

SAVE.WORKBOOK

SAVE.WORKSPACE

SCALE

SCENARIO.ADD

SCENARIO.CELLS

SCENARIO.DELETE

SCENARIO.EDIT

SCENARIO.MERGE

SCENARIO.SHOW

SCENARIO.SHOW.NEXT

SCENARIO.SUMMARY

SELECT

SELECT.ALL

SELECT.CHART

SELECT.END

SELECT.LAST.CELL

SELECT.PLOT.AREA

SELECT.SPECIAL

SEND.MAIL

SEND.TO.BACK

SERIES

SERIES.AXES

SERIES.ORDER

SERIES.X

SERIES.Y

SET.PAGE.BREAK

SET.PREFERRED

SET.PRINT.AREA

SET.PRINT.TITLES

SHORT.MENUS

SHOW.ACTIVE.CELL

SHOW.BAR

SHOW.CLIPBOARD

SHOW.DETAIL

SHOW.INFO

SHOW.LEVELS

SHOW.TOOLBAR

SIZE

SLIDE.COPY.ROW

SLIDE.CUT.ROW

SLIDE.DEFAULTS

SLIDE.DELETE.ROW

SLIDE.EDIT

SLIDE.PASTE

SLIDE.PASTE.ROW

SLIDE.SHOW

SOLVER.ADD

SOLVER.CHANGE

SOLVER.DELETE

SOLVER.FINISH

SOLVER.LOAD

SOLVER.OK

SOLVER.OPTIONS

SOLVER.RESET

SOLVER.SAVE

SOLVER.SOLVE

SORT

SOUND.NOTE

SOUND.PLAY

SPELLING

SPLIT

STANDARD.FONT

STANDARD.WIDTH

STYLE

SUBTOTAL.CREATE

SUBTOTAL.REMOVE

SUMMARY.INFO

TABLE

TEXT.BOX

TEXT.TO.COLUMNS

TRACER.CLEAR

TRACER.DISPLAY

TRACER.ERROR

TRACER.NAVIGATE

UNDO

UNGROUP

UNHIDE

UNLOCKED.NEXT

UNLOCKED.PREV

UPDATE.LINK

VBA.INSERT.FILE

VBA.MAKE.ADDIN

VIEW.3D

VIEW.DEFINE

VIEW.DELETE

VIEW.SHOW

VLINE

VPAGE

VSCROLL

WINDOW.MAXIMIZE

WINDOW.MINIMIZE

WINDOW.MOVE

WINDOW.RESTORE

WINDOW.SIZE

WORKBOOK.ACTIVATE

WORKBOOK.ADD

WORKBOOK.COPY

WORKBOOK.DELETE

WORKBOOK.HIDE

WORKBOOK.INSERT

WORKBOOK.MOVE

WORKBOOK.NAME

WORKBOOK.NEW

WORKBOOK.NEXT

WORKBOOK.OPTIONS

WORKBOOK.PREV

WORKBOOK.PROTECT

WORKBOOK.SCROLL

WORKBOOK.SELECT

WORKBOOK.TAB.SPLIT

WORKBOOK.UNHIDE

WORKGROUP

WORKSPACE

ZOOM


Control Macro Functions

ARGUMENT

BREAK

ELSE

ELSE.IF

END.IF

FOR

FOR.CELL

GOTO

HALT

IF

NEXT

PAUSE

RESTART

RESULT

RETURN

SET.NAME

SET.VALUE

STEP

VOLATILE

WAIT

WHILE


Customizing Macro Functions

ADD.BAR

ADD.CHART.AUTOFORMAT

ADD.COMMAND

ADD.LIST.ITEM

ADD.MENU

ADD.TOOL

ADD.TOOLBAR

ALERT

APP.TITLE

ASSIGN.TO.TOOL

BEEP

CANCEL.KEY

CHECK.COMMAND

CHECKBOX.PROPERTIES

COPY.TOOL

CUSTOM.REPEAT

CUSTOM.UNDO

DELETE.BAR

DELETE.CHART.AUTOFORMAT

DELETE.COMMAND

DELETE.MENU

DELETE.TOOL

DELETE.TOOLBAR

DIALOG.BOX

DISABLE.INPUT

ECHO

EDIT.TOOL

EDITBOX.PROPERTIES

ENABLE.COMMAND

ENABLE.OBJECT

ENABLE.TOOL

ENTER.DATA

ERROR

HELP

HIDE.DIALOG

INPUT

LABEL.PROPERTIES

LINK.COMBO

LINK.FORMAT

LISTBOX.PROPERTIES

MESSAGE

MOVE.TOOL

ON.DATA

ON.DOUBLECLICK

ON.ENTRY

ON.KEY

ON.RECALC

ON.TIME

ON.WINDOW

PASTE.TOOL

PRESS.TOOL

REMOVE.LIST.ITEM

RENAME.COMMAND

RESET.TOOL

RESET.TOOLBAR

SAVE.TOOLBAR

SELECT.LIST.ITEM

SET.CONTROL.VALUE

SET.DIALOG.DEFAULT

SET.DIALOG.FOCUS

SET.LIST.ITEM

SHOW.DIALOG

SHOW.TOOLBAR

TAB.ORDER

WINDOW.TITLE


Database & List Management Macro Functions

DATA.DELETE

DATA.FIND

DATA.FIND.NEXT

DATA.FIND.PREV

DATA.FORM

EXTRACT

SET.CRITERIA

SET.DATABASE

SET.EXTRACT

SQL.BIND

SQL.CLOSE

SQL.ERROR

SQL.EXEC.QUERY

SQL.GET.SCHEMA

SQL.OPEN

SQL.RETRIEVE

SQL.RETRIEVE.TO.FILE


DDE & External Macro Functions

APP.ACTIVATE.MICROSOFT

APP.ACTIVATE

EDIT.OBJECT

EDITION.OPTIONS

EMBED

EXEC

EXECUTE

FCLOSE

FOPEN

FPOS

FREAD

FREADLN

FSIZE

FWRITE

FWRITELN

INITIATE

INSERT.OBJECT

POKE

REGISTER

REQUEST

SEND.KEYS

SET.UPDATE.STATUS

SUBSCRIBE.TO

TERMINATE

UNREGISTER


Engineering Macro Functions

FOURIER

SAMPLE


Information Macro Functions

ACTIVE.CELL

CALLER

DIRECTORY

DOCUMENTS

FILES

GET.BAR

GET.CELL

GET.CHART.ITEM

GET.DEF

GET.DOCUMENT

GET.FORMULA

GET.LINK.INFO

GET.NAME

GET.NOTE

GET.OBJECT

GET.PIVOT.FIELD

GET.PIVOT.ITEM

GET.PIVOT.TABLE

GET.TOOL

GET.TOOLBAR

GET.WINDOW

GET.WORKBOOK

GET.WORKSPACE

LAST.ERROR

LINKS

NAMES

REPORT.GET

SCENARIO.GET

SELECTION

SLIDE.GET

SOLVER.GET

VIEW.GET

WINDOWS


Lookup & Reference Macro Functions

ABSREF

DEREF

EVALUATE

FORMULA.CONVERT

REFTEXT

RELREF

TEXTREF


Text Macro Functions

SPELLING.CHECK

For information on the selected worksheet function , see the List of Worksheet Functions or look for the selected function in the Microsoft Excel online index.


ON Functions

ON functions allow you to specify a macro to be run when a certain event occurs. The ON functions turn on and off this special event handling.

ON functions are turned on by specifying the type of event to wait for, such as recalculation, a specific time, or a key to be pressed, and the macro to be run when the event occurs. ON functions are turned off by using the same formula but omitting the argument specifying the macro to be run.

ON.DATA Runs a macro when data is entered

ON.DOUBLECLICK Runs a macro when you double-click any cell or object on the specified document or double-click any item on the specified chart

ON.ENTRY Runs a macro when a document is recalculated

ON.KEY Runs a macro when a specified key is pressed

ON.RECALC Runs a macro when a document is recalculated

ON.SHEET Runs a macro when a specified sheet is selected

ON.TIME Runs a macro at a specific time

ON.WINDOW Runs a macro when you switch to a window


Hidden Function

This function is available for compatibility with another language version of Microsoft Excel.

See Also

Help

Microsoft Excel Macro Functions Contents


Functions


A1.R1C1

Macro Sheets Only

Displays row and column headings and cell references in either the R1C1 or A1 reference style. A1 is the Microsoft Excel default reference style.

Syntax

A1.R1C1(logical)

Logical is a logical value specifying which reference style to use. If logical is TRUE, all worksheets and macro sheets use A1 references; if FALSE, all worksheets and macro sheets use R1C1 references.

Example

The following macro formula displays an alert box asking you to choose either A1 or R1C1 reference style. This is useful in an Auto_Open macro if several persons who prefer different reference styles must maintain the same worksheet.

A1.R1C1(ALERT("Click OK for A1 style; Cancel for R1C1", 1))

Related Functions

List of Command-Equivalent Functions


ACTIVE.CELL

Macro Sheets Only

Returns the reference of the active cell in the selection as an external reference.

Syntax

ACTIVE.CELL( )

Remarks

  • If an object is selected, ACTIVE.CELL returns the #N/A error value.
  • If a chart window is active, ACTIVE.CELL returns the #REF! error value.
  • If you use ACTIVE.CELL in a function or operation, you will usually get the value contained in the active cell instead of its reference, because the reference is automatically converted to the contents of the reference. See the third example following.
  • If you use ACTIVE.CELL in a function that requires a reference argument, then Microsoft Excel does not convert the reference to a value.
  • If you want to work with the actual reference, use the REFTEXT function to convert the active-cell reference to text, which you can then store or manipulate (or convert back to a reference with TEXTREF). See the second example following.

Tip Use the following macro formula to verify that the current selection is a cell or range of cells:

=ISREF(ACTIVE.CELL( ))

Examples

The following macro formula assigns the name Sales to the active cell:

SET.NAME("Sales", ACTIVE.CELL())

In this example, note that "Sales" refers to a cell on the active worksheet, but the name itself exists only in the macro sheet's list of names. In other words, the preceding formula does not define a name on the worksheet.

The following macro formula puts the reference of the active cell into the cell named Temp:

FORMULA("="&REFTEXT(ACTIVE.CELL()), Temp)

The following macro formula checks the contents of the active cell. If the cell contains only the letter "c" or "s", the macro branches to an area named FinishRefresh:

IF(OR(ACTIVE.CELL()="c", ACTIVE.CELL()="s"), GOTO(FinishRefresh))

In Microsoft Excel for Windows, if the document in the active window is named SALES and A1 is the active cell, then:

ACTIVE.CELL() equals SALES!$A$1

In Microsoft Excel for the Macintosh, if the document in the active window is named SALES 1 and A1 is the active cell, then:

ACTIVE.CELL() equals 'SALES 1'!$A$1

Related Functions

SELECT Selects a cell, worksheet object, or chart item

List of Information Functions


ALERT

Macro Sheets Only

Displays a dialog box and message and waits for you to choose a button. Use ALERT instead of MESSAGE if you want to interrupt the flow of a macro and force the user to make a choice or to notice an important message.

Syntax

ALERT(message_text, type_num, help_ref)

Message_text is the message displayed in the dialog box.

Type_num is a number from 1 to 3 specifying which type of dialog box to display. If you omit type_num, it is assumed to be 2.

  • If type_num is 1, ALERT displays a dialog box containing the OK and Cancel buttons. Choose a button to continue or cancel an action. ALERT returns TRUE if you choose the OK button and FALSE if you choose the Cancel button. See the last example below.
  • If type_num is 2 or 3, ALERT displays a dialog box containing an OK button. Choose the button to continue, and ALERT returns TRUE. The only difference between specifying 2 or 3 is that ALERT displays a different icon on the left side of the dialog box as shown in the examples below. So, for example, you could use 2 for notes or to present general information, and 3 for errors or warnings.

Help_ref is a reference to a custom online Help topic, in the form "filename! topic_number".

  • If help_ref is present, a Help button appears in the lower-right corner of the alert message. Choosing the Help button starts Help and displays the specified topic.
  • If help_ref is omitted, no Help button appears.
  • Help_ref must be given in text form.

Note In Microsoft Excel for the Macintosh, the ALERT dialog box is not a movable window.

Examples

The following dialog boxes show the results of using ALERT with type_num 1, 2, and 3. The first and fourth examples include a Help button.

In Microsoft Excel for Windows, the following macro formulas display these three dialog boxes.

ALERT("Are you sure you want to delete this item?", 1, "CUSTHELP.HLP!101")

ALERT("The number should be between 1 and 100", 2)

ALERT("Your debits and credits are not equal; do not end this transaction.", 3)

In Microsoft Excel for the Macintosh, the following macro formulas display these three dialog boxes.

ALERT("Are you sure you want to delete this item?", 1, "'Custom Help'!101")

ALERT("The number should be between 1 and 100", 2)

ALERT("Your debits and credits are not equal; do not end this transaction.", 3)

A common use of the ALERT function is to give the user a choice of two actions. The following macro formula in an Auto_Open macro asks which reference style to use when the worksheet is opened.

A1.R1C1(ALERT("Click OK for A1 style; Cancel for R1C1", 1))

Related Functions

INPUT Displays a dialog box for user input

MESSAGE Displays a message in the status bar

List of Customizing Functions


ARGUMENT

Macro Sheets Only

Describes the arguments used in a custom function, which is a type of macro, or in a subroutine. A custom function or subroutine must contain one ARGUMENT function for each argument in the macro itself. There are two forms of the ARGUMENT function. In the first form, only name_text is required; in the second form, only reference is required. Use the first form if you want to store the argument as a name. Use the second form if you want to store the argument in a specific cell or cells.

Syntax 1

For name storage

ARGUMENT(name_text, data_type_num)

Syntax 2

For cell storage

ARGUMENT(name_text, data_type_num, reference)

Name_text is the name of the argument or of the cells containing the argument. Name_text is required if you omit reference.

Data_type_num is a number that determines what type of values Microsoft Excel accepts for the argument. The following table lists the possible data types.

Data_type_num Type of value

1 Number

2 Text

4 Logical

8 Reference

16 Error

64 Array

  • Data_type_num can be a sum of the preceding different numbers to allow for more than one possible type of data. For example, if data_type_num is 7, which is the sum of 1, 2, and 4, then the value can be a number, text, or logical value.
  • Data_type_num is an optional argument. If you omit data_type_num, it is assumed to be 7.
  • If the value that is passed to the function macro is not of the type specified by data_type_num, Microsoft Excel first attempts to convert it to the specified type. If the value cannot be converted, the macro returns the #VALUE! error value.

Reference is the cell or cells in which you want to store the argument's value.

  • If you specify reference, the value that is passed to ARGUMENT is entered as a constant in the specified cell, and name_text becomes an optional argument because you can refer to the cell with either reference or name_text.
  • If you omit reference, name_text is defined on the macro sheet and refers to the value that is passed to ARGUMENT. Once name_text is defined, you can use it in formulas.

Remarks

  • Custom functions and subroutines can accept from 1 to 29 arguments.
  • If a macro contains an ARGUMENT function and you omit the corresponding argument in the function that starts the macro, the macro uses the #N/A error value as the value of the argument.

Examples

To create a custom function that calculates profit, use the following functions to specify arguments for cost, sales, and sales volume:

ARGUMENT("UnitsSold", 1)
ARGUMENT("UnitCost", 1)
ARGUMENT("UnitPrice", 1)

Related Function

RESULT Specifies the data type a custom function returns

VOLATILE Makes custom functions recalculate automatically

List of Control Functions


BEEP

Macro Sheets Only

Sounds a tone. Use BEEP to signal a message, a dialog box, or the end of a macro, or whenever you need to get the user's attention.

Syntax

BEEP(tone_num)

Tone_num is a number from 1 to 4 specifying the tone to be played.

  • On most computers, all numbers produce the same sound, the sound that you hear when an error occurs or when you click outside some dialog boxes.
  • If tone_num is omitted, it is assumed to be 1.

Remarks

  • With a Macintosh, you can control the volume of the tone by using the Control Panels desk accessory.
  • With Microsoft Windows version 3.0 or later, you can turn off the tone by using the Control Panel.

Related Functions

ALERT Displays a dialog box and a message

MESSAGE Displays a message in the status bar

List of Customizing Functions


BREAK

Macro Sheets Only

Interrupts a FOR-NEXT, a FOR.CELL-NEXT, or a WHILE-NEXT loop. If BREAK is encountered within a loop, that loop is terminated and the macro proceeds to the statement following the NEXT statement at the end of the current loop.

Syntax

BREAK( )

Example

Use BREAK to test for conditions not anticipated by the FOR or WHILE statement. For example, use the BREAK nested in an IF statement to exit a WHILE-NEXT loop when a certain value is encountered:

=IF(Counter=8, BREAK())

Related Functions

FOR Starts a FOR-NEXT loop

FOR.CELL Starts a FOR.CELL-NEXT loop

NEXT Ends a FOR-NEXT, FOR.CELL-NEXT, or WHILE-NEXT loop

WHILE Starts a WHILE-NEXT loop

List of Control Functions


DUPLICATE

Macro Sheets Only

Duplicates the selected object. If an object is not selected, returns the #VALUE! error value and interrupts the macro.

Syntax

DUPLICATE( )

Related Functions

COPY Copies and pastes data or objects

PASTE Pastes cut or copied data

List of Command-Equivalent Functions


ECHO

Macro Sheets Only

Controls screen updating while a macro is running. If a large macro uses many commands that update the screen, use ECHO to make the macro run faster.

Syntax

ECHO(logical)

Logical is a logical value specifying whether screen updating is on or off.

  • If logical is TRUE, Microsoft Excel selects screen updating.
  • If logical is FALSE, Microsoft Excel clears screen updating.
  • If logical is omitted, Microsoft Excel changes the current screen update condition.

Remarks

  • Screen updating is always turned back on when a macro ends.
  • You can use GET.WORKSPACE to determine whether screen updating is on or off.

Related Functions

GET.WORKSPACE Returns information about the workspace

List of Customizing Functions


ERROR

Macro Sheets Only

Specifies what action to take if an error is encountered while a macro is running. Use ERROR to control whether Microsoft Excel error messages are displayed, or to run your own macro when an error is encountered.

Syntax

ERROR(enable_logical, macro_ref)

Enable_logical is a logical value or number that selects or clears error-checking.

  • If enable_logical is FALSE or 0, all error-checking is cleared. If error-checking is cleared and an error is encountered while a macro is running, Microsoft Excel ignores it and continues. Error-checking is selected again by an ERROR(TRUE) statement, or when the macro stops running.
  • If enable_logical is TRUE or 1, you can either select normal error-checking (by omitting the other argument) or specify a macro to run when an error is encountered by using the macro_ref argument. When normal error-checking is active, the Macro Error dialog box is displayed when an error is encountered. You can choose to halt the macro, start single-stepping through the macro, continue running the macro normally, or go to the macro cell where the error occurred.
  • If enable_logical is 2 and macro_ref is omitted, error-checking is normal except that if the user chooses the Cancel button in an alert message, ERROR returns FALSE and the macro is not interrupted.
  • If enable_logical is 2 and macro_ref is given, the macro goes to that macro_ref when an error is encountered. If the user chooses the Cancel button in an alert message, FALSE is returned and the macro is not interrupted.

Macro_ref specifies a macro to run if enable_logical is TRUE, 1, or 2 and an error is encountered. It can be either the name of the macro or a cell reference. If enable_logical is FALSE or 0, macro_ref is ignored.

Important Both ERROR(FALSE) and ERROR(TRUE, macro_ref ) keep Microsoft Excel from displaying any messages at all, including the message asking whether to save changes when you close an unsaved document. If you want alert messages but not error messages to be displayed, use ERROR(2, macro_ref ).

Remarks

You can use GET.WORKSPACE to determine whether error-checking is on or off.

Examples

ERROR(FALSE) clears error-checking.

ERROR(TRUE, Recover) selects error-checking and runs the macro named Recover when an error is encountered.

The following macro runs the macro ForceMenus if an error occurs in the current macro:

=ERROR(TRUE, ForceMenus)

Related Functions

CANCEL.KEY Disables macro interruption

LAST.ERROR Returns the reference of the cell where the last error occurred

ON.KEY Runs a macro when a specified key is pressed

List of Customizing Functions


FCLOSE

Macro Sheets Only

Closes the specified file.

Syntax

FCLOSE(file_num)

File_num is the number of the file you want to close. File_num is returned by the FOPEN function that originally opened the file. If file_num is not a valid file number, FCLOSE halts the macro and returns the #VALUE! error value.

Examples

The following function closes the file identified by FileNumber:

FCLOSE(FileNumber)

Related Functions

CLOSE Closes the active window

FILE.CLOSE Closes the active document

FOPEN Opens a file with the type of permission specified

List of DDE/External Functions


FONT

Macro Sheets Only

Equivalent to choosing the Font command from the Options menu in Microsoft Excel for the Macintosh version 1.5 or earlier. This function is included only for macro compatibility. Sets the font for the Normal style. Microsoft Excel now uses the FONT.PROPERTIES and DEFINE.STYLE functions. For more information, see FONT.PROPERTIES and DEFINE.STYLE.

Syntax

FONT(name_text, size_num)
FONT?(name_text, size_num)

Related Functions

DEFINE.STYLE Creates or changes a cell style

FONT.PROPERTIES Sets various font properties

List of Command-Equivalent Functions


FOPEN

Macro Sheets Only

Opens a file with the type of permission specified. Unlike OPEN, FOPEN does not load the file into memory and display it; instead, FOPEN establishes a channel with the file so that you can exchange information with it. If the file is opened successfully, FOPEN returns a file ID number. If it can't open the file, FOPEN returns the #N/A error value. Use the file ID number with other file functions (such as FREAD, FWRITE, and FSIZE) when you want to get information from or send information to the file.

Syntax

FOPEN(file_text, access_num)

File_text is the name of the file you want to open.

Access_num is a number from 1 to 3 specifying what type of permission to allow to the file:

Access_num Type of permission

1 or omitted Can read and write to the file (read/write permission)

2 Can read the file, but can't write to the file (read-only permission)

3 Creates a new file with read/write permission

  • If the file doesn't exist and access_num is 3, FOPEN creates a new file.
  • If the file does exist and access_num is 3, FOPEN replaces the contents of the file with any information you supply using the FWRITE or FWRITELN functions.
  • If the file doesn't exist and access_num is 1 or 2, FOPEN returns the #N/A error value.

Remarks

Use FCLOSE to close a file after you finish using it.

Example

The following function opens a file identified as FileName using read-only permission:

FOPEN(FileName, 2)

Related Functions

FCLOSE Closes a text file

FREAD Reads characters from a text file

FWRITE Writes characters to a text file

OPEN Opens a document

List of DDE/External Functions


FOR

Macro Sheets Only

Starts a FOR-NEXT loop. The instructions between FOR and NEXT are repeated until the loop counter reaches a specified value. Use FOR when you need to repeat instructions a specified number of times. Use FOR.CELL when you need to repeat instructions over a range of cells.

Syntax

FOR(counter_text, start_num, end_num, step_num)

Counter_text is the name of the loop counter in the form of text.

Start_num is the value initially assigned to counter_text.

End_num is the last value assigned to counter_text.

Step_num is a value added to the loop counter after each iteration. If step_num is omitted, it is assumed to be 1.

Remarks

  • Microsoft Excel follows these steps as it executes a FOR-NEXT loop:

Step Action

1 Sets counter_text to the value start_num.

2 If counter_text is greater than end_num (or less than end_num if step_num is negative), the loop ends, and the macro continues with the function after the NEXT function.

If counter_text is less than or equal to end_num (or greater than or equal to end_num if step_num is negative), the macro continues in the loop.

3 Carries out functions up to the following NEXT function. The NEXT function must be below the FOR function and in the same column.

4 Adds step_num to the loop counter.

5 Returns to the FOR function and proceeds as described in step 2.

  • You can interrupt a FOR-NEXT loop by using the BREAK function.

Example

The following macro starts a FOR-NEXT loop that is executed once for every open window:

FOR("Counter", 1, COLUMNS(WINDOWS()))

Related Functions

BREAK Interrupts a FOR-NEXT, FOR.CELL-NEXT, or WHILE-NEXT loop

FOR.CELL Starts a FOR.CELL-NEXT loop

NEXT Ends a FOR-NEXT, FOR.CELL-NEXT, or WHILE-NEXT loop

WHILE Starts a WHILE-NEXT loop

List of Control Functions


FOR.CELL

Macro Sheets Only

Starts a FOR.CELL-NEXT loop. This function is similar to FOR, except that the instructions between FOR.CELL and NEXT are repeated over a range of cells, one cell at a time, and there is no loop counter.

Syntax

FOR.CELL(ref_name, area_ref, skip_blanks)

Ref_name is the name in the form of text that Microsoft Excel gives to the one cell in the range that is currently being operated on; ref_name refers to a new cell during each loop.

Area_ref is the range of cells on which you want the FOR.CELL-NEXT loop to operate and can be a multiple selection. If area_ref is omitted, it is assumed to be the current selection.

Skip_blanks is a logical value specifying whether Microsoft Excel skips blank cells as it operates on the cells in area_ref.

Skip_blanks Result

TRUE Skips blank cells in area_ref

FALSE or omitted Operates on all cells in area_ref

Remarks

FOR.CELL operates on each cell in a row from left to right one area at a time before moving to the next row in the selection.

Example

The following macro starts a FOR.CELL-NEXT loop and uses the name CurrentCell to refer to the cell in the range that is currently being operated on:

FOR.CELL("CurrentCell", SELECTION(), TRUE)

Related Functions

BREAK Interrupts a FOR-NEXT, FOR.CELL-NEXT, or WHILE-NEXT loop

FOR Starts a FOR-NEXT loop

NEXT Ends a FOR-NEXT, FOR.CELL-NEXT, or WHILE-NEXT loop

WHILE Starts a WHILE-NEXT loop

List of Control Functions


FPOS

Macro Sheets Only

Sets the position of a file. The position of a file is where a character is read from or written to by an FREAD, FREADLN, FWRITE, or FWRITELN function. Use FPOS when you want to write characters to or read characters from specific locations. For example, to append text to the end of a file, you must set the position to the end of the file; otherwise, you might accidentally overwrite existing characters in the file.

Syntax

FPOS(file_num, position_num)

File_num is the unique ID number of the file for which you want to set the position. File_num is returned by a previously executed FOPEN function. If file_num is not valid, FPOS returns the #VALUE! error value.

Position_num is the location in the file that a character will be read from or written to.

  • The first position in a file is 1, the location of the first byte.
  • The last position in the file is the same as the value returned by FSIZE. For example, the last position in a file with 280 bytes is 280.
  • If position_num is omitted, FPOS returns the current position of the file—that is, the number corresponding to where the next character will be read from or written to.

Whenever you read a character from or write a character to a file, the file's position is automatically incremented.

Examples

The following statement starts a loop that executes until the position in the open file identified as FileNumber reaches the end of the file:

=WHILE(FPOS(FileNumber)<=FSIZE(FileNumber))

Related Functions

FCLOSE Closes a text file

FOPEN Opens a file with the type of permission specified

FREAD Reads characters from a text file

FREADLN Reads a line from a text file

FWRITE Writes characters to a text file

FWRITELN Writes a line to a text file

List of DDE/External Functions


FREAD

Macro Sheets Only

Reads characters from a file, starting at the current position in the file. (For more information about a file's position, see FPOS.) If FREAD is successful, it returns the text to the cell containing FREAD and set's the file's position to the start of the following line. If the end of the file is reached or if FREAD can't read the file, it returns the #N/A error value. Use FREAD instead of FREADLN when you need to read a specific number of characters from a text file.

Syntax

FREAD(file_num, num_chars)

File_num is the unique ID number of the file you want to read data from. File_num is returned by a previously executed FOPEN function. If file_num is not valid, FREAD returns the #VALUE! error value.

Num_chars specifies how many bytes to read from the file. FREAD can read up to 255 bytes at a time.

Example

The following function reads the next 200 bytes from the open file identified as FileNumber:

FREAD(FileNumber, 200)

Related Functions

FOPEN Opens a file with the type of permission specified

FPOS Sets the position in a text file

FREADLN Reads a line from a text file

FWRITE Writes characters to a text file

List of DDE/External Functions


FREADLN

Macro Sheets Only

Reads characters from a file, starting at the current position in the file and continuing to the end of the line, placing the characters in the cell containing FREADLN. (For more information about a file's position, see FPOS.) If FREADLN is successful, it returns the text it read, up to but not including the carriage-return and linefeed characters at the end of the line (in Microsoft Excel for Windows) or the carriage-return character at the end of the line (in Microsoft Excel for the Macintosh). If the current file position is the end of the file or if FREADLN can't read the file, it returns the #N/A error value.

Syntax

FREADLN(file_num)

File_num is the unique ID number of the file you want to read data from. File_num is returned by a previously executed FOPEN function. If file_num is not valid, FREADLN returns the #VALUE! error value.

Example

The following function reads the next line from the open file identified as FileNumber:

FREADLN(FileNumber)

Related Functions

FOPEN Opens a file with the type of permission specified

FPOS Sets the position in a text file

FREAD Reads characters from a text file

FWRITE Writes characters to a text file

FWRITELN Writes a line to a text file

List of DDE/External Functions


FSIZE

Macro Sheets Only

Returns the number of bytes in a file. Use FSIZE to determine the size of the file, which is the same as the position of the last byte in the file.

Syntax

FSIZE(file_num)

File_num is the unique ID number of the file whose size you want to know. File_num is returned by a previously executed FOPEN function. If file_num is not valid, FSIZE returns the #VALUE! error value.

Example

The following function returns the size in bytes of the open file identified as FileNumber:

FSIZE(FileNumber)

Related Functions

FOPEN Opens a file with the type of permission specified

FPOS Sets the position in a text file

List of DDE/External Functions


FWRITE

Macro Sheets Only

Writes text to a file, starting at the current position in that file. (For more information about a file's position, see FPOS.) If FWRITE can't write to the file, it returns the #N/A error value.

Syntax

FWRITE(file_num, text)

File_num is the unique ID number of the file you want to write data to. File_num is returned by a previously executed FOPEN function. If file_num is not valid, FWRITE returns the #VALUE! error value.

Text is the text you want to write to the file.

Example

The following function writes the current month to the open file identified as FileNumber:

FWRITE(FileNumber, TEXT(MONTH(NOW()),"mmmm"))

Related Functions

FOPEN Opens a file with the type of permission specified

FPOS Sets the position in a text file

FREAD Reads characters from a text file

FWRITELN Writes a line to a text file

List of DDE/External Functions


FWRITELN

Macro Sheets Only

Writes text, followed by a carriage return and linefeed, to a file, starting at the current position in that file. (For more information about a file's position, see FPOS.) If FWRITELN can't write to the file, it returns the #N/A error value. Use FWRITELN instead of FWRITE when you want to append a carriage return and linefeed to each group of characters that you write to a text file.

Syntax

FWRITELN(file_num, text)

File_num is the unique ID number of the file you want to write data to. File_num is returned by a previously executed FOPEN function. If file_num is not valid, FWRITELN returns the #VALUE! error value.

Text is the text you want to write to the file.

Remarks

In Microsoft Excel for Windows, FWRITELN writes text followed by a carriage return and a line feed. In Microsoft Excel for the Macintosh, FWRITELN writes text followed by a carriage return only.

Example

The following function writes the current month to the open file identified as FileNumber and starts a new line in the file:

FWRITELN(FileNumber, TEXT(MONTH(NOW()),"mmmm"))

Related Functions

FOPEN Opens a file with the type of permission specified

FPOS Sets the position in a text file

FREAD Reads characters from a text file

FWRITE Writes characters to a text file

List of DDE/External Functions


GOTO

Macro Sheets Only

Directs a macro to continue running at the upper-left cell of reference. Use GOTO to direct macro execution to another cell or a named range.

Syntax

GOTO(reference)

Reference is a cell reference or a name that is defined as a reference. Reference can be an external reference to another macro sheet. If that macro sheet is not open, GOTO displays a message.

Tip It's often preferable to use IF, ELSE, ELSE.IF, and END.IF instead of GOTO when you want to perform multiple actions based on a condition because the IF method makes your macros more structured.

Examples

If A1 contains the #N/A error value, then when the following formula is calculated, the macro branches to C3:

IF(ISERROR($A$1), GOTO($C$3), )

You can also use macro names with GOTO statements. The following macro formula branches macro execution to a macro named Compile:

GOTO(Compile)

Because Compile is a named range, it should not be enclosed in quotation marks.

Related Function

FORMULA.GOTO Selects a named area or reference on any open document

List of Control Functions


HALT

Macro Sheets Only

Stops all macros from running. Use HALT instead of RETURN to prevent a macro from returning to the macro that called it.

Syntax

HALT(cancel_close)

Cancel_close is a logical value that specifies whether a macro sheet, when encountering the HALT function in an Auto_Close macro, is closed.

  • If cancel_close is TRUE, Microsoft Excel halts the macro and prevents the document from being closed.
  • If cancel_close is FALSE or omitted, Microsoft Excel halts the macro and allows the document to be closed.
  • If cancel_close is specified in a macro that is not an Auto_Close macro, it is ignored and the HALT function simply stops the current macro.

Remarks

You can prevent an Auto_Close or Auto_Open macro from running by holding down the SHIFT key while opening or closing the document.

Examples

If A1 contains the #N/A error value, then when the following macro formula is calculated, the macro halts:

IF(ISERROR(A1), HALT(), GOTO(D4))

The following macro formula at the end of an Auto_Close macro ends the macro and prevents the document from being closed:

HALT(TRUE)

Related Functions

BREAK Interrupts a FOR-NEXT, FOR.CELL-NEXT, or WHILE-NEXT loop

RETURN Ends the currently running macro

List of Control Functions


HLINE

Macro Sheets Only

Scrolls through the active window by a specific number of columns. Returns the #VALUE! error value if the active document is a chart.

Syntax

HLINE(num_columns)

Num_columns is the number of columns in the active worksheet or macro sheet you want to scroll through horizontally.

  • If num_columns is positive, HLINE scrolls to the right.
  • If num_columns is negative, HLINE scrolls to the left.
  • Num_columns must be between -256 and 256, inclusive.

Example

The following function scrolls the active window by one-half window to the right:

HLINE(GET.WINDOW(15)/2)

Related Functions

HPAGE Horizontally scrolls through the active window one window at a time

HSCROLL Horizontally scrolls through a document by percentage or by column number

VLINE Vertically scrolls through the active window by rows

VPAGE Vertically scrolls through the active window one window at a time

VSCROLL Vertically scrolls through a document by percentage or by row number

List of Command-Equivalent Functions


LIST.NAMES

Macro Sheets Only

Equivalent to choosing the Paste command on the Name submenu on the Insert menu and selecting the Paste List option button. Lists all names (except hidden names) defined on your worksheet. LIST.NAMES also lists the cells to which the names refer; whether a macro corresponding to a particular name is a command macro or a custom function; the shortcut key for each command macro; and the category of the custom functions.

Syntax

LIST.NAMES( )

Remarks

  • If the current selection is a single cell or five or more columns wide, LIST.NAMES pastes all five types of information about worksheet names into five columns. The first column contains cell names. The second column contains the corresponding cell references. The third column contains the number 1 if the name refers to a custom function, the number 2 if it refers to a command macro, or 0 if it refers to anything else. The fourth column lists the shortcut keys for command macros. The fifth column contains a category name for custom functions or the number of the built-in category.
  • If the selection includes fewer than five columns, LIST.NAMES omits the information that would have been pasted into the other columns.
  • When you use LIST.NAMES, Microsoft Excel completely replaces the contents of the cells it pastes into.

Related Functions

GET.DEF Returns a name matching a definition

GET.NAME Returns the definition of a name

NAMES Returns the names defined in a document

List of Command-Equivalent Functions


NEXT

Macro Sheets Only

Ends a FOR-NEXT, FOR.CELL-NEXT, or WHILE-NEXT loop and continues carrying out the current macro with the formula that follows the NEXT function.

Syntax

NEXT( )

Related Functions

FOR Starts a FOR-NEXT loop

FOR.CELL Starts a FOR.CELL-NEXT loop

WHILE Starts a WHILE-NEXT loop

List of Control Functions


PAUSE

Macro Sheets Only

Pauses a macro. Use the PAUSE function, instead of choosing the Pause button in the Single Step dialog box, as a debugging tool when you do not wish to step through a macro. You can also use PAUSE to enter and edit data, to work directly with Microsoft Excel commands, or to perform other actions that are not normally available when a macro is running.

Syntax

PAUSE(no_tool)

No_tool is a logical value specifying whether to display the Resume Macro button when the macro is paused. If no_tool is TRUE, the toolbar is not displayed; if FALSE, the toolbar is displayed; if omitted, the toolbar is displayed unless you previously clicked the close box on the toolbar.

Remarks

  • All commands and tools that are available when no macro is running are still available when a macro is paused.
  • You can run other macros while a macro is paused, but you can pause only one macro at a time. If a macro is paused when you run a second macro containing a PAUSE function, choosing Macro Resume resumes only the second macro; you cannot resume or return to the first macro automatically.
  • PAUSE is ignored in custom worksheet functions, unless you manually run them by choosing the Run button from the Macro dialog box, which appears when you choose the Macro command from the Tools menu. PAUSE is also ignored if it's placed in a formula for which the resume behavior would be unclear, such as:

    IF(Cost<10, AND(PAUSE(),SUM(!$A$1:$A$4)))
  • If one macro runs a second macro that pauses, Microsoft Excel locks the calling cell in the first macro. If you try to edit this cell, Microsoft Excel displays an error message.
  • To resume a paused macro, choose the Resume Macro button on the toolbar or run a macro containing a RESUME function.
  • If one macro runs a second macro that pauses and you need to halt only the paused macro, use RESUME(2) instead of HALT. HALT halts all macros and prevents resuming or returning to any macro. For more information, see RESUME.

Tip Since the automatic Resume Macro button can be customized, you can create a custom toolbar that will appear whenever a macro pauses.

Example

The following macro formula checks to see if a variable named TestValue is greater than 9. If it is, the macro pauses; otherwise, the macro continues normally.

IF(TestValue>9, PAUSE())

Related Functions

HALT Stops all macros from running

RESUME Resumes a paused macro

STEP Turns on macro single-stepping

List of Control Functions


PRECISION

Macro Sheets Only

Equivalent to selecting or clearing the Precision As Displayed check box in the Calculation tab of the Options dialog box, which appears when you choose the Options command from the Tools menu. Controls how values are stored in cells. Use PRECISION when the results of formulas do not seem to match the values used to calculate the formulas.

Syntax

PRECISION(logical)

Logical is a logical value corresponding to the Precision As Displayed check box in the Calculation tab.

  • If logical is TRUE, Microsoft Excel stores future entries at full precision (15 digits).
  • If logical is FALSE or omitted, Microsoft Excel stores values exactly as they are displayed.

Caution The PRECISION function may permanently alter your data. PRECISION(FALSE) causes Microsoft Excel to change values on your worksheet or macro sheet to match displayed values. PRECISION(TRUE) causes Microsoft Excel to store future values at full precision, but it does not restore previously entered numbers to their original values.

Remarks

  • Precision As Displayed does not affect numbers in General format. Numbers in General format are always calculated to full precision.
  • Microsoft Excel calculates slightly faster when using full precision because with Precision As Displayed selected, Microsoft Excel has to round off numbers as it calculates.

Related Functions

FORMAT.NUMBER Applies a number format to the selection

WORKSPACE Changes workspace settings

List of Command-Equivalent Functions


QUIT

Macro Sheets Only

Equivalent to choosing the Exit command from the File menu in Microsoft Excel for Windows. Equivalent to choosing the Quit command from the File menu in Microsoft Excel for the Macintosh. Quits Microsoft Excel and closes any open documents. If open documents have unsaved changes, Microsoft Excel displays a message asking if you want to save them. You can use QUIT in an Auto_Close macro to force Microsoft Excel to quit when a particular worksheet or macro sheet is closed.

Syntax

QUIT( )

Caution If you have cleared error-checking with an ERROR(FALSE) function, QUIT will not ask whether you want to save changes.

Remarks

When you use the QUIT function, Microsoft Excel does not run any Auto_Close macros before closing the document.

Examples

The following function displays a confirmation alert and quits Microsoft Excel if the user chooses OK:

IF(ALERT("Are you sure you want to quit Microsoft Excel?",1), QUIT(),)

Related Function

FILE.CLOSE Closes the active document

List of Command-Equivalent Functions


RESTART

Macro Sheets Only

Removes a number of RETURN statements from the stack. When one macro calls another, the RETURN statement at the end of the second macro returns control to the calling macro. You can use the RESTART function to determine which macro regains control.

Syntax

RESTART(level_num)

Level_num is a number specifying the number of previous RETURN statements you want to be ignored. If level_num is omitted, the next RETURN statement will halt macro execution.

For example, if the currently running macro has two "ancestors, " that is, was called by one macro that, in turn, was called by another macro, using RESTART(1) in the third macro returns control to the first calling macro when the RETURN statement is encountered. The RESTART(1) formula removes one level of RETURN statements from Microsoft Excel's memory so that the second macro is skipped.

Remarks

RESTART is particularly useful if you frequently use macros to call other macros that in turn call other macros. Use RESTART in combination with IF statements to prevent macro execution from returning to macros that called, either directly or indirectly, the currently running macro.

Related Functions

HALT Stops all macros from running

RETURN Ends the currently running macro

List of Control Functions


RESULT

Macro Sheets Only

Specifies the type of data a macro or custom function returns. Use RESULT to make sure your macros, custom functions, or subroutines return values of the correct data type.

Syntax

RESULT(type_num)

Type_num is a number specifying the data type.

Type_num Type of returned data

1 Number

2 Text

4 Logical

8 Reference

16 Error

64 Array

  • Type_num can be the sum of the numbers in the preceding table to allow for more than one possible result type. For example, if type_num is 12, which equals 4 + 8, the result can be a logical or a reference value.
  • If you omit type_num, it is assumed to be 7. Since 7 equals 1 + 2 + 4, the value returned can be a number (1), text (2), or logical value (4).

Examples

The following function specifies that a custom function's return value can be a number or a logical value (4+1=5):

RESULT(5)

Related Functions

ARGUMENT Passes an argument to a macro

RETURN Ends the currently running macro

List of Control Functions


RETURN

Macro Sheets Only

Ends the currently running macro. If the currently running macro is a subroutine macro that was called by another macro, control is returned to the calling macro. If the currently running macro is a custom function, control is returned to the formula that called the custom function. If the currently running macro is a command macro started by the user with the Run button in the Macro dialog box or a shortcut key or by clicking an object, control is returned to the user.

Syntax

RETURN(value)

Value specifies what to return.

  • If the macro is a custom function or a subroutine, value specifies what value to return. However, not all subroutines return values; the last line in macros that do not return values is =RETURN().
  • If the macro is a command macro run by the user, value should be omitted.

Remarks

RETURN signals the end of a macro. Every macro must end with a RETURN or HALT function, but not every macro returns values.

Example

The following function returns the sum of the range B1:B10:

RETURN(SUM(B1:B10))

Related Functions

BREAK Interrupts a FOR-NEXT, FOR.CELL-NEXT, or WHILE-NEXT loop

HALT Stops all macros from running

RESULT Specifies the data type a custom function returns

List of Control Functions


SET.NAME

Macro Sheets Only

Defines a name on a macro sheet to refer to a value. The SET.NAME function is useful for storing values while the macro is calculating.

Syntax

SET.NAME(name_text, value)

Name_text is the name in the form of text that refers to value.

Value is the value you want to store in name_text.

  • If value is omitted, the name name_text is deleted.
  • If value is a reference, name_text is defined to refer to that reference.

Remarks

  • If you want to define a name as a constant value, you can use the following syntax instead of SET.NAME:

    name_text=value

    See the first two examples following.

  • SET.NAME defines names as absolute references, even if a relative reference is specified. See the third and fourth examples following.
  • If you want name_text to refer permanently to the value of a referenced cell rather than to the reference itself, you must use the DEREF function. Use of DEREF prevents name_text from referring to a new value every time the contents of the referenced cell changes. See the last example following.

Tips

  • If you need to return an array to a macro sheet (for example, if the macro needs a list of all open windows), assign a name to the array instead of placing the array information in a range of cells. For example:

    SET.NAME("OpenDocuments", WINDOWS()) or
    SET.NAME("OpenDocuments", {"WORKSHEET1", "WORKSHEET2"})

    You can then use the INDEX function with the name you have defined to access items in the array stored in the name.

  • When you're debugging a macro and want to know the current value assigned to a name created by SET.NAME, you can halt the macro, choose Define from the Name submenu on the Insert menu, and select the name from the Define Name dialog box.

Examples

Each of these formulas defines the name Counter to refer to the constant number 1 on the macro sheet:

SET.NAME("Counter", 1)
Counter=1

Each of these formulas redefines Counter to refer to the current value of Counter plus 1:

SET.NAME("Counter", Counter+1)
Counter=Counter+1

The following macro formula defines the name Reference to refer to cell $A$1:

SET.NAME("Reference", A1)

The following macro formula defines the name Results to refer to the cells $A$1:$C$3:

SET.NAME("Results", A1:C3)

The following macro formula defines the name Range as the current selection:

SET.NAME("Range", SELECTION())

If $A$1 contains the value 2, the following macro formula defines the name Index to refer to the constant value 2:

SET.NAME("Index", DEREF(A1))

Related Functions

DEFINE.NAME Defines a name on the active worksheet or macro sheet

SET.VALUE Sets the value of a cell on a macro sheet

List of Control Functions


SHOW.ACTIVE.CELL

Macro Sheets Only

Scrolls the active window so the active cell becomes visible. If an object is selected, SHOW.ACTIVE.CELL returns the #VALUE! error value and halts the macro.

Syntax

SHOW.ACTIVE.CELL( )

Related Functions

ACTIVE.CELL Returns the reference of the active cell

FORMULA.GOTO Selects a named area or reference on any open document

List of Command-Equivalent Functions


UNLOCKED.NEXTUNLOCKED.PREV

UNLOCKED.NEXT
UNLOCKED.PREV

Macro Sheets Only

Equivalent to pressing TAB or SHIFT+TAB to move to the next or previous unlocked cell in a protected worksheet. Use these functions when you want to control which cell is active on a protected sheet.

Syntax

UNLOCKED.NEXT( )
UNLOCKED.PREV( )

Related Functions

CELL.PROTECTION Controls protection for the selected cells

PROTECT.DOCUMENT Controls protection for the active document

List of Command-Equivalent Functions


VOLATILE

Macro Sheets Only

Specifies whether a custom worksheet function is volatile or nonvolatile. A volatile custom function is recalculated every time a calculation occurs on the worksheet.

Syntax

VOLATILE(logical)

Logical is a logical value specifying whether the custom function is volatile or nonvolatile. If logical is TRUE or omitted, the function is volatile; if FALSE, nonvolatile.

Remarks

  • VOLATILE must precede every other formula in the custom function except RESULT and ARGUMENT.
  • Normally, a worksheet recalculates a cell containing a nonvolatile custom function only when any part of the complete formula in the cell is recalculated. Use VOLATILE(TRUE) to recalculate the function every time the worksheet is recalculated.
  • Most custom functions are nonvolatile by default, but custom functions with reference arguments are volatile by default. Use VOLATILE(FALSE) to prevent these functions from being recalculated unnecessarily often.

Related Function

RESULT Specifies the data type a custom function returns

List of Control Functions


WAIT

Macro Sheets Only

Pauses the macro until the time specified by the serial number.

Syntax

WAIT(serial_number)

Serial_number is the date-time code used by Microsoft Excel for date and time calculations. You can give serial_number as text, such as "4:30 PM", or as a formula, such as NOW()+"00:00:04", instead of as a number. The text or formula is automatically converted to a serial number. For more information about serial_number, see NOW.

Important WAIT suspends all Microsoft Excel activity and may prevent you from performing other operations on your computer. Background processes, such as printing and recalculation, are continued.

Example

Use WAIT with NOW to pause a macro for a specified length of time. For example, the following macro formula waits 3 seconds from the time the functions are evaluated:

WAIT(NOW()+"00:00:03")

Related Functions

ON.TIME Runs a macro at a specific time

List of Control Functions


WHILE

Macro Sheets Only

Carries out the statements between the WHILE function and the next NEXT function until logical_test is FALSE. Use WHILE-NEXT loops to carry out a series of macro formulas while a certain condition remains TRUE.

Syntax

WHILE(logical_test)

Logical_test is a value or formula that evaluates to TRUE or FALSE. If logical_test is FALSE the first time the WHILE function is reached, the macro skips the loop and resumes running at the statement after the next NEXT function. If there is no NEXT function in the same column, WHILE displays an error message and interrupts the macro.

Remarks

If you know exactly how many times you'll need to carry out the statements within a loop, in most cases you should use a FOR-NEXT loop. Also, avoid creating an infinite loop by making sure logical_test does not always evaluate to TRUE.

Example

The following statement starts a loop that executes while the current cell contains a number, text, or a logical value:

=WHILE(TYPE(ACTIVE.CELL()<5))

The following statement starts a loop that executes until the position in the open file identified as FileNumber reaches the end of the file:

=WHILE(FPOS(FileNumber)<=FSIZE(FileNumber))

Related Functions

FOR Starts a FOR-NEXT loop

FOR.CELL Starts a FOR.CELL-NEXT loop

IF Specifies an action to take if a logical test is TRUE

NEXT Ends a FOR-NEXT, FOR.CELL-NEXT, or WHILE-NEXT loop

List of Control Functions


ANOVA1

Macro Sheets Only

Performs single-factor analysis of variance, which tests the hypothesis that means from several samples are equal.

If this function is not available, you must install the Analysis ToolPak add-in macro.

Syntax

ANOVA1(inprng, outrng, grouped, labels, alpha)
ANOVA1?(inprng, outrng, grouped, labels, alpha)

Inprng is the input range.

Outrng is the first cell (the upper-left cell) in the output table or the name, as text, of a new sheet to contain the output table. If FALSE, blank, or omitted, places the output table in a new workbook.

Grouped is a text character that indicates whether the data in the input range is organized by row or column.

  • If grouped is "C" or omitted, then the data is organized by column.
  • If grouped is "R", then the data is organized by row.

Labels is a logical value that describes where the labels are located in the input range, as shown in the following table:

Labels | Grouped | Labels are in
TRUE | "C" | First row of the input range.
TRUE | "R" | First column of the input range.
FALSE or omitted | (ignored) | No labels. All cells in the input range are data.

Alpha is the significance level at which to evaluate critical values for the F statistic. If omitted, alpha is 0.05.

Related Functions

ANOVA2 Performs two-factor analysis of variance with replication

ANOVA3 Performs two-factor analysis of variance without replication

List of Statistical Functions


ANOVA2

Macro Sheets Only

Performs two-factor analysis of variance with replication.

If this function is not available, you must install the Analysis ToolPak add-in macro.

Syntax

ANOVA2(inprng, outrng, sample_rows, alpha)
ANOVA2?(inprng, outrng, sample_rows, alpha)

Inprng is the input range. The input range should contain labels in the first row and column.

Outrng is the first cell (the upper-left cell) in the output table or the name, as text, of a new sheet to contain the output table. If FALSE, blank, or omitted, places the output table in a new workbook.

Sample_rows is the number of rows in each sample.

Alpha is the significance level at which to evaluate critical values for the F statistic. If omitted, alpha is 0.05.

Related Functions

ANOVA1 Performs single-factor analysis of variance

ANOVA3 Performs two-factor analysis of variance without replication

List of Statistical Functions


ANOVA3

Macro Sheets Only

Performs two-factor analysis of variance without replication.

If this function is not available, you must install the Analysis ToolPak add-in macro.

Syntax

ANOVA3(inprng, outrng, labels, alpha)
ANOVA3?(inprng, outrng, labels, alpha)

Inprng is the input range.

Outrng is the first cell (the upper-left cell) in the output table or the name, as text, of a new sheet to contain the output table. If FALSE, blank, or omitted, places the output table in a new workbook.

Labels is a logical value.

  • If labels is TRUE, then the first row and column of the input range contain labels.
  • If labels is FALSE or omitted, all cells in inprng are considered data. Microsoft Excel will then generate the appropriate data labels for the output table.

Alpha is the significance level at which to evaluate critical values for the F statistic. If omitted, alpha is 0.05.

Related Functions

ANOVA1 Performs single-factor analysis of variance

ANOVA2 Performs two-factor analysis of variance with replication

List of Statistical Functions


DESCR

Macro Sheets Only

Generates descriptive statistics for data in the input range.

If this function is not available, you must install the Analysis ToolPak add-in macro.

Syntax

DESCR(inprng, outrng, grouped, labels, summary, ds_large, ds_small, confid)
DESCR?(inprng, outrng, grouped, labels, summary, ds_large, ds_small, confid)

Inprng is the input range.

Outrng is the first cell (the upper-left cell) in the output table or the name, as text, of a new sheet to contain the output table. If FALSE, blank, or omitted, places the output table in a new workbook.

Grouped is a text character that indicates whether the data in the input range is organized by row or column.

  • If grouped is "C" or omitted, then the data is organized by column.
  • If grouped is "R" then the data is organized by row.

Labels is a logical value that describes where the labels are located in the input range, as shown in the following table:

Labels | Grouped | Labels are in
TRUE | "C" | First row of the input range.
TRUE | "R" | First column of the input range.
FALSE or omitted | (ignored) | No labels. All cells in the input range are data.

Summary is a logical value. If TRUE, DESCR reports the summary statistics. If FALSE or omitted, no summary statistics are reported.

Ds_large is an integer k. If ds_large is present, DESCR reports the k-th largest data point. If ds_large is omitted, the value is not reported.

Ds_small is an integer k. If ds_small is present, DESCR reports the k-th smallest data point. If ds_small is omitted, the value is not reported.

Confid is the confidence level of the mean. If confid is given, DESCR reports the confidence interval for the input range. If confid is omitted, the confidence interval is 95%. For more information about the confidence interval calculation, see CONFIDENCE.

Related Functions

List of Statistical Functions

EXPON

Macro Sheets Only

Predicts a value based on the forecast for the prior period, adjusted for the error in that prior forecast.

If this function is not available, you must install the Analysis ToolPak add-in macro.

Syntax

EXPON(inprng, outrng, damp, stderrs, chart)

Inprng is the input range.

Outrng is the first cell (the upper-left cell) in the output table or the name, as text, of a new sheet to contain the output table. If FALSE, blank, or omitted, places the output table in a new workbook.

Damp is the damping factor. If omitted, damp is 0.3.

Stderrs is a logical value. If TRUE, standard error values are included in the output table. If FALSE, standard errors are not included.

Chart is a logical value. If TRUE, EXPON generates a chart for the actual and forecast values. If FALSE, the chart is not generated.

Related Functions

MOVEAVG Returns values along a moving average trend


FOURIER

Macro Sheets Only

Performs a Fourier transform.

If this function is not available, you must install the Analysis ToolPak add-in macro.

Syntax

FOURIER(inprng, outrng, inverse, labels)
FOURIER?(inprng, outrng, inverse, labels)

Inprng is the input range. The number of cells in the input range must be equal to a power of two (2, 4, 8, 16, ...).

Outrng is the first cell in the output range or the name, as text, of a new sheet to contain the output table. If FALSE, blank, or omitted, places the output table in a new workbook.

Inverse is a logical value. If TRUE, an inverse Fourier transform is performed. If FALSE or omitted, a forward Fourier transform is performed.

Labels is a logical value.

  • If labels is TRUE, then the first row or column of inprng contains labels.
  • If labels is FALSE or omitted, all cells in inprng are considered data. Microsoft Excel generates appropriate data labels for the output table.

Related Function

SAMPLE Samples data

List of Statistical Functions


FTESTV

Macro Sheets Only

Performs a two-sample F-test.

If this function is not available, you must install the Analysis ToolPak add-in macro.

Syntax

FTESTV(inprng1, inprng2, outrng, labels)
FTESTV?(inprng1, inprng2. outrng, labels)

Inprng1 is the input range for the first data set.

Inprng2 is the input range for the second data set.

Outrng is the first cell (the upper-left cell) in the output table or the name, as text, of a new sheet to contain the output table. If FALSE, blank, or omitted, places the output table in a new workbook.

Labels is a logical value.

  • If labels is TRUE, then the first row or column of inprng1 and inprng2 contain labels.
  • If labels is FALSE or omitted, all cells in inprng1 and inprng2 are considered data. Microsoft Excel generates appropriate data labels for the output table.

Related Functions

List of Statistical Functions


HISTOGRAM

Macro Sheets Only

Calculates individual and cumulative percentages for a range of data and a corresponding range of data bins.

If this function is not available, you must install the Analysis ToolPak add-in macro.

Syntax

HISTOGRAM(inprng, outrng, binrng, pareto, chartc, chart, labels)
HISTOGRAM?(inprng, outrng, binrng, pareto, chartc, chart, labels)

Inprng is the input range.

Outrng is the first cell (the upper-left cell) in the output table or the name, as text, of a new sheet to contain the output table. If FALSE, blank, or omitted, places the output table in a new workbook.

Binrng is an optional set of numbers that define the bin ranges. The values must be in ascending order. The values are interpreted as more than value A up to value B, more than value B up to value C, and so on. One additional bin is created for values for less than the minimum value specified in binrng.

Pareto is a logical value.

  • If pareto is TRUE, data in the output table is presented in both ascending-bin order and descending-frequency order.
  • If pareto is FALSE or omitted, data in the output table is presented in ascending-bin order only.

Chartc is a logical value. If chartc is TRUE, HISTOGRAM generates a cumulative percentages column in the output table. If both chartc and chart are TRUE, HISTOGRAM also includes a cumulative percentage line in the histogram chart. If omitted, chartc is FALSE.

Chart is a logical value. If chart is TRUE, HISTOGRAM generates a histogram chart in addition to the output table. If omitted, chart is FALSE.

Labels is a logical value.

  • If labels is TRUE, then the first row or column of inprng contains labels.
  • If labels is FALSE or omitted, all cells in inprng are considered data. Microsoft Excel generates appropriate data labels for the output table.

Related Function

List of Statistical Functions


MCORREL

Macro Sheets Only

Returns a correlation matrix that measures the correlation between two or more data sets that are scaled to be independent of the unit of measurement.

If this function is not available, you must install the Analysis ToolPak add-in macro.

Syntax

MCORREL(inprng, outrng, grouped, labels)
MCORREL?(inprng, outrng, grouped, labels)

Inprng is the input range.

Outrng is the first cell (the upper-left cell) in the output table or the name, as text, of a new sheet to contain the output table. If FALSE, blank, or omitted, places the output table in a new workbook.

Grouped is a text character that indicates whether the data in the input range is organized by row or column.

  • If grouped is "C" or omitted, then the data is organized by column.
  • If grouped is "R", then the data is organized by row.

Labels is a logical value that describes where the labels are located in the input range, as shown in the following table:

Labels | Grouped | Labels are in
TRUE | "C" | First row of the input range.
TRUE | "R" | First column of the input range.
FALSE or omitted | (ignored) | No labels. All cells in the input range are data.

Related Functions

MCOVAR Returns the covariance between two or more data sets

List of Statistical Functions


MCOVAR

Macro Sheets Only

Returns a covariance matrix that measures the covariance between two or more data sets.

If this function is not available, you must install the Analysis ToolPak add-in macro.

Syntax

MCOVAR(inprng, outrng, grouped, labels)
MCOVAR?(inprng, outrng, grouped, labels)

Inprng is the input range.

Outrng is the first cell (the upper-left cell) in the output table or the name, as text, of a new sheet to contain the output table. If FALSE, blank, or omitted, places the output table in a new workbook.

Grouped is a text character that indicates whether the data in the input range is organized by row or column.

  • If grouped is "C" or omitted, then the data is organized by column.
  • If grouped is "R", then the data is organized by row.

Labels is a logical value that describes where the labels are located in the input range, as shown in the following table:

Labels | Grouped | Labels are in
TRUE | "C" | First row of the input range
TRUE | "R" | First column of the input range
FALSE or omitted | (ignored) | No labels. All cells in the input range are data.

Related Functions

MCORREL Returns the correlation coefficient of two or more data sets that are scaled to be independent of the unit of measurement

List of Statistical Functions


MOVEAVG

Macro Sheets Only

Projects values in a forecast period, based on the average value of the variable over a specific number of preceding periods.

If this function is not available, you must install the Analysis ToolPak add-in macro.

Syntax

MOVEAVG(inprng, outrng, interval, stderrs, chart, labels)
MOVEAVG?(inprng, outrng, interval, stderrs, chart, labels)

Inprng is the input range.

Outrng is the first cell (the upper-left cell) in the output table or the name, as text, of a new sheet to contain the output table. If FALSE, blank, or omitted, places the output table in a new workbook.

Interval is the number of values to include in the moving average. If omitted, interval is 3.

Stderrs is a logical value.

  • If stderrs is TRUE, standard error values are included in the output table.
  • If stderrs is FALSE or omitted, standard errors are not included in the output table.

Chart is a logical value.

  • If chart is TRUE, then MOVEAVG generates a chart for the actual and forecast values.
  • If chart is FALSE or omitted, the chart is not generated.

Labels is a logical value.

  • If labels is TRUE, then the first row or column of inprng contains labels.
  • If labels is FALSE or omitted, all cells in inprng are considered data. Microsoft Excel generates appropriate data labels for the output table.

Related Functions

List of Statistical Functions


PTTESTM

Macro Sheets Only

Performs a paired two-sample Student's t-Test for means.

If this function is not available, you must install the Analysis ToolPak add-in macro.

Syntax

PTTESTM(inprng1, inprng2, outrng, labels, alpha, difference)
PTTESTM?(inprng1, inprng2, outrng, labels, alpha, difference)

Inprng1 is the input range for the first data set.

Inprng2 is the input range for the second data set.

Outrng is the first cell (the upper-left cell) in the output table or the name, as text, of a new sheet to contain the output table. If FALSE, blank, or omitted, places the output table in a new workbook.

Labels is a logical value.

  • If labels is TRUE, then labels are in the first row or column of the input ranges.
  • If labels is FALSE or omitted, all cells in inprng1 and inprng2 are considered data. The output table will include default row or column headings.

Alpha is the confidence level for the test. If omitted, alpha is 0.05.

Difference is the hypothesized mean difference. If omitted, difference is 0.

Related Functions

PTTESTV Performs a two-sample Student's t-Test, assuming unequal variances

TTESTM Performs a two-sample Student's t-Test for means, assuming equal variances

List of Statistical Functions


PTTESTV

Macro Sheets Only

Performs a two-sample Student's t-Test, assuming unequal variances.

If this function is not available, you must install the Analysis ToolPak add-in macro.

Syntax

PTTESTV(inprng1, inprng2, outrng, labels, alpha)
PTTESTV?(inprng1, inprng2, outrng, lables, alpha)

Inprng1 is the input range for the first data set.

Inprng2 is the input range for the second data set.

Outrng is the first cell (the upper-left cell) in the output table or the name, as text, of a new sheet to contain the output table. If FALSE, blank, or omitted, places the output table in a new workbook.

Labels is a logical value.

  • If labels is TRUE, then labels are in the first row or column of the input ranges.
  • If labels is FALSE or omitted, all cells in inprng1 and inprng2 are considered data. The output table will include default row or column headings.

Alpha is the confidence level for the test. If omitted, alpha is 0.05.

Related Functions

PTTESTM Performs a paired two-sample Student's t-Test for means

TTESTM Performs a two-sample Student's t-Test for means, assuming equal variances

List of Statistical Functions


RANDOM

Macro Sheets Only

Fills a range with independent random or patterned numbers drawn from one of several distributions.

If this function is not available, you must install the Analysis ToolPak add-in macro.

RANDOM provides six different random distributions and one patterned data option. Because the distributions require different argument lists, there are seven syntax forms for RANDOM.

Syntax 1

Uniform distribution

RANDOM(outrng, variables, points, distribution, seed, from, to)
RANDOM?(outrng, variables, points, distribution, seed, from, to)

Syntax 2

Normal distribution

RANDOM(outrng, variables, points, distribution, seed, mean, standard_dev)
RANDOM?(outrng, variables, points, distribution, seed,mean, standard_dev)

Syntax 3

Bernoulli distribution

RANDOM(outrng, variables, points, distribution, seed, probability)
RANDOM?(outrng, variables, points, distribution, seed, probability)

Syntax 4

Binomial distribution

RANDOM(outrng, variables, points, distribution, seed, probability, trials)
RANDOM?(outrng, variables, points, distribution, seed, probability, trials)

Syntax 5

Poisson distribution

RANDOM(outrng, variables, points, distribution, seed, lambda)
RANDOM?(outrng, variables, points, distribution, seed, lambda)

Syntax 6

Patterned distribution

RANDOM(outrng, variables, points, distribution, seed, from, to, step, repeat_num, repeat_seq)
RANDOM?(outrng, variables, points, distribution, seed, from, to, step, repeat_num, repeat_seq)

Syntax 7

Discrete distribution

RANDOM(outrng, variables, points, distribution, seed, inprng)
RANDOM?(outrng, variables, points, distribution, seed, inprng)

Outrng is the first cell (the upper-left cell) in the output table or the name, as text, of a new sheet to contain the output table. If FALSE, blank, or omitted, places the output table in a new workbook.

Variables is the number of random number sets to generate. RANDOM will generate variables columns of random numbers. If omitted, variables is equal to the number of columns in the output range.

Points is the number of data points per random number set. RANDOM will generate points rows of random numbers for each random number set. If omitted, points is equal to the number of rows in the output range. Points is ignored when distribution is 6 (Patterned).

Distribution indicates the type of number distribution.

Distribution Distribution type

1 Uniform

2 Normal

3 Bernoulli

4 Binomial

5 Poisson

6 Patterned

7 Discrete

Seed is an optional value with which to begin random number generation. Seed is ignored when distribution is 6 (Patterned) or 7 (Discrete).

From is the lower bound.

To is the upper bound.

Mean is the mean.

Standard_dev is the standard deviation.

Probability is the probability of success on each trial.

Trials is the number of trials.

Lambda is the Poisson distribution parameter.

Step is the increment between from and to.

Repeat_num is the number of times to repeat each value.

Repeat_seq is the number of times to repeat each sequence of values.

Inprng is a two-column range of values and their probabilities.

Related Function

List of Statistical Functions


RANKPERC

Macro Sheets Only

Returns a table that contains the ordinal and percent rank of each value in a data set.

If this function is not available, you must install the Analysis ToolPak add-in macro.

Syntax

RANKPERC(inprng, outrng, grouped, labels)
RANKPERC?(inprng, outrng, grouped, labels)

Inprng is the input range.

Outrng is the first cell (the upper-left cell) in the output table or the name, as text, of a new sheet to contain the output table. If FALSE, blank, or omitted, places the output table in a new workbook.

Grouped is a text character that indicates whether the data in the input range is organized by row or column.

  • If grouped is "C" or omitted, then the data is organized by column.
  • If grouped is "R", then the data is organized by row.

Labels is a logical value that describes where the labels are located in the input range, as shown in the following table:

Labels | Grouped | Labels are in
TRUE | "C" | First row of the input range.
TRUE | "R" | First column of the input range.
FALSE or omitted | (ignored) | No labels. All cells in the input range are data.

Related Functions

List of Statistical Functions


REGRESS

Macro Sheets Only

Performs multiple linear regression analysis.

If this function is not available, you must install the Analysis ToolPak add-in macro.

Syntax

REGRESS(inpyrng, inpxrng, constant, labels, confid, soutrng, residuals, sresiduals, rplots, lplots, routrng, nplots, poutrng)
REGRESS?(inpyrng, inpxrng, constant, labels, confid, soutrng, residuals, sresiduals, rplots, lplots, routrng, nplots, poutrng)

Inpyrng is the input range for the y-values (dependent variable).

Inpxrng is the input range for the x-values (independent variable).

Constant is a logical value. If constant is TRUE, the y-intercept is assumed to be zero (the regression line passes through the origin). If constant is FALSE or omitted, the y-intercept is assumed to be a non-zero number.

Labels is a logical value.

  • If labels is TRUE, then the first row or column of the input ranges contain labels.
  • If labels is FALSE or omitted, all cells in inpyrng and inpxrng are considered data. Microsoft Excel will then generate the appropriate data labels for the output table.

Confid is an additional confidence level to apply to the regression. If omitted, confid is 95%.

Soutrng is the first cell (the upper-left cell) in the output table or the name, as text, of the new sheet to contain the summary output table. If FALSE, blank, or omitted, places the summary output table in a new workbook. Microsoft Excel version 5.0 uses a single output table for REGRESS; Microsoft Excel version 4.0 used three different output tables for summary, residual, and probability data.

Residuals is a logical value. If residuals is TRUE, REGRESS includes residuals in the output table. If residuals is FALSE or omitted, residuals are not included.

Sresiduals is a logical value. If sresiduals is TRUE, REGRESS includes standardized residuals in the output table. If sresiduals is FALSE or omitted, standardized residuals are not included.

Rplots is a logical value. If rplots is TRUE, REGRESS generates separate charts for each x versus the residual. If rplots is FALSE or omitted, separate charts are not generated.

Lplots is a logical value. If lplots is TRUE, REGRESS generates a chart showing the regression line fitted to the observed values. If lplots is FALSE or omitted, the chart is not generated.

Routrng is the first cell (the upper-left cell) in the residuals output table or the name, as text, of the new sheet to contain the residuals output table. If FALSE, blank, or omitted, places the residuals output table in a new worksheet. This argument is for compatibility with Microsoft Excel 4.0 only and is ignored in Microsoft Excel version 5.0.

Nplots is a logical value. If nplots is TRUE, REGRESS generates a chart of normal probabilities. If nplots is FALSE or omitted, the chart is not generated.

Poutrng is the first cell (the upper-left cell) in the probability data output table or the name, as text, of the new sheet to contain the probability output table. If FALSE, blank, or omitted, places the probability output table in a new worksheet. This argument is for compatibility with Microsoft Excel 4.0 only and is ignored in Microsoft Excel version 5.0.

Related Functions

List of Statistical Functions


SAMPLE

Macro Sheets Only

Samples data.

If this function is not available, you must install the Analysis ToolPak add-in macro.

Syntax

SAMPLE(inprng, outrng, method, rate, labels)
SAMPLE?(inprng, outrng, method, rate, labels)

Inprng is the input range.

Outrng is the first cell (the upper-left cell) in the output column or the name, as text, of a new sheet to contain the output column. If FALSE, blank, or omitted, places the output table in a new workbook.

Method is a text character that indicates the type of sampling.

  • If method is "P", then periodic sampling is used. The input range is sampled every nth cell, where n = rate.
  • If method is "R", then random sampling is used. The output column will contain rate samples.

Rate is the sampling rate, if method is "P" (periodic sampling). Rate is the number of samples to take if method is "R" (random sampling).

Labels is a logical value.

  • If labels is TRUE, then the first row or column of inprng contains labels.
  • If labels is FALSE or omitted, all cells in inprng are considered data. Microsoft Excel generates appropriate data labels for the output table.

Related Function

List of Statistical Functions


TTESTM

Macro Sheets Only

Performs a two-sample Student's t-Test for means, assuming equal variances.

If this function is not available, you must install the Analysis ToolPak add-in macro.

Syntax

TTESTM(inprng1, inprng2, outrng, labels, alpha, difference)
TTESTM?(inprng1, inprng2, outrng, labels, alpha, difference)

Inprng1 is the input range for the first data set.

Inprng2 is the input range for the second data set.

Outrng is the first cell (the upper-left cell) in the output table or the name, as text, of a new sheet to contain the output table. If FALSE, blank, or omitted, places the output table in a new workbook.

Labels is a logical value.

  • If labels is TRUE, then labels are in the first row or column of the input ranges.
  • If labels is FALSE or omitted, all cells in inprng1 and inprng2 are considered data. The output table will include default row or column headings.

Alpha is the confidence level for the test. If omitted, alpha is 0.05.

Difference is the hypothesized difference in means. If omitted, difference is 0.

Related Functions

PTTESTM Performs a paired two-sample Student's t-Test for means

PTTESTV Performs a two-sample Student's t-Test, assuming unequal variances

List of Statistical Functions


ZTESTM

Macro Sheets Only

Performs a two-sample z-test for means, assuming the two samples have known variances.

If this function is not available, you must install the Analysis ToolPak add-in macro.

Syntax

ZTESTM(inprng1, inprng2, outrng, labels, alpha, difference, var1, var2)
ZTESTM?(inprng1, inprng2, outrng, labels, alpha, difference, var1, var2)

Inprng1 is the input range for the first data set.

Inprng2 is the input range for the second data set.

Outrng is the first cell (the upper-left cell) in the output table or the name, as text, of a new sheet to contain the output table. If FALSE, blank, or omitted, places the output table in a new workbook.

  • Labels is a logical value.
  • labels is TRUE, then the first row or column of the input ranges contains labels.
  • If labels is FALSE or omitted, all cells in inprng1 and inprng2 are considered data. Microsoft Excel will then generate the appropriate data labels for the output table.

Alpha is the confidence level for the test. If omitted, alpha is 0.05.

Difference is the hypothesized difference in means. If omitted, difference is 0.

Var1 is the variance of the first data set.

Var2 is the variance of the second data set.

Related Functions

List of Statistical Functions


CELL.PROTECTION

Macro Sheets Only

Equivalent to choosing the Protection tab in the Format Cells dialog box, which appears when you choose the Cells command from the Format menu. Allows you to control cell protection and display.

Arguments are logical values corresponding to check boxes in the Protection tab. If an argument is TRUE, Microsoft Excel selects the check box; if FALSE, Microsoft Excel clears the check box. If an argument is omitted and the setting has been previously changed from the defaults, the setting is not changed.

Syntax

CELL.PROTECTION(locked, hidden)
CELL.PROTECTION?(locked, hidden)

Locked corresponds to the Locked check box. The default is TRUE.

Hidden corresponds to the Hidden check box. The default is FALSE.

Remarks

Options selected in the Protection tab of the Format Cells dialog box or with the CELL.PROTECTION function are activated only when the Protect Sheet command is chosen from the Protection submenu on the Tools menu or the PROTECT.DOCUMENT function is used to select protection.

Related Functions

PROTECT.DOCUMENT Controls protection for the active document

SAVE.AS Saves a document and allows you to specify the name, file type, password, backup file, and location of the document

List of Command-Equivalent Functions


COLUMN.WIDTH

Macro Sheets Only

Equivalent to choosing the Width command on the Column submenu of the Format menu. Changes the width of the columns in the specified reference.

Syntax

COLUMN.WIDTH(width_num, reference, standard, type_num, standard_num)
COLUMN.WIDTH?(width_num, reference, standard, type_num, standard_num)

Width_num specifies how wide you want the columns to be in units of one character of the font corresponding to the Normal cell style. Width_num is ignored if standard is TRUE or if type_num is provided.

Reference specifies the columns for which you want to change the width.

  • If reference is specified, it must be either an external reference to the active worksheet, such as !$A:$C or !Database, or an R1C1-style reference in the form of text, such as "C1:C3", "C[-4]:C[-2]", or "Database".
  • If reference is a relative R1C1-style reference in the form of text, it is assumed to be relative to the active cell.
  • If reference is omitted, it is assumed to be the current selection.

Standard_num is a logical value corresponding to the Standard Width command from the Column submenu on the Format menu.

  • If standard is TRUE, Microsoft Excel sets the column width to the currently defined standard (default) width and ignores width_num.
  • If standard is FALSE or omitted, Microsoft Excel sets the width according to width_num or type_num.

Type_num is a number from 1 to 3 corresponding to the Hide, Unhide, or AutoFit Selection commands, respectively, on the Column submenu of the Format menu.

Type_num Action taken

1 Hides the column selection by setting the column width to 0

2 Unhides the column selection by setting the column width to the value set before the selection was hidden

3 Sets the column selection to a best-fit width, which varies from column to column depending on the length of the longest data string in each column

Standard_num specifies how wide the standard width is, and is measured in points. If standard_num is omitted, the standard width setting remains unchanged.

Remarks

  • Changing the value of standard_num changes the width of all columns except those that have been set to a custom value.
  • If any of the argument settings conflict, such as when standard is TRUE and type_num is 3, Microsoft Excel uses the type_num argument and ignores any arguments that conflict with type_num.
  • If you are recording a macro while using a mouse and you change column widths by dragging the column border, Microsoft Excel records the references of the columns using R1C1-style references in the form of text.

Related Function

ROW.HEIGHT Changes the heights of rows

List of Command-Equivalent Functions


COMBINATION

Macro Sheets Only

Equivalent to choosing the Combination item from the Galleries list box within the AutoFormat dialog box, which appears when you choose the AutoFormat command from the Format menu. This function is available only when a chart is made active. Changes the format of the active chart to the combination format you select from the gallery.

Syntax

COMBINATION(type_num)
COMBINATION?(type_num)

Type_num is a number corresponding to the combination chart you want.

Related Functions

FORMAT.MAIN Formats a main chart

FORMAT.OVERLAY Formats an overlay chart

List of Command-Equivalent Functions


CUT

Macro Sheets Only

Equivalent to choosing the Cut command from the Edit menu. Cuts or moves data or objects.

Syntax

CUT(from_reference, to_reference)

From_reference is a reference to the cell or range of cells you want to cut. If from_reference is omitted, it is assumed to be the current selection.

To_reference is a reference to the cell or range of cells where you want to paste what you have cut.

  • To_reference should be a single cell or an enlarged multiple of from_reference. For example, if from_reference is a 2 by 4 rectangle, to_reference can be a 4 by 8 rectangle.
  • To_reference can be omitted so that you can paste from_reference later using the PASTE or PASTE.SPECIAL functions.

Remarks

The following information may be helpful if you're having problems with CUT updating references in unexpected ways. When you move cells using CUT, formulas that referred to from_reference will refer to to_reference, and formulas that referred to to_reference may return #REF! error values. However, if from_reference or to_reference contains references that are calculated at runtime (for example, CUT(ACTIVE.CELL(), !B1)), then Microsoft Excel does not update those references when the CUT function is run, so no error values are returned.

Related Functions

COPY Copies and pastes data or objects

PASTE Pastes cut or copied data

List of Command-Equivalent Functions


DEMOTE

Macro Sheets Only

Equivalent to clicking the Group tool. Demotes, or groups, the selected rows or columns in an outline. Use DEMOTE to change the configuration of an outline by grouping rows or columns of information.

Syntax

DEMOTE(row_col)
DEMOTE?(row_col)

Row_col specifies whether to group rows or columns.

Row_col Demotes

1 or omitted Rows

2 Columns

Remarks

  • If the selection consists of an entire row or rows, then rows are demoted even if row_col is 2. Similarly, selection of an entire column overrides row_col 1.
  • If the selection is unambiguous (an entire row or column), then DEMOTE? will not display the dialog box.

Related Functions

PROMOTE Promotes the selection in an outline

SHOW.DETAIL Expands or collapses a portion of an outline

SHOW.LEVELS Displays a specific number of levels of an outline

List of Command-Equivalent Functions


FILE.DELETE

Macro Sheets Only

Deletes a file from the disk. Although you will normally delete files manually, you can, for example, use FILE.DELETE in a macro to delete temporary files created by the macro.

Syntax

FILE.DELETE(file_text)
FILE.DELETE?(file_text)

File_text is the name of the file to delete.

Remarks

  • If Microsoft Excel can't find file_text, it displays a message saying that it cannot delete the file. To avoid this, include the entire path in file_text. See the following second and fifth examples. You can also use FILES to generate an array of filenames and then check if the file you want to delete is in the array. For an example of how to see if an entry is in an array, see OR.
  • If a file is open when you delete it, the file is removed from the disk but remains open in Microsoft Excel.
  • In the dialog-box form, FILE.DELETE?, you can use an asterisk (*) to represent any series of characters and a question mark (?) to represent any single character. See the following third and sixth examples.

Examples

In Microsoft Excel for Windows, the following macro formula deletes a file called CHART1.XLS from the current directory:

FILE.DELETE("CHART1.XLS")

The following macro formula deletes a file called 92INFO.XLS kept in the EXCEL\SALES subdirectory:

FILE.DELETE("C:\EXCEL\SALES\92INFO.XLS")

The following macro formula displays the Delete dialog box listing all documents whose extensions begin with the letters "XL":

FILE.DELETE?("*.XL?")

In Microsoft Excel for the Macintosh, the following macro formula deletes a file called CHART1 from the current folder:

FILE.DELETE("CHART1")

The following macro formula deletes a file called 1992 INFO kept in a series of nested folders:

FILE.DELETE("HARD DISK:EXCEL 5:SALES WORKSHEETS:1992 INFO")

The following macro formula displays the Delete dialog box listing all documents beginning with the word "Clients":

FILE.DELETE?("Clients*")

Related Functions

FILE.CLOSE Closes the active document

FILES Returns the filenames in the specified directory or folder

List of Command-Equivalent Functions


FULL

Macro Sheets Only

Equivalent to pressing CTRL+F10 (full size) and CTRL+F5 (previous size) or double-clicking the title bar in Microsoft Excel for Windows version 3.0 or earlier. Equivalent to double-clicking the title bar or clicking the zoom box in Microsoft Excel for the Macintosh version 3.0 or earlier. This function is included only for macro compatibility. To perform the equivalent of a FULL(TRUE) function in Microsoft Excel version 4.0 or later, use the WINDOW.MAXIMIZE function. To perform the equivalent of a FULL(FALSE) function in Microsoft Excel version 4.0 or later, use the WINDOW.RESTORE function.

Syntax

FULL(logical)

Related Functions

List of Command-Equivalent Functions


GROUP

Macro Sheets Only

Equivalent to choosing the Group command from the Placement submenu on the Format menu. Creates a single object from several selected objects and returns the object identifier of the group (for example, "Group 5"). Use GROUP to combine a number of objects so that you can move or resize them together.

If no object is selected, only one object is selected, or a group is already selected, GROUP returns the #VALUE! error value and interrupts the macro.

Syntax

GROUP( )

Related Function

UNGROUP Separates a grouped object

List of Command-Equivalent Functions


HPAGE

Macro Sheets Only

Horizontally scrolls through the active window one window at a time. Use HPAGE to change the displayed area of a worksheet or macro sheet.

Syntax

HPAGE(num_windows)

Num_windows specifies the number of windows to scroll through the active window horizontally. A window is defined as the number of visible columns. If three columns are visible in the window, HPAGE scrolls through in increments of three columns.

  • If num_windows is positive, HPAGE scrolls to the right.
  • If num_windows is negative, HPAGE scrolls to the left.

Related Functions

HLINE Horizontally scrolls through the active window by columns

HSCROLL Horizontally scrolls through a document by percentage or by column number

VLINE Vertically scrolls through the active window by rows

VPAGE Vertically scrolls through the active window one window at a time

VSCROLL Vertically scrolls through a document by percentage or by row number

List of Command-Equivalent Functions


MOVE

Macro Sheets Only

Equivalent to moving a window by dragging its title bar in Microsoft Excel version 3.0 or earlier. MOVE is also equivalent to choosing the Move command from the Control menu in Microsoft Windows. This function is included only for macro compatibility and will be converted to WINDOW.MOVE when you open older macro sheets. For more information, see WINDOW.MOVE.

Syntax

MOVE(x_pos, y_pos, window_text)
MOVE?(x_pos, y_pos, window_text)

Related Functions

WINDOW.MOVE Sizes a window

WINDOW.SIZE Moves a window

List of Command-Equivalent Functions


NOTE

Macro Sheets Only

Equivalent to choosing the Note command from the Insert menu. Creates a note or replaces characters in a note. Use NOTE to create a cell note or to replace a specified number of characters with other text.

Syntax

NOTE(add_text, cell_ref, start_char, num_chars)
NOTE?( )

Add_text is text of up to 255 characters you want to add to a note. Add_text must be enclosed in quotation marks.

  • If add_text is omitted, it is assumed to be "" (empty text) unless the note includes sound.
  • If a note contains sound and you omit add_text, Microsoft Excel deletes the entire note, but if you explicitly specify empty text, Microsoft Excel deletes only the text, not the sound. To erase only the sound, use the SOUND.NOTE function.

Cell_ref is the cell to which you want to add the note text. If cell_ref is omitted, add_text is added to the active cell's note.

Start_char is the number of the character at which you want add_text to be added. If start_char is omitted, it is assumed to be 1. If there is no existing note, start_char is ignored.

Num_chars is the number of characters that you want to replace in the note. If num_chars is omitted, it is assumed to be equal to the length of the note.

Remarks

  • NOTE returns the number of the last character entered in the cell note. This is useful if you want to know how many characters are in the text string so it can be manipulated with other functions such as RIGHT, LEFT, and MID.
  • The dialog-box form of this function, NOTE?, takes no arguments.
  • NOTE() deletes the note attached to the active cell.

To find out if a cell has a note attached to it, use GET.CELL.

Related Functions

GET.NOTE Returns characters from a note

SOUND.NOTE Records or imports sounds into or erases sound from cell notes

List of Command-Equivalent Functions


OUTLINE

Macro Sheets Only

Creates an outline and defines settings for automatically creating outlines.

The first three arguments are logical values corresponding to check boxes in the Outline dialog box, which appears when you choose the Settings command from the Group and Outline submenu on the Data menu. If an argument is TRUE, Microsoft Excel selects the check box; if FALSE, Microsoft Excel clears the check box. If an argument is omitted, the check box is left in its current state.

Syntax

OUTLINE(auto_styles, row_dir, col_dir, create_apply)
OUTLINE?(auto_styles, row_dir, col_dir, create_apply)

Auto_styles corresponds to the Automatic Styles check box.

Row_dir corresponds to the Summary Rows Below Detail check box.

Col_dir corresponds to the Summary Columns To Right Of Detail check box.

Create_apply is the number 1 or 2 and corresponds to the Create button and the Apply Styles button.

Create_apply Result

1 Creates an outline with the current settings

2 Applies outlining styles to the selection based on outline levels

Omitted Corresponds to choosing the OK button to set the other outline settings

Related Functions

DEMOTE Demotes the selection in an outline

PROMOTE Promotes the selection in an outline

List of Command-Equivalent Functions


PARSE

Macro Sheets Only

Distributes the contents of the current selection to fill several adjacent columns; the selection can be no more than one column wide. Use PARSE to reorganize data, especially data that you've read from files created by another application, such as a database.

Syntax

PARSE(parse_text, destination_ref)
PARSE?(parse_text, destination_ref)

Parse_text is the parse line in the form of text. It is a copy of the first nonblank cell in the selected column, with square brackets indicating where to distribute (or parse) text. If parse_text is omitted, Microsoft Excel guesses where to place the brackets based on the spacing and formatting of data.

Destination_ref is a reference to the upper-left corner of the range of cells where you want to place the parsed data. If destination_ref is omitted, it is assumed to be the current selection, so the parsed data will replace the original data.

Remarks

  • In most cases, it's easier to record the Parse command than to enter the PARSE function manually.
  • When you use the PARSE function, Microsoft Excel splits the first column into as many columns as you specify with parse_text and replaces any information in those columns.

Related Functions

List of Command-Equivalent Functions


PLACEMENT

Macro Sheets Only

Equivalent to choosing the Object Placement command from the Format menu in Microsoft Excel version 3.0. Determines how the selected object or objects are attached to the cells beneath them. This function is included only for macro compatibility and will be converted to OBJECT.PROPERTIES when you load older macro sheets. For more information, see OBJECT.PROPERTIES.

Syntax

PLACEMENT(placement_type)
PLACEMENT?(placement_type)

Related Functions

OBJECT.PROPERTIES Determines an object's relationship to underlying cells

List of Command-Equivalent Functions


PROMOTE

Macro Sheets Only

Equivalent to clicking the Ungroup button. Promotes, or ungroups, the currently selected rows or columns in an outline. Use PROMOTE to change the configuration of an outline by promoting rows or columns of information.

Syntax

PROMOTE(rowcol)
PROMOTE?(rowcol)

Rowcol specifies whether to promote rows or columns.

Rowcol Demotes

1 or omitted Rows

2 Columns

Remarks

  • If the selection consists of an entire row or rows, then rows are promoted even if rowcol is 2. Similarly, selection of an entire column overrides rowcol 1.
  • Also, if the selection is unambiguous (an entire row or column), then PROMOTE? will not display the dialog box.

Related Functions

DEMOTE Demotes the selection in an outline

SHOW.DETAIL Expands or collapses a portion of an outline

SHOW.LEVELS Displays a specific number of levels of an outline


RESUME

Macro Sheets Only

Equivalent to choosing the Resume button on the Macro toolbar. Resumes a paused macro. Returns TRUE if successful or the #VALUE! error value if no macro is paused. A macro can be paused by using the PAUSE function or choosing Pause from the Single Step dialog box, which appears when you choose the Step button from the Macro dialog box.

Syntax

RESUME(type_num)

Type_num is a number from 1 to 4 specifying how to resume.

Type_num How Microsoft Excel resumes

1 or omitted If paused by a PAUSE function, continues running the macro. If paused from the Single Step dialog box, returns to that dialog box.

2 Halts the paused macro

3 Continues running the macro

4 Opens the Single Step dialog box

Tip You can use Microsoft Excel's ON functions to resume based on an event. For an example, see ENTER.DATA.

Remarks

  • If one macro runs a second macro that pauses, and you need to halt only the paused macro, use RESUME(2) instead of HALT. HALT halts all macros and prevents resuming or returning to any macro.
  • If the macro was paused from the Single Step dialog box, RESUME returns to the Single Step dialog box.

Related Functions

HALT Stops all macros from running

PAUSE Pauses a macro

RETURN Ends the currently running macro

List of Command-Equivalent Functions


ROW.HEIGHT

Macro Sheets Only

Equivalent to choosing the Height command on the Row submenu of the Format menu. Changes the height of the rows in a reference.

Syntax

ROW.HEIGHT(height_num, reference, standard_height, type_num)
ROW.HEIGHT?(height_num, reference, standard_height, type_num)

Height_num specifies how high you want the rows to be in points. If standard_height is TRUE, height_num is ignored.

Reference specifies the rows for which you want to change the height.

  • If reference is omitted, the reference is assumed to be the current selection.
  • If reference is specified, it must be either an external reference to the active worksheet, such as !$2:$4 or !Database, or an R1C1-style reference in the form of text or a name, such as "R1:R3", "R[-4]:R[-2]", or Database.
  • If reference is a relative R1C1-style reference in the form of text, it is assumed to be relative to the active cell.

Standard_height is a logical value that sets the row height as determined by the font in each row.

  • If standard_height is TRUE, Microsoft Excel sets the row height to a standard height that may vary from row to row depending on the fonts used in each row, ignoring height_num.
  • If standard_height is FALSE or omitted, Microsoft Excel sets the row height according to height_num.

Type_num is a number from 1 to 3 corresponding to selecting the Hide, Unhide, or AutoFit commands from the Row submenu.

Type_num Action taken

1 Hides the row selection by setting the row height to 0

2 Unhides the row selection by setting the row height to the value set before the selection was hidden

3 Sets the row selection to an AutoFit height, which varies from row to row depending on how large the font is in any cell in each row or on how many lines of text are wrapped

Remarks

  • If any of the argument settings conflict, such as when standard_height is TRUE and type_num is 3, Microsoft Excel uses the type_num argument and ignores any arguments that conflict with type_num.
  • If you are recording a macro while using a mouse, and you change row heights by dragging the row border, Microsoft Excel records the reference of the rows using R1C1-style references in the form of text. If Uses Relative References is selected, Microsoft Excel uses R1C1-style relative references. If Uses Relative References is not selected, Microsoft Excel uses R1C1-style absolute references.

Related Function

COLUMN.WIDTH Sets the widths of the specified columns

List of Command-Equivalent Functions


RUN

Macro Sheets Only

Equivalent to choosing the Run button in the Macro dialog box, which appears when you choose the Macro command from the Tools menu. Runs a macro.

Syntax

RUN(reference, step)
RUN?(reference, step)

Reference is a reference to the macro you want to run or a number from 1 to 4 specifying an Auto macro to run.

If reference is Specifies

1 All Auto_Open macros on the active workbook

2 All Auto_Close macros

3 All Auto_Activate macros

4 All Auto_Deactivate macros

  • If reference is a range of cells, RUN begins with the macro function in the upper-left cell of reference.
  • If the macro sheet containing the macro is not the active document, reference can be an external reference to the name of the macro, such as RUN([BOOK1]Macro!Months) or an external R1C1-style reference to the location of the macro, such as RUN("[Book1]Macro!R2C3"). The reference must be in text form.
  • If reference is omitted, the macro function in the active cell is carried out, and macro execution continues down that column.

Step is a logical value specifying that the macro is to be run in single-step mode. If step is TRUE, Microsoft Excel runs the macro in single-step mode; if FALSE or omitted, Microsoft Excel runs the macro normally.

Remarks

  • RUN is recorded when you choose the Run command from the Macro menu while recording a macro. The reference you enter in the Run dialog box is recorded as text, with A1-style references converted to R1C1-style references.
  • To run a macro from a macro sheet, you could alternatively enter the name of the macro as a formula, followed by a set of parentheses. For example, enter =[Book1]Macro!Months() instead of =RUN([Book1]Macro!Months).

Related Functions

GOTO Directs macro execution to another cell

List of Command-Equivalent Functions


SAVE

Macro Sheets Only

Equivalent to choosing the Save command from the File menu. Saves the active document.

Syntax

SAVE( )

Remarks

Use the SAVE.AS function instead of SAVE when you want to change the filename or file type, specify a password, create a backup file, or save a file to a different directory or folder.

Related Functions

SAVE.AS Saves a document and allows you to specify the name, file type, password, backup file, and location of the document

SAVE.WORKBOOK Saves a workbook

List of Command-Equivalent Functions


SELECT.END

Macro Sheets Only

Selects the cell at the edge of the range or the first cell of the next range in the direction specified. Equivalent to pressing CTRL+ARROW in Microsoft Excel for Windows or COMMAND+ARROW in Microsoft Excel for the Macintosh.

Syntax

SELECT.END(direction_num)

Direction_num is a number from 1 to 4 indicating the direction in which to move.

Direction_num | Direction
1 | Left (equivalent to CTRL+LEFT ARROW or COMMAND+LEFT ARROW)
2 | Right (equivalent to CTRL+RIGHT ARROW or COMMAND+RIGHT ARROW)
3 | Up (equivalent to CTRL+UP ARROW or COMMAND+UP ARROW)
4 | Down (equivalent to CTRL+DOWN ARROW or COMMAND+DOWN ARROW)

Related Function

SELECT.LAST.CELL Selects the last cell on a worksheet or macro sheet that contains a formula, value, or format or that is referred to in a formula or name

List of Command-Equivalent Functions


SELECT.LAST.CELL

Macro Sheets Only

Equivalent to choosing the Special button from the Goto dialog box and selecting the Last Cell Option. The Goto dialog box appears when you choose the Goto command from the Edit menu. Selects the cell at the intersection of the last row and column that contains a formula, value, or format, or that is referred to in a formula or name.

Syntax

SELECT.LAST.CELL( )

Related Function

SELECT.END Selects the last cell in a range

List of Command-Equivalent Functions


SHOW.DETAIL

Macro Sheets Only

Expands or collapses the detail under the specified expand or collapse button.

Syntax

SHOW.DETAIL(rowcol, rowcol_num, expand, show_field)

Rowcol is a number that specifies whether to operate on rows or columns of data.

EXPANDCOLLAPSE|USA|002|003|001|common|URowcol Operates on

1 Rows

2 Columns

3 The current cell's row or column. The second argument, rowcol_num, is then ignored.

Rowcol_num is a number that specifies the row or column to expand or collapse. If you are in A1 mode, you must still give the column as a number. If rowcol_num is not a summary row or column, SHOW.DETAIL returns the #VALUE! error value and interrupts the macro.

Expand is a logical value that specifies whether to expand or collapse the detail under the row or column. If expand is TRUE, Microsoft Excel expands the detail under the row or column; if FALSE, it collapses the detail under the row or column. If expand is omitted, the detail is expanded if it is currently collapsed and collapsed if it is currently expanded.

Show_Field is a string specifying the name of the field to add to a PivotTable, if the selection is inside a PivotTable. The new field is added as the new innermost field. Available for only innermost row or column fields.

Related Function

SHOW.LEVELS Displays a specific number of levels of an outline

List of Command-Equivalent Functions


SHOW.LEVELS

Macro Sheets Only

Displays the specified number of row and column levels of an outline.

Syntax

SHOW.LEVELS(row_level, col_level)

Row_level specifies the number of row levels of an outline to display. If the outline has fewer levels than specified by row_level, Microsoft Excel shows all levels. If row_level is zero or omitted, no action is taken on rows.

Col_level specifies the number of column levels of an outline to display. If the outline has fewer levels than specified by col_level, Microsoft Excel shows all levels. If col_level is zero or omitted, no action is taken on columns.

Remarks

If you omit both arguments, SHOW.LEVELS returns the #VALUE! error value.

Related Function

SHOW.DETAIL Expands or collapses a portion of an outline

List of Command-Equivalent Functions


SPLIT

Macro Sheets Only

Equivalent to choosing the Split command from the Window menu or to dragging the split bar in the active window's scroll bar. Splits the active window into panes. Use SPLIT when you want to view different parts of the active document at the same time.

Syntax

SPLIT(col_split, row_split)

Col_split specifies where to split the window vertically and is measured in columns from the left of the window.

Row_split specifies where to split the window horizontally and is measured in rows from the top of the window.

If an argument is 0 and there is a split in that direction, the split is removed. If an argument is omitted, a split in that direction is not changed.

Related Function

FREEZE.PANES Freezes or unfreezes the panes of a window

List of Command-Equivalent Functions


STYLE

Macro Sheets Only

Checks the fonts for a bold and/or italic font and applies it to the current selection in Microsoft Excel for the Macintosh version 1.5 or earlier. If no appropriate font is available, Microsoft Excel finds the most similar font available and formats the selection using that font. This function is included only for macro compatibility. If you want to change a font to bold or italic, use the FONT.PROPERTIES function.

Syntax

STYLE(bold,italic)
STYLE?(bold,italic)

Related Functions

FONT.PROPERTIES Applies a font to the selection

List of Command-Equivalent Functions


UNGROUP

Macro Sheets Only

Equivalent to choosing the Ungroup command from the Placement submenu on the Format menu. Separates a grouped object into individual objects. Use UNGROUP to separate a group of objects so that you can format, move, or size one of the objects.

If the selection is not a grouped object, UNGROUP returns FALSE.

Syntax

UNGROUP( )

Related Function

GROUP Groups selected objects

List of Command-Equivalent Functions


VLINE

Macro Sheets Only

Scrolls through the active window vertically by the number of rows you specify.

Syntax

VLINE(num_rows)

Num_rows is a number that specifies how many rows to scroll.

  • If num_rows is positive, Microsoft Excel scrolls down by the number of rows indicated by num_rows.
  • If num_rows is negative, Microsoft Excel scrolls up by the number of rows indicated by num_rows.

Related Functions

HLINE Horizontally scrolls through the active window by columns

HPAGE Horizontally scrolls through the active window one window at a time

HSCROLL Horizontally scrolls through a document by percentage or by column number

VPAGE Vertically scrolls through the active window one window at a time

VSCROLL Vertically scrolls through a document by percentage or by row number

List of Command-Equivalent Functions


VPAGE

Macro Sheets Only

Vertically scrolls through the active window one window at a time. Use VPAGE to change the displayed area of a worksheet or macro sheet.

Syntax

VPAGE(num_windows)

Num_windows specifies the number of windows to scroll through the active window vertically. A window is defined as the number of visible rows. If 20 rows are visible in the window, VPAGE scrolls in increments of 20 rows.

  • If num_windows is positive, VPAGE scrolls down.
  • If num_windows is negative, VPAGE scrolls up.

Related Functions

HPAGE Horizontally scrolls through the active window one window at a time

HSCROLL Horizontally scrolls through a document by percentage or by column number

VLINE Vertically scrolls through the active window by rows

VSCROLL Vertically scrolls through a document by percentage or by row number

List of Command-Equivalent Functions


ZOOM

Macro Sheets Only

Equivalent to choosing the Zoom command from the View menu. Enlarges or reduces a document in the active window. Use ZOOM when you need to view more cells than would normally fit in the active windows, or fewer cells at a larger size.

Syntax

ZOOM(magnification)

Magnification is a logical value or a number specifying the size of the document.

  • Magnification can be a number from 10 to 400 specifying the percentage of enlargement or reduction.
  • If magnification is TRUE or omitted, the current selection is enlarged or reduced to completely fill the active window.
  • If magnification is FALSE, the document is restored to normal 100% magnification.

Related Function

PRINT.PREVIEW Previews pages and pagebreaks before printing.

List of Command-Equivalent Functions


ACTIVATE

Macro Sheets Only

Switches to a window if more than one window is open, or a pane of a window if the window is split and its panes are not frozen. Switching to a pane is useful with functions such as VSCROLL, HSCROLL, and GOTO, which operate only on the active pane.

Syntax

ACTIVATE(window_text, pane_num)
ACTIVATE?(window_text, pane_num)

Window_text is text specifying the name of a window to switch to: for example, "Book1" or "Book1:2".

  • If a workbook is displayed in more than one window and window_text does not specify which window to switch to, the first window containing that workbook is switched to.
  • If window_text is omitted, the active window is not changed.

Pane_num is a number from 1 to 4 specifying which pane to switch to. If pane_num is omitted and the window has more than one pane, the active pane is not changed.

Pane_num Activates

1 Upper-left pane of the active sheet. If the window is not split, this is the only pane. If the window is split only horizontally, this is the upper pane. If the window is split only vertically, this is the left pane.

2 Upper-right pane of the active sheet. If the window is split only vertically, this is the right pane. If the window is split only horizontally, an error occurs.

3 Lower-left pane of the active sheet. If the window is split only horizontally, this is the lower pane. If the window is split only vertically, an error occurs.

4 Lower-right pane of the active sheet. If the window is split into only two panes either vertically or horizontally, an error occurs.

Related Functions

ACTIVATE.NEXT Switches to the next window, or switches to the next sheet in a workbook

ACTIVATE.PREV Switches to the previous window, or switches to the previous sheet in a workbook

DOCUMENTS Returns the names of the specified open workbooks

FREEZE.PANES Freezes the panes of a window so that they do not scroll

ON.WINDOW Runs a macro when you switch to a window

SPLIT Splits a window

WINDOWS Returns the names of all open windows

WORKBOOK.SELECT Select a sheet in a workbook

List of Command-Equivalent Functions


ACTIVATE.NEXTACTIVATE.PREV

ACTIVATE.NEXT
ACTIVATE.PREV

Macro Sheets Only

Switches to the next or previous window, respectively, or switches to the next or previous sheet in a workbook.

Syntax

ACTIVATE.NEXT(workbook_text)
ACTIVATE.PREV(workbook_text)

Workbook_text is the name of the workbook for which you want to activate a window.

  • If workbook_text is specified, ACTIVATE.NEXT and ACTIVATE.PREV are equivalent to pressing CTRL+PAGE DOWN and CTRL+PAGE UP (in Microsoft Excel for Windows) or COMMAND+PAGE DOWN and COMMAND+PAGE UP (in Microsoft Excel for the Macintosh). These functions switch to the next and previous sheets, respectively.
  • If workbook_text is omitted, these functions are equivalent to pressing CTRL+TAB or CTRL+SHIFT+TAB (in Microsoft Excel for Windows) or COMMAND+M or COMMAND+SHIFT+M (in Microsoft Excel for the Macintosh). These functions switch to the next and previous windows, respectively.

Related Functions

ACTIVATE Switches to a window

ON.WINDOW Runs a macro when you switch to a window

WORKBOOK.NEXT Switches to the next sheet in a workbook

WORKBOOK.PREV Switches to the previous sheet in a workbook

WORKBOOK.SELECT Select a sheet in a workbook

List of Command-Equivalent Functions


ADD.BAR

Macro Sheets Only

Creates a new menu bar and returns the bar ID number. Use the bar ID number to identify the menu in functions that display and add menus and commands to the menu bar. You can also use ADD.BAR to restore a built-in menu bar with its original menus and commands.

Syntax

ADD.BAR(bar_num)

Bar_num is the number of a built-in menu bar that you want to restore. Use ADD.BAR(bar_num) to restore an unaltered version of a built-in menu bar after you have made changes to the menu bar's menus and commands. See ADD.COMMAND for a list of ID numbers for built-in menu bars.

Important Restoring a built-in menu bar will remove menus and commands added by other macros. Use ADD.COMMAND and ADD.MENU to restore individual commands and menus.

Remarks

ADD.BAR just creates a new menu bar; it does not display it. Use SHOW.BAR to display a menu bar. The argument to the SHOW.BAR function should be the number returned by ADD.BAR or a reference to the cell containing ADD.BAR.

You can define up to 15 custom menu bars at one time. If you carry out an ADD.BAR function when more than 15 custom menu bars are already defined, Microsoft Excel returns the #VALUE! error value.

Example

The following formula creates a new menu bar and returns a bar ID number:

ADD.BAR()

Related Functions

ADD.COMMAND Adds a command to a menu

ADD.MENU Adds a menu to a menu bar

DELETE.BAR Deletes a menu bar

SHOW.BAR Displays a menu bar

List of Customizing Functions


ADD.COMMAND

Macro Sheets Only

Adds a command to a menu. ADD.COMMAND returns the position number on the menu of the added command. Use ADD.COMMAND to add one or more custom menu commands to a menu on a built-in or custom menu bar. You can also use ADD.COMMAND to restore a deleted built-in command to its original menu.

Syntax

ADD.COMMAND(bar_num, menu, command_ref, position1, position2)

Bar_num is the number corresponding to a menu bar or a type of shortcut menu to which you want to add a command.

  • Bar_num can be the ID number of a built-in or custom menu bar. The ID number of a custom menu bar is the number returned by the ADD.BAR function.
  • Bar_num can also refer to a type of shortcut menu; use menu to identify the specific shortcut menu.

The ID numbers of the built-in menu bars and the types of shortcut menus are listed in the following tables. Short menus are abbreviated versions of the normal Microsoft Excel menus. To turn on short menus, use the SHORT.MENUS function.

Bar_num Built-in menu bar

1 Worksheet and macro sheet (Microsoft Excel 4.0 or later)

2 Chart (Microsoft Excel 4.0 or later)

3 Null (the menu displayed when no workbooks are open)

4 Info

5 Worksheet and macro sheet (short menus, Microsoft Excel 3.0 and earlier)

6 Chart (short menus, Microsoft Excel 3.0 and earlier)

7 Cell, toolbar, and workbook (shortcut menus)

8 Object (shortcut menus)

9 Chart (Microsoft Excel 4.0 or later shortcut menus)

10 Worksheet and Macro sheet

11 Chart

12 Visual Basic

Menu is the menu to which you want the new command added.

  • Menu can be either the name of a menu as text or the number of a menu.
  • If bar_num is 1 through 6, menus are numbered starting with 1 from the left of the menu bar.
  • If bar_num is 7, 8, or 9, menu refers to a built-in shortcut menu. The combination of bar_num and menu determines which shortcut menu to modify, as shown in the following table.

Bar_num | Menu | Shortcut menu
7 | 1 | Toolbars
7 | 2 | Toolbar buttons
7 | 3 | Workbook paging icons in Excel 4.0
7 | 4 | Cells (worksheet)
7 | 5 | Column selections
7 | 6 | Row selections
7 | 7 | Workbook tabs
7 | 8 | Cells (macro sheet)
7 | 9 | Workbook titlebar
7 | 10 | Desktop (Microsoft Excel for Windows only)
7 | 11 | Module
7 | 12 | Watch pane
7 | 13 | Immediate pane
7 | 14 | Debug code pane
8 | 1 | Drawn or imported objects on worksheets, dialog sheets, and charts.
8 | 2 | Buttons on sheets
8 | 3 | Text boxes
8 | 4 | Dialog sheet
9 | 1 | Chart series
9 | 2 | Chart and Axis titles
9 | 3 | Chart plot area and walls
9 | 4 | Entire chart
9 | 5 | Chart axes
9 | 6 | Chart gridlines
9 | 7 | Chart floor and arrows
9 | 8 | Chart legend

Note Any commands that you add to the toolbar buttons, watch pane, immediate pane or debug code pane shortcut menus will be dimmed.

Command_ref is an array or a reference to an area on the macro sheet that describes the new command or commands.

  • Command_ref must be at least two columns wide. The first column specifies command names; the second specifies macro names. Optional columns can be specified for shortcut keys (in Microsoft Excel for the Macintosh), status bar messages, and custom Help topics, in that order.
  • Command_ref is similar to menu_ref in ADD.MENU. For more information about command_ref, see the description of menu_ref in ADD.MENU.
  • Command_ref can be the name, as text, of a previously deleted built-in command that you want to restore. You can also use the value returned by the DELETE.COMMAND formula that deleted the command.

Position1 specifies the placement of the new command.

  • Use a hyphen (-) to represent a line separating commands on a menu. If you want to place a command before the second separator on a menu, use two hyphens (--), three hyphens for the third separator, and so on.
  • Position1 can be a number indicating the position of the command on the menu. Commands are numbered from the top of the menu starting with 1.
  • Position1 can be the name of an existing command, as text, above which you want to add the new command.
  • If position1 is omitted, the command is added to the bottom of the menu.
  • For the toolbar shortcut menu (bar_num 7, menu 1) and the shortcut menu for workbook paging icons in Microsoft Excel version 4.0(bar_num 7, menu 3), you cannot add commands to the middle of the toolbar name list or the middle of the workbook contents list.

Position2 specifies the placement of the new command on a submenu.

  • Position2 can be a number indicating the position of the command on the submenu. Commands are numbered from the top of the menu starting with 1.
  • Position2 can be the name of an existing command, as text, above which you want to add the new command.
  • If position2 is omitted, the command is added to the main menu, not the submenu.
  • To add a command to the bottom of a submenu, use 0 for position2.

Tip In general, use menu and command names rather than numbers for arguments. The numbers assigned to menus and commands change as you add and delete menus and commands. Using names ensures that your menu and command macro functions always refer to the correct items.

Example

The following macro formula adds the command described in cells G16:J16 to the bottom of the worksheet cells shortcut menu:

ADD.COMMAND(7, 4, G16:J16)

Related Functions

ADD.BAR Adds a menu bar

ADD.MENU Adds a menu to a menu bar

ADD.TOOL Adds one or more buttons to a toolbar

ADD.TOOLBAR Creates a toolbar with the specified tools

DELETE.COMMAND Deletes a command from a menu

ENABLE.COMMAND Enables or disables a menu or custom command

GET.TOOLBAR Retrieves information about a toolbar

RENAME.COMMAND Changes the name of a command or menu

List of Customizing Functions


ADD.MENU

Macro Sheets Only

Adds a menu to a menu bar. Use ADD.MENU to add a custom menu to a built-in or custom menu bar. You can also use ADD.MENU to restore built-in menus you have deleted with DELETE.MENU. ADD.MENU returns the position number in the menu bar of the new menu.

Syntax

ADD.MENU(bar_num, menu_ref, position1, position2)

Bar_num is the menu bar to which you want a menu added. Bar_num can be the ID number of a built-in or custom menu bar. See ADD.COMMAND for a list of ID numbers for built-in menu bars.

Menu_ref is an array or a reference to an area on the macro sheet that describes the new menu or the name of a deleted built-in menu you want to restore.

  • Menu_ref must be made up of at least two rows and two columns of cells. The upper-left cell of menu_ref specifies the menu title, which is displayed in the menu bar. In the following example, the range A3:E10 is a valid menu_ref.
  • The rest of the first column indicates the names of the commands. The corresponding rows in the second column give the names of the macros that run when the commands are chosen.
  • You can also specify status-bar text and Help topics in the fourth and fifth columns of menu_ref. In Microsoft Excel for the Macintosh, you can specify shortcut keys in the third column of menu_ref.

Position1 specifies the placement of the new menu. Position can be the name of a menu, as text, or the number of a menu. Menus are numbered from left to right starting with 1. Menus are added to the left of the position specified.

  • Use a hyphen (-) to represent a line separating commands on a menu. If you want to place a command before the second separator on a menu, use two hyphens (--), three hyphens for the third separator, and so on.
  • If position1 is omitted, the menu is added to the end of the menu bar.
  • If there is already a menu at position1, that menu is shifted to the right and the new menu is added in its place.
  • If you are using ADD.MENU to restore a deleted built-in menu, you can use the position argument to put it back in its original place on the menu bar. For example, to restore the Data menu on the worksheet and macro sheet menu bar, use position 7. If position1 is omitted, the menu is added to the right of the last menu restored.

Position2 specifies the placement of a submenu.

  • Use a hyphen (-) to represent a line separating commands on a menu. If you want to place a command before the second separator on a menu, use two hyphens (--), three hyphens for the third separator, and so on.
  • Position2 can be a number indicating the position of the submenu on the menu. Commands are numbered from the top of the menu starting with 1 and include separators.
  • Position2 can also be the name, as text, of an existing command above which you want to add the new command.
  • If position2 is omitted, the command is added to the main menu, not the submenu.

Example

The following macro formula adds a new menu to the end of the worksheet menu bar, where A10:B15 is the menu_ref describing the menu:

ADD.MENU(1, A10:B15)

Related Functions

ADD.BAR Adds a menu bar

ADD.COMMAND Adds a command to a menu

DELETE.MENU Deletes a menu

ENABLE.COMMAND Enables or disables a menu or custom command

List of Customizing Functions


ADD.TOOLBAR

Macro Sheets Only

Creates a new toolbar with the specified buttons.

Syntax

ADD.TOOLBAR(bar_name, tool_ref)

Bar_name is a text string identifying the toolbar you want to create.

Tool_ref is either a number specifying a built-in button or a reference to an area on the macro sheet that defines a custom button or set of buttons (or an array containing this information).

For a complete description of tool_ref, see ADD.TOOL.

Remarks

If you create a toolbar without buttons, use ADD.TOOL to add them. Use SHOW.TOOLBAR to display the toolbar.

Example

The following macro formula creates Toolbar9 with one button in it. The cell range B7:I7 contains tool_ref.

ADD.TOOLBAR("Toolbar9", B7:I7)

Related Functions

ADD.TOOL Adds a button to a toolbar

DELETE.TOOL Deletes a button from a toolbar

DELETE.TOOLBAR Deletes custom toolbars

RESET.TOOLBAR Resets a built-in toolbar to its default initial setting

SHOW.TOOLBAR Hides or displays a toolbar

List of Customizing Functions


ALIGNMENT

Macro Sheets Only

Equivalent to choosing the Alignment tab in the Format Cells dialog box, which is displayed when you choose the Cells command from the Format menu. Aligns the contents of the selected cells.

Syntax

ALIGNMENT(horiz_align, wrap, vert_align, orientation, add_indent)
ALIGNMENT?(horiz_align, wrap, vert_align, orientation, add_indent)

Horiz_align is a number from 1 to 7 specifying the type of horizontal alignment, as shown in the following table. If horiz_align is omitted, horizontal alignment does not change.

Horiz_align Horizontal alignment

1 General

2 Left

3 Center

4 Right

5 Fill

6 Justify

7 Center across selection

Wrap is a logical value corresponding to the Wrap Text check box in the Alignment tab. If wrap is TRUE, Microsoft Excel selects the check box and wraps text in cells; if FALSE, Microsoft Excel clears the check box and does not wrap text. If wrap is omitted, wrapping does not change.

Vert_align is a number from 1 to 4 specifying the vertical alignment of the text. If vert_align is omitted, vertical alignment does not change.

Vert_align Vertical alignment

1 Top

2 Center

3 Bottom

4 Justify

Orientation is a number from 0 to 4 specifying the orientation of the text. If orientation is omitted, text orientation does not change.

Orientation Text orientation

0 Horizontal

1 Vertical

2 Upward

3 Downward

4 Automatic (applies to only chart tick labels)

Add_indent This argument is for only Far East versions of Microsoft Excel.

Related Function

FORMAT.TEXT Formats a worksheet text box or a chart text item

List of Command-Equivalent Functions


APP.MAXIMIZE

Macro Sheets Only

Equivalent to choosing the Maximize command from the Control menu for the application window. Maximizes the Microsoft Excel window.

Syntax

APP.MAXIMIZE( )

Note This function is only for Microsoft Excel for Windows. You can use this function in macros created with Microsoft Excel for the Macintosh, but it will return the #N/A error value.

Related Functions

APP.ACTIVATE Switches to an application

APP.MINIMIZE Minimizes the Microsoft Excel application window

APP.MOVE Moves the Microsoft Excel application window

APP.RESTORE Restores the Microsoft Excel application window

APP.SIZE Changes the size of the Microsoft Excel application window

FULL.SCREEN Controls full screen display

List of Command-Equivalent Functions


APP.MINIMIZE

Macro Sheets Only

Equivalent to choosing the Minimize command from the Control menu for the application window. Minimizes the Microsoft Excel window.

Syntax

APP.MINIMIZE( )

Note This function is only for Microsoft Excel for Windows. You can use this function in macros created with Microsoft Excel for the Macintosh, but it will return the #N/A error value.

Related Functions

APP.ACTIVATE Switches to an application

APP.MAXIMIZE Maximizes the Microsoft Excel application window

APP.MOVE Moves the Microsoft Excel application window

APP.RESTORE Restores the Microsoft Excel application window

APP.SIZE Changes the size of the Microsoft Excel application window

List of Command-Equivalent Functions


APP.MOVE

Macro Sheets Only

Equivalent to choosing the Move command from the Control menu for the application window. Moves the Microsoft Excel window. In Microsoft Excel for Windows, if the application window is already maximized APP.MOVE returns the #VALUE! error value and interrupts the macro.

Syntax

APP.MOVE(x_num, y_num)
APP.MOVE?(x_num, y_num)

Note This function is only for Microsoft Excel for Windows. You can use this function in macros created with Microsoft Excel for the Macintosh, but it will return the #N/A error value.

X_num specifies the horizontal position of the Microsoft Excel window measured in points from the left edge of your screen to the left side of the Microsoft Excel window.

Y_num specifies the vertical position of the Microsoft Excel window measured in points from the top edge of your screen to the top of the Microsoft Excel window.

Remarks

  • APP.MOVE?, the dialog-box form of the function, doesn't display a dialog box. Instead, it is equivalent to pressing ALT + SPACEBAR, M or to dragging the title bar with the mouse. With APP.MOVE?, you can move the window with the keyboard or mouse.
  • If you specify x_num and/or y_num in the dialog-box form of the function, the window is moved according to the specified coordinates, and you are left in move mode.

Related Functions

APP.ACTIVATE Switches to an application

APP.MAXIMIZE Maximizes the Microsoft Excel application window

APP.MINIMIZE Minimizes the Microsoft Excel application window

APP.RESTORE Restores the Microsoft Excel application window

APP.SIZE Changes the size of the Microsoft Excel application window

List of Command-Equivalent Functions


APP.RESTORE

Macro Sheets Only

Equivalent to choosing the Restore command from the Control menu for the application window. Restores the Microsoft Excel window to its previous size and location.

Syntax

APP.RESTORE( )

Note This function is only for Microsoft Excel for Windows. You can use this function in macros created with Microsoft Excel for the Macintosh, but it will return the #N/A error value.

Related Functions

APP.ACTIVATE Switches to an application

APP.MAXIMIZE Maximizes the Microsoft Excel application window

APP.MINIMIZE Minimizes the Microsoft Excel application window

APP.MOVE Moves the Microsoft Excel application window

APP.SIZE Changes the size of the Microsoft Excel application window

List of Command-Equivalent Functions


APP.TITLE

Macro Sheets Only

Changes the title of the Microsoft Excel application workspace to the title you specify. The title appears at the top of the application window. Use APP.TITLE to control the application title when you're using Microsoft Excel to create a custom application. This function does not affect Microsoft Excel for the Macintosh.

Syntax

APP.TITLE(text)

Text is the title you want to assign to the Microsoft Excel application workspace. If text is omitted, it is restored to Microsoft Excel.

Remarks

  • The custom application title, followed by the individual workbook title, will appear in the application title bar if the workbook is maximized.
  • APP.TITLE does not affect DDE communications. You will still refer to the application as "Excel".

Related Function

WINDOW.TITLE Changes the title of the active window

List of Customizing Functions


APPLY.STYLE

Macro Sheets Only

Equivalent to choosing the Style command from the Format menu, selecting a style, and choosing the OK button. Applies a previously defined style to the current selection.

Syntax

APPLY.STYLE(style_text)
APPLY.STYLE?(style_text)

Style_text is the name, as text, of a previously defined style. If style_text is not defined, APPLY.STYLE returns the #VALUE! error value and interrupts the macro. If style_text is omitted, the Normal style is applied to the selection.

Related Functions

DEFINE.STYLE Defines a cell style

DELETE.STYLE Deletes a cell style

MERGE.STYLES Imports styles from another workbook into the active workbook

List of Command-Equivalent Functions


ARRANGE.ALL

Macro Sheets Only

Equivalent to choosing the Arrange command from the Window menu. Rearranges open windows and icons and resizes open windows. Also can be used to synchronize scrolling of windows of the active sheet.

Syntax

ARRANGE.ALL(arrange_num, active_doc, sync_horiz, sync_vert)
ARRANGE.ALL?(arrange_num, active_doc, sync_horiz, sync_vert)

Arrange_num is a number from 1 to 7 specifying how to arrange the windows.

Arrange_num Result

1 or omitted Tiled (also used to arrange icons in Microsoft Excel for Windows)

2 Horizontal

3 Vertical

4 None

5 Horizontally arranges and sizes the windows based on the position of the active cell.

6 Vertically arranges and sizes the windows based on the position of the active cell.

7 Arranges windows so that they cascade from the upper left to the bottom right of the application workspace.

If you want to change whether the windows are synchronized for scrolling but not how they are arranged, make sure arrange_num is 4.

Active_doc is a logical value specifying which windows to arrange. If active_doc is TRUE, Microsoft Excel arranges only windows on the active workbook; if FALSE or omitted, all open windows are arranged.

Sync_horiz is a logical value corresponding to the Sync Horizontal check box in Microsoft Excel version 4.0.

  • If sync_horiz is TRUE, Microsoft Excel selects the check box and synchronizes horizontal scrolling.
  • If sync_horiz is FALSE or omitted, Microsoft Excel clears the check box, and windows will not be synchronized when you scroll horizontally.
  • This argument is used only when active_doc is TRUE.

Sync_vert is a logical value corresponding to the Sync Vertical check box in Microsoft Excel version 4.0.

  • If sync_vert is TRUE, Microsoft Excel selects the check box and synchronizes vertical scrolling.
  • If sync_vert is FALSE or omitted, Microsoft Excel clears the check box, and windows will not be synchronized when you scroll vertically.
  • This argument is used only when active_doc is TRUE.

Note If arguments are omitted in the dialog box form of this function, the default values are the previous settings, if any; otherwise the default values are as described above.

Remarks

  • After arranging windows, the top or leftmost window is active.
  • In Microsoft Excel for Windows, if all windows are minimized, ARRANGE.ALL ignores its arguments, if any, and arranges the corresponding icons horizontally along the bottom of the workspace.

Tip You can use synchronized horizontal or vertical scrolling when you need to scroll while viewing macro formulas in one window and corresponding macro values in another window of the same macro sheet.

Related Function

ACTIVATE Switches to a window

List of Command-Equivalent Functions


ASSIGN.TO.OBJECT

Macro Sheets Only

Assigns a macro to the currently select object.

Syntax

ASSIGN.TO.OBJECT(macro_ref)
ASSIGN.TO.OBJECT?(macro_ref)

Macro_ref is the name of, or a reference to, the macro you want to run when the object is clicked. If macro_ref is omitted, Microsoft Excel no longer runs the previously specified macro (ASSIGN.TO.OBJECT is turned off).

Remarks

  • If an object is not selected, ASSIGN.TO.OBJECT returns the #VALUE! error value and interrupts the macro.
  • To change the macro assigned to an object, select the object and use ASSIGN.TO.OBJECT again, using the reference to the new macro as macro_ref. The previous macro is replaced with the new macro.

Related Functions

CREATE.OBJECT Creates an object

RUN Runs a macro

List of Command-Equivalent Functions


ASSIGN.TO.TOOL

Macro Sheets Only

Assigns a macro to be run when a button is clicked with the mouse.

Syntax

ASSIGN.TO.TOOL(bar_id, position, macro_ref)

Bar_id specifies the number or name of a toolbar to which you want to assign a macro. For more information about bar_id, see ADD.TOOL.

Position specifies the position of the button within the toolbar. Position starts with 1 at the left side (if horizontal) or at the top (if vertical).

Macro_ref is the name of, or a reference to, the macro you want to run when the button is clicked. If macro_ref is omitted, Microsoft Excel no longer runs the previously specified macro. After canceling the macro, if the button is a built-in button, Microsoft Excel performs the normal default action when the button is clicked. If the button is a custom button, Microsoft Excel displays the Assign Macro dialog box when the button is clicked.

Related Functions

ADD.TOOL Adds one or more buttons to a toolbar

GET.TOOL Returns information about a button or buttons on a toolbar

List of Command-Equivalent Functions


ATTACH.TEXT

Macro Sheets Only

Equivalent to choosing the Titles command from the Insert menu available when a chart is displayed in the active window. Attaches text to certain parts of the selected chart. Use ATTACH.TEXT to attach text as a title or as a label for an axis or data point.

Syntax

ATTACH.TEXT(attach_to_num, series_num, point_num)
ATTACH.TEXT?(attach_to_num, series_num, point_num)

Attach_to_num specifies which item on a chart to attach text to. Attach_to_num is different for 2-D and 3-D charts. Attach_to_num values for 2-D charts are shown in the following table.

Attach_to_num Attaches text to

1 Chart title

2 Value (y) axis

3 Category (x) axis

4 Series and data point

5 Secondary value (y) axis

6 Secondary category (x) axis

Attach_to_num values for 3-D charts are shown in the following table.

Attach_to_num Attaches text to

1 Chart title

2 Value (z) axis

3 Series (y) axis

4 Category (x) axis

5 Series and data point

Series_num specifies the series number if attach_to_num specifies a series or data point. If attach_to_num specifies a series or data point and series_num is omitted, the macro is interrupted.

Point_num specifies the number of the data point, but only if you specify a series number. Point_num is required if series_num is specified, unless the chart is an area chart.

Remarks

When you record adding an axis title or a chart title, Microsoft Excel records both an ATTACH.TEXT function to attach the text and a FONT.PROPERTIES function to make the text bold.

Example

The following macro functions attach the text "Quarterly Sales" to the X (category) axis of the selected chart:

ATTACH.TEXT(3)
FORMULA("Quarterly Sales")

Related Functions

DATA.LABEL Assigns text labels to point on a chart

FORMULA Enters values into a cell or range or onto a chart

List of Command-Equivalent Functions


AXES

Macro Sheets Only

Equivalent to choosing the Axes command from the Insert menu available when a chart is displayed in the active window. Controls whether the axes on a chart are visible. There are two syntax forms of this function. Syntax 1 is for 2-D charts; syntax 2 is for 3-D charts.

Syntax 1

For 2-D charts

AXES(x_primary, y_primary, x_secondary, y_secondary)
AXES?(x_primary, y_primary, x_secondary, y_secondary)

Syntax 2

For 3-D charts

AXES(x_primary, y_primary, z_primary)
AXES?(x_primary, y_primary, z_primary)

Arguments are logical values corresponding to the check boxes in the Axes dialog box.

  • If an argument is TRUE, Microsoft Excel selects the check box and displays the corresponding axis.
  • If an argument is FALSE, Microsoft Excel clears the check box and hides the corresponding axis.
  • If an argument is omitted, the display of that axis is unchanged.

X_primary corresponds to the primary category (x) axis.

Y_primary corresponds to the primary value (y) axis.

Z_primary corresponds to the value (z) axis on the primary 3-D chart.

X_secondary corresponds to the secondary category (x) axis on a 2-D chart only.

Y_secondary corresponds to the secondary value (y) axis on a 2-D chart only.

If a 2-D chart has no secondary axis, only the first two arguments are used.

Related Function

GRIDLINES Controls whether chart gridlines are visible

List of Command-Equivalent Functions


BRING.TO.FRONT

Macro Sheets Only

Equivalent to choosing the Bring To Front command from the Placement submenu on the Format menu. Puts the selected object or objects on top of all other objects. For example, if some worksheet objects are covering part of an embedded chart, you can select the chart and use BRING.TO.FRONT to display the chart on top of the worksheet objects.

Syntax

BRING.TO.FRONT( )

If the selection is not an object or a group of objects, BRING.TO.FRONT returns the #VALUE! error value.

Related Function

SEND.TO.BACK Sends selected objects behind other objects

List of Command-Equivalent Functions


CALCULATE.NOW

Macro Sheets Only

Equivalent to choosing the Calculation tab from the Options dialog box and then choosing the Calc Now button. Calculates all sheets in all open workbooks. Use CALCULATE.NOW to calculate all open workbooks when calculation is set to manual.

Syntax

CALCULATE.NOW( )

Related Functions

CALCULATE.DOCUMENT Calculates the active sheet only

CALCULATION Controls calculation settings

List of Command-Equivalent Functions


CALCULATION

Macro Sheets Only

Controls when and how formulas in open workbooks are calculated. This function is included for compatibility with Microsoft Excel version 4.0. For controlling calculation in Microsoft Excel version 5.0 or later, see OPTIONS.CALCULATION.

Syntax

CALCULATION(type_num, iter, max_num, max_change, update, precision, date_1904, calc_save, save_values, alt_exp, alt_form)
CALCULATION?(type_num, iter, max_num, max_change, update, precision, date_1904, calc_save, save_values, alt_exp, alt_form)

Arguments correspond to check boxes and options in the Calculation dialog box. Arguments that correspond to check boxes are logical values. If an argument is TRUE, Microsoft Excel selects the check box; if FALSE, Microsoft Excel clears the check box.

Type_num is a number from 1 to 3 indicating the type of calculation.

Type_num Type of calculation

1 Automatic

2 Automatic except tables

3 Manual

Iter corresponds to the Iteration check box. The default is FALSE.

Max_num is the maximum number of iterations. The default is 100.

Max_change is the maximum change of each iteration. The default is 0.001.

Update corresponds to the Update Remote References check box. The default is TRUE.

Precision corresponds to the Precision As Displayed check box. The default is FALSE.

Date_1904 corresponds to the 1904 Date System check box. The default is FALSE in Microsoft Excel for Windows and TRUE in Microsoft Excel for the Macintosh.

Calc_save corresponds to the Recalculate Before Save check box. If calc_save is FALSE, the workbook is not recalculated before saving when in manual calculation mode. The default is TRUE.

Save_values corresponds to the Save External Link Values check box. The default is TRUE.

Alt_exp corresponds to the Transition Formula Evaluation check box in the Transition tab of the Options dialog box.

  • If alt_exp is TRUE, Microsoft Excel uses a set of rules compatible with that of Lotus 1-2-3 when calculating formulas. Text is treated as 0; TRUE and FALSE are treated as 1 and 0; and certain characters in database criteria ranges are interpreted the same way Lotus 1-2-3 interprets them.
  • If alt_exp is FALSE or omitted, Microsoft Excel calculates normally.

Alt_form corresponds to the Transition Formula Entry check box in the Transition tab of the Options dialog box.

  • This argument is available only in Microsoft Excel for Windows.
  • If alt_form is TRUE, Microsoft Excel accepts formulas entered in Lotus 1-2-3 style.
  • If alt_form is FALSE or omitted, Microsoft Excel only accepts formulas entered in Microsoft Excel style.

Note Microsoft Excel for Windows and Microsoft Excel for the Macintosh use different date systems as their default. For more information, see NOW.

Remarks

Use GET.DOCUMENT to return the current calculation settings for your document. For more information, see GET.DOCUMENT.

Related Functions

CALCULATE.DOCUMENT Calculates the active document only

CALCULATE.NOW Calculates all open workbooks immediately

GET.DOCUMENT Returns information about a document

OPTIONS.CALCULATION Controls calculation

OPTIONS.TRANSITION Controls transition options

List of Command-Equivalent Functions


CANCEL.COPY

Macro Sheets Only

Equivalent to pressing ESC in Microsoft Excel for Windows or ESC or COMMAND+PERIOD in Microsoft Excel for the Macintosh to cancel the marquee after you copy or cut a selection.

Syntax

CANCEL.COPY(render_logical)

Render_logical is a logical value that, if TRUE, places the contents of the Excel Clipboard on the Clipboard or, if FALSE or omitted, does not place them on the Clipboard. Render_logical is available only in Microsoft Excel for the Macintosh.

Related Functions

List of Command-Equivalent Functions


CHANGE.LINK

Macro Sheets Only

Equivalent to choosing the Change Source button in the Links dialog box, which appears when you choose the Links command from the Edit menu. Changes a link from one supporting workbook to another.

Syntax

CHANGE.LINK(old_text, new_text, type_of_link)
CHANGE.LINK?(old_text, new_text, type_of_link)

Old_text is the path of the link from the active dependent workbook you want to change.

New_text is the path of the link you want to change to.

Type_of_link is the number 1 or 2 specifying what type of link you want to change.

Type_of_link Link document type

1 or omitted Microsoft Excel link

2 DDE/OLE link

Remarks

The workbook whose links you want to change must be active when this function is calculated.

Related Functions

GET.LINK.INFO Returns information about a link

LINKS Returns the name of all linked documents

OPEN.LINKS Opens specified supporting workbooks

SET.UPDATE.STATUS Controls the update status of a link

UPDATE.LINK Updates a link to another workbook

List of Command-Equivalent Functions


CHART.WIZARD

Macro Sheets Only

Equivalent to choosing the ChartWizard button on the standard or chart toolbar. Creates a chart. It is generally easier to use the macro recorder to enter this function on your macro sheet.

Syntax

CHART.WIZARD(long, ref, gallery_num, type_num, plot_by, categories, ser_titles, legend, title, x_title, y_title, z_title, number_cats, number_titles)
CHART.WIZARD?(long, ref, gallery_num, type_num, plot_by, categories, ser_titles, legend, title, x_title, y_title, z_title, number_cats, number_titles)

Long is a logical value that determines which type of ChartWizard button CHART.WIZARD is equivalent to.

  • If long is TRUE, CHART.WIZARD is equivalent to using the five-step ChartWizard button.
  • If long is FALSE or omitted, CHART.WIZARD is equivalent to using the two-step ChartWizard button, and gallery_num, type_num, legend, and the title arguments are ignored.

Ref is a reference to the range of cells on the active worksheet that contains the source data for the chart, or the object identifier of the chart if it has already been created.

Gallery_num is a number from 1 to 15 specifying the type of chart you want to create.

Gallery_num Chart

1 Area

2 Bar

3 Column

4 Line

5 Pie

6 Radar

7 XY (scatter)

8 Combination

9 3-D area

10 3-D bar

11 3-D column

12 3-D line

13 3-D pie

14 3-D surface

15 Doughnut

Type_num is a number identifying a formatting option. The formatting options are shown in the dialog box of the AutoFormat command. The first formatting option in any gallery is 1.

Plot_by is the number 1 or 2 and specifies whether the data for each data series is in rows or columns. 1 specifies rows; 2 specifies columns. If plot_by is omitted, Microsoft Excel uses the appropriate value for the chart you're creating.

Categories is the number 1 or 2 and specifies whether the first row or column contains a list of x-axis labels, or data for the first data series. 1 specifies x-axis labels; 2 specifies the first data series. If categories is omitted, Microsoft Excel uses the appropriate value for the chart you're creating. If number_cats is specified, this argument is ignored.

Ser_titles is the number 1 or 2 and specifies whether the first column or row contains series titles, or data for the first data point in each series. 1 specifies series titles; 2 specifies the first data point. If ser_titles is omitted, Microsoft Excel uses the appropriate value for the chart you're creating. If number_titles is specified, this argument is ignored.

Legend is the number 1 or 2 and specifies whether to include a legend. 1 specifies a legend; 2 specifies no legend. If legend is omitted, Microsoft Excel does not include a legend.

For the following arguments, if an argument is omitted or is empty text (""), no title is specified.

Title is text that you want to use as a chart title.

X_title is text that you want to use as an x-axis title.

Y_title is text that you want to use as a y-axis title.

Z_title is text that you want to use as a z-axis title.

Number_cats specifies the number of rows or columns (depending on the value of plot_by) to use for the category labels in the chart. This argument overrides the categories argument.

Number_titles specifies the number of rows or columns (depending on the value of plot_by) to use for the series labels in the chart. This argument overrides the ser_title argument.

Remarks

If you are using the macro recorder, Microsoft Excel records a CREATE.OBJECT and a COPY function when the chart is created and a CHART.WIZARD function when the chart is formatted.

Related Functions

CREATE.OBJECT Creates an object

List of Command-Equivalent Functions


CLEAR

Macro Sheets Only

Equivalent to choosing the Clear command from the Edit menu. Clears contents, formats, notes, or all of these from the active worksheet or macro sheet. Clears series or formats from the active chart.

Syntax

CLEAR(type_num)
CLEAR?(type_num)

Type_num is a number from 1 to 4 specifying what to clear. Only values 1, 2, and 3 are valid if the selected item is a chart.

On a worksheet or macro sheet, or if an entire chart is selected, the following occurs.

Type_num Clears

1 All

2 Formats (if a chart, clears the chart format or clears pictures)

3 Contents (if a chart, clears all data series)

4 Notes (including sound notes; this does not apply to charts)

On a chart, if a single point, an entire data series, error bars, or a trend line is selected, the following occurs.

Type_num Clears

1 Selected series, error bars, or trend line

2 Format in the selected point, series, error bars, or trend line

If type_num is omitted, the default values are set as shown in the following table.

Active sheet Type_num

Worksheet 3

Macro sheet 3

Chart (with no selection) 1

Chart (with item selected) Deletes the selected item

Related Function

EDIT.DELETE Removes cells from a sheet

List of Command-Equivalent Functions


CLOSE

Macro Sheets Only

Closes the active window. In Microsoft Excel for Windows, CLOSE is equivalent to choosing the Close command from the Document Control menu. In Microsoft Excel for the Macintosh, CLOSE is equivalent to clicking the close box.

Syntax

CLOSE(save_logical, route_logical)

Save_logical is a logical value that specifies whether to save the file before closing the window.

Save_logical Result

TRUE Saves the file

FALSE Does not save the file

Omitted If you've made changes to the file, displays a dialog box asking if you want to save the file

Route_logical is a logical value that specifies whether to route the file after closing it. This argument is ignored if there is not a routing slip present.

Route_logical Result

TRUE Routes the file

FALSE Does not route the file

Omitted If you've specified recipients for routing, displays a dialog box asking if you want to save the file

Remarks

  • Users of Microsoft Excel versions earlier than 4.0 should note that if the macro sheet containing the function is the active sheet, CLOSE now closes the workbook.

Note When you use the CLOSE function, Microsoft Excel does not run any Auto_Close macros before closing the workbook.

Related Functions

CLOSE.ALL Closes all windows

FILE.CLOSE Closes the active workbook

SAVE Saves the active workbook

List of Command-Equivalent Functions


COLOR.PALETTE

Macro Sheets Only

Copies a color palette from an open workbook to the active workbook. Use COLOR.PALETTE to share color palettes between workbooks.

Syntax

COLOR.PALETTE(file_text)
COLOR.PALETTE?(file_text)

File_text is the name of a workbook, as a text string, that you want to copy a color palette from. The workbook specified by file_text must be open, or COLOR.PALETTE returns the #VALUE! error value and interrupts the macro. If file_text is empty text (""), then COLOR.PALETTE sets colors to the default values.

Related Function

EDIT.COLOR Defines a color on the color palette

List of Command-Equivalent Functions


CONSOLIDATE

Macro Sheets Only

Equivalent to choosing the Consolidate command from the Data menu. Consolidates data from multiple ranges on multiple worksheets into a single range on a single worksheet.

Syntax

CONSOLIDATE(source_refs, function_num, top_row, left_col, create_links)
CONSOLIDATE?(source_refs, function_num, top_row, left_col, create_links)

Source_refs are references to areas that contain data to be consolidated on the destination worksheet. Source_refs must be in text form and include the full path of the file and the cell reference or named ranges in the workbook to be consolidated. Source_refs are usually external references and must be given as an array, for example: {"SHEET1!IncomeOne", "SHEET2!IncomeTwo"}.

To add or delete source_refs from an existing consolidation on a worksheet, reuse the CONSOLIDATE function, specifying the new source_refs.

Function_num is a number from 1 to 11 that specifies one of the 11 functions you can use to consolidate data. If function_num is omitted, the SUM function, number 9, is used. The functions and their corresponding numbers are listed in the following table.

Function_num Function

1 AVERAGE

2 COUNT

3 COUNTA

4 MAX

5 MIN

6 PRODUCT

7 STDEV

8 STDEVP

9 SUM

10 VAR

11 VARP

The following arguments correspond to text boxes and check boxes in the Consolidate dialog box. Arguments that correspond to check boxes are logical values. If an argument is TRUE, Microsoft Excel selects the check box; if FALSE, Microsoft Excel clears the check box.

Top_row corresponds to the Top Row check box. The default is FALSE.

Left_col corresponds to the Left Column check box. The default is FALSE.

If top_row and left_col are both FALSE or omitted, the data is consolidated by position.

Create_links corresponds to the Create Links To Source Data check box.

Remarks

  • If you use the CONSOLIDATE function with no arguments and there is a consolidation on the active worksheet, Microsoft Excel reconsolidates, using the sources, function, and position attributes used to create the existing consolidation.
  • If you use the CONSOLIDATE function with no arguments and there is no consolidation on the active worksheet, the function returns the #VALUE! error value.

Related Functions

CHANGE.LINK Changes supporting workbook links

LINKS Returns the names of all linked workbooks

OPEN.LINKS Opens specified supporting workbooks

UPDATE.LINK Updates a link to another workbook

List of Command-Equivalent Functions


COPY.TOOL

Macro Sheets Only

Equivalent to selecting a button and choosing the Copy Button Image command from the Edit menu. Copies a button face to the Clipboard.

Syntax

COPY.TOOL(bar_id, position)

Bar_id specifies the number or name of a toolbar from which you want to copy the button face. For detailed information about bar_id, see ADD.TOOL.

Position specifies the position of the button within the toolbar. Position starts with 1 at the left side (if horizontal) or at the top (if vertical).

Related Functions

ADD.TOOL Adds one or more buttons to a toolbar

GET.TOOL Returns information about a button or buttons on a toolbar

PASTE.TOOL Pastes a button face from the Clipboard to a specified position on a toolbar

List of Command-Equivalent Functions


DELETE.BAR

Macro Sheets Only

Deletes a custom menu bar.

Syntax

DELETE.BAR(bar_num)

Bar_num is the ID number of the custom menu bar you want to delete.

Tip Rather than trying to discover the ID number of the menu bar you want to delete, use a reference to the ADD.BAR function that created the bar. For example, the following macro formula deletes the menu bar created by the ADD.BAR function in the cell named ReportsBar:

DELETE.BAR(ReportsBar)

Related Functions

ADD.BAR Adds a menu bar

SHOW.BAR Displays a menu bar

List of Customizing Functions


DELETE.COMMAND

Macro Sheets Only

Deletes a command from a custom or built-in menu. Use DELETE.COMMAND to remove commands you don't want the user to have access to or to remove custom commands that you have added.

Syntax

DELETE.COMMAND(bar_num, menu, command, subcommand)

Bar_num is the menu bar from which you want to delete the command. Bar_num can be the ID number of a built-in or custom menu bar. See ADD.COMMAND for a list of ID numbers for built-in menu bars and shortcut menus.

Menu is the menu from which you want to delete the command. Menu can be the name of a menu as text or the number of a menu. Menus are numbered starting with 1 from the left of the screen.

Command is the command you want to delete, or the name of a submenu. Command can be the name of the command as text or the number of the command; the first command on a menu is in position 1.

Subcommand is the command you want to delete from a submenu. If you use subcommand, you must use command as the name of the submenu.

Remarks

  • If the specified command does not exist, DELETE.COMMAND returns the #VALUE! error value and interrupts the macro.
  • After a command is deleted, the command number for all commands below that command is decreased by one.
  • When you delete a built-in command, DELETE.COMMAND returns a unique ID number for that command. You can use this ID number with ADD.COMMAND to restore the built-in command to the original menu.

Example

The following macro formula removes the Compile Reports command from the Reports menu on a custom menu bar created by the ADD.BAR function in a cell named Financials.

DELETE.COMMAND(Financials, "Reports", "Compile Reports...")

Related Functions

ADD.COMMAND Adds a command to a menu

CHECK.COMMAND Adds or deletes a check mark to or from a command

ENABLE.COMMAND Enables or disables a menu or custom command

RENAME.COMMAND Changes the name of a command or menu

List of Customizing Functions


DELETE.FORMAT

Macro Sheets Only

Equivalent to deleting the specified format in the Number tab in the Format Cells dialog box, which appears when you choose the Cells command from the Format menu, or in the Number tab for selected chart objects. Deletes a specified built-in or custom number format.

Syntax

DELETE.FORMAT(format_text)

Format_text is the format given as a text string, for example, "000-00-0000".

Remarks

When you delete a custom number format, all numbers formatted with that number format are formatted with the General format.

Related Functions

FORMAT.NUMBER Applies a number format to the selection

GET.CELL Returns information about the specified cell

List of Command-Equivalent Functions


DELETE.MENU

Macro Sheets Only

Deletes a menu or submenu. Use DELETE.MENU to delete menus you have added to menu bars when the supporting macro sheet is closed (using an Auto_Close macro), or any time you want to remove a menu.

Syntax

DELETE.MENU(bar_num, menu, submenu)

Bar_num is the menu bar from which you want to delete the menu. Bar_num can be the number of a Microsoft Excel built-in menu bar or the number returned by a previously run ADD.BAR function. For a list of ID numbers for built-in menu bars, see ADD.COMMAND.

Menu is the menu you want to delete. Menu can be either the name of a menu as text or the number of a menu. Menus are numbered starting with 1 from the left of the screen. If the specified menu does not exist, DELETE.MENU returns the #VALUE! error value and interrupts the macro. After a menu is deleted, the menu number for each menu to the right of that menu is decreased by 1.

Submenu is the name of the submenu you want to delete or the number of the menu in the list of commands.

Remarks

You cannot delete a shortcut menu. Instead, use ENABLE.COMMAND to prevent the user from accessing a shortcut menu.

Example

The following macro formula deletes the Reports menu from the custom menu bar created by the ADD.BAR function in a cell named Financials:

DELETE.MENU(Financials, "Reports")

Related Functions

ADD.MENU Adds a menu to a menu bar

DELETE.BAR Deletes a menu bar

DELETE.COMMAND Deletes a command from a menu

ENABLE.COMMAND Enables or disables a menu or custom command

List of Customizing Functions


DELETE.TOOL

Macro Sheets Only

Equivalent to selecting a button and dragging it to an area other than a toolbar. Deletes a button from a toolbar.

Syntax

DELETE.TOOL(bar_id, position)

Bar_id specifies the name or number of a toolbar from which you want to delete a button. For detailed information about bar_id, see ADD.TOOL.

Position specifies the position of the button within the toolbar. Position starts with 1 at the left side (if horizontal) or at the top (if vertical).

Related Functions

ADD.TOOL Adds one or more buttons to a toolbar

ADD.TOOLBAR Creates a new toolbar with the specified buttons

DELETE.TOOLBAR Deletes custom toolbars

List of Command-Equivalent Functions


DELETE.TOOLBAR

Macro Sheets Only

Equivalent to choosing the Delete button from the Toolbars dialog box, which appears when you choose the Toolbars command from the View menu. Deletes a custom toolbar.

Syntax

DELETE.TOOLBAR(bar_name)

Bar_name specifies the name of the toolbar that you want to delete. For detailed information about bar_name, see ADD.TOOL.

Remarks

  • You cannot delete built-in toolbars.
  • If DELETE.TOOLBAR successfully deletes the toolbar, it returns TRUE. If you try to delete a built-in toolbar, DELETE.TOOLBAR returns the #VALUE! error value, interrupts the macro, and takes no other action.

Related Functions

ADD.TOOL Adds or more buttons to a toolbar

ADD.TOOLBAR Creates a new toolbar with the specified buttons

RESET.TOOLBAR Resets a built-in toolbar to its initial default setting

List of Command-Equivalent Functions


DISPLAY

Macro Sheets Only

Controls whether the screen displays formulas, gridlines, row and column headings, and other screen attributes. There are two syntax forms of this function. Use syntax 1 to control screen display. Use syntax 2 to control the display of the Info window.

Syntax 1 Controls screen display

Syntax 2 Controls display of Info window


DISPLAY Syntax 1

Macro Sheets Only

Controls whether the screen displays formulas, gridlines, row and column headings, and other screen attributes. There are two syntax forms of this function. Use syntax 1 to control screen display. This function is provided for compatibility with Microsoft Excel version 4.0. To control screen display in Microsoft Excel version 5.0 or later, see OPTIONS.VIEW.

Arguments for this syntax form correspond to options and check boxes in the Display Options dialog box in Microsoft Excel version 4.0. Arguments that correspond to check boxes are logical values. If an argument is TRUE, Microsoft Excel selects the check box; if FALSE, Microsoft Excel clears the check box. If an argument is omitted, no action is taken.

Syntax

DISPLAY(formulas, gridlines, headings, zeros, color_num, reserved, outline, page_breaks, object_num)
DISPLAY?(formulas, gridlines, headings, zeros, color_num, reserved, outline, page_breaks, object_num)

Formulas corresponds to the Formulas check box. The default is FALSE on worksheets and TRUE on macro sheets.

Gridlines corresponds to the Gridlines check box. The default is TRUE.

Headings corresponds to the Row & Column Headings check box. The default is TRUE.

Zeros corresponds to the Zero Values check box. The default is TRUE.

Color_num is a number from 0 to 56 corresponding to the gridline and heading colors in the Display Options dialog box; 0 corresponds to automatic color and is the default value.

Reserved is reserved for certain international versions of Microsoft Excel.

Outline corresponds to the Outline Symbols check box. The default is TRUE.

Page_breaks corresponds to the Automatic Page Breaks check box. The default is FALSE.

Object_num is a number from 1 to 3 corresponding to the display options in the Object box.

Object_num Corresponds to

1 or omitted Show All

2 Show Placeholders

3 Hide

Related Functions

OPTIONS.VIEW Controls display

WORKSPACE Changes workspace settings

ZOOM Enlarges or reduces a sheet in the active window

Syntax 2 Controls display of Info window

List of Command-Equivalent Functions


DISPLAY Syntax 2

Macro Sheets Only

Equivalent to choosing the commands from the Info menu when the Info Window is active. Controls which commands on the Info window are in effect. There are two syntax forms of this function. Use syntax 2 to control the display of the Info window. The Info window must be active to use this form of DISPLAY.

Arguments in this syntax form correspond to commands on the Info menu with the same names.

For these arguments:

  • If the argument is TRUE, Microsoft Excel displays the corresponding Info item.
  • If the argument is FALSE, Microsoft Excel does not display the corresponding Info item.
  • If the argument is omitted, the status of the item is unchanged.

Syntax

For controlling Info window display

DISPLAY(cell, formula, value, format, protection, names, precedents, dependents, note)

Cell is a logical value that corresponds to the Cell command and controls the display of cell information in the Info Window. If TRUE, cell information will be displayed; if FALSE, cell information will not be displayed.

Formula is a logical value that corresponds to the Formula command and controls the display of formula information in the Info Window. If TRUE, formula information will be displayed; if FALSE, formula information will not be displayed.

Value is a logical value that corresponds to the Value command and controls the display of value information in the Info Window. If TRUE, value information will be displayed; if FALSE, value information will not be displayed.

Format is a logical value that corresponds to the Format command and controls the display of format information in the Info Window. If TRUE, format information will be displayed; if FALSE, format information will not be displayed.

Protection is a logical value that corresponds to the Protection command and controls the display of protection information in the Info Window. If TRUE, protection information will be displayed; if FALSE, protection information will not be displayed.

Names is a logical value that corresponds to the Names command and controls the display of name information in the Info Window. If TRUE, name information will be displayed; if FALSE, name information will not be displayed.

Precedents is a number from 1 to 3 that specifies which precedents to list, according to the following table.

Dependents is a number from 1 to 3 that specifies which dependents to list, according to the following table.

Precedents or dependents List

0 None

1 Direct only

2 All levels

Note is a logical value that corresponds to the Note command and controls the display of note information in the Info Window. If TRUE, note information will be displayed; if FALSE, note information will not be displayed.

Related Functions

SHOW.INFO Controls the display of the Info window

ZOOM Enlarges or reduces a sheet in the active window

Syntax 1 Controls screen display

List of Command-Equivalent Functions


EDIT.DELETE

Macro Sheets Only

Equivalent to choosing the Delete command from the Edit menu. Removes the selected cells from the worksheet and shifts other cells to close up the space.

Syntax

EDIT.DELETE(shift_num)
EDIT.DELETE?(shift_num)

Shift_num is a number from 1 to 4 specifying whether to shift cells left or up after deleting the current selection or else to delete the entire row or column.

Shift_num Result

1 Shifts cells left

2 Shifts cells up

3 Deletes entire row

4 Deletes entire column

  • If shift_num is omitted and if one cell or a horizontal range is selected, EDIT.DELETE shifts cells up.
  • If shift_num is omitted and a vertical range is selected, EDIT.DELETE shifts cells left.

Related Function

CLEAR Clears specified information from the selected cells or chart

List of Command-Equivalent Functions


ELSE

Macro Sheets Only

Used with IF, ELSE.IF, and END.IF to control which functions are carried out in a macro. ELSE signals the beginning of a group of formulas in a macro sheet that will be carried out if the results of all preceding ELSE.IF statements and the preceding IF statement are FALSE. Use ELSE with IF, ELSE.IF, and END.IF when you want to perform multiple actions based on a condition. This method is preferable to using GOTO because it makes your macros more structured.

Syntax

ELSE( )

Remarks

ELSE must be entered in a cell by itself. In other words, the cell can contain only "=ELSE()".

For more information about ELSE, ELSE.IF, END.IF, and IF, and for examples of these functions, see form 2 of the IF function.

Related Functions

ELSE.IF Specifies an action to take if an IF or another ELSE.IF function returns FALSE

END.IF Ends a group of macro functions started with an IF statement

IF Specifies an action to take if a logical test is TRUE

List of Control Functions


ELSE.IF

Macro Sheets Only

Used with IF, ELSE, and END.IF to control which functions are carried out in a macro. ELSE.IF signals the beginning of a group of formulas in a macro sheet that will be carried out if the preceding IF or ELSE.IF function returns FALSE and if logical_test is TRUE. Use ELSE.IF with IF, ELSE, and END.IF when you want to perform multiple actions based on a condition. This method is preferable to using GOTO because it makes your macros more structured.

Syntax

ELSE.IF(logical_test)

Logical_test is a logical value that ELSE.IF uses to determine what functions to carry out next—that is, where to branch.

  • If logical_test is TRUE, Microsoft Excel carries out the functions between the ELSE.IF function and the next ELSE.IF, ELSE, or END.IF function.
  • If logical_test is FALSE, Microsoft Excel immediately branches to the next ELSE.IF, ELSE, or END.IF function.

Remarks

  • ELSE.IF must be entered in a cell by itself.
  • Logical_test will always be evaluated, even if the ELSE.IF section is not reached (due to a previous IF or ELSE.IF logical_test evaluating to TRUE). For this reason, you should not use formulas that carry out actions for logical_test. If you need to base the ELSE.IF condition on the return value of a formula that carries out an action, use the form "ELSE, IF(logical_test), and END.IF" in place of "ELSE.IF(logical_test)."

For more information about ELSE, ELSE.IF, END.IF, and IF, and for examples of these functions, see form 2 of the IF function.

Related Functions

ELSE Specifies an action to take if an IF function returns FALSE

END.IF Ends a group of macro functions started with an IF statement

IF Specifies an action to take if a logical test is TRUE

List of Control Functions


ENABLE.COMMAND

Macro Sheets Only

Enables or disables a custom command or menu. Disabled commands appear dimmed and can't be chosen. Use ENABLE.COMMAND to control which commands the user can choose in a menu bar.

Syntax

ENABLE.COMMAND(bar_num, menu, command, enable, subcommand)

Bar_num is the menu bar in which a command resides. Bar_num can be the number of a built-in menu bar or the number returned by a previously run ADD.BAR function. See ADD.COMMAND for a list of the built-in menu bar numbers.

Menu is the menu on which the command resides. Menu can be either the name of a menu as text or the number of a menu. Menus are numbered starting with 1 from the left of the screen.

Command is the command you want to enable or disable. Command can be either the name of the command as text or the number of the command. The top command on a menu is command 1. If command is 0, ENABLE.COMMAND enables or disables the entire menu.

Enable is a logical value specifying whether the command should be enabled or disabled. If enable is TRUE, Microsoft Excel enables the command; if FALSE, it disables the command.

Subcommand is the name of the command on a submenu that you want to enable. If you use subcommand, you must use command as the name of the submenu. Use subcommand 0 to enable an entire submenu.

Remarks

  • You cannot disable built-in commands. If the specified command is a built-in command or does not exist, ENABLE.COMMAND returns the #VALUE! error value and interrupts the macro.
  • You can hide any shortcut menu from users by using ENABLE.COMMAND with command set to 0.

Example

The following macro formula disables a custom command that had been added previously to the View menu on the worksheet and macro sheet menu bar:

ENABLE.COMMAND(10, "View", "Audit...", FALSE)

Related Functions

ADD.COMMAND Adds a command to a menu

CHECK.COMMAND Adds or deletes a check mark to or from a command

DELETE.COMMAND Deletes a command from a menu

RENAME.COMMAND Changes the name of a command or menu

List of Customizing Functions


ENABLE.TOOL

Macro Sheets Only

Enables or disables a button on a toolbar. An enabled button can be accessed by the user. Disabled buttons may still be visible but cannot be accessed. Use ENABLE.TOOL to control which buttons the user can choose in a particular situation.

Syntax

ENABLE.TOOL(bar_id, position, enable)

Bar_id is the number or name of a toolbar on which the button resides. For detailed information about bar_id, see ADD.TOOL.

Position specifies the position of the button on the toolbar. Position starts with 1 at the left side (if horizontal) or from the top (if vertical).

Enable specifies whether the button can be accessed. If enable is TRUE or omitted, the user can access the button; if FALSE, the user cannot access it.

Remarks

Microsoft Excel sounds a tone if you click a disabled button.

Example

The following macro formula enables the fourth button in Toolbar1:

ENABLE.TOOL("Toolbar1", 4, TRUE)

Related Function

GET.TOOL Returns information about a button or buttons on a toolbar

List of Customizing Functions


END.IF

Macro Sheets Only

Ends a block of functions associated with the preceding IF function. You must include one and only one END.IF function for each macro-sheets-only syntax form (syntax 2) of the IF function in a macro. Syntax 1 of the IF function, which can be used on both worksheets and macro sheets, does not require an END.IF function. Use END.IF with IF, ELSE, and ELSE.IF when you want to perform multiple actions based on a condition. This method is preferable to using GOTO because it makes your macros more structured.

Syntax

END.IF( )

Remarks

  • If you accidentally omit an END.IF function, your macro will end with an error at the cell containing the first IF function that does not have a corresponding END.IF function.
  • END.IF must be entered in a cell by itself.
  • For more information about ELSE, ELSE.IF, END.IF, and IF, and for examples of these functions, see form 2 of the IF function.

Related Functions

ELSE Specifies an action to take if an IF function returns FALSE

ELSE.IF Specifies an action to take if an IF or another ELSE.IF function returns FALSE

IF Specifies an action to take if a logical test is TRUE

List of Control Functions


EXTEND.POLYGON

Macro Sheets Only

Adds vertices to a polygon. This function must immediately follow a CREATE.OBJECT function or another EXTEND.POLYGON function. Use multiple EXTEND.POLYGON functions to create arbitrarily complex polygons. It is generally easier to use the macro recorder to enter this function on your macro sheet.

Syntax

EXTEND.POLYGON(array)

Array is an array of values, or a reference to a range of cells containing values, that indicate the position of vertices in the polygon. The position is measured in points and is relative to the upper-left corner of the polygon's bounding rectangle.

  • A vertex is a point. Each vertex is defined by a pair of coordinates in one row of array.
  • The polygon is defined by the array argument to the CREATE.OBJECT function and to all the immediately following EXTEND.POLYGON functions.
  • If the polygon contains many vertices, one array may not be sufficient to define it. If the number of elements in the formula exceeds 1024, you must include additional EXTEND.POLYGON functions. If you're recording a macro, Microsoft Excel automatically records additional EXTEND.POLYGON functions as needed.

Related Functions

CREATE.OBJECT Creates an object

FORMAT.SHAPE Inserts, moves, or deletes vertices of the selected polygon

List of Command-Equivalent Functions


FILL.AUTO

Macro Sheets Only

Equivalent to copying cells or automatically filling a selection by dragging the fill selection handle with the mouse (the AutoFill feature).

Syntax

FILL.AUTO(destination_ref, copy_only)

Destination_ref is the range of cells into which you want to fill data. The top, bottom, left, or right end of destination_ref must include all of the cells in the source reference (the current selection).

Copy_only is a number specifying whether to copy cells or perform an AutoFill operation.

Value Result

0 or omitted Normal AutoFill

1 or TRUE Copy cells

2 Copy formats

3 Fill values

4 Increment

5 Increment by day

6 Increment by weekday

7 Increment by month

8 Increment by year

9 Linear trend

10 Growth trend

Related Functions

COPY Copies and pastes data or objects

DATA.SERIES Fills a range of cells with a series of numbers or dates

List of Command-Equivalent Functions


FILE.CLOSE

Macro Sheets Only

Equivalent to choosing the Close command from the File menu. Closes the active workbook.

Syntax

FILE.CLOSE(save_logical, route_logical)

Save_logical is a logical value specifying whether to save the file before closing it.

Save_logical Result

TRUE Saves the workbook

FALSE Does not save the workbook

Omitted If you've made changes to the workbook, displays a dialog box asking if you want to save the workbook

Route_logical is a logical value that specifies whether to route the file after closing it. This argument is ignored if there is not a routing slip present.

Route_logical Result

TRUE Routes the file

FALSE Does not route the file

Omitted If you've specified recipients for routing, displays a dialog box asking if you want to save the file

Remarks

If you make any changes to the structure of a workbook, such as the name of sheets, their order, and so on, then a message will be displayed reminding you that there are unsaved changes, regardless of the save_logical value.

Note When you use the FILE.CLOSE function, Microsoft Excel does not run any Auto_Close macros before closing the workbook.

Related Functions

CLOSE Closes the active window

CLOSE.ALL Closes all unprotected windows

FCLOSE Closes a text file

List of Command-Equivalent Functions


FORMAT.AUTO

Macro Sheets Only

Equivalent to choosing the AutoFormat command from the Format menu when a worksheet is active or clicking the AutoFormat button. Formats the selected range of cells from a built-in gallery of formats.

Syntax

FORMAT.AUTO(format_num, number, font, alignment, border, pattern, width)
FORMAT.AUTO?(format_num, number, font, alignment, border, pattern, width)

Format_num is a number from 1 to 17 corresponding to the formats in the Table Format list box in the AutoFormat dialog box.

Format_num Table Format

0 None

1 or omitted Classic 1

2 Classic 2

3 Classic 3

4 Accounting 1

5 Accounting 2

6 Accounting 3

7 Colorful 1

8 Colorful 2

9 Colorful 3

10 List 1

11 List 2

12 List 3

13 3D Effects 1

14 3D Effects 2

15 Japan 1 (Far East versions of Microsoft Excel only)

16 Japan 2 (Far East versions of Microsoft Excel only)

17 Accounting 4

18 Simple

The following arguments are logical values corresponding to the Formats To Apply check boxes in the AutoFormat dialog box. If an argument is TRUE or omitted, Microsoft Excel selects the check box; if FALSE, Microsoft Excel clears the check box.

Number corresponds to the Number check box.

Font corresponds to the Font check box.

Alignment corresponds to the Alignment check box.

Border corresponds to the Border check box.

Pattern corresponds to the Pattern check box.

Width corresponds to the Column Width/Row Height check box.

Related Functions

ALIGNMENT Aligns or wraps text in cells

BORDER Adds a border to the selected cell or object

FONT.PROPERTIES Applies a font to the selection

FORMAT.NUMBER Applies a number format to the selection

PATTERNS Changes the appearance of the selected object

List of Command-Equivalent Functions


FORMAT.MOVE

Macro Sheets Only

Equivalent to moving an object with the mouse. Moves the selected object to the specified position and, if successful, returns TRUE. If the selected object cannot be moved, FORMAT.MOVE returns FALSE. There are three syntax forms of this function. Use syntax 1 to move worksheet objects. Use syntax 2 to move chart items. Use syntax 3 to move pie-chart and doughnut-chart items. It is generally easier to use the macro recorder to enter this function on your macro sheet.

Syntax 1 Moves worksheet items

Syntax 2 Moves chart items

Syntax 3 Moves pie-chart and doughnut-chart items


FORMAT.MOVE Syntax 1

Macro Sheets Only

Equivalent to moving an object with the mouse. Moves the selected object to the specified position and, if successful, returns TRUE. If the selected object cannot be moved, FORMAT.MOVE returns FALSE. There are three syntax forms of this function. Use syntax 1 to move worksheet objects. Use syntax 2 to move chart items. Use syntax 3 to move pie-chart and doughnut-chart items. It is generally easier to use the macro recorder to enter this function on your macro sheet.

Syntax

FORMAT.MOVE(x_offset, y_offset, reference)
FORMAT.MOVE?(x_offset, y_offset, reference)

X_offset specifies the horizontal position to which you want to move the object and is measured in points from the upper-left corner of the object to the upper-left corner of the cell specified by reference. A point is 1/72nd of an inch.

Y_offset specifies the vertical position to which you want to move the object and is measured in points from the upper-left corner of the object to the upper-left corner of the cell specified by reference.

Reference specifies which cell or range of cells to place the object in relation to.

  • If reference is a range of cells, only the upper-left cell is used.
  • If reference is omitted, it is assumed to be cell A1.

Remarks

The position of an object is based on its upper-left corner. For ovals and arcs, the position is based on the upper-left corner of the bounding rectangle of the object.

Example

The following macro formula moves an object on the active worksheet so that it is 10 points horizontally offset and 15 points vertically offset from cell D4:

FORMAT.MOVE(10, 15, !$D$4)

Related Functions

CREATE.OBJECT Creates an object

FORMAT.SIZE Sizes an object

WINDOW.MOVE Moves a window

Syntax 2 Moves chart items

Syntax 3 Moves pie-chart and doughnut-chart items

List of Command-Equivalent Functions


FORMAT.MOVE Syntax 2

Macro Sheets Only

Equivalent to moving an object with the mouse. Moves the base of the selected object to the specified position and, if successful, returns TRUE. If the selected object cannot be moved, FORMAT.MOVE returns FALSE. There are three syntax forms of this function. Use syntax 3 to move pie-chart and doughnut-chart items. Use syntax 1 to move worksheet objects. It is generally easier to use the macro recorder to enter this function on your macro sheet.

Syntax

FORMAT.MOVE(x_pos, y_pos)
FORMAT.MOVE?(x_pos, y_pos)

X_pos specifies the horizontal position to which you want to move the object and is measured in points from the base of the object to the lower-left corner of the window. A point is 1/72nd of an inch.

Y_pos specifies the vertical position to which you want to move the object and is measured in points from the base of the object to the lower-left corner of the window.

Remarks

  • The base of a text label on a chart is the lower-left corner of the text rectangle.
  • The base of an arrow is the end without the arrowhead.
  • The base of a pie slice is the point.

Example

On a chart, the following macro formula moves the base of the selected chart object 10 points to the right of and 20 points above the lower-left corner of the window:

FORMAT.MOVE(10, 20)

Related Functions

FORMAT.SIZE Sizes an object

WINDOW.MOVE Moves a window

Syntax 1 Moves worksheet items

Syntax 3 Moves pie-chart and doughnut-chart items

List of Command-Equivalent Functions


FORMAT.MOVE Syntax 3

Macro Sheets only

Equivalent to exploding by moving a pie-chart or doughnut-chart slice with the mouse. Sets the percentage of pie-chart or doughnut-chart slice explosion, and, if successful, returns TRUE. If the selected object cannot be exploded, returns FALSE. There are three syntax forms of this function. Use syntax 1 to move worksheet items. Use syntax 2 to move chart items. It is generally easier to use the macro recorder to enter this function on your macro sheet.

Syntax

FORMAT.MOVE(explosion_num)

Explosion_num is a number specifying the explosion percentage for the selected pie slice or the entire chart (if the series is selected). Zero is no explosion (the tip of the slice is in the center of the pie).

Related Functions

FORMAT.SIZE Sizes an object

Syntax 1 Moves worksheet items

Syntax 2 Moves chart items

WINDOW.MOVE Moves a window

List of Command-Equivalent Functions


FORMAT.SHAPE

Macro Sheets Only

Equivalent to clicking the reshape button on the Drawing toolbar and then inserting, moving, or deleting vertices of the selected polygon. A vertex is a point defined by a pair of coordinates in one row of the array that defines the polygon. The array is created by CREATE.OBJECT and EXTEND.POLYGON functions.

Syntax

FORMAT.SHAPE(vertex_num, insert, reference, x_offset, y_offset)

Vertex_num is a number corresponding to the vertex you want to insert, move, or delete.

Insert is a logical value specifying whether to insert a vertex, or move or delete a vertex.

  • If insert is TRUE, Microsoft Excel inserts a vertex between the vertices vertex_num and vertex_num-1. The number of the new vertex then becomes vertex_num. The number of the vertex previously identified by vertex_num becomes vertex_num+1, and so on.
  • If insert is FALSE, Microsoft Excel deletes the vertex (if the remaining arguments are omitted) or moves the vertex to the position specified by the remaining arguments.

Reference is the reference from which the vertex you are inserting or moving is measured; that is, the cell or range of cells to use as the basis for the x and y offsets.

  • If reference is a range of cells, only the upper-left cell is used.
  • If reference is omitted, the vertex is measured from the upper-left corner of the polygon's bounding rectangle.

X_offset is the horizontal distance from the upper-left corner of reference to the vertex. X_offset is measured in points. A point is 1/72nd of an inch. If reference is omitted, x_offset specifies the horizontal distance from the upper-left corner of the polygon bounding rectangle.

Y_offset is the vertical distance from the upper-left corner of reference to the vertex. Y_offset is measured in points. If reference is omitted, y_offset specifies the vertical distance from the upper-left corner of the polygon bounding rectangle.

Remarks

You cannot delete a vertex if only two vertices remain.

Examples

The following macro formula deletes the second vertex of the selected polygon:

FORMAT.SHAPE(2, FALSE)

The following macro formula moves the thirteenth vertex 6 points to the right and 4 points below the upper-left corner of cell B5 on the active worksheet:

FORMAT.SHAPE(13, FALSE, !$B$5, 6, 4)

The following macro formula inserts a new vertex between vertices 2 and 3. The new vertex is 60 points to the right and 75 points below the upper-left corner of the polygon's bounding rectangle:

FORMAT.SHAPE(3, TRUE, , 60, 75)

Related Functions

CREATE.OBJECT Creates an object

EXTEND.POLYGON Adds vertices to a polygon

List of Command-Equivalent Functions


FORMAT.SIZE

Macro Sheets Only

Equivalent to sizing an object with the mouse. Sizes the selected object and returns TRUE. If the selected chart object cannot be sized, FORMAT.SIZE returns FALSE. There are two syntax forms of this function. Use syntax 1 to size worksheet objects and chart items absolutely. Use syntax 2 relative to a cell or range of cells to size only worksheet objects. It is generally easier to use the macro recorder to enter this function on your macro sheet.

Syntax 1 Sizes worksheet objects and chart items

Syntax 2 Sizes worksheet objects relative to a cell or range


FORMAT.SIZE Syntax 1

Macro Sheets Only

Equivalent to sizing an object with the mouse. Sizes the selected object and returns TRUE. If the selected chart object cannot be sized, FORMAT.SIZE returns FALSE. There are two syntax forms of this function. Use syntax 1 to size worksheet objects and chart items absolutely. Use syntax 2 relative to a cell or range of cells to size only worksheet objects. It is generally easier to use the macro recorder to enter this function on your macro sheet.

Syntax

FORMAT.SIZE(width, height)
FORMAT.SIZE?(width, height)

Width specifies the width of the selected object, measured in points. A point is 1/72nd of an inch.

Height specifies the height of the selected object, measured in points.

You do not always have to use both arguments. For example, if you specify height and not width, the height changes but the width does not.

Remarks

  • The base of a text label on a chart is the lower-left corner of the text rectangle.
  • The base of an arrow is the end without the arrowhead.

Related Functions

FORMAT.MOVE Moves the selected object

SIZE Changes the size of a window

Syntax 2 Sizes worksheet objects relative to a cell or range

List of Command-Equivalent Functions


FORMAT.SIZE Syntax 2

Macro Sheets Only

Equivalent to sizing an object with the mouse. Sizes the selected worksheet object and returns TRUE. If the selected object cannot be sized, FORMAT.SIZE returns FALSE. There are two syntax forms of this function. Use syntax 2 to size worksheet objects relative to a cell or range of cells. Use syntax 1 to size worksheet objects and chart items. It is generally easier to use the macro recorder to enter this function on your macro sheet.

Syntax

FORMAT.SIZE(x_off, y_off, reference)
FORMAT.SIZE?(x_off, y_off, reference)

X_off specifies the width of the selected object and is measured in points from the lower-right corner of the object to the upper-left corner of reference. A point is 1/72nd of an inch. If omitted, x_off is assumed to be 0. If reference is omitted, x_off specifies the horizontal size.

Y_off specifies the height of the selected object and is measured in points from the lower-right corner of the object to the upper-left corner of reference. If omitted, y_off is assumed to be 0. If reference is omitted, y_off specifies the vertical size.

Reference specifies the cell or range of cells to use as the basis for the offset and for sizing. If reference is a range of cells, only the upper-left cell in the range is used.

Related Functions

FORMAT.MOVE Moves the selected object

SIZE Changes the size of a window

Syntax 1 Sizes worksheet objects and chart items

List of Command-Equivalent Functions


FORMULA

Macro Sheets Only

Enters a formula in the active cell or in a reference. There are two syntax forms of this function. Use syntax 1 to enter numbers, text, references, and formulas in a worksheet. Although syntax 1 can also be used to enter values on a macro sheet, you will not generally use FORMULA for this purpose. Use syntax 2 to enter a formula in a chart. For information about setting values on a macro sheet, see "Remarks" later in this topic.

Syntax 1 Enters numbers, text, references, and formulas in a worksheet

Syntax 2 Enters formulas in a chart


FORMULA Syntax 1

Macro Sheets Only

Enters a formula in the active cell or in a reference. If the active sheet is a worksheet, using FORMULA is equivalent to entering formula_text in the cell specified by reference. Formula_text is entered just as if you typed it in the formula bar.

There are two syntax forms of this function. Use syntax 1 to enter numbers, text, references, and formulas in a worksheet. Although syntax 1 can also be used to enter values on a macro sheet, you will not generally use FORMULA for this purpose. Use syntax 2 to enter a formula in a chart. For information about setting values on a macro sheet, see "Remarks" later in this topic.

Syntax

FORMULA(formula_text, reference)

Formula_text can be text, a number, a reference, or a formula in the form of text, or a reference to a cell containing any of the above.

  • If formula_text contains references, they must be R1C1-style references, such as "=RC[1]*(1+R1C1)". If you are recording a macro when you enter a formula, Microsoft Excel converts A1-style references to R1C1-style references. For example, if you enter the formula =B2*(1+$A$1) in cell C2 while recording, Microsoft Excel records that action as =FORMULA("=RC[-1]*(1+R1C1)").
  • If formula_text is a formula, the formula is entered. Text arguments must be surrounded by double sets of quotation marks. For example, to enter the formula =IF($A$1="Hello World", 1, 0) in the active cell with the FORMULA function, you would use the formula FORMULA|USA|002|001|001|common|UFORMULA("=IF|USA|002|001|001|common|UIF(R1C1=""Hello World"", 1, 0)")

    If formula_text is a number, text, or logical value, the value is entered as a constant.

Reference specifies where formula_text is to be entered. It can be a reference to a cell in the active workbook or an external reference to a workbook. If reference is omitted, formula_text is entered in the active cell.

Remarks

Consider the following guidelines as you choose a function to set values on a worksheet or macro sheet:

  • Use FORMULA to enter formulas and change values in a worksheet cell.
  • SET.VALUE changes values on the macro sheet. Use SET.VALUE to assign initial values to a reference and to store values during the calculation of the macro.
  • SET.NAME creates names on the macro sheet. Use SET.NAME to create a name and immediately assign a value to the name.

Examples

If the active sheet is a worksheet, the following macro formula enters the number constant 523 in the active cell:

FORMULA(523)

If the active sheet is a worksheet, the following macro formula enters the result of the INPUT function in cell A5:

FORMULA(INPUT("Enter a formula:", 0), !$A$5)

If you're using R1C1-style references and the active sheet is a worksheet, the following macro formula enters the formula =RC[-1]*(1+R1C1) in the active cell:

FORMULA("=RC[-1]*(1+R1C1)")

If the active sheet is a worksheet, the following macro formulas enter the number 1000 in the cell two rows down and three columns right from the active cell. The R1C1-style formula is shorter, but the OFFSET method may provide faster performance in larger macro sheets.

FORMULA(1000, OFFSET(ACTIVE.CELL(), 2, 3))
FORMULA(1000, "R[2]C[3]")

The following macro formula enters the phrase "Year to Date" in cell B4 on the sheet named SALES 1993:

FORMULA("Year to Date", 'SALES 1993'!B4)

Related Functions

FORMULA.ARRAY Enters an array

FORMULA.FILL Enters a formula in the specified range

SET.VALUE Sets the value of a cell on a macro sheet

Syntax 2 Enters formulas in a chart

List of Command-Equivalent Functions


FORMULA Syntax 2

Macro Sheets Only

Enters a text label or SERIES formula in a chart. To enter formulas on a worksheet or macro sheet, use syntax 1 of this function.

Syntax

FORMULA(formula_text)

Formula_text is the text label or SERIES formula you want to enter into the chart.

If Then

Formula_text can be treated as a text label and the current selection is a text label | The selected text label is replaced with formula_text.
Formula_text can be treated as a text label and there is no current selection or the current selection is not a text label | Formula_text creates a new unattached text label.
Formula_text can be treated as a SERIES formula and the current selection is a SERIES formula | The selected SERIES formula is replaced with formula_text.
Formula_text can be treated as a SERIES formula and the current selection is not a SERIES formula | Formula_text creates a new SERIES formula.

Remarks

You would normally use the EDIT.SERIES function to create or edit a chart series. For more information, see EDIT.SERIES.

Example

The following macro formula enters a SERIES formula on the chart. If the current selection is a SERIES formula, it is replaced:

FORMULA("=SERIES(""Title"", , {1, 2, 3}, 1)")

Related Function

EDIT.SERIES Creates or changes a chart series

Syntax 1 Enters numbers, text, references, and formulas in a worksheet

List of Command-Equivalent Functions


FORMULA.ARRAY

Macro Sheets Only

Enters a formula as an array formula in the range specified or in the current selection. Equivalent to entering an array formula while pressing CTRL+SHIFT+ENTER in Microsoft Excel for Windows or COMMAND+ENTER in Microsoft Excel for the Macintosh.

Syntax

FORMULA.ARRAY(formula_text, reference)

Formula_text is the text you want to enter in the array. For more information on formula_text, see the first form of FORMULA.

Reference specifies where formula_text is entered. It can be a reference to a cell on the active worksheet or an external reference to a named workbook. Reference must be a R1C1-style reference in text form. If reference is omitted, formula_text is entered in the active cell.

Examples

If the selection is D25:E25, the following macro formula enters the array formula {=D22:E22+D23:E23} in the range D25:E25:

FORMULA.ARRAY("=R[-3]C:R[-3]C[1]+R[-2]C:R[-2]C[1]")

Regardless of the selection, the following macro formula enters the array formula {=D22:E22+D23:E23} in the range D25:E25:

FORMULA.ARRAY("=R[-3]C:R[-3]C[1]+R[-2]C:R[-2]C[1]", "R25C4:R25C5")

To use FORMULA.ARRAY to put an array in a specific workbook, specify the name of the workbook as an external reference in the reference argument. Using "[SALES.XLS]North!R25C3:R25C4" as the reference argument in the preceding example would enter the array in cells C25:D25 on the worksheet named North in the workbook SALES.XLS. Using "SALES!R25C3:R25C4" as the reference argument would enter the array in the same cells in the worksheet named SALES.

Related Functions

FORMULA Enters values into a cell or range or onto a chart

FORMULA.FILL Enters a formula in the specified range

List of Command-Equivalent Functions


FORMULA.FILL

Macro Sheets Only

Enters a formula in the range specified or in the current selection. Equivalent to entering a formula in a range of cells while pressing CTRL+ENTER in Microsoft Excel for Windows or OPTION+ENTER in Microsoft Excel for the Macintosh.

Syntax

FORMULA.FILL(formula_text, reference)

Formula_text is the text with which you want to fill the range. For more information on formula_text, see FORMULA.

Reference specifies where formula_text is entered. It can be a reference to a range in the active worksheet or an external reference to a named workbook. If omitted, formula_text is entered in the current selection.

Related Functions

DATA.SERIES Fills a range of cells with a series of numbers or dates

FORMULA Enters values into a cell or range or onto a chart

FORMULA.ARRAY Enters an array

List of Command-Equivalent Functions


FORMULA.FIND

Macro Sheets Only

Equivalent to choosing the Find command from the Edit menu. Selects the next or previous cell containing the specified text and returns TRUE. If a matching cell is not found, FORMULA.FIND returns FALSE and displays a message.

Syntax

FORMULA.FIND(text, in_num, at_num, by_num, dir_num, match_case)
FORMULA.FIND?(text, in_num, at_num, by_num, dir_num, match_case)

Text is the text you want to find. Text corresponds to the Find What box in the Find dialog box.

In_num is a number from 1 to 3 specifying where to search.

In_num Searches

1 Formulas

2 Values

3 Notes

At_num is the number 1 or 2 and specifies whether to find cells containing only text or also cells containing text within a longer string of characters.

At_num Searches for text as

1 A whole string (the only value in the cell)

2 Either a whole string or part of a longer string

By_num is the number 1 or 2 and specifies whether to search by rows or by columns.

By_num Searches by

1 Rows

2 Columns

Dir_num is the number 1 or 2 and specifies whether to search for the next or previous occurrence of text.

Dir_num Searches for

1 or omitted The next occurrence of text

2 The previous occurrence of text

Match_case is a logical value corresponding to the Match Case check box in the Find dialog box. If match_case is TRUE, Microsoft Excel matches characters exactly, including uppercase and lowercase; if FALSE or omitted, matching is not case-sensitive.

Remarks

  • In Microsoft Excel for Windows, the dialog-box form of FORMULA.FIND is equivalent to pressing SHIFT+F5.
  • If more than one cell is selected when you use FORMULA.FIND, Microsoft Excel searches only that selection.

Related Functions

List of Command-Equivalent Functions


FORMULA.FIND.NEXTFORMULA.FIND.PREV

FORMULA.FIND.NEXT
FORMULA.FIND.PREV

Macro Sheets Only

Finds the next and previous cells on the worksheet, as specified in the Find dialog box, and returns TRUE. (To see the Find dialog box, choose Find from the Edit menu.) If a matching cell is not found, the functions return FALSE. For more information see FORMULA.FIND.

Syntax

FORMULA.FIND.NEXT( )
FORMULA.FIND.PREV( )

Related Function

DATA.FIND Selects records in a database that match the specified criteria

FORMULA.FIND Finds text in a workbook

List of Command-Equivalent Functions


FORMULA.GOTO

Macro Sheets Only

Equivalent to choosing the Go To command from the Edit menu or to pressing F5. Scrolls through the worksheet and selects a named area or reference. Use FORMULA.GOTO to select a range on any open workbook; use SELECT to select a range on the active workbook.

Syntax

FORMULA.GOTO(reference, corner)
FORMULA.GOTO?(reference, corner)

Reference specifies where to scroll and what to select.

  • Reference should be either an external reference to a workbook, an R1C1-style reference in the form of text (see the second example following), or a name.
  • If the Go To command has already been carried out, reference is optional. If reference is omitted, it is assumed to be the reference of the cells you selected before the previous Go To command or FORMULA.GOTO macro function was carried out. This feature distinguishes FORMULA.GOTO from SELECT.

Corner is a logical value that specifies whether to scroll through the window so that the upper-left cell in reference is in the upper-left corner of the active window. If corner is TRUE, Microsoft Excel places reference in the upper-left corner of the window; if FALSE or omitted, Microsoft Excel scrolls through normally.

Tip Microsoft Excel keeps a list of the cells you've selected with previous FORMULA.GOTO functions or Go To commands. When you use FORMULA.GOTO with GET.WORKSPACE(41), which returns a horizontal array of previous Go To selections, you can backtrack through multiple previous selections. See the last example below.

Remarks

  • If you are recording a macro when you choose the Go To command, the reference you enter in the Reference box of the Go To dialog box is recorded as text in the R1C1 reference style.
  • If you are recording a macro when you double-click a cell that has precedents on another worksheet, Microsoft Excel records a FORMULA.GOTO function.

Examples

Each of the following macro formulas goes to cell A1 on the active worksheet:

FORMULA.GOTO(!$A$1)
FORMULA.GOTO("R1C1")

Each of the following macro formulas goes to the cells named Sales on the active worksheet and scrolls through the worksheet so that the upper-left corner of Sales is in the upper-left corner of the window:

FORMULA.GOTO(!Sales, TRUE)
FORMULA.GOTO("Sales", TRUE)

The following macro formula goes to the cells that were selected by the third most recent FORMULA.GOTO function or Go To command:

FORMULA.GOTO(INDEX(GET.WORKSPACE(41), 1, 3))

Related Functions

GOTO Directs macro execution to another cell

HSCROLL Horizontally scrolls through a sheet by percentage or by column or row number

SELECT Selects a cell, worksheet object, or chart item

VSCROLL Vertically scrolls through a sheet by percentage or by column or row number

List of Command-Equivalent Functions


FORMULA.REPLACE

Macro Sheets Only

Equivalent to choosing the Replace command from the Edit menu. Finds and replaces characters in cells on your worksheet.

Syntax

FORMULA.REPLACE(find_text, replace_text, look_at, look_by, active_cell, match_case)
FORMULA.REPLACE?(find_text, replace_text, look_at, look_by, active_cell, match_case)

Find_text is the text you want to find. You can use the wildcard characters, question mark (?) and asterisk (*), in find_text. A question mark matches any single character; an asterisk matches any sequence of characters. If you want to find an actual question mark or asterisk, type a tilde (~) before the character.

Replace_text is the text you want to replace find_text with.

Look_at is a number specifying whether you want find_text to match the entire contents of a cell or any string of matching characters.

Look_at Looks for find_text

1 or omitted As the entire contents of a cell

2 As part of the contents of a cell

Look_by is a number specifying whether to search horizontally (through rows) or vertically (through columns).

Look_by Looks for find_text

1 or omitted By rows

2 By columns

Active_cell is a logical value specifying the cells in which find_text is to be replaced.

  • If active_cell is TRUE, find_text is replaced in the active cell only.
  • If active_cell is FALSE, find_text is replaced in the entire selection, or, if the selection is a single cell, in the entire sheet.

Match_case is a logical value corresponding to the Match Case check box in the Replace dialog box. If match_case is TRUE, Microsoft Excel selects the check box; if FALSE, Microsoft Excel clears the check box. If match_case is omitted, the status of the check box is unchanged.

Remarks

  • In FORMULA.REPLACE?, the dialog-box form of the function, omitted arguments are assumed to be the same arguments used in the previous replace operation. If there was no previous replace operation, omitted text arguments are assumed to be "" (empty text).
  • The result of FORMULA.REPLACE must be a valid cell entry. For example, you cannot replace "=" with "= =" at the beginning of a formula.
  • If more than a single cell is selected before you use FORMULA.REPLACE, only the selected cells are searched.

Related Functions

FORMULA.FIND Finds text in a workbook

List of Command-Equivalent Functions


GET.BAR

Macro Sheets Only

Returns the number of the active menu bar. There are two syntax forms of GET.BAR. Use syntax 1 to return information that you can use with other functions that manipulate menu bars. Use syntax 2 to return information that you can use with functions that add, delete, or alter menu commands.

Syntax 1 Returns the number of the active menu bar

Syntax 2 Returns the name or position number of a specified command on a menu or of a specified menu on a menu bar


GET.BAR Syntax 1

Macro Sheets Only

Returns the number of the active menu bar. There are two syntax forms of GET.BAR. Use syntax 1 to return information that you can use with other functions that manipulate menu bars. For a list of the ID numbers for Microsoft Excel's built-in menu bars, see ADD.COMMAND.

Syntax

GET.BAR( )

Example

The following macro formula assigns the name OldBar to the number of the active menu bar. This is useful if you will need to restore the current menu bar after displaying another custom menu bar.

SET.NAME("OldBar", GET.BAR())

Related Functions

ADD.BAR Adds a menu bar

SHOW.BAR Displays a menu bar

Syntax 2 Returns the name or position number of a specified command on a menu or of a specified menu on a menu bar

List of Information Functions


GET.BAR Syntax 2

Macro Sheets Only

Returns the name or position number of a specified command on a menu or of a specified menu on a menu bar. There are two syntax forms of GET.BAR. Use syntax 2 to return information that you can use with functions that add, delete, or alter menu commands.

Syntax

GET.BAR(bar_num, menu, command, subcommand)

Bar_num is the number of a menu bar containing the menu or command about which you want information. Bar_num can be the number of a built-in menu bar or the number returned by a previously run ADD.BAR function. For a list of the ID numbers for Microsoft Excel's built-in menu bars, see ADD.COMMAND.

Menu is the menu on which the command resides or the menu whose name or position you want. Menu can be the name of the menu as text or the number of the menu. Menus are numbered starting with 1 from the left of the menu bar.

Command is the command or submenu whose name or number you want returned. Command can be the name of the command from the menu as text, in which case the number is returned, or the number of the command from the menu, in which case the name is returned. Commands are numbered starting with 1 from the top of the menu. If command is 0, the name or position number of the menu is returned. If an ellipsis (...) follows a command name, such as the Open... command on the File menu, then you must include the ellipsis when referring to that command. See the following examples.

Subcommand returns the name (if number is used for subcommand) or position (if name is used for subcommand) of a command on a submenu. If the command argument refers to an empty submenu, or is a command instead of a submenu, then using subcommand returns #N/A.

Remarks

  • If an ampersand is used to indicate the access key in the name of a custom command, the ampersand is included in the name returned by GET.BAR. All built-in commands have an ampersand before the letter used as the access key.
  • If the command name or position specified does not exist, GET.BAR returns the #N/A error value.

Examples

In the default worksheet and macro sheet menu bar:

GET.BAR(10, "File", "Print...") equals 14

GET.BAR(10, "File", 14) equals "&Print...^tCTRL+P" (where ^t is a tab character)

GET.BAR(10, 1, "Open") equals #N/A

GET.BAR(10, 1, "Open...") equals 2

Related Functions

ADD.COMMAND Adds a command to a menu

DELETE.COMMAND Deletes a command from a menu

GET.TOOLBAR Retrieves information about a toolbar

RENAME.COMMAND Changes the name of a command or menu

Syntax 1 Returns the number of the active menu bar

List of Information Functions


GET.TOOL

Macro Sheets Only

Returns information about a button or buttons on a toolbar. Use GET.TOOL to get information about a button to use with functions that add, delete, or alter buttons.

Syntax

GET.TOOL(type_num, bar_id, position)

Type_num specifies what type of information you want GET.TOOL to return.

Type_num Returns

1 The button's ID number. Gaps are represented by zeros.

2 The reference of the macro assigned to the button. If no macro is assigned, GET.TOOL returns the #N/A error value.

3 If the button is down, returns TRUE. If the button is up, returns FALSE.

4 If the button is enabled, returns TRUE. If the button is disabled, returns FALSE.

5 A logical value indicating the type of the face on the button:
TRUE = bitmap
FALSE = a default button face

6 The help_text reference associated with the custom button. If the button is built-in, returns #N/A.

7 The balloon_text reference associated with the custom button. If the button is built-in, returns the #N/A error value.

8 The Help context string associated with the custom button.

9 The Tip_text associated with the custom button.

Bar_id specifies the number or name of the toolbar for which you want information. For detailed information about bar_id, see ADD.TOOL.

Position specifies the position of the button on the toolbar. Position starts with 1 at the left side (if horizontal) or at the top (if vertical). A position can be occupied by a button or a gap.

Example

The following macro formula requests the help text associated with the third button in Toolbar2:

GET.TOOL(6, "Toolbar2", 3)

Related Functions

ADD.TOOL Adds one or more buttons to a toolbar

DELETE.TOOL Deletes a button from a toolbar

ENABLE.TOOL Enables or disables a button on a toolbar

GET.TOOLBAR Retrieves information about a toolbar

List of Information Functions


GOAL.SEEK

Macro Sheets Only

Equivalent to choosing the Goal Seek command from the Tools menu. Calculates the values necessary to achieve a specific goal. If the goal is an amount returned by a formula, the GOAL.SEEK function calculates values that, when supplied to your formula, cause your formula to return the amount you want.

Syntax

GOAL.SEEK(target_cell, target_value, variable_cell)
GOAL.SEEK?(target_cell, target_value, variable_cell)

Target_cell corresponds to the Set Cell box in the Goal Seek dialog box and is a reference to the cell containing the formula. If target_cell does not contain a formula, Microsoft Excel displays an error message.

Target_value corresponds to the To Value box in the Goal Seek dialog box and is the value you want the formula in target_cell to return. This value is called a goal.

Variable_cell corresponds to the By Changing Cell box in the Goal Seek dialog box and is the single cell that you want Microsoft Excel to change so that the formula in target_cell returns target_value. Target_cell must depend on variable_cell; if it does not, Microsoft Excel will not be able to find a solution.

Remarks

The max_num and max_change values set with the CALCULATION function can be used to change the solution process. Max_num sets the number of iterations; max_change determines the precision of the solution.

Tip You can also use Microsoft Excel Solver to help solve your math equations for optimal values.

Related Functions

Related functions include the SOLVER functions, such as SOLVER.OPTIONS, SOLVER.SOLVE, and so on.

List of Command-Equivalent Functions


HIDE

Macro Sheets Only

Equivalent to choosing the Hide command from the Window menu. Hides the active window.

Syntax

HIDE( )

Tip Hiding windows can speed up your macros. You can switch to hidden windows with the ACTIVATE function. You can continue to use functions that refer to specific sheets, such as FORMULA and the GET functions, even when those sheets are hidden.

Related Function

UNHIDE Displays a hidden window

List of Command-Equivalent Functions


HSCROLL

Macro Sheets Only

Horizontally scrolls through the active sheet by percentage or by column number.

Syntax

HSCROLL(position, col_logical)

Position specifies the column you want to scroll to. Position can be an integer representing the column number or a fraction or percentage representing the horizontal position of the column in the sheet. If position is 0, HSCROLL scrolls through your sheet to its leftmost edge. If position is 1, HSCROLL scrolls through your sheet to its rightmost edge. For charts that do not size with the window, use a fraction or percentage.

Col_logical is a logical value specifying how the function scrolls.

  • If col_logical is TRUE, HSCROLL scrolls through the sheet to column position.
  • If col_logical is FALSE or omitted, then HSCROLL scrolls through the sheet to the horizontal position represented by the fraction position.

Remarks

  • To scroll to a specific column n, either use HSCROLL(n, TRUE) or use HSCROLL(n/256). To scroll to column 38, for example, use HSCROLL(38, TRUE) or HSCROLL(38/256).
  • If you are recording a macro and move the scroll box several times in a row, the recorder only records the final location of the scroll box, omitting any intermediate steps. Remember that scrolling does not change the active cell or the selection.

Related Functions

HLINE Horizontally scrolls through the active window by columns

HPAGE Horizontally scrolls through the active window one window at a time

VLINE Vertically scrolls through the active window by rows

VPAGE Vertically scrolls through the active window one window at a time

VSCROLL Vertically scrolls through a sheet by percentage or row number

List of Command-Equivalent Functions


IF

Macro Sheets Only

Used with ELSE, ELSE.IF, and END.IF to control which formulas in a macro are executed. There are two syntax forms of the IF function. The following syntax can be used on macro sheets only; use it when you want your macro to branch to a particular set of functions based on the outcome of a logical test. The worksheet form of this function can be used on worksheets and macro sheets.

Syntax

IF(logical_test)

Logical_test is a logical value that IF uses to determine which functions to carry out next—that is, where to branch.

  • If logical_test is TRUE, Microsoft Excel carries out the functions between the IF function and the next ELSE, ELSE.IF, or END.IF function. Instructions between ELSE.IF or ELSE and END.IF are not carried out.
  • If logical_test is FALSE, Microsoft Excel immediately branches to the next ELSE.IF, ELSE, or END.IF function.
  • If logical_test produces an error, the macro halts.

Tips

  • Use IF with ELSE, ELSE.IF, and END.IF when you want to perform multiple actions based on a condition. This method is preferable to using GOTO because it makes your macros more structured.
  • If your macro ends with an error at a cell containing this form of the IF function, make sure there is a corresponding END.IF function.

Example

The following macro runs the macro CompleteEntry if the user chooses OK:

IF(ALERT("Are you done with this entry?", 1), CompleteEntry(), )

Tip You can indent formulas in a macro. To indent a formula, type as many spaces as you want between the equal sign and the first letter of the formula.

Related Functions

ELSE Specifies an action to take if an IF function returns FALSE

ELSE.IF Specifies an action to take if an IF or another ELSE.IF function returns FALSE

END.IF Ends a group of macro functions started with an IF statement

ERROR Specifies what action to take if an error occurs while a macro is running

List of Control Functions


LAST.ERROR

Macro Sheets Only

Returns the reference to the cell where the last macro sheet error occurred. If no error has occurred, LAST.ERROR returns the #N/A error value. Use LAST.ERROR in conjunction with the REFTEXT function to quickly locate errors.

Syntax

LAST.ERROR( )

Related Function

ERROR Specifies what action to take if an error is encountered while a macro is running

List of Information Functions


LINKS

Macro Sheets Only

Returns, as a horizontal array of text values, the names of all workbooks referred to by external references in the workbook specified. Use LINKS with OPEN.LINKS to open supporting workbooks.

Syntax

LINKS(document_text, type_num)

Document_text is the name of a workbook, including its path. If document_text is omitted, LINKS operates on the active workbook. If the workbook specified by document_text is not open, LINKS returns the #N/A error value.

Type_num is a number from 1 to 6 specifying the type of linked workbooks to return.

Type_num Returns

1 or omitted Microsoft Excel link

2 DDE/OLE link (Microsoft Excel for Windows)

3 Reserved

4 Not applicable

5 Publisher (Microsoft Excel for the Macintosh)

6 Subscriber (Microsoft Excel for the Macintosh)

Remarks

  • If the active workbook contains no external references, LINKS returns the #N/A error value.
  • With the INDEX function, you can select individual workbook names from the array for use in other functions that take workbook names as arguments.
  • The names of the workbook are always returned in alphabetic order. If supporting workbooks are open, LINKS returns the names of the workbooks; if supporting workbooks are closed, LINKS includes the full path of each workbook.
  • If type_num is 5 or 6, LINKS returns a two-row array in which the first row contains the edition name and the second row contains the reference.

Examples

If a chart named Chart1 is open and contains links to workbook Data1 and Data2, and the LINKS function shown below is entered as an array into a two-cell horizontal range:

LINKS("Chart1") equals "Data1" in the first cell of the range and "Data2" in the second cell.

In Microsoft Excel for Windows, if the chart named VARIANCE.XLS is open and contains data series that refer to workbook named BUDGET.XLS and ACTUAL.XLS, then:

OPEN.LINKS(LINKS("VARIANCE.XLS")) opens BUDGET.XLS and ACTUAL.XLS.

In Microsoft Excel for the Macintosh, if the workbook named SALES 1991 is open and contains references to the workbook WEST SALES, SOUTH SALES, and EAST SALES, then:

OPEN.LINKS(LINKS("SALES 1991")) opens WEST SALES, SOUTH SALES, and EAST SALES.

Related Functions

CHANGE.LINK Changes supporting workbook links

GET.LINK.INFO Returns information about a link

OPEN.LINKS Opens specified supporting workbook

UPDATE.LINK Updates a link to another workbook

List of Information Functions


MERGE.STYLES

Macro Sheets Only

Equivalent to choosing the Merge button from the Style dialog box, which appears when you choose the Style command from the Format menu. Merges all the styles from another workbook into the active workbook. Use MERGE.STYLES when you want to import styles from another sheet in another workbook.

Syntax

MERGE.STYLES(document_text)

Document_text is the name of a sheet in a workbook from which you want to merge styles into the active workbook.

Remarks

  • If any styles from the workbook being merged have the same name as styles in the active workbook, a dialog box appears asking if you want to replace the existing definitions of the styles with the "merged" definitions of the styles. If you choose the Yes button, all the definitions are replaced; if you choose the No button, all the original definitions in the active workbook are retained.
  • When you move a sheet with styles to another workbook with styles, any styles with identical names but conflicting definitions have the sheet name added to the style name.

Related Functions

DEFINE.STYLE Creates or changes a cell style

DELETE.STYLE Deletes a cell style

List of Command-Equivalent Functions


MOVE.TOOL

Macro Sheets Only

Moves or copies a button from one toolbar to another.

Syntax

MOVE.TOOL(from_bar_id, from_bar_position, to_bar_id, to_bar_position, copy, width)

From_bar_id specifies the number or name of a toolbar from which you want to move or copy the button. For detailed information, see the description of bar_id in ADD.TOOL.

From_bar_position specifies the current position of the button within the toolbar. From_bar_position starts with 1 at the left side (if horizontal) or at the top (if vertical).

To_bar_id specifies the number or name of a toolbar to which you want to move or paste the button. For detailed information, see the description of bar_id in ADD.TOOL. To_bar_id is optional if you are moving a button within the same toolbar.

To_bar_position specifies where you want to move or paste the button within the toolbar. To_bar_position starts with 1 at the left side (if horizontal) or at the top (if vertical). To_bar_position is optional if you are only adjusting the width of a drop-down list.

Copy is a logical value specifying whether to copy the button. If copy is TRUE, the button is copied; if FALSE or omitted, the button is moved.

Width is the width, measured in points, of a drop-down list. If the button you are moving is not a drop-down list, width is ignored.

Related Functions

ADD.TOOL Adds one or more buttons to a toolbar

COPY.TOOL Copies a button face to the Clipboard

GET.TOOL Returns information about a button or buttons on a toolbar

List of Command-Equivalent Functions


NAMES

Macro Sheets Only

Returns, as a horizontal array of text, the specified names defined in the specified workbook. The returned array lists the names in alphabetic order. Use NAMES instead of LIST.NAMES when you want to return the names to the macro sheet instead of to the active worksheet.

Syntax

NAMES(document_text, type_num, match_text)

Document_text is text that specifies the workbook whose names you want returned. If document_text is omitted, it is assumed to be the active workbook.

Type_num is a number from 1 to 3 that specifies whether to include hidden names in the returned array.

If type_num is NAMES returns

1 or omitted Normal names only

2 Hidden names only

3 All names

Match_text is text that specifies the names you want returned and can include wildcard characters. If match_text is omitted, all names are returned.

Remarks

  • Hidden names are defined using the DEFINE.NAME macro function and do not appear in the Paste Name, Define Name, or Go To dialog boxes.
  • NAMES returns a horizontal array, so you will normally enter this function as an array in several horizontal cells or define a name to refer to the array that NAMES returns. If you want the names in a vertical array instead, use the TRANSPOSE function.
  • You can use the COLUMNS function to count the number of entries in the horizontal array.

Example

The following macro formula returns all names on the active workbook starting with the letter P.

NAMES(, 3, "P*")

Related Functions

DEFINE.NAME Defines a name on the active worksheet or macro sheet

DELETE.NAME Deletes a name

GET.DEF Returns a name matching a definition

GET.NAME Returns the definition of a name

LIST.NAMES Lists names and their associated information

SET.NAME Defines a name as a value

List of Information Functions


NEW

Macro Sheets Only

Equivalent to choosing the New command from the File menu. Creates a new Microsoft Excel workbook or opens a template.

Syntax

NEW(type_num, xy_series, add_logical)
NEW?(type_num, xy_series, add_logical)

Type_num specifies the type of workbook to create, as shown in the following table. Type_num is most often 5 or quoted text; other values are mainly for compatibility with Microsoft Excel version 4.

Type_num Workbook

Omitted New workbook with a single worksheet of the same type as the active worksheet

1 New workbook with one worksheet

2 New workbook with one chart based on the current selection

3 New workbook with one macro sheet

4 New workbook with one international macro sheet

5 New workbook with 16 worksheets or based on the default workbook

6 New workbook with one Visual Basic module

7 New workbook with one dialog sheet

Quoted text Template.

Xy_series is a number from 0 to 3 that specifies how data is arranged in a chart.

Xy_series Result

0 Displays a dialog box if the selection is ambiguous.

1 or omitted The first row/column is the first data series.

2 The first row/column contains the category (x) axis labels.

3 The first row/column contains the x-values; the created chart is an xy (scatter) chart.

Add_logical specifies whether or not to add the sheet type to the open workbook. If add_logical is TRUE, the sheet type is inserted before the current sheet; if FALSE or omitted, it is not inserted. This argument is for compatibility with Microsoft Excel version 4.0.

Add_logical is ignored if type_num is 5.

Remarks

You can also use NEW to create new sheets from templates that exist in the startup directory or folder, using for type_num the text that appears in the File New list box. To create new sheets from any template that is not in the start-up directory, use the OPEN function.

Related Functions

NEW.WINDOW Creates a new window for an existing worksheet or macro sheet

OPEN Opens a workbook

List of Command-Equivalent Functions


PASTE

Macro Sheets Only

Equivalent to choosing the Paste command from the Edit menu. Pastes a selection or object that you copied or cut using the COPY or CUT function. Use PASTE when you want to paste all components of the selection. To paste only specific components of the selection, use PASTE.SPECIAL.

Syntax

PASTE(to_reference)

To_reference is a reference to the cell or range of cells where you want to paste what you have copied. If to_reference is omitted, Microsoft Excel pastes to the current selection. If there is nothing to paste, the macro halts.

Related Functions

COPY Copies and pastes data or objects

CUT Cuts or moves data or objects

FORMULA Enters values into a cell or range or onto a chart

INSERT Inserts cells

PASTE.LINK Pastes copied data and establishes a link to its source

PASTE.SPECIAL Pastes specific components of copied data

List of Command-Equivalent Functions


PASTE.TOOL

Macro Sheets Only

Equivalent to selecting a button and choosing the Paste Button Image command from the Edit menu. Pastes a button face from the Clipboard to a specified position on a toolbar.

Syntax

PASTE.TOOL(bar_id, position)

Bar_id specifies the number or name of the toolbar into which you want to paste the button face. For detailed information about bar_id, see ADD.TOOL.

Position specifies the position within the toolbar of the button on which you want to paste the button face. Position starts with 1 at the left side (if horizontal) or at the top (if vertical).

Related Function

COPY.TOOL Copies a button face

List of Command-Equivalent Functions


PRESS.TOOL

Macro Sheets Only

Formats a button so that it appears either normal or depressed into the screen.

Syntax

PRESS.TOOL(bar_id, position, down)

Bar_id specifies the number or name of the toolbar in which you want to change the button appearance. For detailed information about bar_id, see ADD.TOOL.

Position specifies the position of the button within the toolbar. Position starts with 1 at the left side (if horizontal) or at the top (if vertical).

Down is a logical value specifying the appearance of the button. If down is TRUE, the button appears depressed into the screen; if FALSE or omitted, it appears normal (up).

Remarks

This function applies only to custom buttons to which macros have already been assigned. An error occurs if you try to process any other type of button.

Example

The following macro formula sets the third button image on Toolbar4 to normal (up).

PRESS.TOOL("Toolbar4", 3, FALSE)

Related Functions

ADD.TOOL Adds one or more buttons to a toolbar

DELETE.TOOL Deletes a button from a toolbar

List of Customizing Functions


MACRO.OPTIONS

Macro Sheets Only

Equivalent to choosing the Options button in the Macro dialog box, which appears when you choose Macro command from the Tools menu.

Syntax

MACRO.OPTIONS(macro_name, description, menu_on, menu_text, shortcut_on, shortcut_key, function_category, status_bar_text, help_id, help_file)

Macro_name is the name of the macro that you want to set options for, including the name of the workbook and sheet containing the macro.

Description is the description of the macro displayed in the Macro dialog box.

Menu_on is a logical value indicating whether a menu item is automatically added for this macro. If TRUE, menu_text must be specified. If FALSE or omitted, no menu item is added. If the macro already has a menu item, setting this argument to FALSE removes the menu item.

Menu_text is the text of the menu item to be added for the macro. Ignored unless menu_on is TRUE.

Shortcut_on is a logical value indicating whether a shortcut key is assigned to the macro. If TRUE, shortcut_key must be specified. If FALSE or omitted, no shortcut key is assigned. If the macro already has a shortcut key, setting this argument to FALSE removes the shortcut key.

Shortcut_key is the letter of the shortcut key for the macro. Ignored if shortcut_key is FALSE.

Function_category is the number of the category in the Function Wizard that the macro is assigned to. Categories are numbered starting at 1 for the category at the top of the list in the Function Wizard.

Status_bar_text the text displayed in the status bar when a menu item or toolbar button assigned to this macro is clicked on. Be sure to enclose the text in quotes.

Help_id is the numerical id for the help topic associated with this macro and any related menu items or toolbar buttons.

Help_file is the pathname of the help file for the macro.

Related Functions

List of Command-Equivalent Functions


PROTECT.DOCUMENT

Macro Sheets Only

Adds protection to or removes protection from the active sheet, macro sheet, chart, dialog sheet, module, or scenario. Use PROTECT.DOCUMENT to prevent yourself or others from changing cell contents, or objects in a workbook. To protect workbooks in Microsoft Excel version 5.0, see WORKBOOK.PROTECT.

Syntax

PROTECT.DOCUMENT(contents, windows, password, objects, scenarios)
PROTECT.DOCUMENT?( contents, windows, password, objects, scenarios)

Contents is a logical value corresponding to the Contents check box in the Protect Sheet dialog box.

  • If contents is TRUE or omitted, Microsoft Excel selects the check box and protects cells and chart elements on the sheet or macro sheet.
  • If contents is FALSE, Microsoft Excel clears the check box (and removes protection if the correct password is supplied).

Windows is provided for compatibility with Microsoft Excel version 4.0. To protect the window placement and structure of workbooks in Microsoft Excel version 5.0 or later, see WORKBOOK.PROTECT.

  • If windows is TRUE, Microsoft Excel prevents a document's windows from being moved or sized.
  • If windows is FALSE or omitted, Microsoft Excel removes protection if the correct password is supplied.

Password is the password you specify in the form of text to protect or unprotect the file. Password is case-sensitive.

  • If password is omitted when you protect a document, then you will be able to remove protection without a password. This is useful if you want only to protect the document from accidental changes.
  • If password is omitted when you try to remove protection from a document that was protected with a password, the normal password dialog box is displayed.
  • Passwords are not recorded into the PROTECT.DOCUMENT function when you use the macro recorder.

Objects is a logical value. This argument applies only to charts, worksheets and macro sheets. Objects corresponds to the Objects check box in the Protect Sheet dialog box.

  • If objects is TRUE or omitted, Microsoft Excel selects the check box and protects all locked objects on the chart, worksheet or macro sheet.
  • If objects is FALSE, Microsoft Excel clears the check box.

Scenarios is a logical value that corresponds to the Scenarios check box on the Protect Sheet dialog box. If TRUE, Microsoft Excel protects all the scenarios. If FALSE, the scenarios are not protected.

Remarks

  • If contents and objects are FALSE, PROTECT.DOCUMENT carries out the Unprotect Sheet command. If contents, or objects is TRUE, it carries out the Protect Sheet command.
  • Make sure that you hide macro sheets that protect or unprotect worksheets. If you type a password directly into the function on an unhidden macro sheet, then someone could see the password needed to unprotect the worksheet. For example, PROTECT.DOCUMENT(TRUE, TRUE, "XD1411C", TRUE).

Warning If you forget the password of a document that was previously protected with a password, you cannot unprotect the document.

Related Functions

CELL.PROTECTION Controls protection for the selected cells

ENTER.DATA Turns Data Entry mode on and off

OBJECT.PROTECTION Controls how an object is protected

SAVE.AS Saves a workbook and allows you to specify the name, file type, password, backup file, and location of the workbook

WORKBOOK.PROTECT Protects a workbook

List of Command-Equivalent Functions


RENAME.COMMAND

Macro Sheets Only

Changes the name of a built-in or custom menu command or the name of a menu. Use RENAME.COMMAND to change the name of a command on a menu, for example, when you create two custom commands that toggle on the menu. Examples of two built-in commands that toggle are the Page Break and Remove Page Break commands on the Insert menu.

Syntax

RENAME.COMMAND(bar_num, menu, command, name_text, position)

Bar_num can be either the number of one of the Microsoft Excel built-in menu bars or the number returned by a previously run ADD.BAR function. See ADD.COMMAND for a list of ID numbers for built-in menu bars.

Menu can be either the name of a menu as text or the number of a menu. Menus are numbered starting with 1 from the left of the screen.

Command can be either the name of the command as text or the number of the command to be renamed (the first command on a menu is command 1). If command is 0, RENAME.COMMAND renames the menu instead of the command. Because other macros can change the position of custom menu commands, you should use the name of the command rather than a number whenever possible.

If the specified menu bar, menu, or command does not exist, RENAME.COMMAND returns the #VALUE! error value and interrupts the macro.

Name_text is the new name for the command.

Position is the name of the command on a submenu that you want to rename. If you use position, you must use command as the name of the submenu.

Tip To specify an access key for the new name, precede the character you want to use with an ampersand (&). The access key is indicated by an underline under one letter of a menu or command name. In Microsoft Excel for the Macintosh, you can use the General tab in the Options dialog box to turn command underlining on or off. To see the Options dialog box, choose Options from the Tools menu.

Example

To rename the Save All command as Global Save, and to make the letter "G" in Global Save an access key, use the following macro formula:

RENAME.COMMAND(10, "File", "Save All", "&Global Save")

Related Functions

ADD.COMMAND Adds a command to a menu

CHECK.COMMAND Adds or deletes a check mark to or from a command

DELETE.COMMAND Deletes a command from a menu

ENABLE.COMMAND Enables or disables a menu or custom command

List of Customizing Functions


RESET.TOOL

Macro Sheets Only

Equivalent to choosing the Reset Button Image command from the Tool shortcut menu. Resets a button to its original button face.

Syntax

RESET.TOOL(bar_id, position)

Bar_id is the number or name of the toolbar containing the button you want to reset. For detailed information about bar_id, see ADD.TOOL.

Position specifies the position of the button within the toolbar. Position starts with 1 at the left side (if horizontal) or at the top (if vertical).

Related Functions

ADD.TOOL Adds one or more buttons to a toolbar

DELETE.TOOL Deletes a button from a toolbar

RESET.TOOLBAR Resets a button to its original button face

List of Customizing Functions


RESET.TOOLBAR

Macro Sheets Only

Resets built-in toolbars to the default Microsoft Excel set.

Syntax

RESET.TOOLBAR(bar_id)

Bar_id specifies the number or name of the toolbar that you want to reset. For detailed information about bar_id, see ADD.TOOL.

Remarks

If RESET.TOOLBAR successfully resets the toolbar, it returns TRUE. If you try to reset a custom toolbar, RESET.TOOLBAR returns #VALUE! and takes no other action.

Related Functions

ADD.TOOL Adds one or more tools to a toolbar

DELETE.TOOLBAR Deletes custom toolbars

List of Customizing Functions


SAVE.AS

Macro Sheets Only

Equivalent to choosing the Save As command from the File menu. Use SAVE.AS to specify a new filename, file type, protection password, or write-reservation password, or to create a backup file.

Syntax

SAVE.AS(document_text, type_num, prot_pwd, backup, write_res_pwd, read_only_rec)

SAVE.AS?(document_text, type_num, prot_pwd, backup, write_res_pwd, read_only_rec)

Document_text specifies the name of a workbook to save, such as SALES.XLS (in Microsoft Excel for Windows) or SALES (in Microsoft Excel for the Macintosh). You can include a full path in document_text, such as C:\EXCEL\ANALYZE.XLS (in Microsoft Excel for Windows) or HARDDISK:FINANCIALS:ANALYZE (in Microsoft Excel for the Macintosh).

Type_num is a number specifying the file format in which to save the workbook.

Type_num File format

1 or omitted Normal

2 SYLK

3 Text

4 WKS

5 WK1

6 CSV

7 DBF2

8 DBF3

9 DIF

10 Reserved

11 DBF4

12 Reserved

13 Reserved

14 Reserved

15 WK3

16 Microsoft Excel 2.x

17 Template

18 Add-in macro (For compatibility only. In Microsoft Excel 5.0, this saves as normal.)

19 Text (Macintosh)

20 Text (Windows)

21 Text (MS-DOS)

22 CSV (Macintosh)

23 CSV (Windows)

24 CSV (MS-DOS)

25 International macro

26 International add-in macro

27 Reserved

28 Reserved

29 Microsoft Excel 3.0

30 WK1 / FMT

31 WK1 / Allways

32 WK3 / FM3

33 Microsoft Excel 4.0

34 WQ1

35 Microsoft Excel 4.0 workbook

36 Formatted text (space delimited)

The following table shows which values of type_num apply to the six Microsoft Excel document types.

Document Type Type_num

Worksheet All except 10, 12-14, 18, 25-28, 36

Chart sheet All except 10, 12-14, 18, 25-28

Visual Basic module 1, 3, 17

Dialog 1, 17

Macro sheet 1-3, 6, 9, 16-29, 33

Workbook 1, 15, 35

Prot_pwd corresponds to the Protection Password box in the Save Options dialog box.

  • Prot_pwd is a password given as text or as a reference to a cell containing text. Prot_pwd should be no more than 15 characters.
  • If a file is saved with a password, the password must be supplied for the file to be opened.

Backup is a logical value corresponding to the Always Create Backup File check box in the Save Options dialog box and specifies whether to make a backup workbook. If backup is TRUE, Microsoft Excel creates a backup file; if FALSE, no backup file is created; if omitted, the status is unchanged.

Write_res_pwd corresponds to the Write Reservation Password box in the Save Options dialog box and allows the user to write to a file. If a file is saved with a password and the password is not supplied when the file is opened, the file is opened read-only.

Read_only_rec is a logical value corresponding to the Read-Only Recommended check box in the Save Options dialog box.

  • If read_only_rec is TRUE, Microsoft Excel saves the workbook as a read-only recommended workbook; if FALSE, Microsoft Excel saves the workbook normally; if omitted, Microsoft Excel uses the current settings.
  • When you open a workbook that was saved as read-only recommended, Microsoft Excel displays a message recommending that you open the workbook as read-only.

Related Functions

CLOSE Closes the active window

GET.DOCUMENT Returns information about a workbook

SAVE Saves the active workbook

SAVE.WORKBOOK Saves a workbook

List of Command-Equivalent Functions


SAVE.TOOLBAR

Macro Sheets Only

Saves one or more toolbar definitions to a specified file.

Syntax

SAVE.TOOLBAR(bar_id, filename)

Bar_id is either the name or number of a toolbar whose definition you want to save or an array of toolbar names or numbers whose definitions you want to save. Use an array to save several toolbar definitions at the same time. For detailed information about bar_id, see ADD.TOOL. If bar_id is omitted, all toolbar definitions are saved.

Filename is text specifying the name of the destination file. If filename does not exist, Microsoft Excel creates a new file. If filename exists, Microsoft Excel overwrites the file. If filename is omitted, Microsoft Excel saves the toolbar or toolbars in EXCEL5.XLB (in Microsoft Excel for Windows) or EXCEL TOOLBARS (in Microsoft Excel for the Macintosh). With Microsoft Windows, EXCEL5.XLB is stored in the directory where Windows is installed; with Apple Macintosh, EXCEL TOOLBARS is stored in the System:Preferences folder

Examples

In Microsoft Excel for Windows, the following macro formula saves Toolbar6 as \EXCDT\TOOLFILE.XLB.

SAVE.TOOLBAR("Toolbar6", "\EXCDT\TOOLFILE.XLB")

In Microsoft Excel for the Macintosh, the following macro formula saves Toolbar6 as TOOLFILE.

SAVE.TOOLBAR("Toolbar6", "TOOLFILE")

Related Functions

ADD.TOOL Adds one or more tools to a toolbar

ADD.TOOLBAR Creates a new toolbar with the specified tools

OPEN Opens a workbook

List of Customizing Functions


SAVE.WORKBOOK

Macro Sheets Only

Equivalent to choosing the Save Workbook command from the File menu in Microsoft Excel version 4.0. Provided for compatibility with Microsoft Excel version 4.0. Saves the workbook to which the active document belongs. To save Microsoft Excel version 5.0 or later workbooks, see SAVE.AS.

Syntax

SAVE.WORKBOOK(document_text, type_num, prot_pwd, backup, write_res_pwd, read_only_rec)

SAVE.WORKBOOK?(document_text, type_num, prot_pwd, backup, write_res_pwd, read_only_rec)

For a description of the arguments, see SAVE.AS.

Related Functions

CLOSE Closes the active window

GET.DOCUMENT Returns information about a document

SAVE Saves the active workbook

SAVE.AS Saves a workbook and allows you to specify the name, file type, password, backup file, and location of the workbook

List of Command-Equivalent Functions


SELECT

Macro Sheets Only

Equivalent to selecting cells or changing the active cell. There are three syntax forms of SELECT. Use syntax 1 to select a cell on a worksheet or macro sheet; use one of the other syntax forms to select worksheet or macro sheet objects or chart items.

Syntax1 Selects cells

Syntax2 Selects objects on worksheets

Syntax3 Selects chart objects


SELECT Syntax 1

Macro Sheets Only

Equivalent to selecting cells or changing the active cell. There are three syntax forms of SELECT. Use syntax 1 to select a cell on a worksheet or macro sheet; use one of the other syntax forms to select worksheet or macro sheet objects or chart items.

Syntax

SELECT(selection, active_cell)

Selection is the cell or range of cells you want to select. Selection can be a reference to the active worksheet, such as !$A$1:$A$3 or !Sales, or an R1C1-style reference to a cell or range relative to the active cell in the current selection, such as "R[-1]C[-1]:R[1]C[1]". The reference must be in text form. If selection is omitted, the current selection is used.

Active_cell is the cell in selection you want to make the active cell. Active_cell can be a reference to a single cell on the active worksheet, such as !$A$1, or an R1C1-style reference relative to the active cell, such as "R[-1]C[-1]". The reference must be in text form. If active_cell is omitted, SELECT makes the cell in the upper-left corner of selection the active cell.

Remarks

  • Active_cell must be within selection. If it is not, an error message is displayed and SELECT returns the #VALUE! error value.
  • If you are recording a macro using relative references, Microsoft Excel records the action using R1C1-style relative references in the form of text.
  • If you are recording using absolute references, Microsoft Excel records the action using R1C1-style absolute references in the form of text.
  • You cannot give an external reference to a specific sheet as the selection argument. The sheet on which you want to make a selection must be active when you use SELECT. Use FORMULA.GOTO to make a selection on another sheet in the same workbook or in an external workbook.

Tip You can enter data in a cell without selecting the cell by using the reference arguments to the CUT, COPY, or FORMULA functions.

Examples

The following macro formula selects cells C3:E5 on the active worksheet and makes C5 the active cell:

SELECT(!$C$3:$E$5, !$C$5)

If the active cell is C3, the following macro formula selects cells E5:G7 and makes cell F6 the active cell in the selection:

SELECT("R[2]C[2]:R[4]C[4]", "R[1]C[1]")

You can also make multiple nonadjacent selections with SELECT. The following macro formula selects a number of nonadjacent ranges:

SELECT("R1C1, R3C2:R4C3, R8C4:R10C5")

The following sequence of macro formulas moves the active cell right, left, down, and up within the selection, just as TAB, SHIFT+TAB, ENTER, and SHIFT+ENTER do:

SELECT(, "RC[1]")
SELECT(, "RC[-1]")
SELECT(, "R[1]C")
SELECT(, "R[-1]C")

Use SELECT with the OFFSET function to select a new range a specified distance away from the current range. For example, the following macro formula selects a range that is the same size as the current range, one column over:

SELECT(OFFSET(SELECTION(), 0, 1))

Related Functions

ACTIVE.CELL Returns the reference of the active cell

SELECT.SPECIAL Selects a group of cells belonging to a category

SELECTION Returns the reference of the selection

Syntax2 Selects objects on worksheets

Syntax3 Selects chart objects

List of Command-Equivalent Functions


SELECT Syntax 2

Macro Sheets Only

Equivalent to selecting objects on a chart, worksheet or macro sheet. There are three syntax forms of SELECT. Use syntax 2 to select an object on which to perform an action; use one of the other syntax forms to select cells on a worksheet or macro sheet or items on a chart.

Syntax

SELECT(object_id_text, replace)

Object_id_text is text that identifies the object to select. Object_id_text can be the name of more than one object. To give the name of more than one object, use the following format:

SELECT("Oval 3, Arc 2, Line 4")

The last item in the object_id_text list will be the active object. The active object is important when moving and sizing a group of objects. A multiple selection of objects is moved and sized relative to the upper-left corner of the active object.

Replace is a logical value that specifies whether previously selected objects are included in the selection. If replace is TRUE or omitted, Microsoft Excel only selects the objects specified by object_id_text; if FALSE, it includes any objects that were previously selected. For example, if a button is selected and a SELECT formula selects an arc and an oval, TRUE leaves only the arc and oval selected, and FALSE includes the button with the arc and oval.

Remarks

Objects can be identified by their object type and number as described in CREATE.OBJECT, or by the unique number that specifies the order of their creation. For example, if the third object you create is an oval, you could use either "oval 3" or "3" as object_id_text.

Examples

The following macro formulas each select a number of objects and specify Arc 2 as the active object:

SELECT("Oval 3, Arc 1, Line 4, Arc 2")
SELECT("3, 1, 4, 2")

Related Functions

FORMAT.MOVE Moves the selected object

FORMAT.SIZE Changes the size of the selected objects

GET.OBJECT Returns information about an object

SELECTION Returns the reference of the selection

Syntax1 Selects cells

Syntax3 Selects chart objects

List of Command-Equivalent Functions


SELECT Syntax 3

Macro Sheets Only

Selects a chart object as specified by the selection code item_text. There are three syntax forms of SELECT. Use syntax 3 to select a chart item to which you want to apply formatting; use one of the other syntax forms to select cells or objects on a worksheet or macro sheet.

Syntax

SELECT(item_text, single_point)

Item_text is a selection code from the following table which specifies which chart object to select.

To select Item_text

Entire chart "Chart"

Plot area "Plot"

Legend "Legend"

Primary chart value axis "Axis 1"

Primary chart category axis "Axis 2"

Secondary chart value axis or 3-D series axis "Axis 3"

Secondary chart category axis "Axis 4"

Chart title "Title"

Label for the primary chart value axis "Text Axis 1"

Label for the primary chart category axis "Text Axis 2"

Label for the primary chart series axis "Text Axis 3"

nth floating text item "Text n"

nth arrow "Arrow n"

Major gridlines of value axis "Gridline 1"

Minor gridlines of value axis "Gridline 2"

Major gridlines of category axis "Gridline 3"

Minor gridlines of category axis "Gridline 4"

Major gridlines of series axis "Gridline 5"

Minor gridlines of series axis "Gridline 6"

Primary chart droplines "Dropline 1"

Secondary chart droplines "Dropline 2"

Primary chart hi-lo lines "Hiloline 1"

Secondary chart hi-lo lines "Hiloline 2"

Primary chart up bar "UpBar1"

Secondary chart up bar "UpBar2"

Primary chart down bar "DownBar1"

Secondary chart down bar "DownBar2"

Primary chart series line "Seriesline1"

Secondary chart series line "Seriesline2"

Entire series "Sn"

Data associated with point m in series n if single_point is TRUE "SnPm"

Text attached to point m of series n "Text SnPm"

Series title text of series n of an area chart "Text Sn"

Base of a 3-D chart "Floor"

Back of a 3-D chart "Walls"

Corners of a 3-D chart "Corners"

Trend line "SnTm"

Error bars "SnEm"

Legend Marker "Legend Marker n"

Legend Entry "Legend Entry n"

For trend lines and error bars, the value m can be X or Y, depending on which point you want to select. If m is blank, selects both.

Single_point is a logical value that determines whether to select a single point. Single_point is available only when item_text is "SnPm".

  • If single_point is TRUE, Microsoft Excel selects a single point.
  • If single_point is FALSE or omitted, Microsoft Excel selects a single point if there is only one series in the chart or selects the entire series if there is more than one series in the chart.
  • If you specify single_point when item_text is any value other than "SnPm", SELECT returns an error value.

Examples

SELECT("Chart") selects the entire chart.

SELECT("Dropline 2") selects the droplines of an overlay chart.

SELECT("S1P3", TRUE) selects the third point in the first series.

SELECT("Text S1") selects the series title text of the first series in an area chart.

Related Function

SELECTION Returns the reference of the selection

Syntax1 Selects cells

Syntax2 Selects objects on worksheets

List of Command-Equivalent Functions


SELECT.SPECIAL

Macro Sheets Only

Equivalent to choosing the Go To command from the Edit menu and then selecting the Special button. Use SELECT.SPECIAL to select groups of similar cells in one of a variety of categories.

Syntax

SELECT.SPECIAL(type_num, value_type, levels)
SELECT.SPECIAL?(type_num, value_type, levels)

Type_num is a number from 1 to 13 corresponding to options in the Select Special dialog box and describes what to select.

Type_num Description

1 Notes

2 Constants

3 Formulas

4 Blanks

5 Current region

6 Current array

7 Row differences

8 Column differences

9 Precedents

10 Dependents

11 Last cell

12 Visible cells only (outlining)

13 All objects

Value_type is a number specifying which types of constants or formulas you want to select. Value_type is available only when type_num is 2 or 3.

Value_type Selects

1 Numbers

2 Text

4 Logical values

16 Error values

These values can be added to select more than one type. The default for value_type is 23, which select all value types.

Levels is a number specifying how precedents and dependents are selected. Levels is available only when type_num is 9 or 10. The default is 1.

Levels Selects

1 Direct only

2 All levels

Related Function

List of Command-Equivalent Functions


SEND.TO.BACK

Macro Sheets Only

Equivalent to choosing the Send To Back command from the Placement submenu on the Format menu. Sends the selected object or objects to the back. Use SEND.TO.BACK to position selected objects behind other objects.

If the selection is not an object or a group of objects, SEND.TO.BACK returns the #VALUE! error value and interrupts the macro.

Syntax

SEND.TO.BACK( )

Related Function

BRING.TO.FRONT Brings selected objects to the front

List of Command-Equivalent Functions


SET.PRINT.AREA

Macro Sheets Only

Defines the print area for the workbook—the area that prints when you choose the Print command from the File menu. Equivalent to entering a range in the Print Area edit box on the Sheet tab in the Page Setup dialog box, which appears when you choose the Page Setup command from the File menu.

Syntax

SET.PRINT.AREA(range)

Range is the reference to the range that you want to be printed. If you specify no range by using a set of empty quotemarks (""), deletes the print area.

Remarks

  • If you use SET.PRINT.AREA with a multiple selection and then use the PRINT function, the individual selections are printed one after the other in the order they were selected.
  • To resume printing the entire worksheet, choose the Page Setup command from the File menu and choose the Sheet tab. Then delete the range in the Print Area edit box.

Related Functions

PRINT Prints the active workbook

SET.PRINT.TITLES Identifies text to print as titles

List of Command-Equivalent Functions


SET.PRINT.TITLES

Macro Sheets Only

Defines the print titles for the sheet. Use SET.PRINT.TITLES if you want Microsoft Excel to print the titles whenever it prints any cells in a row or column that intersect the print titles area; a cell need only share the row or column with a print title for the title to be printed above or to the left of that cell.

Syntax

SET.PRINT.TITLES(titles_for_cols_ref, titles_for_rows_ref)
SET.PRINT.TITLES?(titles_for_cols_ref, titles_for_rows_ref)

Titles_for_cols_ref is a reference to the row to be used as a title for columns.

  • If you specify part of a row, Microsoft Excel expands the title to a full row.
  • If you omit titles_for_cols_ref, Microsoft Excel uses the existing row of column titles, if any.
  • If you specify empty text (""), Microsoft Excel removes the row from the print titles definition.

Titles_for_rows_ref is a reference to the column to be used as a title for rows.

  • If you specify part of a column, Microsoft Excel expands the title to a full column.
  • If you omit titles_for_rows_ref, Microsoft Excel uses the existing column of row titles, if any.
  • If you specify empty text (""), Microsoft Excel removes the column from the print titles definition.

Remarks

  • SET.PRINT.TITLES operates on the current sheet. If you specify a range that is invalid for the current sheet, Microsoft Excel returns the #VALUE error value.
  • The print titles selection can be a multiple selection. Microsoft Excel names this selection Print_Titles when SET.PRINT.TITLES is run.

Related Functions

DEFINE.NAME Defines a name on the active worksheet or macro sheet

PRINT Prints the active sheet

SET.PRINT.AREA Defines the print area

List of Command-Equivalent Functions


SET.VALUE

Macro Sheets Only

Changes the value of a cell or cells on the macro sheet (not the worksheet) without changing any formulas entered in those cells. Use SET.VALUE to assign initial values and to store values during the calculation of a macro. SET.VALUE is especially useful for initializing a dialog box and the conditional test in a WHILE loop. SET.VALUE assigns values to a specific reference or to the name of a reference that has already been defined. For information about creating a new name or entering data on a worksheet, see "Remarks" later in this topic.

Syntax

SET.VALUE(reference, values)

Reference specifies the cell or cells on the macro sheet to which you want to assign a new value or values. If the cell is empty, enters the value in the cell.

  • If a cell in reference previously contained a formula, the formula is not changed, but the value of the cell might change. See the second example following.
  • If reference is a reference to a range of cells, rather than to a single cell, then values should be an array of the same size. If not, Microsoft Excel expands it into multiple values using the normal rules for expanding arrays. See the third example following.

Values is the value or set of values to which you want to assign the cell or cells in reference.

Remarks

Consider the following guidelines as you choose a function to set values on a worksheet or macro sheet:

  • Use SET.VALUE to assign initial values to a reference (including names that have already been defined) on a macro sheet, and to store values during the calculation of a macro.
  • Use FORMULA to enter values in a worksheet cell.
  • Use SET.NAME to change the value of a name on a macro sheet (the name is created if it does not already exist). For more information, see SET.NAME.
  • Use DEFINE.NAME to create or change the value of a name on a worksheet.

Examples

The following macro formula changes the value of cell A1 on the macro sheet to 1:

SET.VALUE($A$1, 1)

Suppose the name TempAverage refers to a cell containing the formula AVERAGE(Temp1, Temp2, Temp3). The following formula assigns the value 99 to this cell, even if the average of the arguments is not 99, without changing the formula in TempAverage:

SET.VALUE(TempAverage, 99)

The preceding formula is useful if a WHILE loop or some other conditional test depends on TempAverage and you want to force the conditional test to have a particular result. Of course, TempAverage is restored to its correct value as soon as it is recalculated. (Recall that unlike formulas in a worksheet, formulas in a macro sheet are not recalculated until the macro actually uses them.)

The following macro formula stores the values 1, 2, 3, and 4 in cells A1:B2:

SET.VALUE($A$1:$B$2, {1, 2;3, 4})

Related Functions

DEFINE.NAME Defines a name on the active worksheet or macro sheet

FORMULA Enters values into a cell or range or onto a chart

SET.NAME Defines a name as a value

List of Control Functions


SHORT.MENUS

Macro Sheets Only

Equivalent to choosing the Short Menus command from the Options menu or the Chart menu in Microsoft Excel version 3.0 or earlier.

Syntax

SHORT.MENUS(logical)

Related Functions

List of Command-Equivalent Functions


SHOW.CLIPBOARD

Macro Sheets Only

Displays the contents of the Clipboard in a new window.

Syntax

SHOW.CLIPBOARD( )

Remarks

  • In Microsoft Excel for Windows, the Clipboard must already be running if you want to display its contents in a new window. If it is not already running, you must run the SHOW.CLIPBOARD function twice, once to start the Clipboard application and again to display it in a new window.
  • If the Clipboard contains cells, the window shows the size of the Clipboard contents in rows and columns. If the Clipboard contains text cut from the formula bar, the window displays the text.

Related Functions

List of Command-Equivalent Functions


SHOW.INFO

Macro Sheets Only

Controls the display of the Info window.

Syntax

SHOW.INFO(logical)

Logical controls the display of the Info window.

  • If logical is TRUE, Microsoft Excel switches to the Info window.
  • If the current window is the Info window and logical is FALSE, Microsoft Excel switches to the workbook linked to the Info window.

Tip Before using SHOW.INFO, use ACTIVATE to switch to the workbook you want information about and SELECT or FORMULA.GOTO to select the cell or range you want information about.

Remarks

The Info window is not available when a chart is active. If SHOW.INFO is carried out when a chart is the active sheet, an Info window will be displayed for the worksheet or macro sheet that was most recently active.

Related Function

FORMULA.GOTO Selects a named area or reference on any open workbook

GET.CELL Returns information about the specified cell

SELECT Selects a cell, worksheet object, or chart item

List of Command-Equivalent Functions


STEP

Macro Sheets Only

Stops the normal flow of a macro and calculates it one cell at a time. Running a macro one cell at a time is called single-stepping and is very useful when you are debugging a macro. Use the STEP function, instead of choosing the Step button in the Macro dialog box when you want to start single-stepping at a specific line in a macro. The Macro dialog box appears when you choose the Macro command on the Tools menu.

Syntax

STEP( )

Remarks

  • When Microsoft Excel encounters a STEP function, it stops running the macro and displays a dialog box. The dialog box tells you which cell in the macro Microsoft Excel is about to calculate, and what formula is in that cell. You can choose Step to carry out the next instruction; choose Evaluate to calculate part of the formula; choose Halt to interrupt the macro; or choose Continue to continue the macro without single-stepping.

    You can evaluate the formula by holding down the SHIFT key while you click the Step button. You can also choose Step Over to carry out, but not step through, a user-defined function call; choose Pause, to suspend the macro so you can perform other tasks; and choose Goto, to stop the macro and select the cell being evaluated.

  • When placed at the beginning of a macro, STEP is equivalent to choosing the Macro command from the Tool menu and selecting the Step button in the Macro dialog box.
  • You can start single-stepping while a macro is running by pressing ESC in Microsoft Excel for Windows or by pressing ESC or COMMAND+PERIOD in Microsoft Excel for the Macintosh.
  • The Single Step dialog box is initially displayed in the lower-right corner of the screen. You can move the dialog box if it's in your way. If you move it, it will remain in the new location until you stop single-stepping.
  • To step through the calculation of a custom function, place the STEP function at the start of the custom function.

Related Functions

HALT Stops all macros from running

RUN Runs a macro

List of Control Functions


TABLE

Macro Sheets Only

Equivalent to choosing the Table command from the Data menu. Creates a table based on the input values and formulas you define on a worksheet. Use data tables to perform a "what-if" analysis by changing certain constant values in your workbook to see how values in other cells are affected.

Syntax

TABLE(row_ref, column_ref)
TABLE?(row_ref, column_ref)

Row_ref specifies the one cell to use as the row input for your table.

  • Row_ref should be either an external reference to a single cell on the active worksheet, such as !$A$1 or !Price, or an R1C1-style reference to a single cell in the form of text, such as "R1C1", "R[-1]C[-1]", or "Price".
  • If row_ref is an R1C1-style reference, it is assumed to be relative to the active cell in the selection.

Column_ref specifies the one cell to use as the column input for your table. Column_ref is subject to the same restrictions as row_ref.

Related Functions

List of Command-Equivalent Functions


VSCROLL

Macro Sheets Only

Vertically scrolls through the active sheet by percentage or by row number.

Syntax

VSCROLL(position, row_logical)

Position specifies the row you want to scroll to. Position can be an integer representing the row number or a fraction or percentage representing the vertical position of the row in the sheet. If position is 0, VSCROLL scrolls through your sheet to its top edge, which is row 1. If position is 1, VSCROLL scrolls through your sheet to its bottom edge, which is row 16, 384. For charts that do not size with the window, use a fraction or percentage.

Row_logical is a logical value specifying how the function scrolls.

  • If row_logical is TRUE, VSCROLL scrolls through the sheet to row position.
  • If row_logical is FALSE or omitted, VSCROLL scrolls through the sheet to the vertical position represented by the fraction position.

Remarks

  • To scroll to a specific row n, either use VSCROLL(n, TRUE) or VSCROLL(n/16384). To scroll to row 138, for example, enter VSCROLL(138, TRUE) or VSCROLL(138/16384).
  • If you are recording a macro and move the scroll box several times in a row, the recorder only records the final location of the scroll box, omitting any intermediate steps. Remember that scrolling does not change the active cell or the selection.

Related Functions

FORMULA.GOTO Selects a named area or reference on any open workbook

HLINE Horizontally scrolls through the active window by columns

HPAGE Horizontally scrolls through the active window one window at a time

HSCROLL Horizontally scrolls through a sheet by percentage or by column number

SELECT Selects a cell, object, or chart item

VLINE Vertically scrolls through the active window by rows

VPAGE Vertically scrolls through the active window one window at a time

List of Command-Equivalent Functions


WINDOW.MAXIMIZE

Macro Sheets Only

Changes the active window from its normal size to full size. In Microsoft Excel for Windows, using WINDOW.MAXIMIZE is equivalent to pressing CTRL+F10 or double-clicking the title bar. In Microsoft Excel for the Macintosh, using WINDOW.MAXIMIZE is equivalent to double-clicking the title bar or clicking the zoom box.

Syntax

WINDOW.MAXIMIZE(window_text)

Window_text specifies which window to switch to and maximize. Window_text is text enclosed in quotation marks or a reference to a cell containing text. If window_text is omitted, the active window is maximized.

Remarks

WINDOW.MAXIMIZE replaces FULL(TRUE) in earlier versions of Microsoft Excel.

Related Functions

WINDOW.MINIMIZE Minimizes a window

WINDOW.MOVE Moves a window

WINDOW.RESTORE Restores a window to its previous size

WINDOW.SIZE Changes the size of a window

List of Command-Equivalent Functions


WINDOW.MINIMIZE

Macro Sheets Only

Shrinks a window to an icon. In Microsoft Excel for Windows, using WINDOW.MINIMIZE is equivalent to clicking the minimize button on a workbook window. In Microsoft Excel for the Macintosh, the minimize feature is not supported.

Syntax

WINDOW.MINIMIZE(window_text)

Window_text specifies which window to minimize.

  • Window_text is text enclosed in quotation marks or a reference to a cell containing text.
  • If window_text is omitted, Microsoft Excel minimizes the active window.

Remarks

If a window is already minimized, WINDOW.MINIMIZE has no effect.

Related Functions

WINDOW.MAXIMIZE Maximizes a window

WINDOW.MOVE Moves a window

WINDOW.RESTORE Restores a window to its previous size

WINDOW.SIZE Changes the size of a window

List of Command-Equivalent Functions


WINDOW.MOVE

Macro Sheets Only

Equivalent to choosing the Move command from the Control menu in Microsoft Excel for Windows or moving a window by dragging its title bar or its icon. Moves the active window so that its upper-left corner is at the specified horizontal and vertical positions. The dialog-box form, WINDOW.MOVE?, is supported only in Microsoft Excel for Windows.

Syntax

WINDOW.MOVE(x_pos, y_pos, window_text)
WINDOW.MOVE?(x_pos, y_pos, window_text)

X_pos is the horizontal position to which you want to move the window. X_pos is measured in points. A point is 1/72nd of an inch.

  • In Microsoft Excel for Windows, x_pos is measured from the left edge of your workspace to the left edge of the window.
  • In Microsoft Excel for the Macintosh, x_pos is measured from the left edge of your screen to the left edge of the window.
  • If x_pos is omitted, the window does not move horizontally.

Y_pos is the vertical position to which you want to move the window. Y_pos in measured in points from the bottom edge of the formula bar to the top edge of the window. If y_pos is omitted, the window does not move vertically.

Window_text specifies which window to restore.

  • Window_text is text enclosed in quotation marks or a reference to a cell containing text.
  • If window_text is omitted, it is assumed to be the name of the active window.

Remarks

  • If the window is minimized, WINDOW.MOVE moves the icon on the workspace. Measurements are relative to the upper-left corner of the workspace and the icon.
  • WINDOW.MOVE does not change the size of the window or affect whether the specified window is active or inactive.
  • In Microsoft Excel for the Macintosh, if window_text is "Clipboard", WINDOW.MOVE moves the Clipboard. The Clipboard must already be available; if it is not available, use the SHOW.CLIPBOARD function before using the WINDOW.MOVE function.
  • WINDOW.MOVE replaces MOVE in earlier versions of Microsoft Excel.

Related Functions

FORMAT.MOVE Moves the selected object

WINDOW.MAXIMIZE Maximizes a window

WINDOW.MINIMIZE Minimizes a window

WINDOW.RESTORE Restores a window to its previous size

WINDOW.SIZE Changes the size of a window

List of Command-Equivalent Functions


WINDOW.RESTORE

Macro Sheets Only

Changes the active window from maximized or minimized size to its previous size. In Microsoft Excel for Windows, using WINDOW.RESTORE is equivalent to pressing CTRL+F5 or double-clicking the title bar (or double-clicking the icon if it is minimized). In Microsoft Excel for the Macintosh, using WINDOW.RESTORE is equivalent to double-clicking the title bar or clicking the zoom box.

Syntax

WINDOW.RESTORE(window_text)

Window_text specifies which window to switch to and restore.

  • Window_text is text enclosed in quotation marks or a reference to a cell containing text.
  • If window_text is omitted, Microsoft Excel restores the active window.

Remarks

  • If the window is minimized, WINDOW.RESTORE restores the icon to its previous size. This operation is equivalent to double-clicking the icon.
  • WINDOW.RESTORE replaces FULL(FALSE) in earlier versions of Microsoft Excel.

Related Functions

WINDOW.MAXIMIZE Maximizes a window

WINDOW.MINIMIZE Minimizes a window

WINDOW.MOVE Moves a window

WINDOW.SIZE Changes the size of a window

List of Command-Equivalent Functions


WINDOW.SIZE

Macro Sheets Only

Equivalent to choosing the Size command from the Control menu or to adjusting the sizing borders (in Microsoft Excel for Windows) or the sizing box (in Microsoft Excel for the Macintosh) of the window with the mouse. Changes the size of the active window by moving its lower-right corner so that the window has the width and height you specify. WINDOW.SIZE does not change the position of the upper-left corner of the window, nor does it affect whether the specified window is active or inactive.

Syntax

WINDOW.SIZE(width, height, window_text)
WINDOW.SIZE?(width, height, window_text)

Width specifies the width of the window and is measured in points. A point is 1/72nd of an inch.

Height specifies the height of the window and is measured in points.

Window_text specifies which window to size.

  • Window_text is text enclosed in quotation marks or a reference to a cell containing text.
  • If window_text is omitted, it is assumed to be the name of the active window.

Remarks

  • In Microsoft Excel for Windows, an error occurs if you try to resize a window that has already been minimized to an icon or enlarged to its maximum size. You must first restore the window to its original size using the WINDOW.RESTORE formula. For more information, see WINDOW.RESTORE.
  • WINDOW.SIZE replaces SIZE in earlier versions of Microsoft Excel.

Related Functions

FORMAT.SIZE Sizes an object

WINDOW.MAXIMIZE Maximizes a window

WINDOW.MINIMIZE Minimizes a window

WINDOW.MOVE Moves a window

WINDOW.RESTORE Restores a window to its previous size

List of Command-Equivalent Functions


ABSREF

Macro Sheets Only

Returns the absolute reference of the cells that are offset from a reference by a specified amount. You should generally use OFFSET instead of ABSREF. This function is provided for users who prefer to supply a absolute reference in text form.

Syntax

ABSREF(ref_text, reference)

Ref_text specifies a position relative to reference. Think of ref_text as "directions" from one range of cells to another.

  • Ref_text must be an R1C1-style relative reference in the form of text, such as "R[1]C[1]".
  • Ref_text is considered relative to the cell in the upper-left corner of reference.

Reference is a cell or range of cells specifying a starting point that ref_text uses to locate another range of cells. Reference can be an external reference.

Remarks

  • If you use ABSREF in a function or operation, you will usually get the values contained in the reference instead of the reference itself because the reference is automatically converted to the contents of the reference.
  • If you use ABSREF in a function that requires a reference argument, then Microsoft Excel does not convert the reference to a value.
  • If you want to work with the actual reference, use the REFTEXT function to convert the active-cell reference to text, which you can then store or manipulate (or convert back to a reference with TEXTREF). See the third example following.

Examples

ABSREF("R[-2]C[-2]", C3) equals $A$1

ABSREF(RELREF(A1, C3), D4) equals $B$2

REFTEXT(ABSREF("R[-2]C[-2]:R[2]C[2]", C3:G7), TRUE) is equivalent to

REFTEXT(ABSREF("R[-2]C[-2]:R[2]C[2]", C3), TRUE), which equals "$A$1:$E$5"

In Microsoft Excel for Windows ABSREF("R[-2]C[-2]", [FINANCE.XLS]Sheet1!C3) equals [FINANCE.XLS]Sheet1!$A$1.

In Microsoft Excel for the Macintosh ABSREF("R[-2]C[-2]", [FINANCE]Sheet1!C3) equals [FINANCE]Sheet1!$A$1

Related Functions

RELREF Returns a relative reference

List of Lookup & Reference Functions


ADD.ARROW

Macro Sheets Only

Equivalent to clicking the Arrow button on the Drawing toolbar. Adds an arrow to the active chart. If a chart is not the active window, displays an error value.

Syntax

ADD.ARROW( )

Remarks

After you create an arrow with ADD.ARROW, the arrow remains selected, so you can use the arrow form of the PATTERNS function to format the arrow and the FORMAT.MOVE and FORMAT.SIZE functions to change the position and size of the arrow.

Related Functions

CREATE.OBJECT Creates an object

DELETE.ARROW Deletes the selected arrow

FORMAT.MOVE Moves the selected object

FORMAT.SIZE Changes the size of the selected object

PATTERNS Changes the appearance of the selected object

List of Command-Equivalent Functions


ADD.CHART.AUTOFORMAT

Adds the format of the currently active chart in the current window to the list of custom formats in the AutoFormat dialog box for charts.

Syntax

ADD.CHART.AUTOFORMAT(name_text, desc_text)

Name_text is the name you want to appear in the list of custom formats.

Desc_text is the description you want to appear when the custom format is selected.

Related Functions

DELETE.CHART.AUTOFORMAT Deletes a custom template

List of Command-Equivalent Functions


ADD.OVERLAY

Macro Sheets Only

Equivalent to choosing the Add Overlay command from the Chart menu in Microsoft Excel 4.0. Adds an overlay to a 2-D chart. If the active chart already has an overlay, ADD.OVERLAY takes no action and returns TRUE. In Microsoft Excel 5.0 or later, ADD.OVERLAY works with charts that have only one chart type.

Syntax

ADD.OVERLAY( )

Related Functions

ADD.ARROW Adds an arrow to a chart

LEGEND Adds a legend to a chart

List of Command-Equivalent Functions


APPLY.NAMES

Macro Sheets Only

Equivalent to choosing the Apply command from the Name submenu on the Insert menu. Replaces definitions with their respective names. If no names are defined in the current selection, APPLY.NAMES returns the #VALUE! error value. Use APPLY.NAMES to replace references and values in formulas with names.

Syntax

APPLY.NAMES(name_array, ignore, use_rowcol, omit_col, omit_row, order_num, append_last)
APPLY.NAMES?(name_array, ignore, use_rowcol, omit_col, omit_row, order_num, append_last)

Name_array is the name or names to apply as text elements in an array.

  • To give more than one name as the argument, you must use an array. For example:
  • APPLY.NAMES({"DataRange", "CriteriaRange"})
  • If the names indicated by the argument name_array have already replaced all of the appropriate references or values, the #VALUE! error value is returned.

The next four arguments correspond to check boxes and options in the Apply Names dialog box. Arguments that correspond to check boxes are logical values. If an argument is TRUE, Microsoft Excel selects the check box; if FALSE, Microsoft Excel clears the check box.

Ignore corresponds to the Ignore Relative/Absolute check box.

Use_rowcol corresponds to the Use Row And Column Names check box. If use_rowcol is FALSE, the next three arguments are ignored.

Omit_col corresponds to the Omit Column Name If Same Column check box.

Omit_row corresponds to the Omit Row Name If Same Row check box.

Order_num determines which range name is listed first when a cell reference is replaced by a row-oriented and a column-oriented range name, as shown in the following table.

Order_num Order of range names

1 Row Column

2 Column Row

Append_last determines whether the names most recently defined are also replaced.

  • If append_last is TRUE, Microsoft Excel replaces the definitions of the names in name_array and also replaces the definitions of the last names defined.
  • If append_last is FALSE or omitted, Microsoft Excel replaces the definitions of the names in name_array only.

Related Functions

CREATE.NAMES Creates names automatically from text labels on a sheet

DEFINE.NAME Defines a name on the active sheet or macro sheet

LIST.NAMES Lists names and their associated information

List of Command-Equivalent Functions


BORDER

Macro Sheets Only

Equivalent to choosing the Border tab in the Format Cells dialog box, which appears when you choose the Cells command from the Format menu. Adds a border to the selected cell or range of cells.

Syntax

BORDER(outline, left, right, top, bottom, shade, outline_color, left_color, right_color, top_color, bottom_color)
BORDER?(outline, left, right, top, bottom, shade, outline_color, left_color, right_color, top_color, bottom_color)

Outline, left, right, top, and bottom are numbers from 0 to 7 corresponding to the line styles in the Border dialog box, as shown in the following table.

Argument Line type

0 No border

1 Thin line

2 Medium line

3 Dashed line

4 Dotted line

5 Thick line

6 Double line

7 Hairline

Note For compatibility with earlier versions of Microsoft Excel, TRUE and FALSE values for the above arguments create a thin border or no border, respectively.

Shade corresponds to the Shade check box in the Border dialog box of Microsoft Excel version 4.0. This argument is included for compatibility only.

Outline_color, left_color, right_color, top_color, and bottom_color are numbers from 1 to 56 corresponding to the Color box in the Border dialog box. Zero corresponds to automatic color.

Related Function

List of Command-Equivalent Functions


CALLER

Macro Sheets Only

Returns information about the cell, range of cells, command on a menu, tool on a toolbar, or object that called the macro that is currently running. Use CALLER in a subroutine or custom function whose behavior depends on the location, size, name, or other attribute of the caller.

Syntax

CALLER( )

Remarks

  • If the custom function is entered in a single cell, CALLER returns the reference of that cell.
  • If the custom function was part of an array formula entered in a range of cells, CALLER returns the reference of the range.
  • If CALLER appears in a macro called by an Auto_Open, Auto_Close, Auto_Activate, or Auto_Deactivate macro, it returns the name of the calling sheet.
  • If CALLER appears in a macro called by a command on a menu, it returns a horizontal array of three elements including the command's position number, the menu number, and the menu bar number.
  • If CALLER appears in a macro called by an assigned-to-object macro, it returns the object identifier.
  • If CALLER appears in a macro called by a tool on a toolbar, it returns a horizontal array containing the position number and the toolbar name.
  • If CALLER appears in a macro called by an ON.DOUBLECLICK or ON.ENTRY function, CALLER returns the name of the chart object identifier or cell reference, if applicable, to which the ON.DOUBLECLICK or ON.ENTRY macro applies.
  • If CALLER appears in a macro that was run manually, or for any reason not described above, it returns the #REF! error value.

Examples

If the custom function MACROS!VALUEONE is entered in cell B3 on a sheet named SALES, the nested CALLER function returns the following values.

Nested function Returns

COLUMN(CALLER()) 2

COLUMNS(CALLER()) 1

GET.CELL(1, CALLER()) SALES!$B$3

ROW(CALLER()) 3

ROWS(CALLER()) 1

If the same custom function was entered into an array in cells B2:C3, the following values would be returned.

Nested function Returns

COLUMN(CALLER()) 2

COLUMNS(CALLER()) 2

ROW(CALLER()) 2

ROWS(CALLER()) 2

Related Functions

GET.BAR Returns the name or position number of menu bars, menus, and commands

GET.CELL Returns information about the specified cell

List of Information Functions


CANCEL.KEY

Macro Sheets Only

Disables macro interruption, or specifies a macro to run when a macro is interrupted. Use CANCEL.KEY to control what happens when a macro is interrupted.

Syntax

CANCEL.KEY(enable, macro_ref)

Enable specifies whether the macro can be interrupted by pressing ESC in Microsoft Excel for Windows or ESC or COMMAND+PERIOD in Microsoft Excel for the Macintosh.

If enable is Then

FALSE Pressing ESC or COMMAND+PERIOD does not interrupt a macro

TRUE and macro_ref is omitted Pressing ESC or COMMAND+PERIOD interrupts a macro

TRUE and macro_ref is specified Macro_ref runs when ESC or COMMAND+PERIOD is pressed

Macro_ref is a reference to a macro, as a cell reference or a name, that runs when enable is TRUE and ESC or COMMAND+PERIOD is pressed.

Remarks

  • CANCEL.KEY affects only the macro that is currently running. Once the macro is stopped by a RETURN or HALT function, ESC or COMMAND+PERIOD is reactivated.
  • When CANCEL.KEY is in effect, users can still cancel a dialog box displayed while the macro is running.

Examples

The following macro formula prevents the macro from being interrupted by pressing ESC or COMMAND+PERIOD:

CANCEL.KEY(FALSE)

The following macro formula reactivates ESC or COMMAND+PERIOD to cancel macro execution:

CANCEL.KEY(TRUE)

The following line in a macro runs CheckCancel when ESC or COMMAND+PERIOD is pressed:

CANCEL.KEY(TRUE, CheckCancel)

Related Functions

ERROR Specifies an action to take if an error occurs while a macro is running

ON.KEY Runs a macro when a specified key is pressed

ON.TIME Runs a macro at a specified time

List of Customizing Functions


CHECK.COMMAND

Macro Sheets Only

Adds or removes a check mark to or from a command name on a menu. A check mark beside a command indicates that the command has been chosen.

Syntax

CHECK.COMMAND(bar_num, menu, command, check, position)

Bar_num is the menu bar containing the command. Bar_num can be the ID number of a built-in or custom menu bar.

Menu is the menu containing the command. Menu can be either the name of a menu as text or the number of a menu. Menus are numbered starting with 1 from the left of the screen.

Command is the command you want to check or the submenu containing the command you want to check. Command can be the name of the command as text or the number of the command; the first command on a menu is in position 1.

Check is a logical value corresponding to the check mark. If check is TRUE, Microsoft Excel adds a check mark to the command; if FALSE, Microsoft Excel removes the check mark.

position is the name of a command on a submenu that you want to check.

Remarks

  • The check mark doesn't affect execution of the command. Microsoft Excel automatically adds and deletes check marks to some commands, such as the name of the active workbook in the Window menu. If you have assigned a check mark to a built-in command that Microsoft Excel automatically changes in response to the user's actions, the check mark will be added or removed as appropriate, and any check marks you have added or deleted with CHECK.COMMAND will be ignored.
  • If you use CHECK.COMMAND with a command on a Microsoft Excel 4.0 menu bar, the corresponding command on the Microsoft Excel 5.0 or later menu bar will not be effected.

Example

The following macro formula adds a check mark to the Sales command on the Weekly menu on a custom menu bar created by the ADD.BAR function in a cell named Reports:

CHECK.COMMAND(Reports, "Weekly", "Sales", TRUE)

Related Functions

ADD.COMMAND Adds a command to a menu

DELETE.COMMAND Deletes a command from a menu

ENABLE.COMMAND Enables or disables a menu or custom command

RENAME.COMMAND Changes the name of a command or menu

List of Customizing Functions


CLOSE.ALL

Macro Sheets Only

Equivalent to choosing the Close All command from the File menu. The Close All command appears when you hold down SHIFT while selecting the File menu. Closes all protected and unprotected windows and all hidden windows. If unsaved changes have been made to the workbook in one or more windows, a message is displayed asking if you want to save each workbook.

Syntax

CLOSE.ALL( )

Related Functions

CLOSE Closes the active window

FILE.CLOSE Closes the active workbook

QUIT Ends a Microsoft Excel session

SAVE Saves the active workbook

List of Command-Equivalent Functions


CREATE.NAMES

Macro Sheets Only

Equivalent to choosing the Create command from the Name submenu on the Insert menu. Use CREATE.NAMES to quickly create names from text labels on a sheet.

Arguments are logical values corresponding to check boxes in the Create Names dialog box. If an argument is TRUE, Microsoft Excel selects the check box; if FALSE or omitted, Microsoft Excel clears the check box.

Syntax

CREATE.NAMES(top, left, bottom, right)
CREATE.NAMES?(top, left, bottom, right)

Top corresponds to the Top Row check box.

Left corresponds to the Left Column check box.

Bottom corresponds to the Bottom Row check box.

Right corresponds to the Right Column check box.

Remarks

The cell containing the label text that Microsoft Excel uses to create the names is not included in the resulting named range.

Related Functions

APPLY.NAMES Replaces references and values with their corresponding names

DEFINE.NAME Defines a name on the active sheet or macro sheet

DELETE.NAME Deletes a name

FORMULA.GOTO Selects a named area or reference on any open workbook

List of Command-Equivalent Functions


CREATE.OBJECT

Macro Sheets Only

Draws an object on a sheet or macro sheet and returns a value identifying the object created. It is generally easier to use the macro recorder to enter this function on your macro sheet.

Syntax 1

Lines, rectangles, ovals, arcs, pictures, text boxes, and buttons

CREATE.OBJECT(obj_type, ref1, x_offset1, y_offset1, ref2, x_offset2, y_offset2, text, fill, editable)

Syntax 2

Polygons

CREATE.OBJECT(obj_type, ref1, x_offset1, y_offset1, ref2, x_offset2,
y_offset2, array, fill)

Syntax 3

Embedded charts

CREATE.OBJECT(obj_type, ref1, x_offset1, y_offset1, ref2, x_offset2,
y_offset2, xy_series, fill, gallery_num, type_num, plot_visible)

Obj_type is a number specifying the type of object to create.

Obj_type Object

1 Line

2 Rectangle

3 Oval

4 Arc

5 Embedded chart

6 Text box

7 Button

8 Picture (created with the camera tool)

9 Closed polygon

10 Open polygon

11 Check box

12 Option button

13 Edit box

14 Label

15 Dialog frame

16 Spinner

17 Scroll bar

18 List box

19 Group box

20 Drop down list box

Ref1 is a reference to the cell from which the upper-left corner of the object is drawn, or from which the upper-left corner of the object's bounding rectangle is defined.

X_offset1 is the horizontal distance from the upper-left corner of ref1 to the upper-left corner of the object or to the upper-left corner of the object's bounding rectangle. X_offset1 is measured in points. A point is 1/72nd of an inch. If x_offset1 is omitted, it is assumed to be 0.

Y_offset1 is the vertical distance from the upper-left corner of ref1 to the upper-left corner of the object or to the upper-left corner of the object's bounding rectangle. Y_offset1 is measured in points. If y_offset1 is omitted, it is assumed to be 0.

Ref2 is a reference to the cell from which the lower-right corner of the object is drawn, or from which the lower-right corner of the object's bounding rectangle is defined.

X_offset2 is the horizontal distance from the upper-left corner of ref2 to the lower-right corner of the object or to the lower-right corner of the object's bounding rectangle. X_offset2 is measured in points. If x_offset2 is omitted, it is assumed to be 0.

Y_offset2 is the vertical distance from the upper-left corner of ref2 to the lower-right corner of the object or to the lower-right corner of the object's bounding rectangle. Y_offset2 is measured in points. If y_offset2 is omitted, it is assumed to be 0.

Text specifies the text that appears in a text box or button. If text is omitted for a button, the button is named "Button n", where n is a number. If obj_type is not 6 or 7, text is ignored.

Fill is a logical value specifying whether the object is filled or transparent. If fill is TRUE, the object is filled; if FALSE, the object is transparent; if omitted, the object is filled with an applicable pattern for the object being created.

Array is an n by 2 array of values, or a reference to a range of cells containing values, that indicate the position of each vertex in a polygon, relative to the upper-left corner of the polygon's bounding rectangle.

  • A vertex is a point that is defined by a pair of coordinates in one row of array.
  • If the polygon contains many vertices, one array may not be sufficient to define it. If the number of characters in the formula exceeds 1024, you must include one or more EXTEND.POLYGON functions. If you're recording a macro, Microsoft Excel automatically records EXTEND.POLYGON functions as needed. For more information, see EXTEND.POLYGON.

Xy_series is a number from 0 to 3 that specifies how data is arranged in a chart and corresponds to options in the Paste Special dialog box.

Xy_series Result

0 Displays a dialog box if the selection is ambiguous

1 or omitted First row/column is the first data series

2 First row/column contains the category (x) axis labels

3 First row/column contains the x-values; the created chart is an xy (scatter) chart

  • Xy_series is ignored unless obj_type is 5 (chart).
  • If you want more control over how the data is arranged, use the plot_by, categories, and ser_titles arguments to the CHART.WIZARD function. For more information, see CHART.WIZARD.

Gallery_num is a number from 1 to 15 specifying the type of embedded chart you want to create.

Gallery_num Chart

1 Area

2 Bar

3 Column

4 Line

5 Pie

6 Radar

7 XY (scatter)

8 Combination

9 3-D area

10 3-D bar

11 3-D column

12 3-D line

13 3-D pie

14 3-D surface

15 Doughnut

Type_num is a number identifying a formatting option for a chart. The formatting options are shown in the dialog box of the AutoFormat command that corresponds to the type of chart you're creating. The first formatting option in any gallery is 1.

Plot_visible is a logical value that corresponds to the Plot Visible Cells Only checkbox in the Chart tab of the Options dialog box. If FALSE or omitted, all values are plotted.

Editable is a logical value that determines whether the drop down list box is editable or not. If TRUE, the drop down list box is editable. If FALSE, the drop down list box is not editable. If obj_type is not 20, this argument is ignored.

Remarks

  • CREATE.OBJECT returns the object identifier of the object it created. Object identifiers include text describing the object, such as "Text" or "Oval", and a number indicating the order in which the object was created. For example, CREATE.OBJECT returns "Oval 3" after creating an oval that is the third object in the workbook.
  • If the offsets are not specified, the object is drawn from the upper-left corner of ref1 to the upper-left corner of ref2.
  • If the object is not a picture and either ref1 or ref2 is omitted, CREATE.OBJECT returns the #VALUE! error value and does not create the object.
  • CREATE.OBJECT also selects the object.
  • You must use the COPY function before the CREATE.OBJECT function to create a chart or a picture.

Tip To assign a macro to an object, use the ASSIGN.TO.OBJECT function immediately after creating the object.

Related Functions

ASSIGN.TO.OBJECT Assigns a macro to an object

EXTEND.POLYGON Adds vertices to a polygon

FORMAT.MOVE Moves the selected object

FORMAT.SHAPE Inserts, moves, or deletes vertices of the selected polygon

FORMAT.SIZE Sizes an object

GET.OBJECT Returns information about an object

OBJECT.PROPERTIES Determines an object's relationship to underlying cells

TEXT.BOX Replaces text in a text box

List of Command-Equivalent Functions


CREATE.PUBLISHER

Macro Sheets Only

Equivalent to choosing the Create Publisher command from the Publishing submenu on the Edit menu. Publishes the selected range or chart to an edition file for use by other Macintosh applications.

Important This function is only available if you are using Microsoft Excel for the Macintosh with system software version 7.0 or later.

Syntax

CREATE.PUBLISHER(file_text, appearance, size, formats)
CREATE.PUBLISHER?(file_text, appearance, size, formats)

File_text is a text string to be used as the name of the new file that will contain the selected data. If file_text is omitted, Microsoft Excel uses the format "<WorkbookName> Edition #n", where WorkbookName is the name of the document from which the publisher is being created, Edition indicates that the file is an edition file, and n is a unique integer.

For example, if you omit file_text and are publishing a selection from a workbook named Seasonal, and it is your third publisher from that document in the current work session, the default name of the publisher would be "Seasonal Edition #3".

Appearance specifies whether the selection is to be published as shown on screen or as shown when printed. The default value for appearance is 1 if the selection is a sheet and 2 if the selection is a chart.

Appearance Selection is published

1 As shown on screen

2 As shown when printed

Size specifies the size at which to publish a chart. Size is only available if a chart is to be published.

Size Chart is published

1 or omitted As shown on screen

2 As shown when printed

Formats is number specifying what file format or formats CREATE.PUBLISHER should use when it creates the Edition file.

Formats File format

1 PICT

2 BIFF

4 RTF

8 VALU

  • You can also use the sum of the allowable file formats for formats. For example, a value of 6 specifies BIFF and RTF.
  • If formats is omitted and the document is a sheet, formats is assumed to be 15 (all formats); if the document is a chart, formats is assumed to be 1 (PICT).

Related Functions

EDITION.OPTIONS Sets publisher and subscriber options

GET.LINK.INFO Returns information about a link

SUBSCRIBE.TO Inserts contents of an edition into the active workbook

UPDATE.LINK Updates a link to another workbook

List of Command-Equivalent Functions


CUSTOM.REPEAT

Macro Sheets Only

Allows custom commands to be repeated using the Repeat tool or the Repeat command on the Edit menu. Also allows custom commands to be recorded using the macro recorder.

Syntax

CUSTOM.REPEAT(macro_text, repeat_text, record_text)

Macro_text is the name of, or a reference to, the macro you want to run when the Repeat command is chosen. If macro_text is omitted, no repeat macro is run, but the custom command can still be recorded.

Repeat_text is the text you want to use as the repeat command on the Edit menu (for example, "Repeat Reports"). You can omit repeat_text and macro_text if you only want to record the formula specified by record_text when using the macro recorder.

Record_text is the formula you want to record. For example, if the user chooses a command named Run Reports in Macro 1, the record_text argument would be "=Macro1!RunReports()", where RunReports is the name of the macro called by the Run Reports command.

  • References in record_text must be in R1C1 format.
  • If record_text is omitted, the macro recorder records normally (a RUN function with the first cell of the macro as its argument).
  • If you are not recording a macro, record_text is ignored.

Tip Place CUSTOM.REPEAT at the end of the macro you will want to repeat. If you place it before the end, then the macro formulas that follow CUSTOM.REPEAT may interfere with the desired effects of CUSTOM.REPEAT. The Repeat tool and the Repeat command continue to change as you choose subsequent commands that can be repeated.

Example

The following macro formula specifies that the macro RepeatReport on the MenuMacros macro sheet in the current workbook will be run when the Repeat Report command is chosen:

CUSTOM.REPEAT("MenuMacros!RepeatReport", "Repeat Report")

Related Function

CUSTOM.UNDO Specifies a macro to run to undo a custom command

List of Customizing Functions


CUSTOM.UNDO

Macro Sheets Only

Creates a customized Undo tool and Undo or Redo command on the Edit menu for custom commands.

Syntax

CUSTOM.UNDO(macro_text, undo_text)

Macro_text is the name of, or an R1C1-style reference to, the macro you want to run when the Undo command is chosen. Macro_text can be the name or cell reference of a macro.

Undo_text is the text you want to use as the Undo command.

Example

The following macro function runs the UndoMult macro when the user chooses the Undo Times100 command, a custom command that multiples the currect cell by 100.

=CUSTOM.UNDO("UndoMult", "&Undo Times100")

Tip Use CUSTOM.UNDO directly after the macro functions you want to be able to repeat, because other macro functions following CUSTOM.UNDO might reset the Undo command.

Related Function

CUSTOM.REPEAT Specifies a macro to run to repeat a custom command

List of Customizing Functions


DATA.SERIES

Macro Sheets Only

Equivalent to choosing the Series command from the Fill submenu on the Edit menu. Use DATA.SERIES to enter an interpolated or incrementally increasing or decreasing series of numbers or dates on a sheet or macro sheet.

Syntax

DATA.SERIES(rowcol, type_num, date_num, step_value, stop_value, trend)
DATA.SERIES?(rowcol, type_num, date_num, step_value, stop_value, trend)

Rowcol is a number that specifies where the series should be entered. If rowcol is omitted, the default value is based on the size and shape of the current selection.

Rowcol Enter series in

1 Rows

2 Columns

Type_num is a number from 1 to 4 that specifies the type of series.

Type_num Type of series

1 or omitted Linear

2 Growth

3 Date

4 AutoFill

Date_num is a number from 1 to 4 that specifies the date unit of the series, as shown in the following table. To use the date_num argument, the type_num argument must be 3.

Date_num Date unit

1 or omitted Day

2 Weekday

3 Month

4 Year

Step_value is a number that specifies the step value for the series. If step_value is omitted, it is assumed to be 1.

Stop_value is a number that specifies the stop value for the series. If stop_value is omitted, DATA.SERIES continues filling the series until the end of the selected range.

Trend is a logical value corresponding to the Trend check box. If trend is TRUE, Microsoft Excel generates a linear or exponential trend; if FALSE or omitted, Microsoft Excel generates a standard data series.

Remarks

  • If you specify a positive value for stop_value that is lower than the value in the active cell of the selection, DATA.SERIES takes no action.
  • If type_num is 4 (AutoFill), Microsoft Excel performs an AutoFill operation just as if you had filled the selection by dragging the fill selection handle or had used the FILL.AUTO macro function.

Related Function

FILL.AUTO Copies cells or automatically fills a selection

List of Command-Equivalent Functions


DEFINE.NAME

Macro Sheets Only

Equivalent to choosing the Define command from the Name submenu on the Insert menu. Defines a name on the active sheet or macro sheet. Use DEFINE.NAME instead of SET.NAME when you want to define a name on the active sheet.

Syntax

DEFINE.NAME(name_text, refers_to, macro_type, shortcut_text, hidden, category, local)
DEFINE.NAME?(name_text, refers_to, macro_type, shortcut_text, hidden, category, local)

Name_text is the text you want to use as the name. Names cannot include spaces, and cannot look like cell references.

Refers_to describes what name_text should refer to, and can be any of the following values.

If refers_to is Then name_text is

A number, text, or logical value | Defined to refer to that value
An external reference, such as !$A$1 or SALES!$A$1:$C$3 | Defined to refer to those cells
A formula in the form of text, such as "=2*PI()/360" (if the formula contains references, they must be R1C1-style references, such as "=R2C2*(1+RC[-1])") | Defined to refer to that formula
Omitted | Defined to refer to the current selection

The next two arguments, macro_type and shortcut_text, apply only if the sheet in the active window is a macro sheet.

Macro_type is a number from 1 to 3 that indicates the type of macro.

Macro_type Type of macro

1 Custom function (also known as a function macro)

2 Command macro.

3 or omitted None (that is, name_text does not refer to a macro)

Shortcut_text is a text value that specifies the macro shortcut key. Shortcut_text must be a single letter, such as "z" or "Z".

Hidden is a logical value specifying whether to define the name as a hidden name. If hidden is TRUE, Microsoft Excel defines the name as a hidden name; if FALSE or omitted, Microsoft Excel defines the name normally.

Category is a number or text identifying the category of a custom function and corresponds to categories in the Function Category list box.

  • Categories are numbered starting with 1, the first category in the list.
  • If category is text but is not one of the existing function types, Microsoft Excel creates a new category and assigns your custom function to it.

Local is a logical value which, if TRUE, defines the name on just the current sheet or macro sheet. If FALSE or omitted, defines the name for all sheets in the workbook.

Remarks

  • You can use hidden names to define values that you want to prevent the user from seeing or changing; they do not appear in the Define Name, Paste Name, or Goto dialog boxes. Hidden names can only be created with the DEFINE.NAME macro function.
  • If you are recording a macro and you define a name to refer to a formula, Microsoft Excel converts A1-style references to R1C1-style references. For example, if the active cell is C2, and you define the name Previous to refer to =B2, Microsoft Excel records that command as DEFINE.NAME("Previous","=RC[-1]").
  • In DEFINE.NAME?, the dialog-box form of the function, if refers_to is not specified, the current selection is proposed in the Refers To box. Also, if a name is not specified, text in the active cell is proposed as the name.

Related Functions

DELETE.NAME Deletes a name

GET.DEF Returns a name matching a definition

GET.NAME Returns the definition of a name

NAMES Returns the names defined in a workbook

SET.NAME Defines a name as a value

List of Command-Equivalent Functions


DELETE.ARROW

Macro Sheets Only

Deletes the selected arrow, either drawn as an arrow with the arrow tool or as a line that is later formatted as an arrow. In Microsoft Excel 5.0 or later, arrows are named lines.

Syntax

DELETE.ARROW( )

If the selection is not an arrow or a line formatted as an arrow, or if the active window is not a chart, DELETE.ARROW interrupts the macro.

Tip Use the SELECT function (chart syntax), with the number of the arrow (or line) you want to delete in order to select the arrow before using the DELETE.ARROW function. For example, SELECT ("Line 1"). You can also use the CLEAR function to delete the arrow.

Related Functions

CLEAR Clears specified information from the selected cells or chart

DELETE.OVERLAY Deletes the overlay on a chart

List of Command-Equivalent Functions


DELETE.CHART.AUTOFORMAT

Deletes a custom format from the list of formats shown in the AutoFormat dialog box for charts.

Syntax

DELETE.CHART.AUTOFORMAT(name_text)

Name_text is the template name you want to delete from the list of custom templates.

Related Functions

ADD.CHART.AUTOFORMAT Adds a custom template

List of Command-Equivalent Functions


DELETE.OVERLAY

Macro Sheets Only

Equivalent to choosing the Delete Overlay command from the Chart menu in Microsoft Excel 4.0. Deletes all overlays from a chart. If the chart has no overlay, DELETE.OVERLAY takes no action and returns TRUE.

Syntax

DELETE.OVERLAY( )

Related Functions

List of Command-Equivalent Functions


DEREF

Macro Sheets Only

Returns the value of the cells in a reference.

Syntax

DEREF(reference)

Reference is the cell or cells from which you want to obtain a value. If reference is the reference of a single cell, DEREF returns the value of that cell. If reference is the reference of a range of cells, DEREF returns the array of values in those cells. If reference refers to the active sheet, it must be an absolute reference. Relative references are converted to absolute references.

Remarks

In most formulas, there is no difference between using a value and using the reference of a cell containing that value. The reference is automatically converted to the value, as necessary. For example, if cell A1 contains the value 2, then the formula =A1+1, like the formula =2+1, returns the result 3, because the reference A1 is converted to the value 2. However, in a few functions, such as the SET.NAME function, references are not automatically converted to values. Instead, those functions behave differently depending on whether an argument is a reference or a value.

Example

See the sixth example for SET.NAME.

Related Functions

SET.NAME Defines a names as a value

List of Lookup & Reference Functions


DIALOG.BOX

Macro Sheets Only

Displays the dialog box described in a dialog box definition table.

Syntax

DIALOG.BOX(dialog_ref)

Dialog_ref is a reference to a dialog box definition table on sheet, or an array containing the definition table.

  • If an OK button in the dialog box is chosen, DIALOG.BOX enters values in fields as specified in the dialog_ref area and returns the position number of the button chosen. The position numbers start with 1 in the second row of the dialog box definition table.
  • If the Cancel button in the dialog box is chosen, DIALOG.BOX returns FALSE.

The dialog box definition table must be at least seven columns wide and two rows high. The definitions of each column in a dialog box definition table are listed in the following table.

Column type Column number

Item number 1

Horizontal position 2

Vertical position 3

Item width 4

Item height 5

Text 6

Initial value or result 7

The first row of dialog_ref defines the position, size, and name of the dialog box. It can also specify the default selected item and the reference for the Help button. The position is specified in columns 2 and 3, the size in columns 4 and 5, and the name in column 6. To specify a default item, place the item's position number in column 7. You can place the reference for the Help button in row 1, column 1 of the table, but the preferred location is column 7 in the row where the Help button is defined. Row 1, column 1 is usually left blank.

The following table lists the numbers for the items you can display in a dialog box.

Dialog-box item Item number

Default OK button 1

Cancel button 2

OK button 3

Default Cancel button 4

Static text 5

Text edit box 6

Integer edit box 7

Number edit box 8

Formula edit box 9

Reference edit box 10

Option button group 11

Option button 12

Check box 13

Group box 14

List box 15

Linked list box 16

Icons 17

Linked file list box (Microsoft Excel for Windows only) 18

Linked drive and directory box (Microsoft Excel for Windows only) 19

Directory text box 20

Drop-down list box 21

Drop-down combination edit/list box 22

Picture button 23

Help button 24

Remarks

  • Add 100 to an item number in the above table to define the item as a trigger. A trigger is a dialog box item that, when chosen, returns to your macro (as choosing OK would) but continues to display the dialog box, allowing your macro to change the dialog box definition or display an alert message or another dialog box. The Help button, edit boxes, group boxes, static text, and icons cannot be triggers.
  • Add 200 to an item number to define it as dimmed. A dimmed (gray) item cannot be chosen or selected. For example, 203 is a dimmed OK button. You can use item 223 to include a picture in your dialog box that does not behave like a button.
  • If a trigger has been chosen and you still want to clear a dynamic dialog box from the screen, use DIALOG.BOX(FALSE). This is useful if you want to confirm that the dialog box has been filled out correctly before dismissing it.
  • The dialog box definition table can be an array. If dialog_ref is an array instead of a reference, DIALOG.BOX returns a modified copy of that array, along with the results of the dialog box in the seventh column. (The first item in the seventh column is the position number of the chosen button or of a triggered item.) This is useful if you want to preserve the original dialog box definition table since DIALOG.BOX does not modify the original array argument. If you cancel the dialog box, or if a dialog box error occurs, DIALOG.BOX returns FALSE instead of an array.

Related Functions

ALERT Displays a dialog box and a message

INPUT Displays a dialog box for user input

List of Customizing Functions


DIRECTORY

Macro Sheets Only

Sets the current drive and directory or folder to the specified path and returns the name of the new directory or folder as text. Use DIRECTORY to get the name of the current directory or folder for use with the OPEN and SAVE.AS functions or to specify a directory or folder from which to return a list of files with the FILES function.

Syntax

DIRECTORY(path_text)

Path_text is the drive and directory or folder you want to change to.

  • If path_text is not specified, DIRECTORY returns the name of the current directory or folder as text.
  • If path_text does not include a drive specifier, the current drive is assumed.

Examples

In Microsoft Excel for Windows, the following macro formula sets the directory to \EXCEL\MODELS on the current drive and returns the value "drive:\EXCEL\MODELS":

DIRECTORY("\EXCEL\MODELS")

The following macro formula sets the current drive to E and sets the directory to \EXCEL\MODELS on E. It returns the value "E:\EXCEL\MODELS":

DIRECTORY("E:\EXCEL\MODELS")

In Microsoft Excel for the Macintosh, the following macro formula sets the folder to HARD DISK: APPS:EXCEL:FINANCIALS and returns the value "HARD DISK:APPS:EXCEL:FINANCIALS":

DIRECTORY("HARD DISK:APPS:EXCEL:FINANCIALS")

Related Functions

FILES Returns the filenames in the specified directory or folder

List of Information Functions


DISABLE.INPUT

Macro Sheets Only

Blocks all input from the keyboard and mouse to Microsoft Excel (except input to displayed dialog boxes). Use DISABLE.INPUT to prevent input from the user or from other applications.

Syntax

DISABLE.INPUT(logical)

Logical is a logical value specifying whether input is currently disabled. If logical is TRUE, input is disabled; if FALSE, input is reenabled.

Remarks

Disabling input can be useful if you are using dynamic data exchange (DDE) to communicate with Microsoft Excel from another application.

Important Be sure to end any macro that uses DISABLE.INPUT(TRUE) with a DISABLE.INPUT(FALSE) function. If you do not include DISABLE.INPUT(FALSE) to allow non-dialog-box input, you will not be able to take any actions on your computer after the macro has finished.

Related Functions

CANCEL.KEY Disables macro interruption

ENTER.DATA Turns Data Entry mode on and off

WORKSPACE Changes workspace settings

List of Customizing Functions


EDIT.COLOR

Macro Sheets Only

Equivalent to choosing the Modify button from the Color tab, which appears when you choose the Options command from the Tools menu. Defines the color for one of the 56 color palette boxes.

Use EDIT.COLOR if you want to use a color that is not currently on the palette and if your system hardware has more than 56 colors available. After you set the color for the color box, any items previously formatted with that color are displayed in the new color.

Syntax

EDIT.COLOR(color_num, red_value, green_value, blue_value)
EDIT.COLOR?(color_num, red_value, green_value, blue_value)

Color_num is a number from 1 to 56 specifying one of the 56 color palette boxes for which you want to set the color.

Red_value, green_value, and blue_value are numbers that specify how much red, green, and blue are in each color.

  • In Microsoft Excel for Windows, red_value, green_value, and blue_value are numbers from 0 to 255.
  • In Microsoft Excel for the Macintosh, red_value, green_value, and blue_value are also numbers from 0 to 255. However, the color editing dialog box displays numbers from 0 to 65, 535. Microsoft Excel automatically converts the numbers between the two ranges. This allows you to display similar colors in all operating environments without modifying your macros.
  • If red_value, green_value, and blue_value are all set to 255, the resulting color is white. If they are all set to zero, the resulting color is black.
  • If red_value, green_value, or blue_value is omitted, Microsoft Excel assumes it to be the appropriate value for that color_num.

Remarks

  • Your system hardware determines the number of unique colors that you can choose from and the number of colors that can be displayed on the screen at the same time.
  • EDIT.COLOR does not use hue, saturation, or brightness values. If you are using the macro recorder and set the color of a color palette box using hue, saturation, and luminance, Microsoft Excel records the corresponding red, green, and blue values instead.
  • The dialog-box form of this function, EDIT.COLOR?(color_num), displays your system's color editing dialog box. The default red_value, green_value, and blue_value are determined by the current settings for the color_num you specify. Color_num is a required argument for the dialog-box form of this function.

Related Function

COLOR.PALETTE Copies a color palette from one workbook to another

List of Command-Equivalent Functions


EDIT.REPEAT

Macro Sheets Only

Equivalent to choosing the Repeat command from the Edit menu. Repeats certain actions and commands. EDIT.REPEAT is available in the same situations as the Repeat command.

Syntax

EDIT.REPEAT( )

Related Functions

List of Command-Equivalent Functions


EDIT.SERIES

Macro Sheets Only

Equivalent to choosing the Edit Series command from the Chart menu in Microsoft Excel version 4.0. Creates or changes chart series by adding a new SERIES formula or modifying an existing SERIES formula in the topmost chart type. Chart types are displayed in the following order from top to bottom: XY (Scatter), Line, Column, Bar, Area.

Syntax

EDIT.SERIES(series_num, name_ref, x_ref, y_ref, z_ref, plot_order)
EDIT.SERIES?(series_num, name_ref, x_ref, y_ref, z_ref, plot_order)

Series_num is the number of the series you want to change. If series_num is 0 or omitted, Microsoft Excel creates a new data series.

Name_ref is the name of the data series. It can be an external reference to a single cell, a name defined as a single cell, or a name defined as a sequence of characters. Name_ref can also be text (for example, "Projected Sales").

X_ref is an external reference to the name of the sheet and the cells that contain one of the following sets of data:

  • Category labels for all charts except xy (scatter) charts
  • X-coordinate data for xy (scatter) charts

Y_ref is an external reference to the name of the sheet and the cells that contain values (or y-coordinate data in xy (scatter) charts) for all 2-D charts. Y_ref is required in 2-D charts but does not apply to 3-D charts.

Z_ref is an external reference to the name of the sheet and the cells that contain values for all 3-D charts. Z_ref is required in 3-D charts but does not apply to 2-D charts.

Plot_order is a number specifying whether the data series is plotted first, second, and so on, in the chart type.

  • If you assign a plot_order to a series, Microsoft Excel plots that series in the order you specify, and the series that previously had that plot order (and any series following it) has its plot order increased by one.
  • If you add a series to a chart with an overlay, the number of series in the main chart does not change, so if the series is added to the main chart, then the series that was plotted last in the main chart will be plotted first in the overlay chart. To change which series is plotted first in the overlay chart, use the (chart type) Group command from the Format menu, and then select the Series Order tab in the Format (chart type) Group dialog box. You can also use the FORMAT.OVERLAY function.
  • If you omit plot_order when you add a new series, then Microsoft Excel plots that series last and assigns it the correct plot_order value.
  • The maximum value for plot_order is 255.

Remarks

To change where a series is plotted within a chart, you can change the chart type, using the FORMAT.CHART function, or the plot order. Plot order affects where the series appears within the chart type only.

X_ref, y_ref, and z_ref can be arrays or references to a nonadjacent selection, although they cannot be names that refer to a nonadjacent selection. If you specify a nonadjacent selection for any of these arguments, make sure to enclose the reference to the selection in parentheses so that Microsoft Excel does not treat the components of the references as separate arguments.

Tip To delete a data series, use the SELECT("Sn") macro function, where n is the series number, followed by the FORMULA("") macro function. You can also use the CLEAR function instead of FORMULA.

Related Functions

FORMAT.CHART

List of Command-Equivalent Functions


ENTER.DATA

Macro Sheets Only

Turns on Data Entry mode and allows you to select and to enter data into the unlocked cells in the current selection only (the data entry area). Use ENTER.DATA when you want to enter data only in a specific part of your sheet. You can then use that part of the sheet as a simple data form.

Syntax

ENTER.DATA(logical)

Logical is a logical value that turns Data Entry mode on or off.

  • If logical is TRUE, Data Entry mode is turned on; if FALSE, Data Entry mode is turned off and data entry, cell movement, and cell selection return to normal. If logical is omitted, ENTER.DATA toggles Data Entry mode.
  • Logical can also be the number 2. This setting turns on Data Entry mode and prevents the ESC key from turning it off.
  • Logical can also be a reference. Using a reference for this argument turns on Data Entry mode for the supplied reference.

Remarks

  • In Data Entry mode, you can move the active cell and select cell ranges only in the data entry area. The arrow keys and the TAB and SHIFT+TAB keys move from one unlocked cell to the next. The HOME and END keys move to the first and last cell in the data entry area, respectively. You cannot select entire rows or columns, and clicking a cell outside the data entry area does not select it.
  • The only commands available in Data Entry mode are commands normally available to protected workbooks.
  • To turn off Data Entry mode, press ESC (unless logical is 2), activate another sheet in the active workbook window, or use another ENTER.DATA function. If you use another ENTER.DATA function, you will usually design your macros in one of two ways:
  • The macro turns on Data Entry mode, pauses while you enter data, resumes, and then turns off Data Entry mode.
  • The macro turns on Data Entry mode and ends. After entering data, another macro turns off Data Entry mode; this latter macro could be assigned to a "Finished" button, for example.

    With either method, you can use Microsoft Excel's ON functions to resume or run other macros based on an event, such as pressing the CONTROL+D keys.

Tips

  • Normally you use Data Entry mode to enter data, but you can also prevent someone from entering data or moving the active cell by locking all the cells in the current selection before turning on Data Entry mode. This is useful if you want a user to view a range of cells but not change it or move the active cell. Similarly, if you unlock certain cells, you can restrict the user's movement to the Data Entry area only.
  • To prevent someone from activating another workbook, which would turn off Data Entry mode, use the ON.WINDOW function or an Auto_Deactivate macro.

Related Function

DISABLE.INPUT Blocks all input to Microsoft Excel

FORMULA Enters values into a cell or range or onto a chart

List of Command-Equivalent Functions


EVALUATE

Macro Sheets Only

Evaluates a formula or expression that is in the form of text and returns the result. To run a macro or subroutine, use the RUN function.

Syntax

EVALUATE(formula_text)

Formula_text is the expression in the form of text that you want to evaluate.

Remarks

Using EVALUATE is similar to selecting an expression within a formula in the formula bar and pressing the Recalculate key (F9 in Microsoft Excel for Windows and COMMAND+= in Microsoft Excel for the Macintosh). EVALUATE replaces an expression with a value.

Example

Suppose you want to know the value of a cell named LabResult1, LabResult2, or LabResult3, where the 1, 2, or 3 is specified by the name TrialNum whose value may change as the macro runs. You can use the following formula to calculate the value:

EVALUATE("LabResult"&TrialNum)

Related Functions

RUN Runs a macro

List of Command-Equivalent Functions


FILES

Macro Sheets Only

Returns a horizontal text array of the names of all files in the specified directory or folder. Use FILES to build a list of filenames upon which you want your macro to operate.

Syntax

FILES(directory_text)

Directory_text specifies which directories or folders to return filenames from.

  • Directory_text accepts an asterisk (*) to represent a series of characters and a question mark (?) to represent a single character in filenames.
  • If directory_text is not specified, FILES returns filenames from the current directory.

Remarks

If you enter FILES in a single cell, only one filename is returned. You will normally use FILES with SET.NAME to assign the returned array to a name. See the last example below.

Tips You can use COLUMNS to count the number of entries in the returned array. You can use TRANSPOSE to change a horizontal array to a vertical one.

Examples

In Microsoft Excel for Windows, the following macro formula returns the names of all files starting with the letter F in the current directory or folder:

FILES("F*.*")

When entered as an array formula in several cells, the following macro formula returns the filenames in the current directory to those cells. If the directory contains fewer files than can fit in the selected cells, the #N/A error value appears in the extra cells.

FILES()

In Microsoft Excel for Windows, the following macro formula returns all files starting with "SALE" and ending with the .XLC extension in the \EXCEL\CHARTS subdirectory:

FILES("C:\EXCEL\CHARTS\SALE*.XLC")

In Microsoft Excel for the Macintosh, the following macro formula returns all files starting with "SALE" in the nested CHART folder:

FILES("DISK:EXCEL:CHART:SALE*")

The following macro stores the names of the files in the current directory in the named array FileArray

SET.NAME("FileArray",FILES())

Related Functions

DOCUMENTS Returns the names of the specified open workbooks

FILE.DELETE Deletes a file

OPEN Opens a workbook

SET.NAME Defines a name as a value

List of Information Functions


FILL.DOWNFILL.LEFTFILL.RIGHTFILL.UP

FILL.DOWN
FILL.LEFT
FILL.RIGHT
FILL.UP

Macro Sheets Only

Equivalent to choosing the Down, Left, Right, and Up commands, respectively, from the Fill submenu on the Edit menu.

Syntax

FILL.DOWN( )
FILL.LEFT( )
FILL.RIGHT( )
FILL.UP( )

FILL.DOWN copies the contents and formats of the cells in the top row of a selection into the rest of the rows in the selection.

FILL.LEFT copies the contents and formats of the cells in the right column of a selection into the rest of the columns in the selection.

FILL.RIGHT copies the contents and formats of the cells in the left column of a selection into the rest of the columns in the selection.

FILL.UP copies the contents and formats of the cells in the bottom row of a selection into the rest of the rows in the selection.

Remarks

If you have a multiple selection, each range in the selection is filled separately with the contents of the source range.

Related Functions

COPY Copies and pastes data or objects

DATA.SERIES Fills a range of cells with a series of numbers or dates

FILL.AUTO Copies cells or automatically fills a selection

FORMULA.FILL Enters a formula in the specified range

List of Command-Equivalent Functions


FORMAT.LEGEND

Macro Sheets Only

Equivalent to choosing the Selected Legend command from the Format menu when a chart is active. Determines the position and orientation of the legend on a chart and returns TRUE; returns an error message if the legend is not already selected.

Syntax

FORMAT.LEGEND(position_num)
FORMAT.LEGEND?(position_num)

Position_num is a number from 1 to 5 specifying the position of the legend.

Position_num Position of legend

1 Bottom

2 Corner

3 Top

4 Right

5 Left

Related Functions

FORMAT.MOVE Moves the selected object

FORMAT.SIZE Sizes an object

LEGEND Adds or deletes a chart legend

List of Command-Equivalent Functions


FORMAT.MAIN

Macro Sheets Only

Equivalent to choosing the Main Chart command from the Format menu in Microsoft Excel version 4.0. Formats a chart according to the arguments you specify. This function is included for compatibility with Microsoft Excel 4.0. In Microsoft Excel 5.0 or later, this is equivalent to choosing the Chart Type command from the Format menu. You can also use the FORMAT.CHART function.

Syntax

FORMAT.MAIN(type_num, view, overlap, gap_width, vary, drop, hilo, angle, gap_depth, chart_depth, up_down, series_line, labels, doughnut_size)
FORMAT.MAIN?(type_num, view, overlap, gap_width, vary, drop, hilo, angle, gap_depth, chart_depth, up_down, series_line, labels, doughnut_size)

Type_num is a number specifying the type of chart.

Type_num Chart

1 Area

2 Bar

3 Column

4 Line

5 Pie

6 XY (Scatter)

7 3-D Area

8 3-D Column

9 3-D Line

10 3-D Pie

11 Radar

12 3-D Bar

13 3-D Surface

14 Doughnut

View is a number specifying one of the views in the Data View box in the Main Chart dialog box. The view varies depending on the type of chart.

Overlap is a number from -100 to 100 specifying how you want bars or columns to be positioned. It corresponds to the Overlap box in the Main Chart dialog box. Overlap is ignored if type_num is not 2 or 3 (bar or column chart).

  • If overlap is positive, it specifies the percentage of overlap you want for bars or columns. For example, 50 would cause one-half of a bar or column to be covered by an adjacent bar or column. A value of zero prevents bars or columns from overlapping.
  • If overlap is negative, then bars or columns are separated by the specified percentage of the maximum available distance between any two bars or columns.
  • If overlap is omitted, it is assumed to be 0 (bars or columns do not overlap), or it is unchanged if a value was previously set.

Gap_width is a number from 0 to 500 specifying the space between bar or column clusters as a percentage of the width of a bar or column. It corresponds to the Gap Width box in the Main Chart dialog box.

  • Gap_width is ignored if type_num is not 2, 3, 8, or 12 (bar or column chart).
  • If gap_width is omitted, it is assumed to be 50, or it is unchanged if a value was previously set.

Several of the following arguments are logical values corresponding to check boxes in the Main Chart dialog box. If an argument is TRUE, Microsoft Excel selects the corresponding check box; if FALSE, Microsoft Excel clears the check box. If an argument is omitted, the setting is unchanged.

Vary corresponds to the Vary By Categories check box. Vary applies only to charts with one data series and is not available for area charts.

Drop corresponds to the Drop Lines check box. Drop is available only for area and line charts.

Hilo corresponds to the Hi-Lo Lines check box. Hilo is available only for line charts.

Angle is a number from 0 to 360 specifying the angle of the first pie slice (in degrees) if the chart is a pie chart. If angle is omitted, it is assumed to be 0, or it is unchanged if a value was previously set.

The next two arguments are for 3-D charts only.

Gap_depth is a number from 0 to 500 specifying the depth of the gap in front of and behind a bar, column, area, or line as a percentage of the depth of the bar, column, area, or line.

  • Gap_depth is ignored if the chart is a pie chart or if it is not a 3-D chart.
  • If gap_depth is omitted and the chart is a 3-D chart, gap_depth is assumed to be 50, or it is unchanged if a value was previously set. If gap_depth is omitted and the view is side-by-side, stacked, or stacked 100%, gap_depth is assumed to be 0, or it is unchanged if a value was previously set.

Chart_depth is a number from 20 to 2000 specifying the visual depth of the chart as a percentage of the width of the chart. Chart_depth corresponds to the Chart Depth box in the Main Chart dialog box.

  • Chart_depth is ignored if the chart is not a 3-D chart.
  • If chart_depth is omitted, it is assumed to be 100, or it is unchanged if a value was previously set.

The next three arguments are logical values corresponding to check boxes in the Main Chart dialog box. If an argument is TRUE, Microsoft Excel selects the corresponding check box; if FALSE, Microsoft Excel clears the check box. If an argument is omitted, the setting is unchanged. The final argument is for compatibility with Microsoft Excel 4.0.

Up_down corresponds to the Up/Down Bars check box. Up_down is available only for line charts.

Series_line corresponds to the Series Lines check box. Series_line is available only for stacked bar and column charts.

Labels corresponds to the Radar Axis Labels check box. Labels is available only for radar charts.

Doughnut_size specifies the size of the hole in a doughnut chart. Can be a value from 10% - 90%. Default is 50%

Related Function

FORMAT.CHART Formats a chart

FORMAT.OVERLAY Formats an overlay chart

List of Command-Equivalent Functions


FORMAT.OVERLAY

Macro Sheets Only

Equivalent to choosing the Overlay command from the Format menu in Microsoft Excel version 4.0. Formats the overlay chart according to the arguments you specify.

Syntax

FORMAT.OVERLAY(type_num, view, overlap, gap_width, vary, drop, hilo, angle, series_dist, series_num, up_down, series_line, labels)
FORMAT.OVERLAY?(type_num, view, overlap, gap_width, vary, drop, hilo, angle, series_dist, series_num, up_down, series_line, labels)

Type_num is a number specifying the type of chart.

Type_num Chart

1 Area

2 Bar

3 Column

4 Line

5 Pie

6 XY (Scatter)

11 Radar

14 Doughnut

View is a number specifying one of the views in the Data View box in the Overlay dialog box. The view varies depending on the type of chart.

Overlap is a number from -100 to 100 specifying how you want bars or columns to be positioned. It corresponds to the Overlap box in the Overlay dialog box. Overlap is ignored if type_num is not 2 or 3 (bar or column chart).

  • If overlap is positive, it specifies the percentage of overlap you want for bars or columns. For example, 50 would cause one-half of a bar or column to be covered by an adjacent bar or column.
  • If overlap is negative, then bars or columns are separated by the specified percentage of the maximum available distance between any two bars or columns.
  • If overlap is omitted, it is assumed to be 0 (bars or columns do not overlap), or it is unchanged if a value was previously set.

Gap_width is a number from 0 to 500 specifying the space between bar or column clusters as a percentage of the width of a bar or column.

  • Gap_width is ignored if type_num is not 2 or 3 (bar or column chart).
  • If gap_width is omitted, it is assumed to be 50, or it is unchanged if a value was previously set.

Several of the following arguments are logical values corresponding to check boxes in the Overlay dialog box. If an argument is TRUE, Microsoft Excel selects the corresponding check box; if FALSE, Microsoft Excel clears the check box. If an argument is omitted, the setting is unchanged.

Vary corresponds to the Vary By Categories check box. Vary is not available for area charts.

Drop corresponds to the Drop Lines check box. Drop is available only for area and line charts.

Hilo corresponds to the Hi-Lo Lines check box. Hilo is available only for line charts.

Angle is a number from 0 to 360 specifying the angle of the first pie slice (in degrees) if the chart is a pie chart. If angle is omitted, it is assumed to be 0, or it is unchanged if a value was previously set.

Series_dist is the number 1 or 2 and specifies automatic or manual series distribution.

  • If series_dist is 1 or omitted, Microsoft Excel uses automatic series distribution.
  • If series_dist is 2, Microsoft Excel uses manual series distribution, and you must specify which series is first in the distribution by using the series_num argument.

Series_num is the number of the first series in the overlay chart and corresponds to the First Overlay Series box in the Overlay dialog box. If series_dist is 1 (automatic series distribution), this argument is ignored.

Up_down corresponds to the Up/Down Bars check box. Up_down is available only for line charts.

Series_line corresponds to the Series Lines check box. Series_line is available only for stacked bar and column charts.

Labels corresponds to the Radar Axis Labels check box. Labels is available only for radar charts.

Related Functions

DELETE.OVERLAY Deletes the overlay on a chart

FORMAT.CHART Formats a chart

List of Command-Equivalent Functions


FORMULA.CONVERT

Macro Sheets Only

Changes the style and type of references in a formula between A1 and R1C1 and between relative and absolute. Use FORMULA.CONVERT to convert references of one style or type to another style or type.

Syntax

FORMULA.CONVERT(formula_text, from_a1, to_a1, to_ref_type, rel_to_ref)

Formula_text is the formula, given as text, containing the references you want to change. Formula_text must be a valid formula, and an equal sign must be included.

From_a1 is a logical value specifying whether the references in formula_text are in A1 or R1C1 style. If from_a1 is TRUE, references are in A1 style; if FALSE, references are in R1C1 style.

To_a1 is a logical value specifying the form for the references FORMULA.CONVERT returns. If to_a1 is TRUE, references are returned in A1 style; if FALSE, references are returned in R1C1 style. If to_a1 is omitted, the reference style is not changed.

To_ref_type is a number from 1 to 4 specifying the reference type of the returned formula. If to_ref_type is omitted, the reference type is not changed.

To_ref_type Reference type returned

1 Absolute

2 Absolute row, relative column

3 Relative row, absolute column

4 Relative

Rel_to_ref is an absolute reference that specifies what cell the relative references are or should be relative to.

Examples

Use FORMULA.CONVERT to convert relative references entered by the user in an INPUT function or custom dialog box into absolute references. The following macro formula converts the given formula to an absolute, R1C1-style reference:

FORMULA.CONVERT("=A1:A10", TRUE, FALSE, 1) equals "=R1C1:R10C1"

The following macro formula converts the references in the given formula to relative, A1-style references:

FORMULA.CONVERT("=SUM(R10C2:R15C2)", FALSE, TRUE, 4) equals "=SUM(B10:B15)"

Tip To put the converted formula into a cell or range of cells, use the FORMULA.CONVERT function as the formula_text argument to the FORMULA function.

Related Functions

ABSREF Returns the absolute reference of a range of cells to another range

FORMULA Enters values into a cell or range or onto a chart

RELREF Returns a relative reference

List of Command-Equivalent Functions


FREEZE.PANES

Macro Sheets Only

Equivalent to choosing the Freeze Panes or Unfreeze Panes commands from the Window menu or clicking the Freeze Panes or Unfreeze Panes button. Splits the active window into panes, creates frozen panes, or freezes or unfreezes existing panes. Use FREEZE.PANES to keep row or column titles on the screen while scrolling to other parts of the sheet.

Syntax

FREEZE.PANES(logical, col_split, row_split)

Logical is a logical value specifying which command FREEZE.PANES is equivalent to.

  • If logical is TRUE, the function is equivalent to the Freeze Panes command. It freezes panes if they exist, or creates them, splits them at the specified position, and freezes them if they do not exist. If the panes are already frozen, FREEZE.PANES takes no action.
  • If logical is FALSE, the function is equivalent to the Unfreeze Panes command. If no panes exist, FREEZE.PANES takes no action.
  • If logical is omitted, FREEZE.PANES creates and then freezes panes if no panes exist, freezes existing panes if they're not currently frozen, or unfreezes existing panes if they're currently frozen.

Col_split specifies where to split the window vertically and is measured in columns from the left of the window.

Row_split specifies where to split the window horizontally and is measured in rows from the top of the window.

Col_split and row_split are ignored unless logical is TRUE and split panes do not exist.

Remarks

To create panes without freezing or unfreezing them, use the SPLIT function. You can freeze the panes later using the FREEZE.PANES function.

Related Functions

ACTIVATE Switches to a window

SPLIT Splits a window

List of Command-Equivalent Functions


GALLERY.3D.AREA

Macro Sheets Only

Equivalent to choosing a 3-D Area template from the AutoFormat dialog box when a chart is active. Changes the format of the active chart to a 3-D area chart.

Syntax

GALLERY.3D.AREA(type_num)
GALLERY.3D.AREA?(type_num)

Type_num is the number of the 3-D Area format that you want to apply to the chart.

Related Functions

List of Command-Equivalent Functions


GALLERY.3D.BAR

Macro Sheets Only

Equivalent to choosing a 3-D Bar template from the AutoFormat dialog box when a chart is active. Changes the active chart to a 3-D bar chart.

Syntax

GALLERY.3D.BAR(type_num)
GALLERY.3D.BAR?(type_num)

Type_num is the number of the 3-D Bar format that you want to apply to the chart.

Related Functions

List of Command-Equivalent Functions


GALLERY.3D.COLUMN

Macro Sheets Only

Equivalent to choosing a 3-D Column template from the AutoFormat dialog box when a chart is active. Changes the format of the active chart to a 3-D column chart.

Syntax

GALLERY.3D.COLUMN(type_num)
GALLERY.3D.COLUMN?(type_num)

Type_num is the number of the 3-D Column format that you want to apply to the chart.

Related Functions

List of Command-Equivalent Functions


GALLERY.3D.LINE

Macro Sheets Only

Equivalent to choosing a 3-D Line template from the AutoFormat dialog box when a chart is active. Changes the format of the active chart to a 3-D line chart.

Syntax

GALLERY.3D.LINE(type_num)
GALLERY.3D.LINE?(type_num)

Type_num is the number of the 3-D Line format that you want to apply to the chart.

Related Functions

List of Command-Equivalent Functions


GALLERY.3D.PIE

Macro Sheets Only

Equivalent to choosing a 3-D Pie template from the AutoFormat dialog box when a chart is active. Changes the format of the active chart to a 3-D pie chart.

Syntax

GALLERY.3D.PIE(type_num)
GALLERY.3D.PIE?(type_num)

Type_num is the number of the 3-D Pie format that you want to apply to the chart.

Related Functions

List of Command-Equivalent Functions


GALLERY.3D.SURFACE

Macro Sheets Only

Equivalent to choosing a 3-D Surface template from the AutoFormat dialog box when a chart is active. Changes the active chart to a 3-D surface chart.

Syntax

GALLERY.3D.SURFACE(type_num)
GALLERY.3D.SURFACE?(type_num)

Type_num is the number of the 3-D Surface format that you want to apply to the chart.

Related Functions

List of Command-Equivalent Functions


GALLERY.AREA

Macro Sheets Only

Equivalent to choosing an Area template from the AutoFormat dialog box when a chart is active. Changes the format of the active chart to an area chart.

Syntax

GALLERY.AREA(type_num, delete_overlay)
GALLERY.AREA?(type_num, delete_overlay)

Type_num is the number of a format in the AutoFormat dialog box when a chart is active dialog box that you want to apply to the area chart.

Delete_overlay is a logical value specifying whether to delete an overlay chart.

  • If delete_overlay is TRUE, Microsoft Excel deletes all overlays, if present, and applies the new format to the main chart.
  • If delete_overlay is FALSE or omitted, Microsoft Excel applies the new format to either the main chart or the overlay, depending on the location of the selected series.

Related Functions

List of Command-Equivalent Functions


GALLERY.BAR

Macro Sheets Only

Equivalent to choosing a Bar template from the AutoFormat dialog box when a chart is active. Changes the format of the active chart to a bar chart.

Syntax

GALLERY.BAR(type_num, delete_overlay)
GALLERY.BAR?(type_num, delete_overlay)

Type_num is the number of a format in the AutoFormat dialog box when a chart is active dialog box that you want to apply to the bar chart.

Delete_overlay is a logical value specifying whether to delete an overlay chart.

  • If delete_overlay is TRUE, Microsoft Excel deletes all overlays, if present, and applies the new format to the main chart.
  • If delete_overlay is FALSE or omitted, Microsoft Excel applies the new format to either the main chart or the overlay, depending on the location of the selected series.

Related Functions

List of Command-Equivalent Functions


GALLERY.COLUMN

Macro Sheets Only

Equivalent to choosing a Column template from the AutoFormat dialog box when a chart is active. Changes the format of the active chart to a column chart.

Syntax

GALLERY.COLUMN(type_num, delete_overlay)
GALLERY.COLUMN?(type_num, delete_overlay)

Type_num is the number of a format in the AutoFormat dialog box when a chart is active dialog box that you want to apply to the column chart.

Delete_overlay is a logical value specifying whether to delete an overlay chart.

  • If delete_overlay is TRUE, Microsoft Excel deletes all overlays, if present, and applies the new format to the main chart.
  • If delete_overlay is FALSE or omitted, Microsoft Excel applies the new format to either the main chart or the overlay, depending on the location of the selected series.

Related Functions

List of Command-Equivalent Functions


GALLERY.CUSTOM

Macro Sheets Only

Equivalent to choosing a custom format from the AutoFormat dialog box when a chart is active. Changes the format of the active chart to the custom format.

Syntax

GALLERY.CUSTOM(name_text)

Name_text is the name of the custom template you want to apply.

Related Functions

ADD.CHART.AUTOFORMAT Formats a chart using a custom gallery

DELETE.CHART.AUTOFORMAT Deletes a custom gallery

List of Command-Equivalent Functions


GALLERY.DOUGHNUT

Macro Sheets Only

Equivalent to choosing a Doughnut template from the AutoFormat dialog box when a chart is active. Changes the format of the active chart to a doughnut chart.

GALLERY.DOUGHNUT(type_num, delete_overlay)
GALLERY.DOUGHNUT?(type_num, , delete_overlay)

Type_num is the number of a format in the AutoFormat dialog box when a chart is active dialog box that you want to apply to the doughnut chart.

Delete_overlay is a logical value specifying whether to delete an overlay chart.

  • If delete_overlay is TRUE, Microsoft Excel deletes all overlays, if present, and applies the new format to the main chart.
  • If delete_overlay is FALSE or omitted, Microsoft Excel applies the new format to either the main chart or the overlay, depending on the location of the selected series.

Related Functions

List of Command-Equivalent Functions


GALLERY.LINE

Macro Sheets Only

Equivalent to choosing a Line template from the AutoFormat dialog box when a chart is active. Changes the format of the active chart to a line chart.

Syntax

GALLERY.LINE(type_num, delete_overlay)
GALLERY.LINE?(type_num, delete_overlay)

Type_num is the number of a format in the AutoFormat dialog box when a chart is active dialog box that you want to apply to the line chart.

Delete_overlay is a logical value specifying whether to delete an overlay chart.

  • If delete_overlay is TRUE, Microsoft Excel deletes all overlays, if present, and applies the new format to the main chart.
  • If delete_overlay is FALSE or omitted, Microsoft Excel applies the new format to either the main chart or the overlay, depending on the location of the selected series.

Related Functions

List of Command-Equivalent Functions


GALLERY.PIE

Macro Sheets Only

Equivalent to choosing a Pie template from the AutoFormat dialog box when a chart is active. Changes the format of the active chart to a pie chart.

Syntax

GALLERY.PIE(type_num, delete_overlay)
GALLERY.PIE?(type_num, delete_overlay)

Type_num is the number of a format in the AutoFormat dialog box when a chart is active dialog box that you want to apply to the pie chart.

Delete_overlay is a logical value specifying whether to delete an overlay chart.

  • If delete_overlay is TRUE, Microsoft Excel deletes all overlays, if present, and applies the new format to the main chart.
  • If delete_overlay is FALSE or omitted, Microsoft Excel applies the new format to either the main chart or the overlay, depending on the location of the selected series.

Related Functions

List of Command-Equivalent Functions


GALLERY.RADAR

Macro Sheets Only

Equivalent to choosing a Radar template from the AutoFormat dialog box when a chart is active. Changes the format of the active chart to a radar chart.

Syntax

GALLERY.RADAR(type_num, delete_overlay)
GALLERY.RADAR?(type_num, delete_overlay)

Type_num is the number of a format in the AutoFormat dialog box when a chart is active dialog box that you want to apply to the radar chart.

Delete_overlay is a logical value specifying whether to delete an overlay chart.

  • If delete_overlay is TRUE, Microsoft Excel deletes all overlays, if present, and applies the new format to the main chart.
  • If delete_overlay is FALSE or omitted, Microsoft Excel applies the new format to either the main chart or the overlay, depending on the location of the selected series.

Related Functions

List of Command-Equivalent Functions


GALLERY.SCATTER

Macro Sheets Only

Equivalent to choosing an XY (Scatter) template from the AutoFormat dialog box when a chart is active. Changes the format of the active chart to an xy (scatter) chart.

Syntax

GALLERY.SCATTER(type_num, delete_overlay)
GALLERY.SCATTER?(type_num, delete_overlay)

Type_num is the number of a format in the AutoFormat dialog box when a chart is active dialog box that you want to apply to the xy (scatter) chart.

Delete_overlay is a logical value specifying whether to delete an overlay chart.

  • If delete_overlay is TRUE, Microsoft Excel deletes all overlays, if present, and applies the new format to the main chart.
  • If delete_overlay is FALSE or omitted, Microsoft Excel applies the new format to either the main chart or the overlay, depending on the location of the selected series.

Related Functions

List of Command-Equivalent Functions


GET.CHART.ITEM

Macro Sheets Only

Returns the vertical or horizontal position of a point on a chart item. Use these position numbers with FORMAT.MOVE and FORMAT.SIZE to change the position and size of chart items. Position is measured in points; a point is 1/72nd of an inch.

Syntax

GET.CHART.ITEM(x_y_index, point_index, item_text)

X_y_index is a number specifying which of the coordinates you want returned.

X_y_index Coordinate returned

1 Horizontal coordinate

2 Vertical coordinate

Point_index is a number specifying the point on the chart item. These indexes are described later. If point_index is omitted, it is assumed to be 1.

If the specified item is a point, point_index must be 1.

If the specified item is any line other than a data line, use the following values for point_index.

Point_index Chart item position

1 Lower or left

2 Upper or right

If the selected item is a legend, plot area, chart area, or an area in an area chart, use the following values for point_index.

Point_index Chart item position

1 Upper left

2 Upper middle

3 Upper right

4 Right middle

5 Lower right

6 Lower middle

7 Lower left

8 Left middle

If the selected item is an arrow in Microsoft Excel 4.0, use the following values for point_index. In Microsoft Excel 5.0 or later, arrows are named lines, and the arrowhead position returned is equivalent to the end of a line where the arrowhead begins.

Point_index Chart item position

1 Arrow shaft

2 Arrowhead

If the selected item is a pie slice, use the following values for point_index.

Point_index Chart item position

1 Outermost counterclockwise point

2 Outer center point

3 Outermost clockwise point

4 Midpoint of the most clockwise radius

5 Center point

6 Midpoint of the most counterclockwise radius

Item_text is a selection code that specifies which item of a chart to select. See the chart form of SELECT for the item_text codes to use for each item of a chart.

  • If item_text is omitted, it is assumed to be the currently selected item.
  • If item_text is omitted and no item is selected, GET.CHART.ITEM returns the #VALUE! error value.

Remarks

If the specified item does not exist, or if a chart is not active when the function is carried out, the #VALUE! error value is returned.

Examples

The following macro formulas return the horizontal and vertical locations, respectively, of the top of the main-chart value axis:

GET.CHART.ITEM(1, 2, "Axis 1")
GET.CHART.ITEM(2, 2, "Axis 1")

You could then use FORMAT.MOVE to move a floating text item to the position returned by these two formulas.

Related Functions

GET.DOCUMENT Returns information about a workbook

GET.FORMULA Returns the contents of a cell

List of Command-Equivalent Functions


GET.DEF

Macro Sheets Only

Returns the name, as text, that is defined for a particular area, value, or formula in a workbook. Use GET.DEF to get the name corresponding to a definition. To get the definition of a name, use GET.NAME.

Syntax

GET.DEF(def_text, document_text, type_num)

Def_text can be anything you can define a name to refer to, including a reference, a value, an object, or a formula.

  • References must be given in R1C1 style, such as "R3C5".
  • If def_text is a value or formula, it is not necessary to include the equal sign that is displayed in the Refers To box in the Define Name dialog box, which appears when you choose the Name command from the Define submenu on the Insert Menu.
  • If there is more than one name for def_text, GET.DEF returns the first name. If no name matches def_text, GET.DEF returns the #NAME? error value.

Document_text specifies the sheet or macro sheet that def_text is on. If document_text is omitted, it is assumed to be the active macro sheet.

Type_num is a number from 1 to 3 specifying which types of names are returned.

Type_num Returns

1 or omitted Normal names only

2 Hidden names only

3 All names

Examples

If the specified range in Sheet4 is named Sales, the following macro formula returns "Sales":

GET.DEF("R2C2:R9C6", "Sheet4")

If the value 100 in Sheet4 is defined as Constant, the following macro formula returns "Constant":

GET.DEF("100", "Sheet4")

If the specified formula in Sheet4 is named SumTotal, the following macro formula returns "SumTotal":

GET.DEF("SUM(R1C1:R10C1)", "Sheet4")

If 3 is defined as the hidden name Counter on the active macro sheet, the following macro formula returns "Counter":

GET.DEF("3", , 2)

Related Functions

GET.CELL Returns information about the specified cell

GET.NAME Returns the definition of a name

GET.NOTE Returns characters from a note

NAMES Returns the names defined on a workbook

List of Information Functions


GET.FORMULA

Macro Sheets Only

Returns the contents of a cell as they would appear in the formula bar. The contents are given as text, for example, "=2*PI()/360". If the formula contains references, they are returned as R1C1-style references, such as "=RC[1]*(1+R1C1)". Use GET.FORMULA to get a formula from a cell in order to edit its arguments. Use GET.CELL(6) to get a formula in either A1 or R1C1 format, depending on the workspace setting.

Syntax

GET.FORMULA(reference)

Reference is a cell or range of cells on a sheet or macro sheet.

  • If a range of cells is selected, GET.FORMULA returns the contents of the upper-left cell in reference.
  • Reference can be an external reference.
  • Reference can be the object identifier of a picture created by the camera tool.
  • Reference can also be a reference to a chart series in the form "Sn" where n is the number of the series. When a chart series is specified, GET.FORMULA returns the series formula using R1C1-style references.

Tip If you want to get the formula in the active cell, use the ACTIVE.CELL function as the reference argument.

Examples

If cell A3 on the active sheet contains the number 523, then:

GET.FORMULA(!$A$3) equals "523"

If cell C2 on the active sheet contains the formula =B2*(1+$A$1), then:

GET.FORMULA(!$C$2) equals "=RC[-1]*(1+R1C1)"

The following macro formula returns the contents of the active cell on the active sheet:

GET.FORMULA(ACTIVE.CELL())

Related Functions

GET.CELL Returns information about the specified cell

GET.DEF Returns a name matching a definition

GET.NAME Returns the definition of a name

GET.NOTE Returns characters from a note

List of Information Functions


GET.LINK.INFO

Macro Sheets Only

Returns information about the specified link. Use GET.LINK.INFO to get information about the update settings of a link.

Syntax

GET.LINK.INFO(link_text, type_num, type_of_link, reference)

Link_text is the path of the link as displayed in the Links dialog box, which appears when you choose the Links command from the Edit menu. The path to the file you wish to return DDE information on must be surrounded by single quotes.

Type_num is a number that specifies what type of information about the currently selected link to return. Type_num 2 applies only to publishers and subscribers in Microsoft Excel for the Macintosh.

Type_num Returns

1 If the link is set to automatic update, returns 1; otherwise 2.

2 Date of the latest edition as a serial number. Returns #N/A if link_text is not a publisher or a subscriber.

Type_of_link is a number from 1 to 6 that specifies what type of link you want to get information about.

Type_of_link Link document type

1 Not applicable

2 DDE link (Microsoft Windows)

3 Not applicable

4 Not applicable

5 Publisher (Macintosh)

6 Subscriber (Macintosh)

Reference specifies the cell range in R1C1 format of the publisher or subscriber that you want information about. Reference is required if you have more than one publisher or subscriber of a single edition name on the active workbook. Use reference to specify the location of the subscriber you want to return information about. If the subscriber is a picture, or if the publisher is an embedded chart, reference is the number of the object as displayed in the Name box.

Remarks

  • If Microsoft Excel cannot find link_text, or if type_of_link does not match the link specified by link_text, GET.LINK.INFO returns the #VALUE! error value.
  • If you have more than one subscriber to the edition link_text or if the same area is published more than once, you must specify reference.

Example

In Microsoft Excel for Windows, the following macro formula returns information about a DDE link to a Microsoft Word for Windows document. The document is named NEWPROD.DOC.

GET.LINK.INFO("WinWord|'C:\WINWORD\NEWPROD.DOC'!DDE_LINK1", 1, 2)

In Microsoft Excel for the Macintosh, the following macro formula returns information about a link to a publisher defined in cells A1:C3 on a workbook named New Products.

GET.LINK.INFO("A1:C3 New Products Edition #1", 2, 5, "'New Products'!R1C1:R3C3")

Related Functions

CREATE.PUBLISHER Creates a publisher from the selection

SUBSCRIBE.TO Inserts contents of an edition into the active workbook

UPDATE.LINK Updates a link to another workbook

List of Information Functions


GET.NAME

Macro Sheets Only

Returns the definition of a name as it appears in the Refers To box of the Define Name dialog box, which appears when you choose the Define command from the Name submenu on the Insert menu. If the definition contains references, they are given as R1C1-style references. Use GET.NAME to check the value defined by a name. To get the name corresponding to a definition, use GET.DEF.

Syntax

GET.NAME(name_text, info_type)

Name_text can be a name defined on the macro sheet; an external reference to a name defined on the active workbook, for example, "!Sales"; or an external reference to a name defined on a particular open workbook, for example, "[Book1]SHEET1!Sales". Name_text can also be a hidden name.

Info_type specifies the type of information to return about the name. If 1 or omitted, the definition is returned. If 2, returns TRUE if the name is defined for just the sheet, FALSE if the name is defined for the entire workbook.

Remarks

If the Contents check box has been selected in the Protect Sheet dialog box to protect the workbook containing the name, GET.NAME returns the #N/A error value. To see the Protect Sheet dialog box, choose the Protect Sheet command on the Protection submenu from the Tools menu.

Examples

If the name Sales on a macro sheet is defined as the number 523, then:

GET.NAME("Sales") equals "=523"

If the name Profit on the active sheet is defined as the formula =Sales-Costs, then:

GET.NAME("!Profit") equals "=Sales-Costs"

If the name Database on the active sheet is defined as the range A1:F500, then:

GET.NAME("!Database") equals "=R1C1:R500C6"

Related Functions

DEFINE.NAME Defines a name on the active or macro sheet

GET.CELL Returns information about the specified cell

GET.DEF Returns a name matching a definition

NAMES Returns the names defined in a workbook

SET.NAME Defines a name as a value

List of Information Functions


GET.NOTE

Macro Sheets Only

Returns characters from a note.

Syntax

GET.NOTE(cell_ref, start_char, num_chars)

Cell_ref is the cell to which the note is attached. If cell_ref is omitted, the note attached to the active cell is returned.

Start_char is the number of the first character in the note to return. If start_char is omitted, it is assumed to be 1, the first character in the note.

Num_chars is the number of characters to return. Num_chars must be less than or equal to 255. If num_chars is omitted, it is assumed to be the length of the note attached to cell_ref.

Examples

The following macro formula returns the first 200 characters in the note attached to cell A3 on the active sheet:

GET.NOTE(!$A$3, 1, 200)

In Microsoft Excel for Windows, the following macro formula returns the 10th through the 39th characters of the note attached to cell C2 on SALES.XLS:

GET.NOTE("[SALES.XLS]Sheet1!R2C3", 10, 30)

In Microsoft Excel for the Macintosh, the following macro formula returns the 10th through the 39th characters of the note attached to cell C2 on SALES:

GET.NOTE("[SALES]Sheet1!R2C3", 10, 30)

Use GET.NOTE with the NOTE function to move the contents of a note to a cell or text box or to another cell note:

NOTE(GET.NOTE(!$B$10),ACTIVE.CELL())

Related Functions

GET.CELL Returns information about the specified cell

NOTE Creates or changes a cell note.

SOUND.NOTE Records or imports sound into or erases sound from cell notes

List of Information Functions


GET.TOOLBAR

Macro Sheets Only

Returns information about one toolbar or all toolbars. Use GET.TOOLBAR to get information about a toolbar to use with functions that add, delete, or alter toolbars.

Syntax

GET.TOOLBAR(type_num, bar_id)

Type_num specifies what type of information to return. If type_num is 8 or 9, GET.TOOLBAR returns an array of names or numbers of all visible or hidden toolbars. Otherwise, bar_id is required, and GET.TOOLBAR returns the requested information about the specified toolbar.

GET.TOOLBAR|USA|002|003|001|common|UType_num Returns

1 A horizontal array of all tool IDs on the toolbar, ordered by position. Gaps are represented by zeros.

2 Number indicating the horizontal position (x-coordinate) of the toolbar in the docked or floating region. For more information, see SHOW.TOOLBAR.

3 Number indicating the vertical position (y-coordinate) of the toolbar in the docked or floating region.

4 Number indicating the width of the toolbar in points.

5 Number indicating the height of the toolbar in points.

6 Number indicating the toolbar location:
1 = Top dock in the workspace
2 = Left dock in the workspace
3 = Right dock in the workspace
4 = Bottom dock in the workspace
5 = Floating

7 If the toolbar is visible, returns TRUE. If the toolbar is hidden, returns FALSE.

8 An array of toolbar IDs (names or numbers in the bar_id array) for all toolbars, visible and hidden.

9 An array of toolbar IDs (names or numbers in the bar_id array) for all visible toolbars.

10 If the toolbar is visible in full-screen mode, returns TRUE; otherwise, returns FALSE.

Bar_id specifies the number or name of a toolbar for which you want information. If type_num is 8 or 9, Microsoft Excel ignores bar_id. For detailed information about bar_id, see ADD.TOOL.

Remarks

If you request position information for a hidden toolbar, Microsoft Excel returns the position where the toolbar would appear if shown.

Examples

The following macro formula returns information about the width of Toolbar1:

GET.TOOLBAR(4, "Toolbar1")

When the following macro formula is entered as an array with CTRL+SHIFT+ENTER, the IDs of all visible toolbars are returned, and the array is named All_Bar_Ids:

SET.NAME("All_Bar_Ids", GET.TOOLBAR(9))

Related Functions

ADD.TOOLBAR Creates a new toolbar with the specified tools

DELETE.TOOLBAR Deletes custom toolbars

GET.TOOL Returns information about a tool or tools on a toolbar

SHOW.TOOLBAR HIdes or displays a toolbar

List of Information Functions


GRIDLINES

Macro Sheets Only

Equivalent to choosing the Gridlines command from the Insert menu. Allows you to turn chart gridlines on and off.

Arguments are logical values corresponding to the check boxes in the Gridlines dialog box. If an argument is TRUE, Microsoft Excel selects the check box; if FALSE, Microsoft Excel clears the check box. If omitted, the setting is not changed. If a chart is not active, produces a error and halts the macro.

Syntax

GRIDLINES(x_major, x_minor, y_major, y_minor, z_major, z_minor, 2D_effect)
GRIDLINES?(x_major, x_minor, y_major, y_minor, z_major, z_minor, 2D_effect)

X_major corresponds to the Category (X) Axis: Major Gridlines check box.

X_minor corresponds to the Category (X) Axis: Minor Gridlines check box.

Y_major corresponds to the Value (Y) Axis: Major Gridlines check box. On 3-D charts, y_major corresponds to the Series (Y) Axis: Major Gridlines check box.

Y_minor corresponds to the Value (Y) Axis: Minor Gridlines check box. On 3-D charts, y_minor corresponds to the Series (Y) Axis: Minor Gridlines check box.

Z_major corresponds to the Value (Z) Axis: Major Gridlines check box (3-D only).

Z_minor corresponds to the Value (Z) Axis: Minor Gridlines check box (3-D only).

2D_effect corresponds to the 2-D Walls and Gridlines check box (3-D only).

Related Functions

List of Command-Equivalent Functions


HELP

Macro Sheets Only

Starts or switches to Help and displays the specified custom Help topic. Use HELP with custom Help files to create your own Help system, which can be used just like the built-in Microsoft Excel Help.

Syntax

HELP(help_ref)

Help_ref is a reference to a topic in a Help file, in the form "filename!topic_number".

  • Help_ref must be given as text.

Remarks

  • Microsoft Excel for Windows does not support the use of Help files in the text file format for custom Help.
  • In Microsoft Excel for the Macintosh, custom Help files are plain text files or text files with line breaks.

Tips

In Microsoft Excel for Windows, the following macro formula switches back to Microsoft Excel when Help is active:

APP.ACTIVATE()

The following macro formula closes Help when Help is active:

SEND.KEYS("%{F4}")

Examples

In Microsoft Excel for Windows, the following macro formula displays the Help topic numbered 101 in the file CUSTHELP.DOC. The Help window remains open if the user switches to another window or application.

HELP("CUSTHELP.DOC!101")

If the custom Help file is not in the current directory, specify the full path along with the name of the file. For example:

HELP("C:\EXCEL\CUSTHELP.DOC!101")

In Microsoft Excel for the Macintosh, the following macro formula displays the Help topic numbered 101 in the file CUSTOM HELP:

HELP("CUSTOM HELP!101")

If the custom Help file is not in the current folder, specify the full path along with the name of the file. For example:

HELP("HARD DISK:EXCEL:HELP:CUSTOM HELP!101")

Related Functions

List of Customizing Functions


HIDE.OBJECT

Macro Sheets Only

Hides or displays the specified object.

Syntax

HIDE.OBJECT(object_id_text, hide)

Object_id_text is the name and number, or number alone, of the object, as text, as it appears in the reference area when the object is selected. The name of the object is also the text returned by the CREATE.OBJECT function, so object_id_text can be a reference to a cell containing CREATE.OBJECT. To give the name of more than one object, use the following format for object_id_text:

"oval 3, text 2, arc 5"

If object_id_text is omitted, the function operates on all selected objects. If no object is selected or if the object specified by object_id_text does not exist, HIDE.OBJECT returns the #VALUE! error value.

Hide is a logical value that specifies whether to hide or display the specified object. If hide is TRUE or omitted, Microsoft Excel hides the object; if FALSE, Microsoft Excel displays the object.

Remarks

Objects are not automatically selected after they are unhidden.

Examples

The following macro formula hides the selected object:

HIDE.OBJECT(, TRUE)

The following macro formula displays the object named Oval 3:

HIDE.OBJECT("Oval 3", FALSE)

The following macro formula displays the three specified objects:

HIDE.OBJECT("oval 3, text 2, arc 5", FALSE)

Related Functions

CREATE.OBJECT Creates an object

DISPLAY Controls how an object is displayed

List of Customizing Functions


INPUT

Macro Sheets Only

Displays a dialog box for user input. Returns the information entered in the dialog box. Use INPUT to display a simple dialog box for the user to enter information to be used in a macro.

The dialog box has an OK and a Cancel button. If you choose the OK button, INPUT returns the default value specified or the value typed in the edit box. If you choose the Cancel button, INPUT returns FALSE.

Syntax

INPUT(message_text, type_num, title_text, default, x_pos, y_pos, help_ref)

Message_text is the text to be displayed in the dialog box. Message_text must be enclosed in quotation marks.

Type_num is a number specifying the type of data to be entered.

Type_num Data type

0 Formula

1 Number

2 Text

4 Logical

8 Reference

16 Error

64 Array

You can also use the sum of the allowable data types for type_num. For example, for an input box that can accept formulas, text, or numbers, set type_num equal to 3 (the sum of 0, 1, and 2, which are the type specifiers for formula, number, and text). If type_num is omitted, it is assumed to be 2.

  • If type_num is 0, INPUT returns the formula in the form of text, for example, "=2*PI()/360".
  • To enter a formula, include an equal sign at the beginning of the formula; otherwise the formula is returned as text.
  • If the formula contains references, they are returned as R1C1-style references, for example, "=RC[-1]*(1+R1C1)".
  • If type_num is 8, INPUT returns an absolute reference to the specified cells.
  • If you enter a single-cell reference in the dialog box, the value in that cell is returned by the INPUT function.
  • If the information entered in the dialog box is not of the correct data type, Microsoft Excel attempts to convert it to the specified type. If the information can't be converted, Microsoft Excel displays an error message.

Title_text is text specifying a title to be displayed in the title bar of the dialog box. If title_text is omitted, it is assumed to be "Input".

Default specifies a value to be shown in the edit box when the dialog box is initially displayed. If default is omitted, the edit box is left empty.

X_pos, y_pos specify the horizontal and vertical position, in points, of the dialog box. A point is 1/72nd of an inch. If either or both arguments are omitted, the dialog box is centered in the corresponding direction.

Help_ref is a reference to a custom online Help topic in a text file, in the form "filename!topic_number".

  • If help_ref is present, a Help button appears in the lower-right corner of the dialog box. Choosing the Help button starts Help and displays the specified topic.
  • If help_ref is omitted, no Help button appears.
  • Help_ref must be given as text.

For more information about custom Help topics, see HELP.

Remarks

Relative references entered in formulas in the INPUT dialog box are relative to the active cell at the time the INPUT function is calculated. If you are using the reference entered into the dialog box in a cell other than the active cell, it may not refer to the cells you intend it to. For example, if the active cell is A3 and you enter the formula "=A1+A2" in an INPUT dialog box, intending to add the values in those cells, and then use the FORMULA function to enter the formula in cell B3, the formula in cell B3 will read "=B1+B2" because you gave a relative reference. You can use FORMULA.CONVERT to solve this problem.

Examples

In Microsoft Excel for Windows, the following macro formula displays the following dialog box:

INPUT("Enter the inflation rate:", 1, "Inflation Rate", , , , "CUSTHELP.DOC!101")

If you then enter 12%, INPUT returns the value 0.12.

In Microsoft Excel for the Macintosh, the following macro formula displays the following dialog box:

INPUT("Enter the inflation rate:", 1, "Inflation Rate", , , , "CUSTOM HELP!101")

If you then enter 12%, INPUT returns the value 0.12.

If the active cell is C2 and you enter the formula =B2*(1+$A$1) in response to the following macro formula:

INPUT("Enter your monthly increase formula:", 0)

INPUT returns "=RC[-1]*(1+R1C1)"

If you select the range $A$2:$A$8 in the INPUT dialog box:

REFTEXT|USA|002|001|001|common|UREFTEXT(INPUT("Please make your selection.", 8)) returns R2C1:R8C1

Related Functions

ALERT Displays a dialog box and a message

DIALOG.BOX Displays a custom dialog box

FORMULA.CONVERT Changes the style and type of references in a formula

HELP Displays a custom Help topic

List of Customizing Functions


INSERT

Macro Sheets Only

Inserts a blank cell or range of cells or pastes cells from the Clipboard into a sheet. Shifts the selected cells to accommodate the new ones. The size and shape of the inserted range are the same as those of the current selection.

Syntax

INSERT(shift_num)
INSERT?(shift_num)

Shift_num is a number from 1 to 4 specifying which way to shift the cells. If an entire row or column is selected, shift_num is ignored. If shift_num is omitted, Microsoft Excel shifts cells in the logical direction based on the selection.

Shift_num Direction

1 Shift cells right

2 Shift cells down

3 Shift entire row

4 Shift entire column

Remarks

If you have just cut or copied information to the Clipboard, INSERT performs both an insert and a paste operation. First, Microsoft Excel inserts new blank cells into the sheet; then, Microsoft Excel pastes information from the Clipboard into the newly inserted cells. If you have used the INSERT function in macros written for Microsoft Excel version 2.2 or earlier, make sure you consider this feature when you use your old macros with later versions of Microsoft Excel.

Related Functions

COPY Copies and pastes data or objects

CUT Cuts or moves data or objects

EDIT.DELETE Removes cells from a sheet

PASTE Pastes cut or copied data

List of Command-Equivalent Functions


LEGEND

Macro Sheets Only

Equivalent to choosing the Legend command from the Insert menu or the Clear command from the Edit menu when a chart legend is selected. Adds a legend to or removes a legend from a chart. This is also equivalent to choosing the Legend button on the Chart toolbar when a chart is active.

Syntax

LEGEND(logical)

Logical is a logical value specifying which command LEGEND is equivalent to.

  • If logical is TRUE or omitted, LEGEND is equivalent to the Legend command on the Insert menu.
  • If logical is FALSE, LEGEND is equivalent to the Delete command on the Edit menu.
  • If logical is FALSE and the active chart has no legend, LEGEND takes no action.

Related Function

FORMAT.LEGEND Determines the position and orientation of the legend on a chart

List of Command-Equivalent Functions


LINE.PRINT

Macro Sheets Only

Prints the active worksheet using methods compatible with those of Lotus 1-2-3. LINE.PRINT does not use the Microsoft Windows printer drivers. Unless you have a specific need for the LINE.PRINT function, use the PRINT function instead.

Note This function is only available in Microsoft Excel for Windows.

Syntax 1

Go, Line, Page, Align, and Clear

LINE.PRINT(command, file, append)

Syntax 2

Worksheet settings

LINE.PRINT(command, setup_text, leftmarg, rightmarg, topmarg, botmarg, pglen, formatted)

Syntax 3

Global settings

LINE.PRINT(command, setup_text, leftmarg, rightmarg, topmarg, botmarg, pglen, wait, autolf, port, update)

Command is a number corresponding to the command you want LINE.PRINT to carry out. For syntax 2, command must be 5. For syntax 3, command must be 6.

Command Command that is carried out

1 Go

2 Line

3 Page

4 Align

5 Worksheet settings

6 Global settings (saved in EXCEL5.INI)

7 Clear (change to current global settings)

File is the name of a file to which you want to print. If omitted, Microsoft Excel prints to the printer port determined by the current global settings.

Append is a logical value specifying whether to append text to file. If TRUE, the file you are printing is appended to file; if FALSE or omitted, the file you are printing overwrites the contents of file.

Setup_text is text that includes a printer initialization sequence or other control codes to prepare your printer for printing. If omitted, no setup text is used.

Leftmarg is the size of the left margin measured in characters from the left side of the page. If omitted, it is assumed to be 4.

Rightmarg is the size of the right margin measured in characters from the left side of the page. If omitted, it is assumed to be 76.

Topmarg is the size of the top margin measured in lines from the top of the page. If omitted, it is assumed to be 2.

Botmarg is the size of the bottom margin measured in lines from the bottom of the page. If omitted, it is assumed to be 2.

Pglen is the number of lines on one page. If omitted, it is assumed to be 66 (11 inches with 6 lines per inch). If you're using an HP LaserJet or compatible printer, set pglen to 60 (the printer reserves six lines).

Formatted is a logical value specifying whether to format the output. If TRUE or omitted, the output is formatted; if FALSE, it is not formatted.

Wait is a logical value specifying whether to wait after printing a page. If TRUE, Microsoft Excel waits; if FALSE or omitted, Microsoft Excel continues printing.

Autolf is a logical value specifying whether your printer has automatic line feeding. If TRUE, Microsoft Excel prints lines normally; if FALSE or omitted, Microsoft Excel sends an additional line feed character after printing each line.

Port is a number from 1 to 8 specifying which port to use when printing.

Port Port used when printing

1 or omitted LPT1

2 COM1

3 LPT2

4 COM2

5 LPT1

6 LPT2

7 LPT3

8 LPT4

Update is a logical value specifying whether to update and save global settings. If TRUE, the settings are saved in the EXCEL5.INI file; if FALSE or omitted, the global settings are not saved.

Remarks

The default values for print settings on your worksheet are determined by the current global settings.

Example

The following macro formula prints the currently defined print area to the currently defined printer port:

LINE.PRINT(1)

Related Functions

PRINT Prints the active document

List of Command-Equivalent Functions


MAIN.CHART

Macro Sheets Only

Equivalent to choosing the Main Chart command from the Format menu when a chart document is active in Microsoft Excel version 2.2 or earlier. This function is included only for macro compatibility.

Syntax

MAIN.CHART(type_num, stack, 100, vary, overlap, drop, hilo, overlap%,
cluster, angle)
MAIN.CHART?(type_num, stack, 100, vary, overlap, drop, hilo, overlap%,
cluster, angle)

Related Functions

List of Command-Equivalent Functions


MAIN.CHART.TYPE

Macro Sheets Only

Equivalent to choosing the Main Chart Type command from the Chart menu in Microsoft Excel for the Macintosh version 1.5 or earlier. This function is included only for macro compatibility.

Syntax

MAIN.CHART.TYPE(type_num)

Related Functions

List of Command-Equivalent Functions


MESSAGE

Macro Sheets Only

Displays and removes messages in the message area of the status bar. MESSAGE is useful for displaying text that doesn't need a response, such as descriptions of commands in user-defined menus.

Syntax

MESSAGE(logical, text)

Logical is a logical value specifying whether to display or remove a message.

  • If logical is TRUE, Microsoft Excel displays text in the message area of the status bar.
  • If logical is FALSE, Microsoft Excel removes any messages, and the status bar is returned to normal (that is, command help messages are displayed).

Text is the message you want to display in the status bar. If text is "" (empty text), Microsoft Excel removes any messages currently displayed in the status bar.

Remarks

  • Only one message can be displayed in the status bar at a time. Messages are always displayed in the same place.
  • MESSAGE works the same way whether the status bar is displayed or not. You can, for example, use MESSAGE while the status bar isn't displayed. As soon as you display the status bar, you see your message.
  • If you display any message (even empty text) and don't remove it with MESSAGE(FALSE), that message is displayed until you quit Microsoft Excel.
  • You can also use the ALERT function to get the user's attention; however, this interrupts the macro and requires the user's intervention before the macro can continue.

Example

The following lines in a macro display a message warning that you must wait for a moment while the macro calls a subroutine.

MESSAGE(TRUE, "One moment please...")

Related Functions

ALERT Displays a dialog box and a message

BEEP Sounds a tone

List of Command-Equivalent Functions


NEW.WINDOW

Macro Sheets Only

Equivalent to choosing the New Window command from the Window menu. Creates a new window for the active workbook.

Syntax

NEW.WINDOW( )

After you use NEW.WINDOW, use the WINDOW.MOVE, WINDOW.SIZE, and ARRANGE.ALL functions to size and position the new window.

Related Functions

ARRANGE.ALL Arranges all displayed windows to fill the workspace and synchronizes windows for scrolling

WINDOW.MOVE Moves a window

WINDOW.SIZE Changes the size of a window

List of Command-Equivalent Functions


OBJECT.PROPERTIES

Macro Sheets Only

Equivalent to choosing the Properties tab in the Object dialog box, which appears when you choose the Object command from the Format menu. Determines how the selected object or objects are attached to the cells beneath them and whether they are printed. The way an object is attached to the cells beneath it affects how the object is moved or sized whenever you move or size the cells.

OBJECT.PROPERTIES(placement_type, print_object)
OBJECT.PROPERTIES?(placement_type, print_object)

Placement_type is a number from 1 to 3 specifying how to attach the selected object or objects. If placement_type is omitted, the current status is unchanged.

If placement_type is The selected object is

1 Moved and sized with cells.

2 Moved but not sized with cells.

3 Free-floating—it is not affected by moving and sizing cells.

Print_object is a logical value specifying whether to print the selected object or objects. If TRUE or omitted, the objects are printed; if FALSE, they are not printed.

Remarks

If an object is not selected, OBJECT.PROPERTIES interrupts the macro and returns the #VALUE! error value.

Related Functions

CREATE.OBJECT Creates an object

FORMAT.MOVE Moves the selected object

FORMAT.SIZE Changes the size of the selected object

List of Command-Equivalent Functions


OBJECT.PROTECTION

Macro Sheets Only

Equivalent to choosing the Protection tab in the Format Object dialog box, which appears when you choose the Object command from the Format menu. Changes the protection status of the selected object.

Syntax

OBJECT.PROTECTION(locked, lock_text)
OBJECT.PROTECTION?(locked, lock_text)

Locked is a logical value that determines whether the selected object is locked or unlocked. If locked is TRUE, Microsoft Excel locks the object; if FALSE, Microsoft Excel unlocks the object.

Lock_text is a logical value that determines whether text in a text box or button can be changed. Lock_text applies only if the object is a text box, button, or worksheet control. If lock_text is TRUE or omitted, text cannot be changed; if FALSE, text can be changed.

Remarks

  • You cannot lock or unlock an individual object with OBJECT.PROTECTION when document protection is selected for objects in the Protect Sheet dialog box.
  • If an object is not selected, the function returns the #VALUE! error value and halts the macro.
  • In order for an object to be protected, you must use the PROTECT.DOCUMENT(, , , TRUE) function after changing the object's status with OBJECT.PROTECTION.

Related Functions

PROTECT.DOCUMENT Controls protection for the active worksheet

WORKBOOK.PROTECT Controls protection for the active workbook

List of Command-Equivalent Functions


OPEN.MAIL

Macro Sheets Only

Equivalent to choosing the Open Mail command from the Mail submenu on File menu.

Note This function is available for only Microsoft Excel for the Macintosh and Microsoft Mail version 2.0 or later.

Syntax

OPEN.MAIL(subject, comments)
OPEN.MAIL?(subject, comments)

Subject is the subject of the message containing a file that Microsoft Excel can open.

  • For each message whose subject matches the subject argument and contains a file that Microsoft Excel can open, the file is opened in Microsoft Excel; if the message has no unread enclosures, it is deleted from the list of pending mail.
  • If subject is omitted, then for all messages containing files that Microsoft Excel can open, the files are opened; each message that has no unread enclosures is deleted from the list of pending mail.

Comments is a logical value that specifies whether comments associated with the Microsoft Excel files are displayed. If comments is TRUE, Microsoft Excel displays the comments; if FALSE, comments are not displayed. If omitted, the current setting is not changed.

Tips

  • If you use consistent subjects in your Microsoft Mail messages, you can easily create a macro that always opens mail messages with certain files attached. For example, an OPEN.MAIL formula with subject specified as "Weekly Report" would open the Microsoft Excel file attached to the message containing that subject each week.
  • In OPEN.MAIL?, the dialog-box form of the function, the currently running macro pauses while the Microsoft Mail documents window is displayed. The macro resumes after you close the Microsoft Mail documents window.

Related Function

SEND.MAIL Sends the active workbook

List of Command-Equivalent Functions


PASTE.PICTURE

Macro Sheets Only

Equivalent to choosing the Paste Picture command from the Edit menu while holding down the SHIFT key in Microsoft Excel version 4.0. Pastes a picture of the Clipboard contents onto the sheet. This picture is not linked, so changes to the source data will not be reflected in the picture. In Microsoft Excel for Windows version 5.0 or later, use INSERT.PICTURE to import pictures.

Syntax

PASTE.PICTURE( )

Related Functions

COPY.PICTURE Creates a picture of the current selection for use in another program

INSERT.PICTURE Inserts a picture from a file

PASTE.PICTURE.LINK Pastes a linked picture of the currently copied area

List of Command-Equivalent Functions


PASTE.PICTURE.LINK

Macro Sheets Only

Equivalent to holding down the SHIFT key and choosing the Paste Picture Link command from the Edit menu in Microsoft Excel version 4.0 or to using the camera tool. Pastes a linked picture of the Clipboard contents. This picture is linked, so changes to the source data will be reflected in the picture.

Syntax

PASTE.PICTURE.LINK( )

Related Functions

COPY.PICTURE Copies and pastes data or object

COPY.PICTURE Creates a picture of the current selection for use in another program

CREATE.OBJECT Creates an object

PASTE Pastes cut or copied data

PASTE.PICTURE Pastes a picture of the currently copied area

List of Command-Equivalent Functions


PREFERRED

Macro Sheets Only

Equivalent to choosing the Preferred command from the Gallery menu in Microsoft Excel version 4.0. Changes the format of the active chart to the format currently defined by the Default Chart Template option in the Chart tab of the Options dialog box or the SET.PREFERRED macro function. The Options dialog appears when you choose the Options command from the Tools menu.

Syntax

PREFERRED( )

Related Function

SET.PREFERRED Changes the default chart format

List of Command-Equivalent Functions


PRINTER.SETUP

Macro Sheets Only

Equivalent to choosing the Print command from the File menu and then choosing the Printer button in Microsoft Excel for Windows. Use PRINTER.SETUP to change the printer you are using.

Syntax

PRINTER.SETUP(printer_text)
PRINTER.SETUP?(printer_text)

Printer_text is the name of the printer you want to switch to. Enter printer_text exactly as it appears in the Setup dialog box.

Note This function is only available in Microsoft Excel for Windows.

Related Functions

PAGE.SETUP Sets page printing specifications

PRINT Prints the active workbook

List of Command-Equivalent Functions


REMOVE.PAGE.BREAK

Macro Sheets Only

Equivalent to choosing the Remove Page Break command from the Insert menu. Removes manual page breaks that you set with the SET.PAGE.BREAK function or the Page Break command on the Insert menu. If the active cell is not below or to the right of a manual page break, REMOVE.PAGE.BREAK takes no action. If the entire sheet is selected, REMOVE.PAGE.BREAK removes all manual page breaks. REMOVE.PAGE.BREAK does not remove automatic page breaks.

Syntax

REMOVE.PAGE.BREAK( )

Related Function

SET.PAGE.BREAK Sets manual page breaks

List of Command-Equivalent Functions


SELECT.CHART

Macro Sheets Only

Equivalent to the Select Chart command on the Chart menu in Microsoft Excel version 4. This function is equivalent to using the third form of SELECT with "Chart" as the item_text argument.

Syntax

SELECT.CHART( )

Remarks

This function is included for compatibility with macros written with Microsoft Excel for the Macintosh version 1.5 or earlier.

Related Functions

SELECT Selects a chart object

List of Command-Equivalent Functions


SELECT.PLOT.AREA

Macro Sheets Only

Equivalent to choosing the Select Plot Area command from the Chart menu in Microsoft Excel version 4. Selects the plot area of the active chart.

Syntax

SELECT.PLOT.AREA( )

Remarks

SELECT.PLOT.AREA is included only for compatibility with previous versions of Microsoft Excel for the Macintosh. SELECT.PLOT.AREA is the same as the SELECT("Plot") function.

Related Function

SELECT Selects a cell, graphic object, or chart

List of Command-Equivalent Functions


SELECTION

Macro Sheets Only

Returns the reference or object identifier of the selection as an external reference. Use SELECTION to return information about the current selection for use in other macro formulas.

Syntax

SELECTION( )

If a cell or range of cells is selected, Microsoft Excel returns the corresponding external reference. If an object is selected, Microsoft Excel returns the object identifier listed in the following table.

Item selected Identifier returned

Imported graphic Picture n

Linked graphic Picture n

Chart picture Picture n

Linked chart Chart n

Range Picture n

Linked range Picture n

Text box Text n

Button Button n

Rectangle Rectangle n

Oval Oval n

Line Line n

Arc Arc n

Group Group n

Freehand drawing or polygon Drawing n

SELECTION also returns the identifiers of chart items. The identifiers returned are the same as the identifiers you specify when you use the SELECT function. For a list of these identifiers, see the description of item_text in SELECT.

If you select cells and use the value returned by SELECTION in a function or operation, you usually get the value contained in the selection instead of its reference. References are automatically converted to the contents of the reference. If you want to work with the actual reference, use SET.NAME to assign a name to it, even if the reference refers to objects. See the last example following. You can also use the REFTEXT function to convert the reference to text, which you can then store or manipulate.

Remarks

  • If an object is selected, SELECTION returns the identifier of the object. If multiple objects are selected, it returns the identifiers of all the selected objects, as a string separated by commas.
  • If more than 1024 characters would be returned, SELECTION returns the #VALUE! error value.

Examples

If the sheet in the active window is named SHEET1 in the workbook BOOK1, and if A1:A3 is the selection, then:

SELECTION() equals [BOOK1]SHEET1!A1:A3

The following macro formula moves the current selection one row down:

SELECT(OFFSET(SELECTION(), 1, 0))

The above formula is particularly useful for moving incrementally through a database to add or modify records.

The following macro formula defines the name "EntryRange" on the active sheet to refer to one row below the current selection on the active sheet:

DEFINE.NAME("EntryRange", OFFSET(SELECTION(), 1, 0))

The following macro formula defines the name "Objects" on your macro sheet to refer to the object names in the current multiple selection:

SET.NAME("Objects", SELECTION())

Related Functions

ACTIVE.CELL Returns the reference of the active cell

SELECT Selects a cell, graphic object, or chart

List of Information Functions


SEND.MAIL

Macro Sheets Only

Equivalent to choosing the Send Mail command from the File menu. Sends the active workbook using email.

Syntax

SEND.MAIL(recipients, subject, return_receipt)
SEND.MAIL?(recipients, subject, return_receipt)

Important To use SEND.MAIL in Microsoft Excel for Windows, you must be using a mail client that supports the Messaging Applications Programming Interface (MAPI) or Vendor-Independent Messaging (VIM). To use SEND.MAIL in Microsoft Excel for the Macintosh, you must be using Microsoft Mail version 2.0 or later.

Recipients is the name of the person to whom you want to send the mail. The name should be given as text.

  • To specify more than one name, give the list of names as an array. For example, SEND.MAIL({"John", "Paul", "George", "Ringo"}) would send the active workbook to the four names in the array. You can also refer to a range on a sheet or macro sheet that contains a list of names to whom you want the mail to be sent.
  • To send mail to users on different Microsoft Mail for the Macintosh servers, specify the server name along with the user name. The following text, as the recipients argument, sends mail to wandagr on server2, gregpr on the current server, and victorge on server7:
    • {"wandagr@server2", "gregpr", "victorge@server7"}

Subject is a text string that specifies the subject of the message. If subject is omitted, the name of the active workbook is used as the subject.

Return_receipt is a logical value that corresponds to the Return Receipt check box. If return_receipt is TRUE, Microsoft Excel selects the check box and sends a return receipt; if FALSE or omitted, Microsoft Excel clears the check box.

Related Function

OPEN.MAIL Opens files sent via Microsoft Mail that Microsoft Excel can open

List of Command-Equivalent Functions


SET.PAGE.BREAK

Macro Sheets Only

Equivalent to choosing the Page Break command from the Insert menu. Sets manual page breaks. Use SET.PAGE.BREAK to override the automatic page breaks. Setting a manual page break changes the automatic page breaks that follow it.

The page break occurs above and to the left of the active cell and appears as dotted lines if you have set up a printer. If the active cell is in column A, a manual page break is added only above the cell. If the active cell is in row 1, a manual page break is added only at the left edge of the cell. If the row or column next to the active cell already has a page break, SET.PAGE.BREAK takes no action.

Syntax

SET.PAGE.BREAK( )

Related Functions

PRINT.PREVIEW Previews pages and page breaks before printing

REMOVE.PAGE.BREAK Removes manual page breaks

List of Command-Equivalent Functions


SET.PREFERRED

Macro Sheets Only

Equivalent to setting the Default Chart Format in the Chart tab of the Options dialog box, which appears when you choose the Options command from the Tools menu. Changes the default format that Microsoft Excel uses when you create a new chart or when you format a chart PREFERRED macro function. When you use the SET.PREFERRED function, the format of the active chart becomes the preferred format.

Syntax

SET.PREFERRED(format)

Format is the name of the format that you want as the default format for charts. If omitted, the format of the currently active chart is used. If format is "Built_in", then Microsoft Excel will use the standard, built-in chart as the default. If the chart was created in Microsoft Excel 4.0 and if format is "PREFERRED", then the preferred chart format used in Microsoft Excel 4.0 will be used. Format is case sensitive.

Related Function

PREFERRED Changes the format of the active chart to the preferred format

List of Command-Equivalent Functions


SOUND.NOTE

Macro Sheets Only

Records sound into or erases sound from a cell note or imports sound from another file into a cell note. This function requires that you have recording hardware installed in your computer, and you must be running Microsoft Windows version 3.1 or later, or Apple system software version 6.07 or later.

Syntax 1

Recording or erasing sound

SOUND.NOTE(cell_ref, erase_snd)

Syntax 2

Importing sound from another file

SOUND.NOTE(cell_ref, file_text, resource)

Cell_ref is a reference to the cell containing a note into which you want to record or import sounds or from which you want to erase a sound.

Erase_snd is a logical value specifying whether to erase the sound in the note. If erase_snd is TRUE, Microsoft Excel erases only the sound from the note. If FALSE or omitted, Microsoft Excel displays the Record dialog box so that you can record sound into the note.

File_text is the name of a file containing sounds.

Resource is the number or name of a sound resource in file_text that you want to import into your note.

  • This argument applies only to Microsoft Excel for the Macintosh.
  • If resource is omitted, Microsoft Excel uses the first resource in the file.
  • If the file does not contain a sound resource with the specified name or number, Microsoft Excel halts the macro and displays an error message.

Remarks

To find out if a cell has sound attached to it, use GET.CELL(47).

Examples

The following macro formula erases the sound, if present, from cell A1 on the active sheet:

SOUND.NOTE(!$A$1, TRUE)

The following macro formula displays the Record dialog box so that you can record sound into a note for cell A1 on the active sheet:

SOUND.NOTE(!$A$1)

In Microsoft Excel for Windows, the following macro formula imports the sound from a file named CHIMES.WAV into a note for the cell named Doorbell on the active sheet:

SOUND.NOTE(!Doorbell, "C:\SOUNDS\CHIMES.WAV")

In Microsoft Excel for the Macintosh, the following macro formula imports a sound called Chimes from a file named SOFT SOUNDS into a note for the cell named Doorbell on the active sheet:

SOUND.NOTE(!Doorbell, "HARD DISK:SOUNDS:SOFT SOUNDS", "Chimes")

Related Functions

NOTE Creates or changes a cell note

SOUND.PLAY Plays the sound from a cell note or a file

List of Command-Equivalent Functions


SOUND.PLAY

Macro Sheets Only

Plays the sound from a cell note or a file. Equivalent to choosing the Note command from the Insert menu and choosing the Play button, or choosing the Note command from the Insert menu, choosing the Import button, and then opening a file, selecting a sound, and choosing the Play button. To play sounds in Microsoft Excel for Windows, you must have have a sound board installed in your computer.

Syntax

SOUND.PLAY(cell_ref, file_text, resource)

Cell_ref is a reference to the cell note containing sound that you want to play. If cell_ref is omitted, Microsoft Excel plays the sound from the active cell, or from a file if you specify one.

File_text is the name of a file containing sounds. If cell_ref is specified, file_text is ignored.

Resource is a number or name given as text specifying a sound resource in file_text that you want to play.

  • This argument applies only to Microsoft Excel for the Macintosh.
  • If cell_ref is specified, resource is ignored.
  • If resource is omitted, Microsoft Excel uses the first sound resource in the file.
  • If the file does not contain a sound resource with the specified name or number, Microsoft Excel halts the macro and displays an error message.

Related Function

SOUND.NOTE Records or imports sound into or erases sound from cell notes

List of Command-Equivalent Functions


SPELLING.CHECK

Macro Sheets Only

Checks the spelling of a word. Returns TRUE if the word is spelled correctly; FALSE otherwise.

Syntax

SPELLING.CHECK(word_text, custom_dic, ignore_uppercase)

Word_text is the word whose spelling you want to check. It can be text or a reference to text.

Custom_dic is the filename of a custom dictionary to examine if the word is not found in the main dictionary.

Ignore_uppercase is a logical value corresponding to the Ignore Words In Uppercase check box. If ignore_uppercase is TRUE, the check box is selected, and Microsoft Excel ignores words in all uppercase letters; if FALSE, the check box is cleared, and Microsoft Excel checks all words; if omitted, the current setting is used.

Remarks

This function does not have a dialog-box form. To display the Spelling dialog box, use SPELLING.

Related Function

SPELLING Checks the spelling of words in the current selection

List of Command-Equivalent Functions


TEXT.BOX

Macro Sheets Only

Replaces characters in a text box or button with the text you specify.

Syntax

TEXT.BOX(add_text, object_id_text, start_num, num_chars)

Add_text is the text you want to add to the text box or button.

Object_id_text is the name of the text box or button to which you want to add text (for example, "Text 1" or "Button 2"). If object_id_text is omitted, it is assumed to be the selected item.

Start_num is a number specifying the position of the first character you want to replace (or the position at which you want to insert characters if you do not want to replace any). If start_num is omitted, it is assumed to be 1.

Num_chars is the number of characters you want to replace. If num_chars is 0, then no characters are replaced, and add_text is inserted starting at the position start_num. If num_chars is omitted, all the characters are replaced.

Examples

The following macro formula replaces the first five characters in a text box named "Text 5" with the text "Net Income":

TEXT.BOX("Net Income", "Text 5", 1, 5)

The following macro formula inserts the words "Account Summary for 1991" at the beginning of a text box named "Text 6":

TEXT.BOX("Account Summary for 1991", "Text 6", 1, 0)

Related Functions

CREATE.OBJECT Creates an object

FONT.PROPERTIES Applies a font to the selection

GET.OBJECT Returns information about an object

List of Command-Equivalent Functions


WINDOW.TITLE

Macro Sheets Only

Changes the title of the active window to the title you specify. The title appears at the top of the workbook window. Use WINDOW.TITLE to control window titles when you're using Microsoft Excel to create a custom application.

Syntax

WINDOW.TITLE(text)

Text is the title you want to assign to the window. If text is omitted, it is assumed to be the name of the workbook as it is stored on your disk. Empty text ("") specifies no title.

Important WINDOW.TITLE changes the name of the window, not the actual name of the workbook as it is stored on your disk. To change the name of the workbook, use the SAVE.AS function.

Remarks

  • The window name you create using WINDOW.TITLE will appear on the Window menu, and will be returned by the WINDOWS function, but not by the DOCUMENTS function. You must use the new window name in the ACTIVATE function and the ON.WINDOW function.
  • If you want to communicate with a Microsoft Excel workbook using DDE functions like INITIATE or REQUEST, you must specify the filename of the workbook and not the window title specified with the WINDOW.TITLE function.
  • If you use NEW.WINDOW to create new windows on the workbook, the window title will be restored to its original name.

Example

The following macro formula changes the title of the active window to First Quarter.

WINDOW.TITLE("First Quarter")

Related Function

APP.TITLE Changes the title of the application workspace

SAVE.AS Specifies a new filename, file type, protection password, or write-reservation password, or to create a backup file

List of Customizing Functions


WINDOWS

Macro Sheets Only

Returns the names of the specified open Microsoft Excel windows, including hidden windows. Use WINDOWS to get a list of active windows for use by other macro functions that return information about or manipulate windows, such as GET.WINDOW and ACTIVATE. The names are returned as a horizontal array of text values, in order of their appearance on your screen. The first name is the active window, the next name is the window directly under the active window, and so on.

Syntax

WINDOWS(type_num, match_text)

Type_num is a number that specifies which types of workbooks are returned by WINDOWS, according to the following table.

Type_num Returns window names from these types of documents

1 or omitted All windows except those belonging to add-in workbooks

2 Add-in workbooks only

3 All types of workbooks

Match_text specifies the windows whose names you want returned and can include wildcard characters. If match_text is omitted, WINDOWS returns the names of all open windows.

Tips

  • You can change the output of a horizontal array to vertical with the TRANSPOSE function.
  • You can use WINDOWS with the INDEX function to choose individual window names from the array for use in other functions that take window names as arguments.
  • You can use the COLUMNS functions to count the number of entries in the array, which is the number of windows.

Examples

If the active window, named BOOK1, is on top of a window named MACROS:2, which is on top of a window named MACROS:1, then:

WINDOWS() equals {"BOOK1", "MACROS:2", "MACROS:1"}

Related Functions

ACTIVATE Switches to a window

DOCUMENTS Returns the names of the specified open workbooks

GET.WINDOW Returns information about a window

NEW.WINDOW Creates a new window for an existing sheet or macro sheet

ON.WINDOW Runs a macro when you switch to a window

List of Information Functions


APP.ACTIVATE

Macro Sheets Only

Switches to an application. Use APP.ACTIVATE to switch to another application that is already running or that you have started by using EXEC.

Syntax

APP.ACTIVATE(title_text, wait_logical)

Important Microsoft Excel for the Macintosh requires system software version 7.0 or later for this function.

Title_text is the name of an application as displayed in its title bar.

  • If title_text is omitted, APP.ACTIVATE switches to Microsoft Excel.
  • If title_text is not a currently running application, APP.ACTIVATE returns the #VALUE! error value and interrupts the macro.
  • Title_text is not necessarily the name of the application file. Use the text that appears in the title bar of the application, which might include the name of the open document and path information.
  • In Microsoft Excel for the Macintosh, title_text can also refer to the Process Serial Number (PSN) that is returned by an EXEC function.

Wait_logical is a logical value determining when to switch to the application specified by title_text.

  • If wait_logical is TRUE, Microsoft Excel waits to be switched to before switching to the application specified by title_text.
  • If wait_logical is FALSE or omitted, Microsoft Excel immediately switches to the application specified by title_text.

Remarks

If you are running an application using Microsoft Excel macros, and you want to switch to a third application without switching to Microsoft Excel first, use FALSE as the wait_logical argument. With FALSE, you can use the application title_text without having to switch to Microsoft Excel first.

Examples

The following macro formula switches to Microsoft Word, which is currently displaying the document MONTHRPT.DOC in full screen mode:

APP.ACTIVATE("MICROSOFT WORD - MONTHRPT.DOC")

In Microsoft Excel for the Macintosh, the following macro formula switches to Microsoft Word:

APP.ACTIVATE("MICROSOFT WORD")

Tip Use an IF statement with APP.ACTIVATE to run an EXEC function if the application you want to switch to is not yet running.

Related Functions

The first five functions following are only for Microsoft Excel for Windows.

APP.MAXIMIZE Maximizes the Microsoft Excel application window

APP.MINIMIZE Minimizes the Microsoft Excel application window

APP.MOVE Moves the Microsoft Excel application window

APP.RESTORE Restores the Microsoft Excel application window

APP.SIZE Changes the size of the Microsoft Excel application window

EXEC Starts another application

List of DDE/External Functions


COPY

Macro Sheets Only

Equivalent to choosing the Copy command from the Edit menu. Copies and pastes data or objects.

Syntax

COPY(from_reference, to_reference)

From_reference is a reference to the cell or range of cells you want to copy. If from_reference is omitted, it is assumed to be the current selection.

To_reference is a reference to the cell or range of cells where you want to paste what you have copied.

  • To_reference should be a single cell or an enlarged multiple of from_reference. For example, if from_reference is a 2 by 4 rectangle, to_reference can be a 4 by 8 rectangle.
  • To_reference can be omitted so that you can subsequently paste using the PASTE, PASTE.LINK, or PASTE.SPECIAL functions.

Related Functions

CUT Cuts or moves data or objects

PASTE Pastes cut or copied data

PASTE.LINK Pastes copied data or objects and establishes a link to the source of the data or object

PASTE.SPECIAL Pastes specific components of copied data

List of Command-Equivalent Functions


DATA.DELETE

Macro Sheets Only

Equivalent to choosing the Delete command from the Data menu in Microsoft Excel version 4.0. Deletes data that matches the current criteria in the current database.

In the dialog-box form, DATA.DELETE?, Microsoft Excel displays a message warning you that matching records will be permanently deleted, and you can approve or cancel. In the plain form, DATA.DELETE, matching records are deleted without any message being displayed.

Syntax

DATA.DELETE( )
DATA.DELETE?( )

Related Functions

List of Command-Equivalent Functions


DATA.FIND

Macro Sheets Only

Equivalent to choosing the Find and Exit Find commands from the Data menu in Microsoft Excel version 4.0. Selects records in the database range which match criteria in the criteria range.

Syntax

DATA.FIND(logical)

Logical is a logical value that specifies whether to enter or exit the Data Find mode. If logical is TRUE, Microsoft Excel carries out the Find command; if FALSE, Microsoft Excel carries out the Exit Find command. If logical is omitted, the function toggles between Find and Exit Find.

Related Functions

DATA.FIND.NEXT Finds next matching record in a database

DATA.FIND.PREV Finds previous matching record in a database

List of Command-Equivalent Functions


DATA.FIND.NEXTDATA.FIND.PREV

DATA.FIND.NEXT
DATA.FIND.PREV

Macro Sheets Only

Equivalent to pressing the DOWN ARROW or UP ARROW key after the Find command has been chosen from the Data menu in Microsoft Excel version 4.0. Finds the next or previous matching record in a database. If the function cannot find a matching record, it returns the logical value FALSE.

Syntax

DATA.FIND.NEXT( )
DATA.FIND.PREV( )

Related Function

DATA.FIND Enters or exits Data Find mode

List of Command-Equivalent Functions


DATA.FORM

Macro Sheets Only

Equivalent to choosing the Form command from the Data menu. Displays the data form.

If Microsoft Excel cannot determine what database or list of information to use, the function returns the #VALUE! error value and interrupts the macro.

Syntax

DATA.FORM( )

Remarks

  • You can still use custom data forms created in Microsoft Excel version 4.0 or earlier. To edit the definition table of the custom data form, use the Dialog Editor from Microsoft Excel version 4.0.
  • The data form can handle up to 32 fields.

Related Functions

List of Command-Equivalent Functions


DEFINE.STYLE

Equivalent to choosing the Define button in the Style dialog box, which appears when you choose the Style command from the Format menu. Creates and changes cell styles. There are seven syntax forms of this function. Use syntax 1 of DEFINE.STYLE to define styles based on the format of the active cell. To create a style by specifying number, font, and other formats, use syntaxes 2 through 7 of DEFINE.STYLE.

Syntax 1

Syntaxes 2-7


DEFINE.STYLE - Syntax 1

Macro Sheets Only

Equivalent to choosing the Define button in the Style dialog box, which appears when you choose the Style command from the Format menu. Creates and changes cell styles. There are seven syntax forms of this function. Use syntax 1 of DEFINE.STYLE to define styles based on the format of the active cell. To create a style by specifying number, font, and other formats, use syntaxes 2 through 7 of DEFINE.STYLE.

Syntax

DEFINE.STYLE(style_text, number, font, alignment, border, pattern, protection)
DEFINE.STYLE?(style_text, number, font, alignment, border, pattern, protection)

Style_text is the name, as text, that you want to assign to the style.

The following arguments are logical values corresponding to check boxes in the Style dialog box. If an argument is TRUE, Microsoft Excel selects the check box and uses the corresponding format of the active cell in the style; if FALSE, Microsoft Excel clears the check box and omits formatting descriptions for that attribute. If style_text is omitted and all selected cells have identical formatting, the default is TRUE; if cells have different formatting, the default is FALSE.

Number corresponds to the Number check box.

Font corresponds to the Font check box.

Alignment corresponds to the Alignment check box.

Border corresponds to the Border check box.

Pattern corresponds to the Pattern check box.

Protection corresponds to the Protection check box.

Related Functions

APPLY.STYLE Applies a style to the selection

DELETE.STYLE Deletes a cell style

MERGE.STYLES Imports styles from another workbook into the active workbook

Syntaxes 2-7

List of Command-Equivalent Functions


DEFINE.STYLE - Syntaxes 2 - 7

Macro Sheets Only

Equivalent to choosing the Define button in the Style dialog box, which appears when you choose the Style command from the Format menu. Creates and changes cell styles. Use one of the following syntax forms of DEFINE.STYLE to select cell formats for a new style or to alter the formats of an existing style. Use syntax 1 of DEFINE.STYLE to define styles based on the format of the active cell.

Syntax 2

Number format, using the arguments from the FORMAT.NUMBER function

DEFINE.STYLE(style_text, attribute_num, format_text)

Syntax 3

Font format, using the arguments from the FORMAT.FONT and FONT.PROPERTIES functions

DEFINE.STYLE(style_text, attribute_num, name_text, size_num, bold, italic, underline, strike, color, outline, shadow, superscript, subscript)

Syntax 4

Alignment, using the arguments from the ALIGNMENT function

DEFINE.STYLE(style_text, attribute_num, horiz_align, wrap, vert_align, orientation)

Syntax 5

Border, using the arguments from the BORDER function

DEFINE.STYLE(style_text, attribute_num, left, right, top, bottom, left_color, right_color, top_color, bottom_color)

Syntax 6

Pattern, using the arguments from the cell form of the PATTERNS function

DEFINE.STYLE(style_text, attribute_num, apattern, afore, aback)

Syntax 7

Cell protection, using the arguments from the CELL.PROTECTION function

DEFINE.STYLE(style_text, attribute_num, locked, hidden)

Style_text is the name, as text, that you want to assign to the style.

Attribute_num is a number from 2 to 7 that specifies which attribute of the style, such as its font, alignment, or number format, you want to designate with this function.

Attribute_num Specifies

2 Number format

3 Font format

4 Alignment

5 Border

6 Pattern

7 Cell protection

Remarks

  • The remaining arguments are different for each form and are identical to arguments in the corresponding function. For example, form 2 of DEFINE.STYLE defines the number format of a style and corresponds to the FORMAT.NUMBER function. The exception is form 5, which does not include every argument for BORDER. For details on the values you can use for these arguments, see the description under the corresponding function.
  • If you define a style using one of these forms, then any attributes you don't explicitly define are not changed.

Related Functions

ALIGNMENT Aligns or wraps text in cells

APPLY.STYLE Applies a style to the selection

BORDER Adds a border to the selected cell or object

CELL.PROTECTION Allows you to control cell protection and display

DELETE.STYLE Deletes a cell style

FONT.PROPERTIES Applies a font to the selection

FORMAT.NUMBER Formats numbers, dates, and times in the selected cells

MERGE.STYLES Imports styles from another workbook into the active workbook

PATTERNS Changes the appearance of the selected object

Syntax 1

List of Command-Equivalent Functions


DELETE.NAME

Macro Sheets Only

Equivalent to choosing the Delete button in the Define Name dialog box, which appears when you choose the Define command from on the Name submenu on the Insert menu. Deletes the specified name.

Syntax

DELETE.NAME(name_text)

Name_text is a text value specifying the name that you want to delete.

Important Formulas that use names in their arguments may return incorrect or error values when a name used in the formula is deleted.

Related Functions

DEFINE.NAME Defines a name on the active worksheet or macro sheet

GET.NAME Returns the definition of a name

SET.NAME Defines a name as a value

List of Command-Equivalent Functions


DOCUMENTS

Macro Sheets Only

Returns, as a horizontal array in text form, the names of the specified open workbooks. Use DOCUMENTS to retrieve the names of open workbooks to use in other functions that manipulate open workbooks.

Syntax

DOCUMENTS(type_num, match_text)

Type_num is a number specifying whether to include add-in workbooks in the array of workbooks, according to the following table.

Type_num Returns

1 or omitted Names of all open workbooks except add-in workbooks

2 Names of add-in workbooks only

3 Names of all open workbooks

Match_text specifies the workbooks whose names you want returned and can include wildcard characters. If match_text is omitted, DOCUMENTS returns the names of all open workbooks.

Remarks

  • Use the INDEX function to select individual workbook names from the array to use in other functions that take workbook names as arguments.
  • Use COLUMNS to count the number of entries in the horizontal array.
  • Use TRANSPOSE to change a horizontal array to a vertical one.
  • Since the DOCUMENTS function only returns actual workbook names, it ignores any changes made by the WINDOW.TITLE function.

Examples

In Microsoft Excel for Windows, if your workspace contains windows named BUDGET.XLS, CHART1, ACTUAL.XLS:1, ACTUAL.XLS:2, and BOOK.XLS, then:

DOCUMENTS (1) equals the four-cell array {"ACTUAL.XLS", "BOOK.XLS",
"BUDGET.XLS", "CHART1"}

SET.NAME("Document_array", DOCUMENTS()) defines the name, Document_array, as {"ACTUAL.XLS", "BOOK.XLS", "BUDGET.XLS", "CHART1"}

In Microsoft Excel for the Macintosh, if your workspace contains windows named BUDGET CHART1, ACTUALS, ACTUALS:2, and BOOK then:

DOCUMENTS(1) equals the four-cell array {"ACTUALS", "BOOK", "BUDGET", "CHART1"}

Related Functions

FILES Returns the filenames in the specified directory or folder

GET.DOCUMENT Returns information about a workbook

GET.WINDOW Returns information about a window

WINDOWS Returns the names of all open windows

List of Information Functions


EDIT.OBJECT

Macro Sheets Only

Equivalent to choosing the Edit command from the (selected object) Object submenu on the Edit menu. Starts the application associated with the selected object and makes the object available for editing or other actions.

Syntax

EDIT.OBJECT(verb_num)

Verb_num is a number specifying which verb to use while working with the object, that is, what you want to do with the object.

  • The available verbs are determined by the object's source application. 1 often specifies "edit, " and 2 often specifies "play" (for sound, animation, and so on). For more information, consult the documentation for the object's application to see how it supports object linking and embedding (OLE).
  • If the object does not support multiple verbs, verb_num is ignored.
  • If verb_num is omitted, it is assumed to be 1.

Remarks

Your macro pauses while you're editing the object and resumes when you return to Microsoft Excel.

Related Function

INSERT.OBJECT Creates an object of a specified type

List of Command-Equivalent Functions


EDITION.OPTIONS

Macro Sheets Only

Sets options in, or performs actions on, the specified publisher or subscriber. In Microsoft Excel for Windows, EDITION.OPTIONS also allows you to cancel a publisher or subscriber created in Microsoft Excel for the Macintosh.

Syntax

EDITION.OPTIONS(edition_type, edition_name, reference, option, appearance, size, formats)

Edition_type is the number 1 or 2 specifying the type of edition.

Edition_type Type of edition

1 Publisher

2 Subscriber

Edition_name is the name of the edition you want to change the edition options for or to perform actions on. If edition_name is omitted, reference is required.

Reference specifies the range (given in text form as a name or an R1C1-style reference) occupied by the publisher or subscriber.

  • Reference is required if you have more than one publisher or subscriber of edition_name on the active workbook. Use reference to specify the location of the publisher or subscriber for which you want to set options.
  • If edition_type is 1 and the publisher is an embedded chart, or if edition_type is 2 and the subscriber is a picture, reference is the object identifier as displayed in the reference area.
  • If reference is omitted, edition_name is required.

Option is a number from 1 to 6 specifying the edition option you want to set or the action you want to take, according to the following two tables. Options 2 to 6 are only available if you are using Microsoft Excel for the Macintosh with system software version 7.0 or later.

If a publisher is specified, then option applies as follows.

Option Action

1 Cancels the publisher

2 Sends the edition now

3 Selects the range or object published to the specified edition

4 Automatically updates the edition when the file is saved

5 Updates the edition on request only

6 Changes the edition file as specified by appearance, size, and formats

If a subscriber is specified, then option applies as follows.

Option Action

1 Cancels the subscriber

2 Gets the latest edition

3 Opens the publisher workbook

4 Automatically updates when new data is available

5 Update on request only

The following three arguments are available only when option is 6.

Appearance specifies whether the selection is published as shown on screen or as shown when printed. The default value for appearance is 1 if the selection is a sheet or macro sheet and 2 if the selection is a chart.

Appearance Selection is published

1 As shown on screen

2 As shown when printed

Size specifies the size of a published chart. Size is only available if a chart is to be published.

Size Chart size is published

1 or omitted As shown on screen

2 As shown when printed

Formats is a number specifying the format of the file.

Formats File format

1 or omitted PICT

2 BIFF

4 RTF

8 VALU

You can also use the sum of the allowable file formats. For example, a value of 6 specifies BIFF and RTF.

Example

The following macro formula opens the workbook (and application) that published the edition named Monthly Totals:

EDITION.OPTIONS(2, "Monthly Totals", , 3)

Related Functions

CREATE.PUBLISHER Creates a publisher from the selection

GET.LINK.INFO Returns information about a link

SUBSCRIBE.TO Inserts contents of an edition into the active workbook

List of Command-Equivalent Functions


EMBED

Displayed in the formula bar when an embedded object is selected. EMBED cannot be entered on a sheet or used in a macro.

Syntax

EMBED(object_class, item)

Object_class is the name of the application and document type that created the embedded object. For example, the object_class arguments used when Microsoft Excel sheets are embedded in other applications are "Excel.sheet.5" and "Excel.Chart.5".

Item is the area selected to copy, and determines the view on the embedded document. When item is empty text (""), EMBED creates a view on the entire document.

Remarks

If you delete the EMBED formula, the embedded object remains on the document as a graphic, and the link to the creating application is deleted. Double-clicking the object no longer starts the creating application.


EXEC

Macro Sheets Only

Starts a separate program. Use EXEC to start other programs with which you want to communicate. Use EXEC with Microsoft Excel's other DDE functions (INITIATE, EXECUTE, and SEND.KEYS) to create a channel to another program and to send keystrokes and commands to the program. (SEND.KEYS is available only in Microsoft Excel for Windows.)

Syntax 1 is for Microsoft Excel for Windows. Syntax 2 is for Microsoft Excel for the Macintosh.

Syntax 1

For Microsoft Excel for Windows

EXEC(program_text, window_num)

Syntax 2

For Microsoft Excel for the Macintosh

EXEC(program_text, , background, preferred_size_only)

Important Microsoft Excel for the Macintosh requires system software version 7.0 or later for the last two arguments of this function.

Program_text is the name, as a text string, of any executable file or, in Microsoft Excel for Windows, any data file that is associated with an executable file.

  • Use paths when the file or program to be started is not in the current directory or folder.
  • In Microsoft Excel for Windows, program_text can include any arguments and switches that are accepted by the program to be started. Also, if program_text is the name of a file associated with a specific installed program, EXEC starts the program and loads the specified file.

Note In Microsoft Excel for the Macintosh, you must use an extra comma after the program_text argument. This skips the window_num argument that does not apply to the Macintosh.

Window_num is a number from 1 to 3 that specifies how the window containing the program should appear. Window_num is only available for use with Microsoft Excel for Windows. The window_num argument is allowed on the Macintosh, but it is ignored.

Window_num Window appears

1 Normal size

2 or omitted Minimized size

3 Maximized size

Background is a logical value that determines whether the program specified by program_text is opened as the active program or in the background, leaving Microsoft Excel as the active program. If background is TRUE, the program is started in the background; if FALSE or omitted, the program is started in the foreground. Background is only available for use with Microsoft Excel for the Macintosh and system software version 7.0 or later.

Preferred_size_only is a logical value that determines the amount of memory allocated to the program. If preferred_size_only is TRUE, the program is opened with its preferred memory allocation; if FALSE or omitted, it opens with the available memory if greater than its minimum requirement. Preferred_size_only is only available for use with Microsoft Excel for the Macintosh and system software version 7.0 or later. For information about changing the preferred memory size, see your Macintosh documentation.

Remarks

In Microsoft Excel for Windows and in Microsoft Excel for the Macintosh with system software version 7.0, if the EXEC function is successful, it returns the task ID number of the started program. The task ID number is a unique number that identifies a program. Use the task ID number in other macro functions, such as APP.ACTIVATE, to refer to the program. In Microsoft Excel for the Macintosh with system software version 6.0, if EXEC is successful, it returns TRUE. If EXEC is unsuccessful, it returns the #VALUE! error value.

Examples

In Microsoft Excel for Windows, the following macro formula starts the program SEARCH.EXE. Use paths when the file or program to be started is not in the current directory:

EXEC("C:\WINDOWS\SEARCH.EXE")

The following macro formula starts Microsoft Word for Windows and loads the document SALES.DOC:

EXEC("C:\WINWORD\WINWORD.EXE C:\MYFILES\SALES.DOC")

In Microsoft Excel for the Macintosh, the following macro formula starts Microsoft Word:

EXEC("HARD DISK:APPS:WORD")

Related Functions

APP.ACTIVATE Switches to another application

EXECUTE Carries out a command in another application

INITIATE Opens a channel to another application

SEND.KEYS Sends a key sequence to an application

TERMINATE Closes a channel to another application

REQUEST Requests an array of a specific type of information from an application with which you have a dynamic data exchange (DDE) link

POKE Sends data to another application with which you have a dynamic data exchange (DDE) link

List of DDE/External Functions


EXECUTE

Macro Sheets Only

Carries out commands in another program with which you have a dyamic data exchange (DDE) link. Use with EXEC, INITIATE, and SEND.KEYS to run another program through Microsoft Excel. (SEND.KEYS is available only in Microsoft Excel for Windows.)

Important Microsoft Excel for the Macintosh requires system software version 7.0 or later for this function.

Syntax

EXECUTE(channel_num, execute_text)

Channel_num is a number returned by a previously run INITIATE function. Channel_num refers to a channel through which Microsoft Excel communicates with another program.

Execute_text is a text string representing commands you want to carry out in the program specified by channel_num. The form of execute_text depends on the program you are referring to. To include specific key sequences in execute_text, use the format described under key_text in the ON.KEY function.

If EXECUTE is not successful, it returns one of the following error values:

Value returned Situation

#VALUE! Channel_num is not a valid channel number.

#N/A The program you are accessing is busy.

#DIV/0! The program you are accessing does not respond after a certain length of time or you have pressed ESC to cancel.

#REF! The keys specified in execute_text are refused by the application which you want to access.

Remarks

Commands sent to another program with EXECUTE will not work when a dialog box is displayed in the program. In Microsoft Excel for Windows, you can use SEND.KEYS to send commands that make selections in a dialog box.

Examples

The following macro formula sends the number 25 and a carriage return to the application identified by channel_num 14:

EXECUTE(14, "25~")

Related Functions

EXEC Starts another application

INITIATE Opens a channel to another application

POKE Sends data to another application

REQUEST Returns data from another application

SEND.KEYS Sends a key sequence to an application

TERMINATE Closes a channel to another application

List of DDE/External Functions


EXTRACT

Macro Sheets Only

Equivalent to choosing the Extract command from the Data menu in Microsoft Excel version 4.0. Finds database records that match the criteria defined in the criteria range and copies them into a separate extract range.

Syntax

EXTRACT(unique)
EXTRACT?(unique)

Unique is a logical value corresponding to the Unique Records Only check box in the Extract dialog box.

  • If unique is TRUE, Microsoft Excel selects the check box and excludes duplicate records from the extract list.
  • If unique is FALSE or omitted, Microsoft Excel clears the check box and extracts all records matching the criteria.

Related Functions

DATA.FIND Finds records in a database

SET.CRITERIA Defines the name Criteria for the selected range on the active sheet

SET.DATABASE Defines the name Database for the selected range on the active sheet

SET.EXTRACT Defines the name Extract for the selected range on the active sheet

List of Command-Equivalent Functions


FORMAT.NUMBER

Macro Sheets Only

Equivalent to choosing the Number tab in the Format Cells dialog box, which appears when you choose Cells from the Format menu. Formats numbers, dates, and times in the selected cells, data labels, and axis labels on charts. Use FORMAT.NUMBER to apply built-in formats or to create and apply custom formats.

Syntax

FORMAT.NUMBER(format_text)
FORMAT.NUMBER?(format_text)

Format_text is a format string, such as "#, ##0.00", specifying which format to apply to the selection.

Related Functions

DELETE.FORMAT Deletes the specified custom number format

FONT.PROPERTIES Applies a font to the selection

FORMAT.TEXT Formats a sheet text box or a chart text item

List of Command-Equivalent Functions


GET.OBJECT

Macro Sheets Only

Returns information about the specified object. Use GET.OBJECT to return information you can use in other macro formulas that manipulate objects.

Syntax

GET.OBJECT(type_num, object_id_text, start_num, count_num, item_index)

Type_num is a number specifying the type of information you want returned about an object. GET.OBJECT returns the #VALUE! error value (and the macro is halted) if an object isn't specified or if more than one object is selected.

Type_num Returns

1 | Number specifying the type of the selected object: 0 = Grouped objects 1 = Line 2 = Rectangle 3 = Oval 4 = Arc 5 = Embedded chart 6 = Text box 7 = Button 8 = Picture 9 = Closed polygon 10 = Open polygon (freehand drawing) 11 = Check box 12 = Option button 13 = Edit box 14 = Label 15 = Dialog Frame 16 = Spinner 17 = Scroll bar 18 = List box 19 = Group box 20 = Drop down box
2 | If the object is locked, returns TRUE; otherwise FALSE.
3 | Z-order position (layering) of the object; that is, the relative position of the overlapping objects, starting with 1 for the object that is most under the others.
4 | Reference of the cell under the upper-left corner of the object as text in R1C1 reference style; for a line or arc, returns the start point.
5 | X offset from the upper-left corner of the cell under the upper-left corner of the object, measured in points.
6 | Y offset from the upper-left corner of the cell under the upper-left corner of the object, measured in points.
7 | Reference of the cell under the lower-right corner of the object as text in R1C1 reference style; for a line or arc, returns the end point.
8 | X offset from the upper-left corner of the cell under the lower-right corner of the object, measured in points.
9 | Y offset from the upper-left corner of the cell under the lower-right corner of the object, measured in points.
10 | Name, including the filename, of the macro assigned to the object. If no macro is assigned, returns FALSE.
11 | Number indicating how the object moves and sizes: 1 = Object moves and sizes with cells 2 = Object moves with cells 3 = Object is fixed

Values 12 to 21 for type_num apply only to text boxes and buttons. If another type of object is selected, GET.OBJECT returns the #VALUE! error value.

Type_num Returns

12 | Text starting at start_num for count_num characters.
13 | Font name of all text starting at start_num for count_num characters. If the text contains more than one font name, returns the #N/A error value.
14 | Font size of all text starting at start_num for count_num characters. If the text contains more than one font size, returns the #N/A error value.
15 | If all text starting at start_num for count_num characters is bold, returns TRUE. If text contains only partial bold formatting, returns the #N/A error value.
16 | If all text starting at start_num for count_num characters is italic, returns TRUE. If text contains only partial italic formatting, returns the #N/A error value.
17 | If all text starting at start_num for count_num characters is underlined, returns TRUE. If text contains only partial underline formatting, returns the #N/A error value.
18 | If all text starting at start_num for count_num characters is struck through, returns TRUE. If text contains only partial struck-through formatting, returns the #N/A error value.
19 | In Microsoft Excel for the Macintosh, if all text starting at start_num for count_num characters is outlined, returns TRUE. If text contains only partial outline formatting, returns the #N/A error value. Always returns FALSE in Microsoft Excel for Windows.
20 | In Microsoft Excel for the Macintosh, if all text starting at start_num for count_num characters is shadowed, returns TRUE. If text contains only partial shadow formatting, returns the #N/A error value. Always returns FALSE in Microsoft Excel for Windows.
21 | Number from 0 to 56 indicating the color of all text starting at start_num for count_num characters; if color is automatic, returns 0. If more than one color is used, returns the #N/A error value.

Values 22 to 25 for type_num also apply only to text boxes and buttons. If another type of object is selected, GET.OBJECT returns the #N/A error value.

Type_num Returns

22 | Number indicating the horizontal alignment of text: 1 = Left 2 = Center 3 = Right 4 = Justified
23 | Number indicating the vertical alignment of text: 1 = Top 2 = Center 3 = Bottom 4 = Justified
24 | Number indicating the orientation of text: 0 = Horizontal 1 = Vertical 2 = Upward 3 = Downward
25 | If button or text box is set to automatic sizing, returns TRUE; otherwise FALSE.

The following values for type_num apply to all objects, except where indicated.

Type_num Returns

26 | If the object is visible, returns TRUE; if the object has been hidden by the HIDE.OBJECT function, returns FALSE.
27 | Number indicating the type of the border or line: 0 = Custom 1 = Automatic 2 = None
28 | Number indicating the style of the border or line as shown in the Patterns tab in the Format Objects dialog box: 0 = None 1 = Solid line 2 = Dashed line 3 = Dotted line 4 = Dashed dotted line 5 = Dashed double-dotted line 6 = 50% gray line 7 = 75% gray line 8 = 25% gray line
29 | Number from 0 to 56 indicating the color of the border or line; if the border is automatic, returns 0.
30 | Number indicating the weight of the border or line: 1 = Hairline 2 = Thin 3 = Medium 4 = Thick
31 | Number indicating the type of fill: 0 = Custom 1 = Automatic 2 = None
32 | Number from 1 to 18 indicating the fill pattern as shown in the Format Object dialog box.
33 | Number from 0 to 56 indicating the foreground color of the fill pattern; if the fill is automatic, returns 0. If the object is a line, returns the #N/A error value.
34 | Number from 0 to 56 indicating the background color of the fill pattern; if the fill is automatic, returns 0. If the object is a line, returns the #N/A error value.
35 | Number indicating the width of the arrowhead: 1 = Narrow 2 = Medium 3 = Wide If the object is not a line, returns the #N/A error value.
36 | Number indicating the length of the arrowhead: 1 = Short 2 = Medium 3 = Long If the object is not a line, returns the #N/A error value.
37 | Number indicating the style of the arrowhead: 1 = No head 2 = Open head 3 = Closed head 4 = Open double-ended head 5 = Closed double-ended head If the object is not a line, returns the #N/A error value.
38 | If the border has round corners, returns TRUE; if the corners are square, returns FALSE. If the object is a line, returns the #N/A error value.
39 | If the border has a shadow, returns TRUE; if the border has no shadow, returns FALSE. If the object is a line, returns the #N/A error value.
40 | If the Lock Text check box in the Protection Tab of the Format Object dialog box is selected, returns TRUE; otherwise FALSE.
41 | If objects are set to be printed, returns TRUE; otherwise FALSE.
42 | The horizontal distance, measured in points, from the left edge of the active window to the left edge of the object. May be a negative number if the window is scrolled beyond the object.
43 | The vertical distance, measured in points, from the top edge of the active window to the top edge of the object. May be a negative number if the window is scrolled beyond the object.
44 | The horizontal distance, measured in points, from the left edge of the active window to the right edge of the object. May be a negative number if the window is scrolled beyond the object.
45 | The vertical distance, measured in points, from the top edge of the active window to the bottom edge of the object. May be a negative number if the window is scrolled beyond the object.
46 | The number of vertices in a polygon, or the #N/A error value if the object is not a polygon.
47 | A count_num by 2 array of vertex coordinates starting at start_num in a polygon's array of vertices.
48 | If the object is a text box, returns the cell reference that the text box is linked to. If the object is a control on a worksheet, returns the cell reference that the control's value is linked to. This information is returned as a string.
49 | Returns the ID number of the object. For example, "Rectangle 5" returns 5. Note that the name of the object may not have this index in it if the object has been renamed by the user.
50 | Returns the object's classname. For example, "Rectangle".
51 | Returns the object name. By default, object names are the classname followed by the ID. For example, "Rectangle 1" is an object name, of which "Rectangle" is the classname, and 1 is the ID number. The object can also be renamed, in which case the name picked by the user is returned.
52 | Returns the distance from cell A1 to the Left of the object bounding rectangle in points
53 | Returns the distance from Cell A1 to the top of the object bounding rectangle in points
54 | Returns the width of object bounding rectangle in points
55 | Returns the height of object bounding rectangle in points
56 | If the object is enabled, returns TRUE; otherwise, it returns FALSE.
57 | Returns the shortcut key assignment for the control object, as text.
58 | Returns TRUE is the button control on a dialog sheet is the default button of the dialog; otherwise, returns FALSE
59 | Returns TRUE if the button control on the dialog sheet is clicked when the user presses the ESCAPE Key; otherwise, returns FALSE.
60 | Returns TRUE if the button control on a dialog sheet will close the dialog box when pressed; otherwise, returns FALSE
61 | Returns TRUE if the button control on a dialog sheet will be clicked when the user presses F1.
62 | Returns the value of the control. For a check box or radio button, Returns 1 if it is selected, zero if it is not selected, or 2 if mixed. For a List box or dropdown box, returns the index number of the selected item, or zero if no item is selected. For a scroll bar, returns the numeric value of the scroll bar.
63 | Returns the minimum value that a scroll bar or spinner button can have
64 | Returns the maximum value that a scroll bar or spinner button can have
65 | Returns the step increment value added or subtracted from the value of a scroll bar or spinner. This value is used when the arrow buttons are pressed on the control.
66 | Returns the large, or "page" step increment value added or subtracted from the value of a scroll bar when it is clicked in the region between the thumb and the arrow buttons.
67 | Returns the input type allowed in an edit box control: 1 = Text 2 = Integer 3 = Number (what type) 4 = Cell reference 5 = Formula
68 | Returns TRUE if the edit box control allows multi-line editing with wrapped text; otherwise, it returns FALSE.
69 | Returns TRUE if the edit box has a vertical scroll bar; otherwise, it returns FALSE.
70 | Returns the object ID of the object that is linked to a list box or edit box. For a dropdown combo box that has an editable entry field, returns the object ID of itself. A dropdown box that can't be edited, returns FALSE.
71 | Returns the number of entries in a List box, dropdown List box, or dropdown combo box.
72 | Returns the text of the selected entry in a List box, dropdown List box, or dropdown combo box.
73 | Returns the range used to fill the entries in a List box, dropdown List box, or dropdown combo box, as text. If an empty string is returned, then the control isn't filled from a range.
74 | Returns the number of list lines displayed when a dropdown control is dropped.
75 | Returns TRUE the object is displayed as 3-D; otherwise, it returns FALSE.
76 | Returns the Far East phonetic accelerator key as text. Used for Far East versions of Microsoft Excel.
77 |  | Returns the select status of the list box: 0 = single 1 = simple multi-select 2 = extended multi-select
78 |  | Returns an array of TRUE and FALSE values indicating which items are selected in a list box. If TRUE, the item is selected; If FALSE, the item is not selected.
79 |  | Returns TRUE if the add indent attribute is on for alignment. Returns FALSE if the add indent attribute is off for alignment. Used for only Far East versions of Microsoft Excel.

Object_id_text is the name and number, or number alone, of the object you want information about. Object_id_text is the text displayed in the reference area when the object is selected. If object_id_text is omitted, it is assumed to be the selected object. If object_id_text is omitted and no object is selected, GET.OBJECT returns the #REF! error value and interrupts the macro.

Start_num is the number of the first character in the text box or button or the first vertex in a polygon you want information about. Start_num is ignored unless a text box, button, or polygon is specified by type_num and object_id_text. If start_num is omitted, it is assumed to be 1.

Count_num is the number of characters in a text box or button, or the number of vertices in a polygon, starting at start_num, that you want information about. Count_num is ignored unless a text box, button, or polygon is specified by type_num and object_id_text. If count_num is omitted, it is assumed to be 255.

Item_index is the index number or position of the item in the list box or drop-down box that you want information about, ranging from 1 to the number of items in the list box or drop-down box.

Tip Use GET.OBJECT(45) - GET.OBJECT(43) to determine the height of an object and GET.OBJECT(44) - GET.OBJECT(42) to determine the width.

Examples

The following macro formula returns the reference of the cell under the upper-left corner of the object Oval 3 (assume the cell is E2):

GET.OBJECT(4, "Oval 3") returns "R2C5"

The following macro formula changes the protection status of the object Rectangle 2 if it is locked:

IF(GET.OBJECT(2, "Rectangle 2"), OBJECT.PROTECTION(FALSE))

The following macro formula returns characters 25 through 185 from the object Text 5:

GET.OBJECT(12, "Text 5", 25, 160)

Related Functions

CREATE.OBJECT Creates an object

FONT.PROPERTIES Applies a font to the selection

OBJECT.PROTECTION Controls how an object is protected

PLACEMENT Determines an object's relationship to underlying cells

List of Information Functions


INITIATE

Macro Sheets Only

Opens a dynamic data exchange (DDE) channel to an application and returns the number of the open channel. Once you have opened a channel to another application with INITIATE, you can use EXECUTE and SEND.KEYS to control the other application from a Microsoft Excel macro. (SEND.KEYS is available only with Microsoft Excel for Windows.) If INITIATE is successful, it returns the number of the open channel. All the subsequent DDE macro functions use this number to specify the channel. If INITIATE is unsuccessful, FALSE is returned.

Important Microsoft Excel for the Macintosh requires system software version 7.0 or later for this function.

Syntax

INITIATE(app_text, topic_text)

App_text is the DDE name of the application with which you want to begin a DDE session, in text form. The form of app_text depends on the application you are accessing. The DDE name of Microsoft Excel, for example, is "Excel".

Topic_text describes something, such as a document or a record in a database, in the application that you are accessing; the form of topic_text depends on the application you are accessing. Microsoft Excel accepts the names of the current documents as topic_text, as well as the name "System".

Remarks

  • You can specify an instance of an application by appending the application's task ID number to the app_text argument. If you start an application by using the EXEC function, EXEC returns the task ID number for that instance of the application.
  • If more than one instance of an application is running and you do not specify which instance you would like to open a channel to, INITIATE displays a dialog box from which you can choose the instance you want. You can prevent this dialog box from appearing by disabling or redirecting errors with the ERROR function.

Example

The following macro formula opens a channel to the document named MEMO in the application named WORD:

INITIATE("WORD", "MEMO")

Related Functions

POKE Sends data to another application

REQUEST Returns data from another application

TERMINATE Closes a channel to another application

EXECUTE Carries out a command in another application

EXEC Starts a separate program

List of DDE/External Functions


INSERT.OBJECT

Macro Sheets Only

Equivalent to choosing the Object command from the Insert menu, and then selecting an object type and choosing the OK button. Creates an embedded object whose source data is supplied by another application. Also starts an application of the appropriate class for the specified object type.

Syntax

INSERT.OBJECT(object_class, file_name, link_logical, display_icon_logical, icon_file, icon_number, icon_label)
INSERT.OBJECT?(object_class, file_name, link_logical, display_icon_logical, icon_file, icon_number, icon_label)

Object_class is a text string containing the classname for the object you want to create.

  • Object_class is the classname corresponding to the Object Type selection in the Insert Object dialog box.
  • For more information about object classnames, consult the documentation for your source application to see how it supports object linking and embedding (OLE).

File_name is a text string specifying the file from which to create an OLE object.

Link_logical is a logical value indicating whether the new object based on file_name should be linked to file_name. If it is not linked, the object is created as a copy or the file. Link_logical is ignored if file_name is not specified. If link_logical is FALSE or omitted, then no link is established.

Display_icon_logical is a logical value corresponding to the Display as Icon checkbox. If it is FALSE or omitted, then the regular picture for the object is displayed. If it is TRUE, then the icon icon_number found in icon_file is displayed with the label icon_label. If display_icon_logical is not TRUE, then icon_file, icon_number, and icon_label are ignored.

Icon_file is the name of the file where the icon to display is located.

Icon_number is the number of the icon within icon_file that should be used.

Icon_label is a text string indicating a label to display beneath the icon. If the parameter is an empty string ("") or is omitted, no label is displayed.

Remarks

  • If INSERT.OBJECT starts another application, your macro pauses. Your macro resumes when you return to Microsoft Excel.
  • Although you will not normally use Microsoft Excel classnames in a Microsoft Excel macro, you may need them in macros written for other applications. Microsoft Excel uses classnames "Excel.Sheet.5" and "Excel.Chart.5".

Related Function

EDIT.OBJECT Edits an object

List of Command-Equivalent Functions


ON.DATA

Macro Sheets Only

Runs a specified macro when another application sends data to a particular workbook via dynamic data exchange (DDE) or via Publish and Subscribe on the Macintosh. Workbook links to other applications are called remote references.

Syntax

ON.DATA(document_text, macro_text)

Important Microsoft Excel for the Macintosh requires system software version 7.0 or later for this function.

Document_text is the name of the sheet to which remote data will be sent or the name of the source of the remote data.

  • If document_text is the name of the remote data source, it must be in the form app|topic!item. You can use the form app|topic to include all items for a particular topic, or app| to specify an app alone, but you must include the | to indicate that you are specifying the name of a data source.
  • If document_text is omitted, the macro specified by macro_text is run whenever remote data is sent to any sheet not already assigned to another ON.DATA function.
  • In Microsoft Excel for the Macintosh, document_text can also be the name of a published edition file. Unless the file is in the current folder, document_text must include the complete path.

Macro_text is the name of, or an R1C1-style reference to, a macro that you want to run when data comes into the workbook or from the source specified by document_text. The name or reference must be in text form.

  • If macro_text is omitted, the ON.DATA function is turned off for the specified workbook or source.

Remarks

  • ON.DATA remains in effect until you either clear it or quit Microsoft Excel. You can clear ON.DATA by specifying document_text and omitting the macro_text argument.
  • If the macro sheet containing macro_text is closed when data is sent to document_text, an error is returned.
  • If the incoming data causes recalculation, Microsoft Excel first runs the macro macro_text and then performs the recalculation.

Examples

In Microsoft Excel for Windows, the following macro formula runs the macro AddOrders when data is sent to the sheet New in the workbook ORDERSDB.XLS:

ON.DATA("[ORDERSDB.XLS]New", "AddOrders")

In Microsoft Excel for the Macintosh, the following macro formula runs the macro beginning at cell R2C3 when data is sent to the sheet North in the workbook SALES DATABASE:

ON.DATA("[SALES DATABASE]North", "R2C3")

Related Functions

ERROR Specifies what action to take if an error is encountered while a macro is running

INITIATE Opens a channel to another application

ON.ENTRY Runs a macro when data is entered

ON.RECALC Runs a macro when a workbook is recalculated

List of Customizing Functions


ON.DOUBLECLICK

Macro Sheets Only

Runs a macro when you double-click any cell or object on the specified sheet or macro sheet or double-click any item on the specified chart.

Syntax

ON.DOUBLECLICK(sheet_text, macro_text)

Sheet_text is a text value specifying the name of a sheet in a workbook. If sheet_text is omitted, the macro is run whenever you double-click any sheet not specified by a previous ON.DOUBLECLICK formula. Sheet_text must be in the form "[book1]sheet1".

Macro_text is the name of, or an R1C1-style reference to, a macro you want to run when you double-click the sheet specified by sheet_text. The name or reference must be in text form. If macro_text is omitted, double-clicking reverts to its normal behavior, and any macros assigned by previous ON.DOUBLECLICK functions are turned off.

Remarks

  • ON.DOUBLECLICK overrides Microsoft Excel's normal double-click behavior, such as displaying cell notes, displaying the Patterns dialog box, or allowing editing cell text directly in cells.
  • To determine what cell, object, or chart item has been double-clicked, use a CALLER function in the macro specified by macro_text.
  • ON.DOUBLECLICK does not affect objects to which ASSIGN.TO.OBJECT macros have already been assigned. Use ON.DOUBLECLICK (TRUE) to make Microsoft Excel carry out the action that would normally occur if you double-click on the current selection.

Related Functions

ASSIGN.TO.OBJECT Assigns a macro to an object

ON.WINDOW Runs a macro when you switch to a window

List of Customizing Functions


ON.ENTRY

Macro Sheets Only

Runs a macro when you enter data into any cell on the specified sheet.

Syntax

ON.ENTRY(sheet_text, macro_text)

Sheet_text is a text value specifying the name of a sheet in a workbook. If sheet_text is omitted, the macro is run whenever you enter data into any sheet or macro sheet.

Macro_text is the name of, or an R1C1-style reference to, a macro you want to run when you enter data into the sheet specified by sheet_text. The name or reference must be in text form. If macro_text is omitted, entering data reverts to its normal behavior, and any macros assigned by previous ON.ENTRY functions are turned off.

Remarks

  • The macro is run only when you enter data in a cell, not when you use edit commands or macro functions.
  • To determine what cell had data entered into it, use a CALLER function in the macro specified by macro_text.

Related Functions

ENTER.DATA Turns Data Entry mode on or off

ON.RECALC Runs a macro when a workbook is recalculated

List of Customizing Functions


ON.KEY

Macro Sheets Only

Runs a specified macro when a particular key or key combination is pressed.

Syntax

ON.KEY(key_text, macro_text)

Key_text can specify any single key, or any key combined with ALT, CTRL, or SHIFT, or any combination of those keys (in Microsoft Excel for Windows) or COMMAND, CTRL, OPTION, or SHIFT or any combination of those keys (in Microsoft Excel for the Macintosh). Each key is represented by one or more characters, such as "a" for the character a, or "{ENTER}" for the ENTER key.

To specify characters that aren't displayed when you press the key, such as ENTER or TAB, use the codes shown in the following table. Each code in the table represents one key on the keyboard.

Key Code

BACKSPACE "{BACKSPACE}" or "{BS}"

BREAK "{BREAK}"

CAPS LOCK "{CAPSLOCK}"

CLEAR "{CLEAR}"

DELETE or DEL "{DELETE}" or "{DEL}"

DOWN "{DOWN}"

END "{END}"

ENTER (numeric keypad) "{ENTER}"

ENTER "~" (tilde)

ESC "{ESCAPE} or {ESC}"

HELP "{HELP}"

HOME "{HOME}"

INS "{INSERT}"

LEFT "{LEFT}"

NUM LOCK "{NUMLOCK}"

PAGE DOWN "{PGDN}"

PAGE UP "{PGUP}"

RETURN "{RETURN}"

RIGHT "{RIGHT}"

SCROLL LOCK "{SCROLLLOCK}"

TAB "{TAB}"

UP "{UP}"

F1 through F15 "{F1}" through "{F15}"

In Microsoft Excel for Windows, you can also specify keys combined with SHIFT and/or CTRL and/or ALT. In Microsoft Excel for the Macintosh, you can also specify keys combined with SHIFT and/or CTRL and/or OPTION and/or COMMAND. To specify a key combined with another key or keys, use the following table.

To combine with Precede the key code by

SHIFT "+" (plus sign)

CTRL "^" (caret)

ALT or OPTION "%" (percent sign)

COMMAND "*" (asterisk)

To assign a macro to one of the special characters (+, ^, %, and so on), enclose the character in brackets. For example, ON.KEY("^{+}", "InsertItem") assigns a macro named InsertItem to the key sequence CTRL+PLUS SIGN.

Macro_text is the name of a macro that you want to run when key_text is pressed. The reference must be in text form.

  • If macro_text is "" (empty text), nothing happens when key_text is pressed. This form of ON.KEY disables the normal meaning of keystrokes in Microsoft Excel.
  • If macro_text is omitted, key_text reverts to its normal meaning in Microsoft Excel, and any special key assignments made with previous ON.KEY functions are cleared.

Remarks

  • ON.KEY remains in effect until you clear it or quit Microsoft Excel. You can clear ON.KEY by specifying key_text and omitting the macro_text argument.
  • If the macro sheet containing macro_text is closed when you press key_text, an error is returned.
  • If another macro is running when you press key_text, macro_text will not run.

Examples

Suppose you wanted the key combination SHIFT+CTRL+RIGHT to run the macro Print. You use the following macro formula:

ON.KEY("+^{RIGHT}", "Print")

To return SHIFT+CTRL+RIGHT to its normal meaning, you would use the following macro formula:

ON.KEY("+^{RIGHT}")

To disable SHIFT+CTRL+RIGHT altogether, you would use the following macro formula:

ON.KEY("+^{RIGHT}", "")

Related Functions

CANCEL.KEY Disables macro interruption

ERROR Specifies what action to take if an error is encountered while a macro is running

SEND.KEYS Sends a key sequence to an application

List of Customizing Functions


ON.RECALC

Macro Sheets Only

Runs a macro when a specific sheet is recalculated. Use ON.RECALC to perform an operation on a sheet each time the sheet is recalculated, such as checking that a certain condition is still being met.

Syntax

ON.RECALC(sheet_text, macro_text)

Sheet_text is the name of a sheet, given as text. If sheet_text is omitted, the macro is run whenever any open sheet not specified by a previous ON.RECALC formula is recalculated. Only one ON.RECALC formula can be run for each recalculation.

Macro_text is the name of, or an R1C1-style reference to, a macro you want to run when the sheet specified by sheet_text is recalculated. The name or reference must be in text form. The macro will be run each time the sheet is recalculated until ON.RECALC is cleared. If macro_text is omitted, recalculating reverts to its normal behavior, and any macros assigned by previous ON.RECALC functions are turned off.

Remarks

A macro specified to be run by ON.RECALC is not run by actions taken by other macros. For example, a macro specified by ON.RECALC will not be run after the CALCULATE.NOW function is carried out, but will be run if you change data in a sheet set to calculate automatically or choose the Calc Now button in the Calculation panel of the Options dialog box, which appears when you choose the Options command from the Tools menu.

Examples

In Microsoft Excel for Windows, the following macro formula specifies that the macro Printer on the macro sheet AUTOREPT.XLS be run when the worksheet named REPORT.XLS is recalculated:

ON.RECALC("REPORT.XLS", "AUTOREPT.XLS!Printer")

In Microsoft Excel for the Macintosh, the following macro formula turns off ON.RECALC for the workbook named SALES:

ON.RECALC("SALES")

Related Functions

CALCULATE.DOCUMENT Calculates the active document only

CALCULATE.NOW Calculates all open documents immediately

CALCULATION Controls calculation settings

ON.ENTRY Runs a macro when data is entered

List of Customizing Functions


ON.TIME

Macro Sheets Only

Runs a macro at a specified time. Use ON.TIME to run a macro at a specific time of day or after a specified period has passed.

Syntax

ON.TIME(time, macro_text, tolerance, insert_logical)

Time is the time and date, given as a serial number, at which the macro is to be run. If time does not include a date (that is, if time is a serial number less than 1), the macro is run the next time time occurs.

Macro_text is the name of, or an R1C1-style reference to, a macro to run at the specified time and every subsequent day at that time.

Tolerance is the time and date, given as a serial number, that you are willing to wait until and still have the macro run. For example, if Microsoft Excel is not in Ready, Copy, Cut, or Find mode at time, because another macro is running, but is in Ready mode 15 seconds later, and tolerance is set to time plus 30 seconds, the macro specified by macro_text will run. If Microsoft Excel was not in Ready mode within 30 seconds, the macro would not run. If tolerance is omitted, it is assumed to be infinite.

Insert_logical is a logical value specifying whether you want every day macro_text to run at time. Use insert_logical when you want to clear a previously set ON.TIME formula. If insert_logical is TRUE or omitted, the macro specified by macro_text is carried out at time. If insert_logical is FALSE and macro_text is not set to run at time, ON.TIME returns the #VALUE error value.

Examples

The following macro formula runs a macro called Test at 5:00:00 P.M. every day when Microsoft Excel is in Ready mode:

ON.TIME("5:00:00 PM", "Test")

The following macro formula runs a macro called Test 5 seconds after the formula is evaluated:

ON.TIME(NOW()+"00:00:05", "Test")

The following macro formula runs a macro called Test 10 seconds after the formula is evaluated. If Microsoft Excel is not in Ready mode at that time (because it is in Edit mode, for example), the tolerance argument specifies 5 seconds of additional time to wait to run the macro. If Microsoft Excel is still not in Ready mode at that time, macro_text is not run.

ON.TIME(NOW()+"00:00:10", "Test", NOW()+"00:00:15")

Related Functions

List of Customizing Functions


ON.WINDOW

Macro Sheets Only

Runs a specified macro when you switch to a particular window.

Syntax

ON.WINDOW(window_text, macro_text)

Window_text is the name of a window in the form of text. If window_text is omitted, ON.WINDOW starts the macro whenever you switch to any window, except for windows that are named in other ON.WINDOW statements.

Macro_text is the name of, or an R1C1-style reference to, a macro to run when you switch to window_text. If macro_text is omitted, switching to window_text no longer runs the previously specified macro.

Remarks

  • A macro specified to be run by ON.WINDOW is not run when other macros switch to the window or when a command to switch to a window is received through a DDE channel. Instead, ON.WINDOW responds to a user's actions, such as clicking a window with the mouse, choosing the Copy command from the Edit menu, and so on.
  • If a sheet or macro sheet has an Auto_Activate or Auto_Deactivate macro defined for it, those macros will be run after the macro specified by ON.WINDOW.

Examples

In Microsoft Excel for Windows, the following macro formula runs the macro beginning at cell R1C2 when you switch to the window MAIN.XLS:

ON.WINDOW("MAIN.XLS", "R1C2")

The following macro formula stops the macro from running when you switch to MAIN.XLS:

ON.WINDOW("MAIN.XLS")

In Microsoft Excel for the Macintosh, the following macro formula runs the macro named ShowAlert when you switch to the window MAIN WINDOW:

ON.WINDOW("MAIN WINDOW", "ShowAlert")

The following macro formula stops the macro from running when you switch to MAIN WINDOW:

ON.WINDOW("MAIN WINDOW")

Related Functions

GET.WINDOW Returns information about a window

ON.KEY Runs a macro when a specified key is pressed

ON.SHEET Triggers a macro whenever the specified sheet is activated from another sheet

WINDOWS Returns the names of all open windows

List of Customizing Functions


OPEN

Macro Sheets Only

Equivalent to choosing the Open command from the File menu. Opens an existing workbook.

Syntax

OPEN(file_text, update_links, read_only, format, prot_pwd, write_res_pwd, ignore_rorec, file_origin, custom_delimit, add_logical, editable, file_access, notify_logical, converter)
OPEN?(file_text, update_links, read_only, format, prot_pwd, write_res_pwd, ignore_rorec, file_origin, custom_delimit, add_logical, editable, file_access, notify_logical, converter)

File_text is the name, as text, of the workbook you want to open. File_text can include a drive and path, and can be a network pathname. In the dialog-box form in Microsoft Excel for Windows, file_text can include an asterisk (*) to represent any sequence of characters and a question mark (?) to represent any single character.

Update_links specifies whether and how to update external and remote references. If update_links is omitted, Microsoft Excel displays a message asking if you want to update links.

If update_links is Then Microsoft Excel

0 Updates neither external nor remote references

1 Updates external references only

2 Updates remote references only

3 Updates external and remote references

Note When you are opening a file in WKS, WK1, or WK3 format, the update_links argument specifies whether Microsoft Excel generates charts from any graphs attached to the WKS, WK1, or WK3 file.

If update_links is Charts are

0 Not created

2 Created

Read_only corresponds to the Read Only check box in the Open dialog box. If read_only is TRUE, the workbook can be modified but changes cannot be saved; if FALSE or omitted, changes to the workbook can be saved.

Format specifies what character to use as a delimiter when opening text files. If format is omitted, Microsoft Excel uses the current delimiter setting.

If format is Values are separated by

1 Tabs

2 Commas

3 Spaces

4 Semicolons

5 Nothing

6 Custom characters

Prot_pwd is the password, as text, required to unprotect a protected file. If prot_pwd is omitted and file_text requires a password, the Password dialog box is displayed. Passwords are case-sensitive. Passwords are not recorded when you open a workbook and supply the password with the macro recorder on.

Write_res_pwd is the password, as text, required to open a read-only file with full write privileges. If write_res_pwd is omitted and file_text requires a password, the Password dialog box is displayed.

Ignore_rorec is a logical value that controls whether the read-only recommended message is displayed. If ignore_rorec is TRUE, Microsoft Excel prevents display of the message; if FALSE or omitted, and if read_only is also FALSE or omitted, Microsoft Excel displays the alert when opening a read-only recommended workbook.

File_origin is a number specifying whether a text file originated on the Macintosh or in Windows.

File_origin Original operating environment

1 Macintosh

2 Windows (ANSI)

3 MS-DOS (PC-8)

Omitted Current operating environment

Custom_delimit is the character you want to use as a custom delimiter when opening text files.

  • Custom_delimit is text or a reference or formula that returns text, such as CHAR(124).
  • Custom_delimit is required if format is 6; it is ignored if format is not 6.
  • Only the first character in custom_delimit is used.

Add_logical is a logical value that specifies whether or not to add file_text to the open workbook. If add_logical is TRUE, the document is added; if FALSE or omitted, it is not added. This argument is for compatibility with workbooks from Microsoft Excel version 4.0.

Editable is a logical valule that corresponds to opening a file (such as a template) while holding down SHIFT key. If TRUE, editable is the equivalent to holding down the SHIFT key while choosing the OK button in the Open dialog box. If FALSE or omitted, this argument is ignored.

File_access is a number specifying how the file is to be accessed. If the file is being opened for the first time, this argument is ignored. If the file is already opened, this argument determines how to change the user's access permissions for the file.

File Access How Accessed

1 Revert to saved copy

2 Change to read/write access

3 Change to read only access

Notify_logical is a logical value that specifies whether the user should be notified when the shared document is available to be opened across a network. If TRUE, the user will be notified when the document is available to be opened. If FALSE or omitted, the user will not be notified when the file available to be opened.

Converter is a number corresponding to the file converter to use to open the file. Normally, Microsoft Excel automatically determines which file converter to use; therefore, this argument can usually be excluded. If you want to be certain, however, that a specific manually installed converter be used, then include this argument. Use GET.WORKSPACE(62) to determine which numbers corresponds to all of the installed converters.

Related Functions

CLOSE Closes the active window

FCLOSE Closes a text file

FOPEN Opens a file with the type of permission specified

OPEN.LINKS Opens specified supporting workbooks

List of Command-Equivalent Functions


PAGE.SETUP

Macro Sheets Only

Equivalent to choosing the Page Setup command from the File menu. Use PAGE.SETUP to control the printed appearance of your sheets.

There are three syntax forms of PAGE.SETUP. Syntax 1 applies if a sheet or macro sheet is active; syntax 2 applies if a chart is active; syntax three applies to Visual Basic modules and the info Window.

Arguments correspond to check boxes and text boxes in the Page Setup dialog box. Arguments that correspond to check boxes are logical values. If an argument is TRUE, Microsoft Excel selects the check box; if FALSE, Microsoft Excel clears the check box. Arguments for margins are always in inches, regardless of your country setting.

Syntax 1

Worksheets and macro sheets

PAGE.SETUP(head, foot, left, right, top, bot, hdng, grid, h_cntr, v_cntr, orient, paper_size, scale, pg_num, pg_order, bw_cells, quality, head_margin, foot_margin, notes, draft)

PAGE.SETUP?(head, foot, left, right, top, bot, hdng, grid, h_cntr, v_cntr, orient, paper_size, scale, pg_num, pg_order, bw_cells, quality, head_margin, foot_margin, notes, draft)

Syntax 2

Charts

PAGE.SETUP(head, foot, left, right, top, bot, size, h_cntr, v_cntr, orient, paper_size, scale, pg_num, bw_chart, quality, head_margin, foot_margin, draft)

PAGE.SETUP?(head, foot, left, right, top, bot, size, h_cntr, v_cntr, orient, paper_size, scale, pg_num, bw_chart, quality, head_margin, foot_margin, draft)

Syntax 3

Visual Basic Modules and the Info Window

PAGE.SETUP(head, foot, left, right, top, bot, orient, paper_size, scale, quality, head_margin, foot_margin, pg_num)
PAGE.SETUP?(head, foot, left, right, top, bot, orient, paper_size, scale, quality, head_margin, foot_margin, pg_num)

Head specifies the text and formatting codes for the header for the current sheet . For information about formatting codes, see "Remarks" later in this topic.

Foot specifies the text and formatting codes for the workbook footer.

Left corresponds to the Left box and is a number specifying the left margin.

Right corresponds to the Right box and is a number specifying the right margin.

Top corresponds to the Top box and is a number specifying the top margin.

Bot corresponds to the Bottom box and is a number specifying the bottom margin.

Hdng corresponds to the Row & Column Headings check box. Hdng is available only in the sheet and macro sheet form of the function.

Grid corresponds to the Cell Gridlines check box. Grid is available only in the sheet and macro sheet form of the function.

H_cntr corresponds to the Center Horizontally check box in the Margins panel of the Page Setup dialog box.

V_cntr corresponds to the Center Vertically check box in the Margins panel of the Page Setup dialog box.

Orient determines the direction in which your workbook is printed.

Orient Print format

1 Portrait

2 Landscape

Paper_size is a number from 1 to 26 that specifies the size of the paper.

Paper_size Paper type

1 Letter

2 Letter (small)

3 Tabloid

4 Ledger

5 Legal

6 Statement

7 Executive

8 A3

9 A4

10 A4 (small)

11 A5

12 B4

13 B5

14 Folio

15 Quarto

16 10x14

17 11x17

18 Note

19 ENV9

20 ENV10

21 ENV11

22 ENV12

23 ENV14

24 C Sheet

25 D Sheet

26 E Sheet

Scale is a number representing the percentage to increase or decrease the size of the sheet. All scaling retains the aspect ratio of the original.

  • To specify a percentage of reduction or enlargement, set scale to the percentage.
  • For worksheets and macros, you can specify the number of pages that the printout should be scaled to fit. Set scale to a two-item horizontal array, with the first item equal to the width and the second item equal to the height. If no constraint is necessary in one direction, you can set the corresponding value to #N/A.
  • Scale can also be a logical value. To fit the print area on a single page, set scale to TRUE.

Pg_num specifies the number of the first page. If zero, sets first page to zero. If "Auto" is used, then the page numbering is set to automatic. If omitted, PAGE.SETUP retains the existing pg_num.

Pg_order specifies whether pagination is left-to-right and then down, or top-to-bottom and then right.

Pg_order Pagination

1 Top-to-bottom, then right

2 Left-to-right, then down

Bw_cells is a logical value that specifies whether to print cells and all graphic objects, such as text boxes and buttons, in color.

  • If bw_cells is TRUE, Microsoft Excel prints cell text and borders in black and cell backgrounds in white.
  • If bw_cells is FALSE , Microsoft Excel prints cell text, borders, and background patterns in color (or in gray scale).

Bw_chart is a logical value that specifies whether to print chart in color.

Size is a number corresponding to the options in the Chart Size box, and determines how you want the chart printed on the page within the margins. Size is available only in the chart form of the function.

Size Size to print the chart

1 Screen size

2 Fit to page

3 Full page

Quality specifies the print quality in dots-per-inch. To specify both horizontal and vertical print quality, use an array of two values.

Head_margin is the placement, in inches, of the running head margin from the edge of the page.

Foot_margin is the placement, in inches, of the running foot margin from the edge of the page.

Draft corresponds to the Draft Quality checkbox in the Sheet tab and in the Chart tab of the Page Setup dialog box. If FALSE or omitted, graphics are printed with the sheet. If TRUE, no graphics are printed.

Notes specifies whether to print cell notes with the sheet. If TRUE, both the sheet and the cell notes are printed. If FALSE or omitted, just the sheet is printed.

Remarks

Microsoft Excel no longer requires you to enter formatting codes to format headers and footers, but the codes are still supported and recorded by the macro recorder. You can include these codes as part of the head and foot text strings to align portions of the header or footer to the left, right, or center; to include the page number, date, time, or workbook name; and to print the header or footer in bold or italic.

Formatting code Result

&L Left-aligns the characters that follow.

&C Centers the characters that follow.

&R Right-aligns the characters that follow.

&B Turns bold printing on or off (now obsolete).

&I Turns italic printing on or off.

&U Turns single underlining printing on or off.

&S Turns strikethrough printing on or off.

&O Turns outline printing on or off (Macintosh only).

&H Turns shadow printing on or off (Macintosh only).

&D Prints the current date.

&T Prints the current time.

&A Prints the name of the sheet

&F Prints the name of the workbook.

&P Prints the page number.

&P+number Prints the page number plus number.

&P-number Prints the page number minus number.

&& Prints a single ampersand.

& "fontname, fontstyle" Prints the characters that follow in the specified font and style. Be sure to include a comma immediately following the fontname, and double quotation marks around fontname and fontstyle.

&nn Prints the characters that follow in the specified font size. Use a two-digit number to specify a size in points.

&N Prints the total number of pages in the workbook.

&E Prints a double underline

&X Prints the character as superscript

&Y Prints the chararcter as subscript

Related Functions

DISPLAY Controls screen and Info Window display

GET.DOCUMENT Returns information about a workbook

PRINT Prints the active workbook

WORKSPACE Changes workspace settings

List of Command-Equivalent Functions


PATTERNS

Macro Sheets Only

Equivalent to choosing the Patterns tab in the Format Cells dialog box, which appears when you choose the Cells command from the Format menu. Changes the appearance of the selected cells or objects or the selected chart item (you can select only one chart item at a time). The PATTERNS function has eight syntax forms: syntax 1 is for cells on a sheet or macro sheet. Syntax 2 is for lines or arrows on a worksheet, macro sheet, or chart. Syntax 3 is for objects on a sheet or macro sheet. Syntax 4 through syntax 8 are for chart items.

Syntax 1

Cells

PATTERNS(apattern, afore, aback, newui)
PATTERNS?(apattern, afore, aback, newui)

Syntax 2

Lines (arrows) on worksheets or charts

PATTERNS(lauto, lstyle, lcolor, lwt, hwidth, hlength, htype)
PATTERNS?(lauto, lstyle, lcolor, lwt, hwidth, hlength, htype)

Syntax 3

Text boxes, rectangles, ovals, arcs, and pictures on worksheets or macro sheets

PATTERNS(bauto, bstyle, bcolor, bwt, shadow, aauto, apattern, afore, aback, rounded, newui)
PATTERNS?(bauto, bstyle, bcolor, bwt, shadow, aauto, apattern, afore, aback, rounded, newui)

Syntax 4

Chart plot areas, bars, columns, pie slices, and text labels

PATTERNS(bauto, bstyle, bcolor, bwt, shadow, aauto, apattern, afore, aback, invert, apply, new_fill)
PATTERNS?(bauto, bstyle, bcolor, bwt, shadow, aauto, apattern, afore, aback, invert, apply, new_fill)

Syntax 5

Chart axes

PATTERNS(lauto, lstyle, lcolor, lwt, tmajor, tminor, tlabel)
PATTERNS?(lauto, lstyle, lcolor, lwt, tmajor, tminor, tlabel)

Syntax 6

Chart gridlines, hi-lo lines, drop lines, lines on a picture line chart, and picture charts of bar and column charts

PATTERNS(lauto, lstyle, lcolor, lwt, apply, smooth)
PATTERNS?(lauto, lstyle, lcolor, lwt, apply, smooth)

Syntax 7

Chart data lines

PATTERNS(lauto, lstyle, lcolor, lwt, mauto, mstyle, mfore, mback, apply, smooth)
PATTERNS?(lauto, lstyle, lcolor, lwt, mauto, mstyle, mfore, mback, apply, smooth)

Syntax 8

Picture chart markers

PATTERNS(type, picture_units, apply)
PATTERNS?(type, picture_units, apply)

The following argument descriptions are in alphabetic order. Arguments correspond to check boxes, list boxes, and options in the Patterns tab of the Format Cells dialog box for the selected item. The default for each argument reflects the setting in the dialog box.

Aauto is a number from 0 to 2 specifying area settings (that is, the object's "surface area").

If aauto is Area settings are

0 Set by the user (custom)

1 Automatic (set by Microsoft Excel)

2 None

Aback is a number from 1 to 56 corresponding to the 56 area background colors in the Patterns tab of the Format Cells dialog box.

Afore is a number from 1 to 56 corresponding to the 56 area foreground colors in the Patterns tab of the Foramt Cells dialog box.

Apattern is a number corresponding to the area patterns in the Patterns tab of the Format Cells or Format Object dialog box. If an object is selected, apattern can be from 1 to 18; if a cell is selected, apattern can be from 0 to 18. If apattern is 0 and a cell is selected, Microsoft Excel applies no pattern.

Apply is a logical value corresponding to the Apply To All check box in Microsoft Excel version 4.0. This argument is for compatibility with previous versions of Microsoft Excel and applies only when a chart data point or a data series is selected.

  • If apply is TRUE, Microsoft Excel applies any formatting changes to all items that are similar to the selected item on the chart.
  • If apply is FALSE, Microsoft Excel applies formatting changes only to the selected item on the chart.

Bauto is a number from 0 to 2 specifying border settings.

If bauto is Border settings are

0 Set by the user (custom)

1 Automatic (set by Microsoft Excel)

2 None

Bcolor is a number from 1 to 56 corresponding to the 56 border colors in the Border tab of the Format Object or Format (chart element) dialog box.

Bstyle is a number from 1 to 8 corresponding to the eight border styles in the Border tab of the Format Object or Format (chart element) dialog box.

Bwt is a number from 1 to 4 corresponding to the four border weights in the Border tab of the Format Object or Format (chart element) dialog box.

If bwt is Border is

1 Hairline

2 Thin

3 Medium

4 Thick

Hlength is a number from 1 to 3 specifying the length of the arrowhead.

If hlength is Arrowhead is

1 Short

2 Medium

3 Long

Htype is a number from 1 to 5 specifying the style of the arrowhead.

If htype is Style of arrowhead is

1 No head

2 Open head

3 Closed head

4 Double open head

5 Double closed head

Hwidth is a number from 1 to 3 specifying the width of the arrowhead.

If hwidth is Arrowhead is

1 Narrow

2 Medium

3 Wide

Invert is a logical value corresponding to the Invert If Negative check box in the Patterns tab of the Format Data Series dialog box. This argument applies only to data markers.

  • If invert is TRUE, Microsoft Excel inverts the pattern in the selected item if it corresponds to a negative number.
  • If invert is FALSE, Microsoft Excel removes the inverted pattern, if present, from the selected item corresponding to a negative value.

Lauto is a number from 0 to 2 specifying line settings.

If lauto is Line settings are

0 Set by the user (custom)

1 Automatic (set by Microsoft Excel)

2 None

Lcolor is a number from 1 to 56 corresponding to the 16 line colors in the Patterns tab of the Format Object or Format (chart element) dialog box.

Lstyle is a number from 1 to 8 corresponding to the eight line styles in the Patterns tab of the Format Object or Format (chart element) dialog box.

Lwt is a number from 1 to 4 corresponding to the four line weights in the Patterns tab of the Format Object or Format (chart element) dialog box.

If lwt is Line is

1 Hairline

2 Thin

3 Medium

4 Thick

Mauto is a number from 0 to 2 specifying marker settings.

If mauto is Marker settings are

0 Set by the user

1 Automatic (set by Microsoft Excel)

2 None

Mback is a number from 1 to 56corresponding to the 56 marker background colors in the Patterns tab of the Format Data Series dialog box.

Mfore is a number from 1 to 56 corresponding to the 56 marker foreground colors in the Patterns tab of the Format Data Series dialog box.

Mstyle is a number from 1 to 9 corresponding to the nine marker styles in the Patterns tab of the Format Data Series dialog box.

Picture_units is the number of units you want each picture to represent in a scaled, stacked picture chart. This argument applies only to picture charts and only if type is 3.

Rounded is a logical value corresponding to the Round Corners check box and specifying whether to make the corners on text boxes and rectangles rounded. If rounded is TRUE, the corners are rounded; if FALSE, the corners are square. If the selection is an arc or an oval, rounded is ignored.

Newui is a logical value that specifies whether to use the foreground, background, and patterns of Microsoft Excel 5.0 or later. If TRUE or omitted, the colors and patterns of Microsoft Excel 5.0 or later will be used. If FALSE, the colors and patterns of Microsoft Excel 4.0 will be used.

Newfill is a logical value that specifies whether to use the chart patterns of Microsoft Excel 5.0 or later. If TRUE or omitted, the chart patterns of Microsoft Excel 5.0 or later will be used. If FALSE, the chart patterns of Microsoft Excel 4.0 will be used.

Shadow is a logical value corresponding to the Shadow check box. Shadow does not apply to area charts or bars in bar charts. If shadow is TRUE, Microsoft Excel adds a shadow to the selected item; if FALSE, Microsoft Excel removes the shadow, if one is present, from the selected item. If the selection is an arc, shadow is ignored.

Smooth is a logical value that applies smoothing to picture markers in line or xy (scatter) charts. The default is FALSE.

Tlabel is a number from 1 to 4 specifying the position of tick labels.

If tlabel is Tick label position is

1 None

2 Low

3 High

4 Next to axis

Tmajor is a number from 1 to 4 specifying the type of major tick marks.

If tmajor is Type of major tick marks is

1 None

2 Inside

3 Outside

4 Cross

Tminor is a number from 1 to 4 specifying the type of minor tick marks.

If tminor is Type of minor tick marks is

1 None

2 Inside

3 Outside

4 Cross

Type is a number from 1 to 3 specifying the type of pictures to use in a picture chart.

If type is Pictures should be

1 Stretched to reach a particular value

2 Stacked on top of each other to reach a particular value

3 Stacked on top of each other, but you specify the number of units each picture represents

Remarks

  • You can select many graphic objects on a sheet or macro sheet and apply formatting to them at the same time, but you can select only one chart item at a time.
  • If you select multiple objects and if one or more of the objects requires a different form of the PATTERNS function, then choose the syntax corresponding to the object with the most formatting attributes—that is, the syntax with the most arguments. If you specify an argument that does not apply to an item, the argument has no effect on that item.
  • To apply formatting to similar items on a chart, use the apply argument described above.

Related Functions

FONT.PROPERTIES Applies a font to the selection

FORMAT.TEXT Formats a text box or a chart text item

List of Command-Equivalent Functions


POKE

Macro Sheets Only

Sends data to another application. Use POKE to send data to documents in other applications you are communicating with through dynamic data exchange (DDE).

Syntax

POKE(channel_num, item_text, data_ref)

Important Microsoft Excel for the Macintosh requires system software version 7.0 or later for this function.

Channel_num is the channel number returned by a previously run INITIATE function.

Item_text is text that identifies the item you want to send data to in the application you are accessing through channel_num. The form of item_text depends on the application connected to channel_num.

Data_ref is a reference to the document containing the data to send.

If POKE is not successful, it returns the following values.

Value returned Meaning

#VALUE! Channel_num is not a valid channel number.

#DIV/0! The application you are accessing does not respond after a certain length of time, and you press ESC to cancel.

#REF! POKE is refused.

Examples

In Microsoft Excel for Windows, the following macro inserts the text from cell C3 into the Microsoft Word for Windows document SALES.DOC at the start of the document.

=POKE(SendChanl, "StartOfDoc", C3)

In Microsoft Excel for the Macintosh, the following macro inserts the text from cell C3 into the Microsoft Word document named Report.

=POKE(SendChanl, "TopicName", C3)

Related Functions

INITIATE Opens a channel to another application

REQUEST Returns data from another application

TERMINATE Closes a channel to another application

List of DDE/External Functions


PRINT

Macro Sheets Only

Equivalent to choosing the Print command from the File menu. Prints the active workbook.

Arguments correspond to options, check boxes, and edit boxes in the Print dialog box. Arguments corresponding to check boxes are logical values. If an argument is TRUE, Microsoft Excel selects the check box; if FALSE, Microsoft Excel clears the check box.

Syntax

PRINT(range_num, from, to, copies, draft, preview, print_what, color, feed, quality, y_resolution, selection)

PRINT?(range_num, from, to, copies, draft, preview, print_what, color, feed, quality, y_resolution, selection)

Range_num is a number specifying which pages to print.

Range_num Prints the following pages

1 All the pages

2 Prints a specified range. If range_num is 2, then from and to are required arguments.

From specifies the first page to print. This argument is ignored unless range_num equals 2.

To specifies the last page to print. This argument is ignored unless range_num equals 2.

Copies specifies the number of copies to print. If omitted, the default is 1.

Draft This argument overrides the draft argument from the PAGE.SETUP function. If omitted, the Draft Setting from the Page.Setup function is used.

Preview is a logical value corresponding to the Print Preview button in the Print dialog box. If TRUE, the print preview window will be displayed. If FALSE, the window will not be displayed

Print_what is a number from 1 to 3 that specifies what parts of the sheet or macro sheet to print. If a chart is active, print_what is ignored. This argument will override the setting in the Page Setup dialog box. If omitted, the note argument in the Page.Setup function is used to determine whether to print notes or not.

Print_what Prints

1 Sheet only

2 Notes only

3 Sheet and then notes

Color corresponds to the Print Using Color check box. Color is available only in Microsoft Excel for the Macintosh. If omitted, the setting is not changed.

Feed is a number specifying the type of paper feed. Feed is available only in Microsoft Excel for the Macintosh.

Feed Type of paper feed

1 or omitted Continuous (paper cassette)

2 Cut sheet or manual (manual feed)

Quality Specifies the DPI output quality you want. If omitted, the corresponding settings in the Page Setup dialog box will be used. If included, this argument overrides the quality argument in the PAGE SETUP dialog box.

Y_resolution corresponds to the Print Quality box in the Page Setup dialog box if you have specified a printer where the horizontal and vertical resolution are not equal, such as a dot-matrix printer. If omitted, the corresponding settings in the Page Setup dialog box will be used. If included, this argument overrides the print quality setting in the Page Setup dialog box.

Selection specifies what portion of the sheet to print.

Selection Portion printed

1 Prints the current selection from all selected sheets. For example, if A1:F40 is selected on the active sheet, A1:F40 will be printed from each of the selected sheets.

2 Prints the print area or entire sheet from all selected sheets.

3 Prints print area or entire sheet from all sheets in the workbook.

Related Functions

PAGE.SETUP Sets page printing specifications

PRINT.PREVIEW Previews pages and page breaks before printing

PRINTER.SETUP Identifies the printer

SET.PRINT.AREA Defines the print area

SET.PRINT.TITLES Defines text to print as titles

DEFINE.NAME Equivalent to choosing the Define command from the Name submenu on the Insert menu

List of Command-Equivalent Functions


PRINT.PREVIEW

Macro Sheets Only

Equivalent to choosing the Print Preview command from the File menu. Previews the pages and page breaks of the active workbook on the screen before printing.

Syntax

PRINT.PREVIEW( )

Related Function

PRINT Prints the active workbook

List of Command-Equivalent Functions


REFTEXT

Macro Sheets Only

Converts a reference to an absolute reference in the form of text. Use REFTEXT when you need to manipulate references with text functions. After manipulating the reference text, you can convert it back into a normal reference by using TEXTREF.

Syntax

REFTEXT(reference, a1)

Reference is the reference you want to convert.

A1 is a logical value specifying A1-style or R1C1-style references.

  • If a1 is TRUE, REFTEXT returns an A1-style reference.
  • If a1 is FALSE or omitted, REFTEXT returns an R1C1-style reference.

Examples

REFTEXT(C3, TRUE) equals "$C$3"

REFTEXT(B2:F2) equals "R2C2:R2C6"

If the active cell is B9 on the active sheet named SHEET1, then:

REFTEXT(ACTIVE.CELL()) equals "[Book1]SHEET1!R9C2"

REFTEXT(ACTIVE.CELL(), TRUE) equals "[Book1]SHEET1!$B$9"

Related Functions

ABSREF Returns the absolute reference of a range of cells to another range

DEREF Returns the values of cells in the reference

RELREF Returns a relative reference

TEXTREF Converts text to a reference

List of Lookup & Reference Functions


REGISTER

Macro Sheets Only

Registers the specified dynamic link library (DLL) or code resource and returns the register ID. You can also specify a custom function name and argument names that will appear in the Function Wizard. If you register a command (macro_type = 2), you can also specify a shortcut key. Because Microsoft Excel for Windows and Microsoft Excel for the Macintosh use different types of code resources, REGISTER has a slightly different syntax form when used in each operating environment.

Important This function is provided for advanced users only. If you use the CALL function incorrectly, you could cause errors that will require you to restart your computer.

Syntax 1

For Microsoft Excel for Windows

REGISTER(module_text, procedure, type_text, function_text, argument_text, macro_type, category, shortcut_text, help_topic, function_help, argument_help1, argument_help2,...)

Syntax 2

For Microsoft Excel for the Macintosh

REGISTER(file_text, resource, type_text, function_text, argument_text, macro_type, category, shortcut_text, help_topic, function_help, argument_help1, argument_help2,...)

Module_text or file_text is text specifying the name of the DLL that contains the function (in Microsoft Excel for Windows) or the name of the file that contains the code resource (in Microsoft Excel for the Macintosh).

Procedure or resource is text specifying the name of the function in the DLL (in Microsoft Excel for Windows) or the name of the code resource (in Microsoft Excel for the Macintosh). In Microsoft Excel for Windows, you can also use the ordinal value of the function from the EXPORTS statement in the module-definition file (.DEF). In Microsoft Excel for the Macintosh, you can also use the resource ID number. The ordinal value or resource ID number should not be in text form.

This argument may be omitted for stand-alone DLLs or code resources. In this case, REGISTER will register all functions or code resources and then return module_text or file_text.

Type_text is text specifying the data type of the return value and the data types of all arguments to the DLL or code resource. The first letter of type_text specifies the return value.

Function_text is text specifying the name of the function as you want it to appear in the Function Wizard. If you omit this argument, the function will not appear in the Function Wizard.

Argument_text is text specifying the names of the arguments you want to appear in the Function Wizard. Argument names should be separated by commas.

Macro_type specifies the macro type: 1 for a function or 2 for a command. If macro_type is omitted, it is assumed to be 1 (function).

Category specifies the function category in the Function Wizard in which you want the registered function to appear. You can use the category number or the category name for category. If you use the category name, be sure to enclose it in double quotation marks. If category is omitted, it is assumed to be 14 (User Defined).

Category number Category name

1 Financial

2 Date & Time

3 Math & Trig

4 Text

5 Logical

6 Lookup & Matrix

7 Database

8 Statistical

9 Information

10 Commands (macro sheets only)

11 Actions (macro sheets only)

12 Customizing (macro sheets only)

13 Macro Control (macro sheets only)

14 User Defined

Shortcut_text is a character specifying the shortcut key for the registered command. The shortcut key is case-sensitive. This argument is used only if macro_type = 2 (command). If shortcut_text is omitted, the command will not have a shortcut key.

Help_topic is the reference (including path) to the help file that you want displayed when the user chooses the Help button when your custom function is displayed.

Function_help is a text string describing your custom function when it is selected in the Function Wizard. The maximum number of characters is 255.

Argument_help1, argument_help2 are 1 to 21 text strings that describes you custom function's arguments when the function is selected in the Function Wizard.

Example
Syntax 1

In Microsoft Excel for Windows, the following macro formula registers the GetTickCount function from Microsoft Windows. This function returns the number of milliseconds that have elapsed since Microsoft Windows was started.

REGISTER("User", "GetTickCount", "J")

Assuming that the REGISTER function is in cell A5, after your macro registers GetTickCount, you can use the CALL function to return the number of milliseconds that have elapsed:

CALL(A5)

Example
Syntax 1 with optional function_text

You can use the following macro formula to register the GetTickCount function from Microsoft Windows and assign the custom name GetTicks to it. To do this, include "GetTicks" as the optional function_text argument to the REGISTER function.

REGISTER("User", "GetTickCount", "J", "GetTicks", , 1, 9)

After the function is registered, the custom name GetTicks will appear in the Information function category (category = 9) in the Function Wizard.

You can call the function from the same macro sheet on which it was registered using the following formula:

GetTicks()

You can call the function from another sheet or macro sheet by including the name of the original macro sheet in the formula. For example, assuming the macro sheet on which GetTicks was registered is named MACRO1.XLS, the following formula calls the function from another sheet:

MACRO1.XLS!GetTicks()

Tip You can use functions in a DLL or code resource directly on a sheet without first registering them from a macro sheet. Use syntax 2a or 2b of the CALL function. For more information, see CALL.

Related Functions

UNREGISTER Removes a registered code resource from memory

List of DDE/External Functions


RELREF

Macro Sheets Only

Returns the reference of a cell or cells relative to the upper-left cell of rel_to_ref. The reference is given as an R1C1-style relative reference in the form of text, such as "R[1]C[1]".

Syntax

RELREF(reference, rel_to_ref)

Reference is the cell or cells to which you want to create a relative reference.

Rel_to_ref is the cell from which you want to create the relative reference.

Tip If you know the absolute reference of a cell that you want to include in a formula, but your formula requires a relative reference, use RELREF to generate the relative reference. This is especially useful with the FORMULA function, since its formula_text argument requires R1C1-style references, and RELREF returns relative R1C1-style references. You can also use the FORMULA.CONVERT function to convert absolute references to relative references.

Examples

RELREF($A$1, $C$3) equals "R[-2]C[-2]"

RELREF($A$1:$E$5, $C$3:$G$7) equals "R[-2]C[-2]:R[2]C[2]"

RELREF($A$1:$E$5, $C$3) equals "R[-2]C[-2]:R[2]C[2]"

Related Functions

ABSREF Returns the absolute reference of a range of cells to another range

DEREF Returns the value of the cells in the reference

FORMULA Enters values into a cell or range or onto a chart

FORMULA.CONVERT Changes the reference style and type

List of Lookup & Reference Functions


REPORT.DEFINE

Macro Sheets Only

Equivalent to choosing the Print Report command from the View menu and then choosing the Add option from the Print Report dialog box. Creates or replaces a report definition. If this function is not available, you must install the Reports add-in macro.

Syntax

REPORT.DEFINE(report_name, sections_array, pages_logical)

Report_name specifies the name of the report. If the workbook already contains a report with report_name, the new report replaces the existing one.

Sections_array is an array that contains one or more rows of view, scenario, and sheet name that define the report. The sheet name is the sheet on which the view and scenario are defined. If the sheet name is not specified, the current sheet is used when REPORT.DEFINE is run.

Pages_logical is a logical value that, if TRUE or omitted, specifies continuous page numbers for multiple sections or, if FALSE, resets page numbers to 1 for each new section.

Remarks

  • REPORT.DEFINE returns the #VALUE error value if report_name is invalid or if the workbook is protected.
  • If there are no reports defined, this funcition will bring up the Add Report dialog box

Related Functions

REPORT.DELETE Removes a report from the active workbook

REPORT.PRINT Prints a report

REPORT.GET Returns information about reports defined for the active workbook

List of Command-Equivalent Functions


REPORT.DELETE

Macro Sheets Only

Equivalent to choosing the Print Report command from the View menu and then selecting a report in the Print Report dialog box and choosing the Delete button. Removes a report definition from the active workbook.

If this function is not available, you must install the Reports add-in macro.

Syntax

REPORT.DELETE(report_name)

Report_name specifies the name of the report to be removed. Report_name can be any text that does not contain quotation marks.

Remarks

REPORT.DELETE returns the #VALUE error value if report_name is invalid or if the workbook is protected.

Related Functions

REPORT.DEFINE Creates a report

REPORT.PRINT Prints a report

REPORT.GET Returns information about reports defined for the active workbook

List of Command-Equivalent Functions


REPORT.GET

Macro Sheets Only

Returns information about reports defined for the active workbook. Use REPORT.GET to return information you can use in other macro commands that manipulate reports.

If this function is not available, you must install the Reports add-in macro.

Syntax

REPORT.GET(type_num, report_name)

Type_num is a number from 1 to 3 specifying the type of information to return, as shown in the following table.

Type_num Returns

1 An array of reports from all sheets in the active workbook or the #N/A error value if none are specified

2 An array of views, scenarios, and sheet names for the specified report in the active workbook. REPORT.GET returns the #N/A error value if the scenario check box is not selected. Returns the #VALUE! error value if name is invalid or the workbook is protected.

3 If continuous page numbers are used, returns TRUE. If page numbers start at 1 for each section, returns FALSE. Returns the #VALUE! error value if report_name is invalid or the workbook is protected.

Report_name specifies the name of a report in the active workbook.

Remarks

Report_name is required if type_num is 2 or 3.

Example

The following macro formula returns an array of reports from the active workbook.

REPORT.GET(1)

Related Functions

REPORT.DEFINE Creates a report

REPORT.DELETE Removes a report from the active workbook

REPORT.PRINT Prints a report

List of Command-Equivalent Functions


REPORT.PRINT

Macro Sheets Only

Equivalent to choosing the Print button from the Print Reports dialog box. Prints a report.

If this function is not available, you must install the Reports add-in macro.

Syntax

REPORT.PRINT(report_name, copies_num, show_print_dlg_logical)
REPORT.PRINT?(report_name, copies_num)

Report_name specifies the name of a report in the active workbook.

Copies_num is the number of copies you want to print. If omitted, the default is 1.

Show_print_dlg_logical is a logical value that, if TRUE, displays a dialog box asking how many copies to print, or, if FALSE or omitted, prints the report immediately using existing print settings.

Remarks

REPORT.PRINT returns the #VALUE! error value if report_name is invalid or if the workbook is protected.

Related Functions

REPORT.DEFINE Creates a report

REPORT.DELETE Removes a report from the active workbook

List of Command-Equivalent Functions


REQUEST

Macro Sheets Only

Requests an array of a specific type of information from an application with which you have a dynamic data exchange (DDE) link. Use REQUEST with other Microsoft Excel DDE functions to move information from another application into Microsoft Excel.

Syntax

REQUEST(channel_num, item_text)

Important Microsoft Excel for the Macintosh requires system software version 7.0 or later for this function.

Channel_num is a number returned by a previously run INITIATE function. Channel_num refers to a channel through which Microsoft Excel communicates with another program.

Item_text is a code indicating the type of information you want to request from another application. The form of item_text depends on the application connected to channel_num.

REQUEST returns the data as an array. For example, suppose the remote data to be returned came from a sheet that looked like the following illustration.

REQUEST would return that data as the following array:

{1, 2, 3;4, 5, 6}

If REQUEST is not successful, it returns the following error values.

Value returned Situation

#VALUE! Channel_num is not a valid channel number.

#N/A The application you are accessing is busy doing something else.

#DIV/0! The application you are accessing does not respond after a certain length of time, or you have pressed ESC or COMMAND+PERIOD to cancel.

#REF! The request is refused.

Tip Use the ERROR.TYPE function to distinguish between the different error values.

Example

Suppose you had opened a DDE channel to Microsoft Word for Windows. WChan contains the number of the open channel. In Microsoft Excel for Windows, the following function returns the text specified by the bookmark named BMK1.

=REQUEST(WChan, "BMK1")

Related Functions

EXECUTE Carries out a command in another application

INITIATE Opens a channel to another application

POKE Sends data to another application

SEND.KEYS Sends a key sequence to another application

TERMINATE Closes a dynamic data exchange (DDE) channel previously opened with the INITIATE function

List of DDE/External Functions


SCENARIO.ADD

Macro Sheets Only

Equivalent to choosing the Scenarios command from the Tools menu and then choosing the Add button. Defines the specified values as a scenario. A scenario is a set of values to be used as input for a model on your worksheet.

Syntax

SCENARIO.ADD(scen_name, value_array, changing_ref, scen_comment, locked, hidden)

Scen_name is the name of the scenario you want to define.

Value_array is a horizontal array of values you want to use as input for the model on your worksheet.

  • Any entry that would be valid for a cell in your model can be a value in value_array.
  • The values must be arranged in the same order as the model's changing cells. The changing cells are listed in the Changing Cells box in the Scenario Manager dialog box.
  • If value_array is omitted, it is assumed to contain the current values of the changing cells.

Changing_ref is a reference to cells you want to define as changing cells for a scenario.

  • If omitted, uses the changing cells for the last scenario defined for the sheet.
  • If changing_ref contains nonadjacent references, you must separate the reference areas by commas (or other list separator). If you are using A1-style references, then you must enclose reference in an extra set of parentheses.

Scen_comment is text specifying a descriptive comment for the scenario defined by scen_name.

Locked is a logical value that corresponds to the Prevent Changes check box in the Add or Edit Scenario dialogs boxes. If TRUE or omitted , prevents users from changing values in a scenario. If FALSE, users are allowed to make changes to the scenario. The locking will not become enabled until the sheet is protected with the Protect Sheet command from the Protection submenu on the Tools menu.

Hidden is a logical value that corresponds to the Hide check box in the Add or Edit Scenario dialog boxes. If TRUE, the scenario will be hidden from view from the users and will not appear in the Scenario Manager dialog box. If FALSE or omitted, the scenario will remain unhidden. The scenario will not become hidden until the sheet is protected with the Protect Sheet command from the Protection submenu on the Tools menu.

Related Function

REPORT.DEFINE Creates a report

SCENARIO.GET Returns the specified information about the scenarios defined on your worksheet

List of Command-Equivalent Functions


SCENARIO.CELLS

Macro Sheets Only

Equivalent to choosing the Scenarios command from the Tools menu and then editing the Changing Cells box. Defines the changing cells for a model on your worksheet. Changing cells are the cells into which values will be entered when you display a scenario. If you have only one set of changing cells on your sheet, SCENARIO.CELLS will change the changing cells for all scenarios. If your sheet has scenarios defined with multiple sets of changing cell, this function returns an error and the macro is halted. This function is provided for compatibility with Microsoft Excel 4.0. Use SCENARIO.EDIT with the changing_ref argument instead of SCENARIO.CELLS if you want to change the changing cells of a scenario.

Syntax

SCENARIO.CELLS(changing_ref)
SCENARIO.CELLS? (changing_ref)

Changing_ref is a reference to the cells you want to define as changing cells for the model. If changing_ref contains nonadjacent references, you must separate the reference areas by commas and enclose changing_ref in an extra set of parentheses.

Related Functions

SCENARIO.EDIT Equivalent to choosing the Scenarios command from the Tools menu and then choosing the Edit button

List of Command-Equivalent Functions


SCENARIO.DELETE

Macro Sheets Only

Equivalent to choosing the Scenarios command from the Tools menu and then selecting a scenario and choosing the Delete button. Deletes the specified scenario.

Syntax

SCENARIO.DELETE(scen_name)

Scen_name is the name of the scenario you want to delete.

Related Function

SCENARIO.GET Returns the specified information about the scenarios defined on your worksheet

SCENARIO.ADD Equivalent to choosing the Scenario Manager command from the Tools menu and then choosing the Add button

SCENARIO.EDIT Equivalent to choosing the Scenario Manager command from the Tools menu and then choosing the Edit button

List of Command-Equivalent Functions


SCENARIO.EDIT

Macro Sheets Only

Equivalent to choosing the Scenarios command from the Tools menu and then choosing the Edit button.

Syntax

SCENARIO.EDIT(scen_name, new_scenname, value_array, changing_ref, scen_comment, locked, hidden)
SCENARIO.EDIT?(scen_name, new_scenname, value_array, changing_ref, scen_comment, locked, hidden)

Scen_name is the name of the scenario that you want to edit.

New_scenname is the new name you want to give to the scenario.

Value_array is a horizontal array of values that you want to use for the scenario.

  • If value_array is omitted but changing_ref is specified, Scenario Manager uses the values in changing_ref as value_array.
  • Value_array must match the dimensions of changing_ref for the scenario being edit.

Changing_ref is a reference to cells you want to define as changing cells for a scenario.

Scen_comment is text specifying a descriptive comment for the scenario you want to edit.

Locked is a logical value that corresponds to the Prevent Changes check box in the Add or Edit Scenario dialogs boxes. If TRUE or omitted , prevents users from changing values in a scenario. If FALSE, users are allowed to make changes to the scenario. The locking will not become enabled until the sheet is protected with the Protect Sheet command from the Protection submenu on the Tools menu.

Hidden is a logical value that corresponds to the Hide check box in the Add or Edit Scenario dialog boxes. If TRUE, the scenario will be hidden from view from the users. If FALSE or omitted, the scenario will remain unhidden. The scenario will not become hidden until the sheet is hidden with the Hide command from the Window menu.

Related Function

SCENARIO.GET Returns the specified information about the scenarios defined on your worksheet

SCENARIO.ADD Equivalent to choosing the Scenario Manager command from the Tools menu and then choosing the Add button

SCENARIO.DELETE Equivalent to choosing the Scenario Manager command from the Tools menu and then selecting a scenario and choosing the Delete button

List of Command-Equivalent Functions


SCENARIO.GET

Macro Sheets Only

Returns the specified information about the scenarios defined on your worksheet.

Syntax

SCENARIO.GET(type_num, scen_name)

Type_num is a number from 1 to 8 specifying the type of information you want.

Type_num Information returned

1 A horizontal array of all scenario names in the form of text

2 A reference to the set of changing cells of scen_name (specified in the Changing Cells box of the Scenario Manager dialog box). If scen_name is omitted, the first scenario is used.

3 A reference to the result cells (specified in the Result Cells box in the Scenario Summary dialog box)

4 An array of scenario values for the scenario scen_name . Each scenario is in a separate row. If scen_name is omitted, the first scenario is used.

5 Comment, as text, for the scenario

6 Returns TRUE if the specified scenario is locked to prevent changes; FALSE, if unlocked. Scen_name is required.

7 Returns TRUE if the specified scenario is hidden; FALSE, if visible to the user. Scen_name is required.

8 Returns the user name of the person who last modified the scenario by either adding or editing a scenario. Scen_name is required.

Scen_name is the name of the scenario that you want information about. Ignored if type_num equals 1 or 3.

Remarks

In the returned array of scenario values, the number of rows is the number of scenarios, and the number of columns is the number of changing cells.


SCENARIO.SHOW

Macro Sheets Only

Equivalent to choosing the Scenarios command from the Tools menu and then selecting a scenario and choosing the Show button. Recalculates a model using the specified scenario and displays the result.

Syntax

SCENARIO.SHOW(scen_name)

Scen_name is the name of the previously defined scenario whose values you want to switch to.

Related Functions

List of Command-Equivalent Functions


SCENARIO.SHOW.NEXT

Macro Sheets Only

Equivalent to choosing the Scenarios command from the Tools menu, selecting the next scenario from the Scenarios list, and choosing the Show button. Recalculates a model using the next scenario and displays the result.

Syntax

SCENARIO.SHOW.NEXT( )

Remarks

After displaying the last scenario, running SCENARIO.SHOW.NEXT again displays the first scenario.

Related Functions

List of Command-Equivalent Functions


SCENARIO.SUMMARY

Macro Sheets Only

Equivalent to choosing the Scenarios command from the Tools menu and then choosing the Summary button. Generates a table summarizing the results of all the scenarios for the model on your worksheet.

Syntax

SCENARIO.SUMMARY(result_ref, report_type)
SCENARIO.SUMMARY?(result_ref, report_type)

Result_ref is a reference to the result cells you want to include in the summary report. Normally, result_ref refers to one or more cells containing the formulas that depend on the changing cell values for your model—that is, the cells that show the results of a particular scenario.

  • If result_ref is omitted, no result cells are included in the report.
  • If result_ref contains nonadjacent references, you must separate the reference areas by commas and enclose result_ref in an extra set of parentheses.

Report_type is a number specifying the type of report desired.

Report_type Type of Report

1 or omitted A scenario summary report (Microsoft Excel 4.0)

2 A scenario PivotTable. Requires result_ref.

Remarks

  • SCENARIO.SUMMARY generates a summary table of the changing cell and result cell values for each scenario.
  • The table is generated on a new sheet in the current workbook. The sheet becomes active after SCENARIO.SUMMARY runs.

Related Functions

List of Command-Equivalent Functions


SEND.KEYS

Macro Sheets Only

Sends keystrokes to the active application just as if they were typed at the keyboard. Use SEND.KEYS to send keystrokes that perform actions and execute commands to applications you are running with Microsoft Excel's other dynamic data exchange (DDE) functions.

Syntax

SEND.KEYS(key_text, wait_logical)

Note This function is available only in Microsoft Excel for Windows.

Key_text is the key or key combination you want to send to another application. The format for key_text is described in the ON.KEY function.

Wait_logical is a logical value that determines whether the macro continues before the actions caused by key_text are carried out.

  • If wait_logical is TRUE, Microsoft Excel waits for the keys to be processed before returning control to the macro.
  • If wait_logical is FALSE or omitted, the macro continues running without waiting for the keys to be processed.

Remarks

If Microsoft Excel is the active application, wait_logical is assumed to be FALSE, even if you enter wait_logical as TRUE. This is because if wait_logical is TRUE, Microsoft Excel waits for the keys to be processed in the other application before returning control to the macro. Microsoft Excel doesn't process keys while a macro is running.

Example

The following macro uses the Calculator application in Microsoft Excel for Windows to multiply some numbers, and then cuts the result and pastes it into Microsoft Excel.

=EXEC("CALC.EXE", 1)
=SEND.KEYS("10*30", TRUE)
=SEND.KEYS("~", TRUE)
=SEND.KEYS("%ec", TRUE)
=APP.ACTIVATE(, FALSE)
=SELECT(!B1)
=PASTE()
=RETURN()

Related Functions

APP.ACTIVATE Switches to an application

EXECUTE Carries out a command in another application

ON.KEY Runs a macro when a specified key is pressed

List of DDE/External Functions


SET.CRITERIA

Macro Sheets Only

Equivalent to choosing the Set Criteria command from the Data menu in Microsoft Excel version 4.0. Defines the name Criteria for the selected range on a sheet or macro sheet.

Syntax

SET.CRITERIA( )

Related Functions

SET.DATABASE Equivalent to choosing the Set Database command from the Data menu in Microsoft Excel version 4.0

SET.EXTRACT Equivalent to choosing the Set Extract command from the Data menu in Microsoft Excel version 4.0

List of Command-Equivalent Functions


SET.DATABASE

Macro Sheets Only

Equivalent to choosing the Set Database command from the Data menu in Microsoft Excel version 4.0. Defines the name Database for the selected range on a sheet or macro sheet.

Syntax

SET.DATABASE( )

Related Functions

SET.CRITERIA Equivalent to choosing the Set Criteria command from the Data menu in Microsoft Excel version 4.0

SET.EXTRACT Equivalent to choosing the Set Extract command from the Data menu in Microsoft Excel version 4.0

List of Command-Equivalent Functions


SET.EXTRACT

Macro Sheets Only

Equivalent to choosing the Set Extract command from the Data menu in Microsoft Excel version 4.0. Defines the name Extract for the selected range on the active sheet.

Syntax

SET.EXTRACT( )

Related Functions

SET.DATABASE Equivalent to choosing the Set Database command from the Data menu in Microsoft Excel version 4.0

SET.CRITERIA Equivalent to choosing the Set Criteria command from the Data menu in Microsoft Excel version 4.0

List of Command-Equivalent Functions


SET.UPDATE.STATUS

Macro Sheets Only

Sets the update status of a link to automatic or manual. Use SET.UPDATE.STATUS to change the way a link is updated.

Syntax

SET.UPDATE.STATUS(link_text, status, type_of_link)

Link_text is the path of the linked file for which you want to change the update status.

Status is the number 1 or 2 and describes how you want the link to be updated.

Status Update method

1 Automatic

2 Manual

Type_of_link is a number from 1 to 4 that specifies what type of link you want to get information about.

Type_of_link Link document type

1 Not available

2 DDE/OLE link

3 Not available

4 Not available

Example

In Microsoft Excel for Windows, the following macro formula sets the update status of the DDE link to Microsoft Word for Windows to manual:

SET.UPDATE.STATUS("WordDocument|'C:\MEMO.DOC'!DDE.LINK1", 2, 2)

Related Functions

GET.LINK.INFO Returns information about a link

UPDATE.LINK Updates a link to another document

List of Command-Equivalent Functions


SIZE

Macro Sheets Only

Equivalent to choosing the Size command from the Control menu in Microsoft Excel for Windows version 3.0 or earlier or to changing the size of a window by dragging its border. In Microsoft Excel for the Macintosh version 3.0 or earlier, equivalent to changing the size of a window by dragging its size box. This function is included only for macro compatibility and will be converted to WINDOW.SIZE when you open older macro sheets. For more information, see WINDOW.SIZE.

Syntax

SIZE(width,height,window_text)
SIZE?(width,height,window_text)

Related Functions

WINDOW.SIZE Changes the size of the acive window

List of Command-Equivalent Functions


SLIDE.COPY.ROW

Macro Sheets Only

Equivalent to choosing the Copy Row button on a slide show document. Copies the selected slides, each of which is defined on a single row, to the Clipboard.

If this function is not available, you must install the Slide Show add-in macro.

Syntax

SLIDE.COPY.ROW( )

Remarks

  • SLIDE.COPY.ROW, SLIDE.CUT.ROW, SLIDE.DELETE.ROW, and SLIDE.PASTE.ROW return TRUE if successful, or FALSE if not successful. If the active document is not a slide show or is protected, these functions return the #N/A error value. If the current selection is not valid, these functions return the #VALUE! error value.

Related Functions

SLIDE.CUT.ROW Cuts the selected slides and pastes them onto the Clipboard

SLIDE.DEFAULTS Specifies default values for the active slide show document

SLIDE.DELETE.ROW Deletes the selected slides

SLIDE.EDIT Changes the attributes of the selected slide

SLIDE.GET Returns information about a slide or slide show

SLIDE.PASTE Pastes the contents of the Clipboard onto a slide

SLIDE.PASTE.ROW Pastes previously cut or copied slides onto the current selection

SLIDE.SHOW Starts a slide show in the active document

List of Command-Equivalent Functions


SLIDE.CUT.ROW

Macro Sheets Only

Equivalent to choosing the Cut Row button on a slide show document. Cuts the selected slides, each of which is defined on a single row, and pastes them onto the Clipboard. For more information, see SLIDE.COPY.ROW.

If this function is not available, you must install the Slide Show add-in macro.

Syntax

SLIDE.CUT.ROW( )

Related Functions

SLIDE.COPY.ROW Copies the selected slides and pastes them onto the Clipboard

List of Command-Equivalent Functions


SLIDE.DEFAULTS

Macro Sheets Only

Equivalent to choosing the Set Defaults button on a slide show document. Specifies the default values for the transition effect, speed, advance rate, and sound on the active slide show document.

If this function is not available, you must install the Slide Show add-in macro.

Syntax

SLIDE.DEFAULTS(effect_num, speed_num, advance_rate_num, soundfile_text)
SLIDE.DEFAULTS?(effect_num, speed_num, advance_rate_num, soundfile_text)

For a description of the arguments, see SLIDE.PASTE. If an argument is omitted, its default value is not changed.

Remarks

  • SLIDE.DEFAULT returns TRUE if it successfully changes the default values, or FALSE if you choose the Cancel button when using the dialog-box form. If the active document is not a slide show or is protected, SLIDE.DEFAULT returns the #N/A error value.

Related Functions

List of Command-Equivalent Functions


SLIDE.DELETE.ROW

Macro Sheets Only

Equivalent to choosing the Delete Row button on a slide show document. Deletes the selected slides, each of which is defined on a single row. For more information, see SLIDE.COPY.ROW.

If this function is not available, you must install the Slide Show add-in macro.

Syntax

SLIDE.DELETE.ROW( )

Related Functions

SLIDE.COPY.ROW Copies the selected slides and pastes them onto the Clipboard

List of Command-Equivalent Functions


SLIDE.EDIT

Macro Sheets Only

Equivalent to choosing the Edit button in a slide show document. Gives the currently selected slide the attributes you specify.

If this function is not available, you must install the Slide Show add-in macro.

Syntax

SLIDE.EDIT(effect_num, speed_num, advance_rate_num, soundfile_text)
SLIDE.EDIT?(effect_num, speed_num, advance_rate_num, soundfile_text)

For a description of the arguments, see SLIDE.PASTE.

Remarks

  • SLIDE.EDIT returns TRUE if it successfully edits the slide, or FALSE if you choose the Cancel button when using the dialog-box form. If the active document is not a slide show or is protected, SLIDE.EDIT returns the #N/A error value. If the current selection is not a valid slide, SLIDE.EDIT returns the #VALUE error value.

Related Functions

SLIDE.PASTE Pastes the contents of the Clipboard onto a slide

List of Command-Equivalent Functions


SLIDE.GET

Macro Sheets Only

Returns the specified information about a slide show or a specific slide in the slide show.

If this function is not available, you must install the Slide Show add-in macro.

Syntax

SLIDE.GET(type_num, name_text, slide_num)

Type_num is a number specifying the type of information you want.

These values of type_num return information about a slide show.

Type_num Type of information

1 Number of slides in the slide show

2 A two-item horizontal array containing the numbers of the first and last slides in the current selection, or the #VALUE error value if the selection is nonadjacent

3 Version number of the Slide Show add-in macro that created the slide show document

These values of type_num return information about a specific slide in the slide show.

Type_num Type of information

4 Transition effect number

5 Transition effect name

6 Transition effect speed

7 Number of seconds the slide is displayed before advancing

8 Name of the sound file associated with the slide, or empty text ("") if none is specified (in Microsoft Excel for the Macintosh, this includes the number or name of the sound resource within the sound file)

Name_text is the name of an open slide show document for which you want information. If name_text is omitted, it is assumed to be the active document.

Slide_num is the number of the slide about which you want information.

  • If slide_num is omitted, it is assumed to be the slide associated with the active cell on the document specified by name_text.
  • If type_num is 1 through 3, slide_num is ignored.

Related Functions

List of Information Functions


SLIDE.PASTE

Macro Sheets Only

Equivalent to choosing the Paste button in a slide show document. Pastes the contents of the Clipboard as the next available slide of the active slide show document, and gives the slide the attributes you specify.

If this function is not available, you must install the Slide Show add-in macro.

Syntax

SLIDE.PASTE(effect_num, speed_num, advance_rate_num, soundfile_text)
SLIDE.PASTE?(effect_num, speed_num, advance_rate_num, soundfile_text)

Effect_num is a number specifying the transition effect you want to use when displaying the slide.

  • The numbers correspond to the effects in the Effect list in the Edit Slide dialog box. The first effect in the list is 1 (None).
  • If effect_num is omitted, the default setting is used.

Speed_num is a number from 1 to 10 specifying the speed of the transition effect.

  • If speed_num is omitted, the default setting is used.
  • If speed_num is greater than 10, Microsoft Excel uses the value 10 anyway.
  • If effect_num is 1 (none), speed_num is ignored.

Advance_rate_num is a number specifying how long (in seconds) the slide is displayed before advancing to the next one.

  • If advance_rate_num is omitted, the default setting is used.
  • If advance_rate_num is 0, you must press a key or click with the mouse to advance to the next slide.

Soundfile_text is the name of a file enclosed in quotation marks and specifies sound that will be played when the slide is displayed.

  • If soundfile_text is omitted, Microsoft Excel plays the default sound defined for the slide show document, if any.
  • If soundfile_text is empty text (""), no sound is played.
  • In Microsoft Excel for the Macintosh, soundfile_text also includes the number or name of the sound resource to play in the file.

Resource is the number or name of a sound resource in soundfile_text.

  • This argument applies only to Microsoft Excel for the Macintosh.
  • If resource is omitted, Microsoft Excel uses the first resource in the file.
  • If the file does not contain a sound resource with the specified name or number, Microsoft Excel halts the macro and displays an error message.

Remarks

  • SLIDE.PASTE returns TRUE if it successfully pastes the slide, or FALSE if you choose the Cancel button when using the dialog-box form. If the active document is not a slide show or is protected, SLIDE.PASTE returns the #N/A error value. If the Clipboard format is not compatible with the slide show document's format, SLIDE.PASTE returns the #VALUE error value.

Examples

In Microsoft Excel for Windows, the following macro formula pastes the contents of the Clipboard into the active slide show document. The slide's transition effect is fade, at a speed of 8; it is displayed for five seconds; and Microsoft Excel plays the specified sound file:

SLIDE.PASTE(3, 8, 5, "C:\SLIDES\SOUND\MACHINES.WAV")

In Microsoft Excel for the Macintosh, the formula is:

SLIDE.PASTE(3, 8, 5, "HARD DISK:SLIDES:SOUND:MACHINE SOUNDS")

Related Functions

List of Command-Equivalent Functions


SLIDE.PASTE.ROW

Macro Sheets Only

Equivalent to choosing the Paste Row button in a slide show document. Pastes previously cut or copied slides onto the current selection. For more information, see SLIDE.COPY.ROW.

If this function is not available, you must install the Slide Show add-in macro.

Syntax

SLIDE.PASTE.ROW( )

Related Functions

SLIDE.COPY.ROW Copies the selected slides and pastes them onto the Clipboard

List of Command-Equivalent Functions


SLIDE.SHOW

Macro Sheets Only

Equivalent to choosing the Start Show button in a slide show document. Starts the slide show in the active document.

If this function is not available, you must install the Slide Show add-in macro.

Syntax

SLIDE.SHOW(initialslide_num, repeat_logical, dialogtitle_text, allownav_logical, allowcontrol_logical)
SLIDE.SHOW?(initialslide_num, repeat_logical, dialogtitle_text, allownav_logical, allowcontrol_logical)

All arguments except dialogtitle_text correspond to options and settings in the Start Show dialog box.

Initialslide_num is a number from 1 to the number of slides in the slide show and specifies which slide to display first. If omitted, it is assumed to be 1.

Repeat_logical is a logical value specifying whether to repeat or end the slide show after displaying the last slide. If repeat_logical is TRUE, the slide show repeats; if FALSE or omitted, the slide show ends.

Dialogtitle_text is text enclosed in quotation marks that specifies the title of the dialog boxes displayed during the slide show. If dialogtitle_text is omitted, it is assumed to be "Slide Show".

Allownav_logical is a logical value specifying whether to enable or disable navigational keys (arrow keys, PAGE UP, PAGE DOWN, and so on) or the mouse during the slide show. If allownav_logical is TRUE or omitted, you can press navigational keys or use the mouse to move between slides; if FALSE, all movement is controlled by the slide show document settings.

Allowcontrol_logical is a logical value specifying whether to enable or disable the Slide Show Options dialog box during the slide show. If allowcontrol_logical is TRUE or omitted, you can press ESC to interrupt the slide show and display the dialog box; if FALSE, pressing ESC stops the slide show but does not display the dialog box.

Tip If you want to display the last slide in a show but don't know its number, use SLIDE.GET(1) as the initialslide_num argument.

Remarks

SLIDE.SHOW returns the values shown in the following table:

Situation Returned value

The slide show ends normally. TRUE

You press the Cancel button when using the dialog-box form. FALSE

The active document is not a slide show or is protected. #N/A

You interrupt the slide show, and then stop it. 1

Related Functions

List of Command-Equivalent Functions


SOLVER.ADD

Macro Sheets Only

Equivalent to choosing the Solver command from the Tools menu and choosing the Add button in the Solver Parameters dialog box. Adds a constraint to the current problem. For an explanation of constraints, see "Remarks" later in this topic.

If this function is not available, you must install the Solver add-in macro.

Syntax

SOLVER.ADD(cell_ref, relation, formula)

Cell_ref is a reference to a cell or range of cells on the active sheet and forms the left side of the constraint.

Relation specifies the arithmetic relationship between the left and right sides, or whether cell_ref must be an integer.

Relation Arithmetic relationship

1 <=

2 =

3 >=

4 Int (cell_ref is an integer)

Formula is the right side of the constraint and will often be a single number, but it may be a formula (as text) or a reference to a range of cells.

  • If relation is 4, cell_ref must be a subset of the references in the By Changing cells text box.
  • if relation is 4, formula must be either "=integer" or "integer".
  • Any cell reference in a formula must use the R1C1 reference style.
  • If formula is a reference to a range of cells, the number of cells in the range usually matches the number of cells in cell_ref, although the shape of the areas need not be the same. For example, cell_ref could be a row and formula could refer to a column, as long as the number of cells is the same. Formula can also be a single reference, as in the following relationship: A1:A4 <= B1.

Remarks

  • The SOLVER.ADD, SOLVER.CHANGE and SOLVER.DELETE functions correspond to the Add, Change, and Delete buttons in the Tools Solver Parameters dialog box. You use these functions to define constraints. For many macro applications, however, you may find it more convenient to load the problem specifications from the sheet in a single step using the SOLVER.LOAD function.
  • Each constraint is uniquely identified by the combination of the cell reference on the left and the relationship (<=, =, or >=) between its left and right sides, or the cell reference may be defined as an integer only. This takes the place of selecting the appropriate constraint in the Tools Solver Parameters dialog box. You can manipulate the constraints with SOLVER.CHANGE or SOLVER.DELETE. The constraints in a Solver problem can refer to a maximum of 400 cells.

Related Functions

List of Command-Equivalent Functions


SOLVER.CHANGE

Macro Sheets Only

Equivalent to choosing the Solver command from the Tools menu and choosing the Change button in the Solver Parameters dialog box. Changes the right side of an existing constraint.

If this function is not available, you must install the Solver add-in macro.

Syntax

SOLVER.CHANGE(cell_ref, relation, formula)

For an explanation of the arguments and constraints, see SOLVER.ADD.

Remarks

  • If the combination of cell_ref and relation does not match any existing constraint, the function returns the value 4 and no action is taken.
  • To change the cell_ref or relation of an existing constraint, use SOLVER.DELETE to delete the old constraint and then use SOLVER.ADD to add the constraint in the form you want.

Related Functions

SOLVER.DELETE Deletes an existing constraint

SOLVER.ADD Adds a constraint to the current problem

List of Command-Equivalent Functions


SOLVER.DELETE

Macro Sheets Only

Equivalent to choosing the Solver command from the Tools menu and choosing the Delete button in the Solver Parameters dialog box. Deletes an existing constraint.

If this function is not available, you must install the Solver add-in macro.

Syntax

SOLVER.DELETE(cell_ref, relation, formula)

For an explanation of the arguments and constraints, see SOLVER.ADD.

Remarks

If the combination of cell_ref and relation does not match any existing constraint, the function returns the value 4 and no action is taken. If the constraint is found, it is deleted, and the function returns the value 0.

Related Functions

SOLVER.ADD Adds a constraint to the current problem

List of Command-Equivalent Functions


SOLVER.FINISH

Macro Sheets Only

Equivalent to choosing OK in the Solver Results dialog box that appears when the solution process is complete. The dialog-box form displays the dialog box with the arguments that you supply as defaults. This function must be used if you supplied the value TRUE for the userfinish argument to SOLVER.SOLVE.

If this function is not available, you must install the Solver add-in macro.

Syntax

SOLVER.FINISH(keep_final, report_array)
SOLVER.FINISH?(keep_final, report_array)

Keep_final is the number 1 or 2 and specifies whether to keep the final solution. If keep_final is 1 or omitted, the final solution values are kept in the changing cells. If keep_final is 2, the final solution values are discarded and the former values of the changing cells are restored.

Report_array is an array argument specifying what reports to create when Solver is finished.

If report_array is Microsoft Excel creates

{1} An answer report

{2} A sensitivity report

{3} A limit report

Any combination of these produces multiple reports. For example, if report_array is {1, 2}, Microsoft Excel creates an answer report and a sensitivity report.

Related Functions

SOLVER.SOLVE Equivalent to choosing the Solver command from the Tools menu and choosing the Solve button in the Solver Parameters dialog box

List of Command-Equivalent Functions


SOLVER.GET

Macro Sheets Only

Returns information about current settings for Solver. The settings are specified in the Solver Parameters and Solver Options dialog boxes.

If this function is not available, you must install the Solver add-in macro.

Syntax

SOLVER.GET(type_num, sheet_name)

Type_num is a number specifying the type of information you want.

The following settings are specified in the Solver Parameters dialog box.

Type_Num Returns

1 | The reference in the Set Cell box, or the #N/A error value if Solver has not been used on the active sheet
2 | A number corresponding to the Equal To option 1 = Max 2 = Min 3 = Value of
3 | The value in the Value Of box
4 | The reference (as a multiple reference if necessary) in the By Changing Cells box
5 | The number of constraints
6 | An array of the left sides of the constraints in the form of text
7 | An array of numbers corresponding to the relationships between the left and right sides of the constraints: 1 = <= 2 = = 3 = >= 4 = int
8 | An array of the right sides of the constraints in the form of text

The following settings are specified in the Solver Options dialog box:

Type_Num Returns

9 | The maximum calculation time
10 | The maximum number of iterations
11 | The precision
12 | The integer tolerance value
13 | TRUE if the Assume Linear Model check box is selected; FALSE otherwise
14 | TRUE if the Show Iteration Results check box is selected; FALSE otherwise
15 | TRUE if the Use Automatic Scaling check box is selected; FALSE otherwise
16 | A number corresponding to the type of estimates: 1 = Tangent 2 = Quadratic
17 | A number corresponding to the type of derivatives: 1 = Forward 2 = Central
18 | A number corresponding to the type of search: 1 = Quasi-Newton 2 = Conjugate Gradient

Sheet_name is the name of a sheet that contains the scenario for which you want information. If sheet_name is omitted, it is assumed to be the active sheet.

Related Functions

List of Information Functions


SOLVER.LOAD

Macro Sheets Only

Equivalent to choosing the Solver command from the Tools menu, choosing the Options button from the Solver Parameters dialog box, and choosing the Load Model button in the Solver Options dialog box. Loads Solver problem specifications that you have previously saved on the worksheet.

If this function is not available, you must install the Solver add-in macro.

Syntax

SOLVER.LOAD(load_area)

Load_area is a reference on the active sheet to a range of cells from which you want to load a complete problem specification.

  • The first cell in load_area contains a formula for the Set Cell box; the second cell contains a formula for the changing cells; subsequent cells contain constraints in the form of logical formulas. The last cell optionally contains an array of Solver option values. The order of the Solver option values is the same as the top-to-bottom order in the Solver Options dialog box.
  • Although load_area must be on the active sheet, it need not be the current selection.

Related Functions

List of Command-Equivalent Functions


SOLVER.OK

Macro Sheets Only

Equivalent to choosing the Solver command from the Tools menu and specifying options in the Solver Parameters dialog box. Specifies basic Solver options, except that constraints are added via SOLVER.ADD.

If this function is not available, you must install the Solver add-in macro.

Syntax

SOLVER.OK(set_cell, max_min_val, value_of, by_changing)
SOLVER.OK?(set_cell, max_min_val, value_of, by_changing)

Set_cell corresponds to the Set Target Cell box in the Solver Parameters dialog box.

  • Set_cell must be a reference to a cell on the active worksheet.
  • If you enter a cell reference, you must also enter a value for max_min_val. If you do not enter a cell, you must include three commas before the by_changing value.

Max_min_val corresponds to the options Max, Min, and Value Of in the Solver Parameters dialog box. Use this option only if you entered a reference for set_cell.

Max_min_val Option specified

1 Maximize

2 Minimize

3 Match specific value

Value_of is a number that becomes the target for the cell in the Set Target Cell box if max_min_val is 3. Value_of is ignored if the cell is being maximized or minimized.

By_changing indicates the changing cells, as entered in the By Changing Cells box. By_changing must refer to a cell or range of cells on the active worksheet, and can be a multiple selection.

Remarks

The constraints in a Solver problem can refer to a maximum of 400 cells.

Related Function

SOLVER.SOLVE Returns an integer value indicating the condition that caused Solver to stop

List of Command-Equivalent Functions


SOLVER.OPTIONS

Macro Sheets Only

Equivalent to choosing the Solver command from the Tools menu and then choosing the Options button in the Solver Parameters dialog box. Specifies the available options.

If this function is not available, you must install the Solver add-in macro.

Syntax

SOLVER.OPTIONS(max_time, iterations, precision, assume_linear, step_thru, estimates, derivatives, search, int_tolerance, scaling)

The arguments correspond to the options in the dialog box. If an argument is omitted, Microsoft Excel uses an appropriate value based on the current situation. If any of the arguments are the wrong type, the function returns the #N/A error value. If an argument has the correct type but an invalid value, the function returns a positive integer corresponding to its position. A zero indicates all options were accepted.

Max_time must be an integer greater than zero and less than 32768. It corresponds to the Max Time box.

Iterations must be an integer greater than zero and less than 32768. It corresponds to the Iterations box.

Precision must be a number between zero and one, but not equal to zero or one. It corresponds to the Precision box.

Assume_linear is a logical value corresponding to the Assume Linear Model check box and allows Solver to arrive at a solution more quickly. If TRUE, Solver assumes that the underlying model is linear; if FALSE, it does not.

Step_thru is a logical value corresponding to the Show Iteration Results check box. If you have supplied SOLVER.SOLVE with a valid command macro reference, your macro will be called each time Solver pauses. If TRUE, Solver pauses at each trial solution; if FALSE, it does not.

Estimates is the number 1 or 2 and corresponds to the Estimates options: 1 for the Tangent option and 2 for the Quadratic option.

Derivatives is the number 1 or 2 and corresponds to the Derivatives options: 1 for the Forward option and 2 for the Central option.

Search is the number 1 or 2 and corresponds to the Search options: 1 for the Quasi-Newton option and 2 for the Conjugate Gradient option.

Int_tolerance is a decimal number corresponding to the Tolerance box in the Solver Options dialog box, and must be between zero and 1, inclusively. This argument applies only if integer constraints have been defined.

Scaling is a logical value corresponding to the Use Automatic Scaling check box. If scaling is TRUE, then if two or more constraints differ by several orders of magnitude, Solver scales the constraints to similar orders of magnitude during computation. If scaling is FALSE, Solver calculates normally.

Related Functions

List of Command-Equivalent Functions


SOLVER.RESET

Macro Sheets Only

Equivalent to choosing the Solver command from the Tools menu and choosing the Reset All button in the Solver Parameters dialog box. Erases all cell selections and constraints from the Solver Parameters dialog box and restores all the settings in the Solver Options dialog box to their defaults.

If this function is not available, you must install the Solver add-in macro.

Syntax

SOLVER.RESET( )

Related Functions

List of Command-Equivalent Functions


SOLVER.SAVE

Macro Sheets Only

Equivalent to choosing the Solver command from the Tools menu, choosing the Options button from the Solver Parameters dialog box, and choosing the Save Model button in the Solver Options dialog box. Saves the Solver problem specifications on the worksheet.

If this function is not available, you must install the Solver add-in macro.

Syntax

SOLVER.SAVE (save_area)

Save_area is a reference on the active sheet to a range of cells or to the upper-left corner of a range of cells into which you want to paste the current problem specification.

  • If you specify only one cell for save_area, the area is extended downwards for as many cells as are required to hold the problem specifications (3 plus the number of constraints).
  • If you specify more than one cell and if the area is too small, the last constraints (in alphabetic order by cell reference) or options will be omitted and the function will return a nonzero value.
  • Save_area must be on the active worksheet, but it need not be the current selection.

Related Functions

List of Command-Equivalent Functions


SOLVER.SOLVE

Macro Sheets Only

Equivalent to choosing the Solver command from the Tools menu and choosing the Solve button in the Solver Parameters dialog box. If successful, returns an integer value indicating the condition that caused Solver to stop as described in "Remarks" later in this topic.

If this function is not available, you must install the Solver add-in macro.

Syntax

SOLVER.SOLVE(user_finish, show_ref)

User_finish is a logical value specifying whether to display the Solver Results dialog box.

  • If user_finish is TRUE, SOLVER.SOLVE returns its integer value without displaying anything. Your macro should decide what action to take (for example, by examining the return value or presenting its own dialog box); it must call SOLVER.FINISH in any case to restore the sheet to its proper state.
  • If user_finish is FALSE or omitted, Solver displays the Solver Results dialog box, which allows you to keep or discard the final solution and run reports.

Show_ref is a macro to be called in place of the Show Trial Solution dialog box. It is used when you want to regain control whenever Solver finds a new intermediate solution value.

  • For this argument to have an effect, the Show Iteration Results check box must be selected in the Solver Options dialog box. This can be done manually by selecting the check box, or automatically by calling SOLVER.OPTIONS in your macro.
  • The macro you call can inspect the current solution values on the sheet or take other actions such as saving or charting the intermediate values. It must return the value TRUE with a statement such as =RETURN(TRUE) if the solution process is to continue, or FALSE if the solution process should stop at this point.

Remarks

If a problem has not been completely defined, SOLVER.SOLVE returns the #N/A error value. Otherwise, the Solver application is started and the problem specifications are passed to it. When the solution process is complete, SOLVER.SOLVE returns an integer value indicating the stopping condition:

Value Stopping condition

0 Solver found a solution. All constraints and optimality conditions are satisfied.

1 Solver has converged to the current solution. All constraints are satisfied.

2 Solver cannot improve the current solution. All constraints are satisfied.

3 Stop chosen when the maximum iteration limit was reached.

4 The Set Cells values do not converge.

5 Solver could not find a feasible solution.

6 Solver stopped at user's request.

7 The conditions for Assume Linear Model are not satisfied.

8 The problem is too large for Solver to solve.

9 Solver encountered an error value in a target or constraint cell.

10 Stop chosen when the maximum time limit was reached.

11 There is not enough memory available to solve the problem.

12 Another Excel instance is using SOLVER.DLL. Try again later.

13 Error in model. Please verify that all cells and constraints are valid.

Related Functions

SOLVER.FINISH Equivalent to choosing OK in the Solver Results dialog box that appears when the solution process is complete

List of Command-Equivalent Functions


SUBSCRIBE.TO

Macro Sheets Only

Inserts the contents of the edition into the active sheet at the point of the current selection. Use SUBSCRIBE.TO to incorporate editions published from other workbooks into your Microsoft Excel worksheets and macro sheets. SUBSCRIBE.TO returns TRUE if successful.

Syntax

SUBSCRIBE.TO(file_text, format_num)

Important This function is only available if you are using Microsoft Excel for the Macintosh with system software version 7.0 or later.

File_text is the name, as a text string, of the edition you want to insert into the active sheet. Unless file_text is in the current folder, supply the full path of the workbook. If file_text cannot be found, SUBSCRIBE.TO returns the #VALUE! error value and interrupts the macro.

Remarks

  • If a single cell is selected, the data from the edition file is placed into as large a range of cells as is required by the data. Data already present in those cells is replaced. If the data is a picture, it is inserted from the upper-left corner of the selected cell.
  • If a range of cells is selected, and the range is not big enough to contain the edition data, Microsoft Excel displays a dialog box asking if you want to clip the data to fit the range.

Format_num is the number 1 or 2 and specifies the format type of the file you are subscribing to.

Format_num Format type

1 or omitted Picture

2 Text (includes BIFF, VALU, TEXT, and CSV formats)

Related Functions

CREATE.PUBLISHER Creates a publisher from the selection

EDITION.OPTIONS Sets publisher and subscriber options

GET.LINK.INFO Returns information about a link

List of Command-Equivalent Functions


TERMINATE

Macro Sheets Only

Closes a dynamic data exchange (DDE) channel previously opened with the INITIATE function. Use TERMINATE to close a channel after you have finished communicating with another application.

Syntax

TERMINATE(channel_num)

Important Microsoft Excel for the Macintosh requires system software version 7.0 or later for this function.

Channel_num is the number returned by a previously run INITIATE function. Channel_num identifies a DDE channel to close.

If TERMINATE is not successful, it returns the #VALUE! error value.

Related Functions

EXEC Starts another application

INITIATE Opens a channel to another application

List of DDE/External Functions


TEXTREF

Macro Sheets Only

Converts text to an absolute reference in either A1- or R1C1-style. Use TEXTREF to convert references stored as text to references so that you can use them with other functions, such as OFFSET.

Syntax

TEXTREF(text, a1)

Text is a reference in the form of text.

A1 is a logical value specifying the reference type of text. If a1 is TRUE, text is assumed to be an A1-style reference; if FALSE or omitted, text is assumed to be an R1C1-style reference.

Remarks

  • If you use TEXTREF by itself in a cell, you will get the value contained in the cell specified by text, not the reference itself, because references are automatically converted into the contents of the referenced cell.
  • If you use TEXTREF as a reference argument to a function, Microsoft Excel does not convert the reference to a value.

Tip You can convert a reference to text with REFTEXT, manipulate it with the REPLACE and MID functions, and convert it back to a reference with TEXTREF.

Examples

TEXTREF("B7", TRUE) equals the reference value $B$7

TEXTREF("R5C5", FALSE) equals the reference value R5C5

TEXTREF("B7", FALSE) equals the #REF! error value, because "B7" can't be interpreted as an R1C1-style reference.

Related Functions

DEREF Returns the values of the cells in a reference

REFTEXT Converts a reference to text

List of Lookup & Reference Functions


UNDO

Macro Sheets Only

Equivalent to choosing the Undo command from the Edit menu. Reverses certain actions and commands. UNDO is available in the same situations as the Undo command.

Syntax

UNDO( )

Related Functions

List of Command-Equivalent Functions


UNREGISTER

Macro Sheets Only

Unregisters a previously registered dynamic link library (DLL) or code resource. You can use UNREGISTER to free memory that was allocated to a DLL or code resource when it was registered. There are two syntax forms of this function. Use syntax 1 when you want Microsoft Excel to unregister a function or code resource according to its use count. Use syntax 2 when you want Microsoft Excel to unregister a function or code resource regardless of the use count.

Syntax 1

UNREGISTER(register_id)

Register_id is the register ID returned by the REGISTER or REGISTER.ID function, which corresponds to the function or code resource to be removed from memory.

Microsoft Excel counts the number of times you register a function or code resource. This number is called the use count. Each time you unregister a function or code resource, its use count is decremented by 1. When the use count equals 0, Microsoft Excel frees the allocated memory. Therefore, if you register a function or code resource more than once, you must use a corresponding number of UNREGISTER functions to ensure that it is completely unregistered.

Note Because Microsoft Excel for Windows and Microsoft Excel for the Macintosh use different types of code resources, UNREGISTER has a slightly different syntax form when used in each operating environment.

Syntax 2a

For Microsoft Excel for Windows

UNREGISTER(module_text)

Syntax 2b

For Microsoft Excel for the Macintosh

UNREGISTER(file_text)

Module_text or file_text is text specifying the name of the dynamic link library (DLL) that contains the function (in Microsoft Excel for Windows) or the name of the file that contains the code resource (in Microsoft Excel for the Macintosh).

If you use this syntax of UNREGISTER, all functions in the DLL (or all code resources in the file) are immediately unregistered, regardless of the use count.

Examples

Assuming that a REGISTER function in cell A5 of a macro sheet has already run (and has run only once), the following macro formula unregisters the corresponding function or code resource:

UNREGISTER(A5)

You could also use REGISTER.ID to return the register ID, instead of specifying a cell reference:

UNREGISTER(REGISTER.ID("User", "GetTickCount")

Assuming that you have registered several different functions from the USER.EXE DLL of Microsoft Windows, the following macro formula unregisters all functions in that DLL:

UNREGISTER("User")

Tip If you register a function or code resource, and use the optional function_text argument to specify a custom name that will appear in the Paste Function dialog box, this custom name will not be removed by the UNREGISTER function. To remove the custom name, use the SET.NAME function without its second argument

Related Functions

REGISTER Registers a code resource

List of DDE/External Functions


VIEW.3D

Macro Sheets Only

Equivalent to choosing the 3-D View command from the Format menu in Microsoft Excel version 4.0, available when a chart is the active document. Adjusts the view of the active 3-D chart. Use VIEW.3D to emphasize different parts of your chart by viewing it from different angles and perspectives.

Syntax

VIEW.3D(elevation, perspective, rotation, axes, height%, autoscale)
VIEW.3D?(elevation, perspective, rotation, axes, height%, autoscale)

Elevation is a number from -90 to 90 specifying the viewing elevation of the chart and is measured in degrees. Elevation corresponds to the Elevation box in the 3-D View dialog box in Microsoft Excel version 4.0.

  • If elevation is 0, you view the chart straight on. If elevation is 90, you view the chart from above (a "bird's eye view"). If elevation is -90, you view the chart from below.
  • If elevation is omitted, the current value is used..
  • Elevation is limited to 0 to 44 for 3-D bar charts and 0 to 80 for 3-D pie charts.

Perspective is a number from 0 to 100% specifying the perspective of the chart. Perspective corresponds to the Perspective box in the 3-D View dialog box in Microsoft Excel version 4.0.

  • A higher perspective value simulates a closer view.
  • If perspective is omitted, the current value is used..
  • Perspective is ignored on 3-D bar and pie charts.

Rotation is a number from 0 to 360 specifying the rotation of the chart around the value (z) axis and is measured in degrees. Rotation corresponds to the Rotation box in the 3-D View dialog box in Microsoft Excel version 4.0. As you rotate the chart, the back and side walls are moved so that they do not block the chart.

  • If rotation is omitted, the current value is used..
  • Rotation is limited to 0 to 44 for 3-D bar charts.

Axes is a logical value specifying whether axes are fixed in the plane of the screen or can rotate with the chart. Axes corresponds to the Right Angle Axes check box in the 3-D View dialog box in Microsoft Excel version 4.0.

  • If axes is TRUE, Microsoft Excel locks the axes.
  • If axes is FALSE, Microsoft Excel allows the axes to rotate.
  • If axes is omitted and the chart view is 3-D layout, axes is assumed to be FALSE.
  • Axes is TRUE for 3-D bar charts and ignored for 3-D pie charts.

Height% is a number from 5 to 500 specifying the height of the chart as a percentage of the length of the base. Height% corresponds to the Height box in the 3-D View dialog box in Microsoft Excel version 4.0. Height% is useful for controlling the appearance of charts with many series or data points. If height% is omitted, the current value is used..

Autoscale is a logical value corresponding to the Auto Scaling check box in the 3-D View dialog box in Microsoft Excel version 4.0. If TRUE, automatic scaling is used; if FALSE, it is not; if omitted, the current setting is not changed.

Related Function

FORMAT.MAIN Formats a main chart

List of Command-Equivalent Functions


VIEW.DEFINE

Macro Sheets Only

Equivalent to choosing the Add button from the View Manager dialog box, which appears when you choose the View Manager command from the View menu. Creates or replaces a view.

If this function is not available, you must install the View Manager add-in macro.

Syntax

VIEW.DEFINE(view_name, print_settings_log, row_col_log)

View_name is text enclosed in quotation marks and specifies the name of the view you want to define for the sheet. If the workbook already contains a view with view_name, the new view replaces the existing one.

Print_settings_log is a logical value that, if TRUE or omitted, includes current print settings in the view or, if FALSE, does not include current print settings in the view.

Row_col_log is a logical value that, if TRUE or omitted, includes current row and column settings in the view or, if FALSE, does not include current row and column settings in the view.

Related Functions

VIEW.DELETE Removes a view from the active workbook

VIEW.SHOW Shows a view

List of Command-Equivalent Functions


VIEW.DELETE

Macro Sheets Only

Equivalent to selecting a view and choosing the Delete button from the View Manager dialog box, which appears when you choose the View Manager command from the View menu. Removes a view from the active workbook.

If this function is not available, you must install the View Manager add-in macro.

Syntax

VIEW.DELETE(view_name)

View_name is text enclosed in quotation marks and specifies the name of the view in the current workbook that you want to delete.

Remarks

VIEW.DELETE returns the #VALUE error value if view_name is invalid or if the workbook is protected.

Related Functions

VIEW.DEFINE Creates or replaces a view

VIEW.SHOW Shows a view

List of Command-Equivalent Functions


VIEW.GET

Macro Sheets Only

Equivalent to displaying a list of views in the View Manager dialog box, which appears when you choose the View Manager command from the View menu. Returns an array of views from the active workbook.

If this function is not available, you must install the View Manager add-in macro.

Syntax

VIEW.GET(type_num, view_name)

Type_num is a number from 1 to 3 that specifies the type of information to return, as shown in the following table.

Type_num Result

1 Returns an array of views from all the sheets in the active workbook or the #N/A error value if none are defined.

2 Returns TRUE if print settings are included in the specified view. Returns FALSE if print settings are not included. Returns the #VALUE! error value if the name is invalid or the workbook is protected.

3 Returns TRUE if row and column settings are included in the specified view. Returns FALSE if row and column settings are not included. Returns the #VALUE! error value if the name is invalid or the workbook is protected.

View_name is text enclosed in quotation marks and specifies the name of a view in the active workbook. View_name is required if type_num is 2 or 3.

Example

The following macro formula returns an array of views from the active workbook:

VIEW.GET(1)

Related Functions

VIEW.DEFINE Creates or replaces a view

VIEW.DELETE Removes a view from the active workbook

VIEW.SHOW Shows a view

List of Information Functions


VIEW.SHOW

Macro Sheets Only

Equivalent to selecting a view and choosing the Show button in the View Manager dialog box, which appears when you choose the View Manager command from the View menu. Shows a view.

If this function is not available, you must install the View Manager add-in macro.

Syntax

VIEW.SHOW(view_name)
VIEW.SHOW?(view_name)

View_name is text enclosed in quotation marks and specifies the name of a view in the active workbook.

Remarks

VIEW.SHOW returns the #VALUE error value if view_name is invalid or the workbook is protected.

Related Functions

VIEW.DEFINE Creates or replaces a view

VIEW.DELETE Removes a view from the active workbook

List of Command-Equivalent Functions


SERIES

Charts Only

Represents a data series in the active chart. SERIES is used only in charts; you cannot enter it on a sheet or macro sheet. You normally create or change data series by using the Chart Wizard or EDIT.SERIES macro function, which is equivalent to the Edit Series command on the Chart menu in Microsoft Excel version 4.0. However, you can edit a data series manually by selecting it, switching to the formula bar, and typing the changes.

Syntax

SERIES(name_ref, categories, values, plot_order)

Name_ref is the name of the data series. It can be an external reference to a single cell or a name defined as a single cell. Name_ref can also be text enclosed in quotation marks (for example, "Projected Sales").

Categories is an external reference to the name of the workbook and to the cells that contain one of the following sets of data:

  • Category labels for all charts except xy (scatter) charts
  • X-coordinate data for xy (scatter) charts

Values is an external reference to the name of the workbook and to the cells that contain values (or y-coordinate data in scatter charts).

Plot_order is an integer specifying whether the series is plotted first, second, or third, and so on, in the chart. No two series can have the same plot_order.

Remarks

  • Categories and values can be arrays or references to a multiple selection, although they cannot be names that refer to a multiple selection. If you specify a multiple selection for any of these arguments, make sure you include the necessary sets of parentheses so that Microsoft Excel does not treat the components of the references as separate arguments.
  • If either categories or values is a multiple selection, then all areas in that selection must be either vertical (more rows than columns) or horizontal (more columns than rows).

Related Functions

CHART.WIZARD Creates and formats a chart

EDIT.SERIES Creates or changes a chart series


ADD.TOOL

Macro Sheets Only

Adds one or more buttons to a toolbar.

Syntax

ADD.TOOL(bar_id, position, tool_ref)

Bar_id is either a number specifying one of the built-in toolbars or the name of a custom toolbar.

Bar_id Built-in toolbar

1 Standard

2 Formatting

3 Query and Pivot

4 Chart

5 Drawing

6 TipWizard

7 Forms

8 Stop Recording

9 Visual Basic

10 Auditing

11 WorkGroup

12 Microsoft

13 Full Screen

Position specifies the position of the button within the toolbar. Position starts with 1 at the left side (if horizontal) or at the top (if vertical).

Tool_ref is either a number specifying a built-in button or a reference to an area on the macro sheet that defines a custom button or set of buttons (or an array containing this information). For a complete list of built-in buttons and their corresponding numbers, see Appendix D, "Toolbar Buttons in Microsoft Excel," in the Microsoft Excel Visual Basic User's Guide.

For customized buttons, the following example shows the components of a button reference area on a macro sheet and defines custom tools. The range A1:I5 is a valid tool_ref. Row 1 refers to a built-in tool. Row 2 defines a gap. For this illustration, values are displayed instead of formulas so that text can wrap in cells.

  • Tool_id is a number associated with the tool. A zero specifies a gap on the toolbar. To specify a custom button, use a name, or a number between 201 and 231. For a complete list of built-in buttons and their corresponding numbers, see Appendix D, "Toolbar Buttons in Microsoft Excel," in the Microsoft Excel Visual Basic User's Guide.
  • Macro is the name of, or a quoted R1C1-style reference to, the macro you want to run when the button is clicked.
  • Down is a logical value specifying the default image of the tool. If down is TRUE, the button appears depressed into the screen; if FALSE or omitted, it appears normal (up).
  • Enabled is a logical value specifying whether the button can be used. If enabled is TRUE, the button is enabled; if FALSE, it is disabled.
  • Face specifies a face associated with the tool. Face must be a reference to a picture-type object, for example "Picture 1". If face is omitted, Microsoft Excel uses the default face for the tool.
  • Status_text is the text, if any, that you want displayed in the status bar when the button is selected.
  • Balloon_text is the balloon help text, if any, associated with the tool. Balloon_text is available only in Microsoft Excel for the Macintosh using system software version 7.0 or later.
  • Help_topics is a reference to a topic in a Help file, in the form "filename!topic_number". Help_topics must be text. If help_topics is omitted, HELP displays the Contents topic for Microsoft Excel Help.
  • Tip_text is the text, if any, that you want displayed as a ToolTip when the mouse pointer moves over a tool button.

To indicate that a particular component of tool_ref is not used, clear the contents of the corresponding cell.

Remarks

  • If you do not want to reserve a section of your macro sheet to define the buttons, you can use an array as the tool_ref argument as shown in the following syntax:

    ADD.TOOL(bar_id, position, {tool_id1, macro1, down1, enabled1, face1,
    status_text1, balloon_text1, help_topics1;tool_id2, macro2, down2, enabled2,
    face2, status_text2, balloon_text2, help_topics2;...})

  • Picture objects can be created with the camera button or pasted in from another application. In Microsoft Excel for Windows, the graphic object must be either a Windows bitmap or picture object. In Microsoft Excel for the Macintosh, the object must be a picture object.

Examples

The following macro formula adds a button to Toolbar5. The cell range B6:I6 contains tool_ref.

ADD.TOOL("Toolbar5", 6, B6:I6)

The following macro formula adds the New Macro Sheet button to the fifth position on the Standard toolbar:

ADD.TOOL(1, 5, 6)

Related Functions

ADD.COMMAND Adds a command to a menu

ADD.TOOLBAR Creates a toolbar with the specified tools

DELETE.TOOL Deletes a button from a toolbar

DELETE.TOOLBAR Deletes custom toolbars

RESET.TOOLBAR Resets a built-in toolbar to its default initial setting

List of Customizing Functions


APP.SIZE

Macro Sheets Only

Equivalent to choosing the Size command from the Control menu for the application window. Changes the size of the Microsoft Excel window.

Syntax

APP.SIZE(x_num, y_num)
APP.SIZE?(x_num, y_num)

Note This function is only for Microsoft Excel for Windows. You can use this function in macros created with Microsoft Excel for the Macintosh, but it will return the #N/A error value.

X_num specifies the width of the Microsoft Excel window in points.

Y_num specifies the height of the Microsoft Excel window in points.

APP.SIZE?, the dialog-box form of the function, doesn't display a dialog box. Instead, it is equivalent to pressing ALT, SPACEBAR, S or to dragging a window border with the mouse. Using APP.SIZE?, you can size the window with the keyboard or mouse. If you specify x_num and/or y_num in the dialog-box form of the function, the window is sized according to the specified coordinates, and you are left in size mode.

Related Functions

APP.ACTIVATE Switches to an application

APP.MAXIMIZE Maximizes the Microsoft Excel application window

APP.MINIMIZE Minimizes the Microsoft Excel application window

APP.MOVE Moves the Microsoft Excel application window

APP.RESTORE Restores the Microsoft Excel application window

List of Command-Equivalent Functions


CALCULATE.DOCUMENT

Macro Sheets Only

Equivalent to choosing the Calc Sheet button in the Calculation tab on the Options dialog, which appears when you choose the Options command from the Tools menu. Calculates only the active worksheet.

Syntax

CALCULATE.DOCUMENT( )

Remarks

If a chart is active, CALCULATE.DOCUMENT returns the #VALUE! error value.

Related Functions

CALCULATE.NOW Calculates all open workbooks immediately

CALCULATION Controls calculation settings

List of Command-Equivalent Functions


CLEAR.ROUTING.SLIP

Equivalent to the Clear button in the Routing Slip dialog box. Clears the routing slip.

Syntax

CLEAR.ROUTING.SLIP(reset_only_logical)

Reset_only_logical is a logical value that specifies whether the routing slip should be cleared.

  • This option is valid only after every recipient on the routing slip has received and forwarded the workbook. Setting reset_only_logical to TRUE in this case is equivalent to the Reset button in the routing slip dialog.
  • If some recipients have not recieved or routed the workbook, reset_only_logical is ignored.
  • If reset_only_logical is FALSE or omitted and the workbook has been routed to all recipients, then the routing slip is removed from the workbook. A new slip can be subsequently added using ROUTING.SLIP().

Related Functions

List of Command-Equivalent Functions


CONSTRAIN.NUMERIC

Macro Sheets Only

Equivalent to pressing the Constrain Numeric button in the Formula category of the Customize dialog box, which appears when you choose the Toolbars command from the View menu and then choose the customize button. Constrains handwriting recognition to numbers and punctuation only. Use this function in a macro to improve the accuracy of handwriting recognition when the user is entering a series of numbers or formulas.

Note This function is only available if you are using Microsoft Windows for Pen Computing.

Syntax

CONSTRAIN.NUMERIC(numeric_only)

Numeric_only is a logical value that turns the numeric constraint on or off. If numeric_only is TRUE, only numbers and digits are recognized; if FALSE, all characters are recognized as usual. if numeric_only is omitted, the numeric constraint is toggled.

Remarks

When the numeric constraint is on, Microsoft Excel recognizes only the following symbols:

0 1 2 3 4 5 6 7 8 9 $ # @ % ( ) - + = { } : < > , ? | .

Tip Use GET.WORKSPACE(45) to make sure you're running Microsoft Windows for Pen Computing.

Related Functions

List of Command-Equivalent Functions


COPY.CHART

Macro Sheets Only

Equivalent to choosing the Copy Chart command from the Edit menu in Microsoft Excel for the Macintosh version 1.5 or earlier. This function is included only for macro compatibility. You can copy a chart with the COPY.PICTURE function by omitting the appearance_num argument.

Syntax

COPY.CHART(size_num)

Size_num is a number describing how to copy the picture and is only available if the current selection is a chart.

Size_num Action

1 or omitted Copies the chart in the same size as the window on which it is displayed

2 Copies what you would see if you printed the chart

Related Function

COPY.PICTURE Creates a picture of the current selection for use in another program

List of Command-Equivalent Functions


COPY.PICTURE

Macro Sheets Only

Equivalent to choosing the Copy Picture command from the Edit menu. The Copy Picture command appears if you hold down SHIFT while choosing the Edit menu. It copies a chart or range of cells to the Clipboard as a graphic. Use COPY.PICTURE to create an image of the current selection or chart for use in another program.

Syntax

COPY.PICTURE(appearance_num, size_num, type_num)
COPY.PICTURE?(appearance_num, size_num, type_num)

Remarks

Graphics are created differently on screen and on a printer. Thus, the printed picture may look different from the one on screen.

Appearance_num is a number describing how to copy the picture.

Appearance_num Action

1 or omitted Copies a picture as closely as possible to the picture displayed on your screen

2 Copies what you would see if you printed the selection

Size_num is a number describing how to copy the picture and is only available if the current selection is a chart.

Size_num Action

1 or omitted Copies the chart in the same size as the window on which it is displayed

2 Copies what you would see if you printed the chart

Type_num is a number specifying the format of the picture. This argument is available only in Microsoft Excel for Windows.

Type_num Format of the picture

1 or omitted Picture

2 Bitmap

Related Functions

COPY Copies and pastes data or objects

CUT Cuts or moves data or objects

PASTE Pastes cut or copied data

PASTE.PICTURE.LINK Pastes a linked picture of the currently copied area

PASTE.SPECIAL Pastes specific components of copied data

List of Command-Equivalent Functions


CUSTOMIZE.TOOLBAR

Macro Sheets Only

Equivalent to choosing the Toolbars command from the View menu and choosing the Customize button. Displays the Customize Toolbar dialog box. This function has a dialog-box syntax only.

Syntax

CUSTOMIZE.TOOLBAR?(category)

Category is a number that specifies which category of tools you want displayed in the dialog box. If omitted, the previous setting is used.

Category Category of tools

1 File

2 Edit

3 Formula

4 Formatting

5 Text Formatting

6 Drawing

7 Macro

8 Charting

9 Utility

10 Data

11 TipWizard

12 Auditing

13 Forms

14 Custom

Related Functions

ADD.TOOLBAR Creates a new toolbar with the specified tools

SHOW.TOOLBAR Hides or displays a toolbar

List of Customizing Functions


DATA.LABEL

Equivalent to choosing the Data Labels command on the Insert menu when a chart is active. Specifies label contents and position.

Syntax

DATA.LABEL(show_option, auto_text, show_key)

Show_option is a number that specifies what type of labels to display.

Show_option Type displayed

1 none

2 Show value

3 Show percent

4 Show label

5 Show label and percent

Auto_text is a logical value that corresponds the Automatic Checkbox in the Data Labels dialog box. If TRUE, resets a chart's data labels back to their actual values. If FALSE, they are not reset. The Automatic Text checkbox appears only if the label has been selected and its value changed.

Show_key is a logical value that specified whether to show the legend key next to the label. If TRUE, displays the legend key. If FALSE or omitted,does not display the legend key.

Related Functions

List of Command-Equivalent Functions


DELETE.STYLE

Macro Sheets Only

Equivalent to choosing the Delete button from the Style dialog box, which appears when you choose the Style command from the Format menu. Deletes a style from a workbook. Cells formatted with the deleted style revert to the Normal style.

Syntax

DELETE.STYLE(style_text)

Style_text is the name of a style to be deleted. If style_text does not exist, DELETE.STYLE returns the #VALUE! error value and interrupts the macro.

Remarks

You can only delete styles from the active workbook. External references are not permitted as part of the style_text argument.

Related Functions

APPLY.STYLE Applies a style to the selection

DEFINE.STYLE Creates or changes a cell style

MERGE.STYLES Merges styles from another document into the active document

List of Command-Equivalent Functions


FIND.FILE

Equivalent to choosing the Find File command from the File menu. Lets you search for files based on criteria such as author or creation date.

Syntax

FIND.FILE?( )

Remarks

This function has a dialog-box form only.

Related Functions

List of Command-Equivalent Functions


FILTER

Filters lists of data one column at a time. Only one list can be filtered on any one sheet at a time.

Syntax

FILTER(field_num, criteria1, operation, criteria2)

FILTER?(field_num, criteria1, operation, criteria2)

Field_num is the number of the field that you want to filter. Fields are numbered from left to right starting with 1.

Criteria1 is a text string specifying criteria for filtering a list, such as ">2". If you want to include all items in the list, omit this argument.

Operation is a number that specifies how you want criteria2 used with criteria1:

Number Operation Used

1 AND

2 OR

Criteria2 is a text string specifying criteria for filtering a list, such as ">2". If you include this argument, operation is required.

Remarks

If you omit all arguments, FILTER toggles the display of filter arrows.

Related Functions

FILTER.ADVANCED Lets you set options for filtering a list

List of Command-Equivalent Functions


FILTER.ADVANCED

Equivalent to choosing the Advanced Filter command from the Filter submenu on the Data menu. Lets you set options for filtering a list.

Syntax

FILTER.ADVANCED(operation, list_ref, criteria_ref, copy_ref, unique)
FILTER.ADVANCED?(operation, list_ref, criteria_ref, copy_ref, unique)

Operation is a number specifying whether to copy the filter list to a new location. To filter a list without copying, use 1; to copy the filter list to a new location, use 2.

List_ref specifies the location of the list to be filtered. If operation is 1, then list_ref must be on the active sheet.

Criteria_ref is a reference to a range containing criteria for filtering the list. If omitted, uses "All" as the criteria.

Copy_ref is a reference on the active sheet where you want the filtered list copied. Ignored if operation is 1.

Unique is a logical value that specifies whether only unique records are displayed. To display only unique records, use TRUE. To display all records that match the criteria, use FALSE or omit this argument.

Related Functions

FILTER Filters lists of data one column at a time

List of Command-Equivalent Functions


FILTER.SHOW.ALL

Equivalent to choosing the Show All command from the Filter submenu on the Data menu. Displays all items in a filtered list.

Syntax

FILTER.SHOW.ALL()

Related Functions

List of Command-Equivalent Functions


FILL.GROUP

Macro Sheets Only

Equivalent to choosing the Across Worksheets command from the Fill submenu on the Edit menu. Copies the contents of the active worksheet's selection to the same area on all other worksheets in the group. Use FILL.GROUP to fill a range of cells on all worksheets in a group at once.

Syntax

FILL.GROUP(type_num)
FILL.GROUP?(type_num)

Type_num is a number from 1 to 3 that corresponds to the choices in the Fill Across Worksheets dialog box.

Type_num Type of information filled

1 All

2 Contents

3 Formats

Related Functions

NEW Creates a new workbook

WORKBOOK.SELECT Selects one or more sheets in a workbook

List of Command-Equivalent Functions


FORMAT.CHART

Macro Sheets Only

Equivalent to choosing the Options button in the Chart Type dialog box, which is available when you choose the Chart Type command from the Format menu when a chart is active. Formats the chart according to the arguments you specify.

Syntax

FORMAT.CHART(layer_num, view, overlap, angle, gap_width, gap_depth, chart_depth, doughnut_size, axis_num, drop, hilo, up_down, series_line, labels, vary)

FORMAT.CHART?(layer_num, view, overlap, angle, gap_width, gap_depth, chart_depth, doughnut_size, axis_num, drop, hilo, up_down, series_line, labels, vary)

Several of the following arguments are logical values corresponding to check boxes in the Options tab of Format (chart type) Group dialog box. If an argument is TRUE, Microsoft Excel selects the corresponding check box; if FALSE, Microsoft Excel clears the check box. If an argument is omitted, the setting is unchanged.

layer_num is a number specifying which chart you want to change.

View is a number specifying one of the subtypes in the Subtype tab of the Format (type) Group dialog box. The subtype varies depending on the type of chart.

Overlap is a number from -100 to 100 specifying how you want bars or columns to be positioned. It corresponds to the Overlap edit box in the Options tab on the Format Bar Group Dialog box, which appears when you choose the Bar Group from the Format menu. Overlap is ignored if type_num is not 2 or 3 (bar or column chart).

  • If overlap is positive, it specifies the percentage of overlap you want for bars or columns. For example, 50 would cause one-half of a bar or column to be covered by an adjacent bar or column. A value of zero prevents bars or columns from overlapping.
  • If overlap is negative, then bars or columns are separated by the specified percentage of the maximum available distance between any two bars or columns.
  • If overlap is omitted, it is assumed to be 0 (bars or columns do not overlap), or it is unchanged if a value was previously set.

Angle is a number from 0 to 360 specifying the angle of the first pie or doughnut slice (in degrees) if the chart is a pie or doughnut chart. If angle is omitted, it is assumed to be 0, or it is unchanged if a value was previously set.

Gap_width is a number from 0 to 500 specifying the space between bar or column clusters as a percentage of the width of a bar or column. It corresponds to the Gap Width edit box in the Options tab on the Format Bar Group Dialog box, which appears when you choose the Bar Group from the Format menu.

  • Gap_width is ignored if type_num is not 2, 3, 8, or 12 (bar or column chart).
  • If Gap_width is omitted, it is assumed to be 50, or it is unchanged if a value was previously set.

The next two arguments are for 3-D charts only, and correspond to check boxes in the Options tab of Format (chart type) Group dialog box.

Gap_depth is a number from 0 to 500 specifying the depth of the gap in front of and behind a bar, column, area, or line as a percentage of the depth of the bar, column, area, or line.

  • gap_depth is ignored if the chart is a pie chart or if it is not a 3-D chart.
  • If gap_depth is omitted and the chart is a 3-D chart, gap_depth is assumed to be 50, or it is unchanged if a value was previously set. If gap_depth is omitted and the view is side-by-side, stacked, or stacked 100%, gap_depth is assumed to be 0, or it is unchanged if a value was previously set.

Chart_depth is a number from 20 to 2000 specifying the visual depth of the chart as a percentage of the width of the chart.

  • Chart_depth is ignored if the chart is not a 3-D chart.
  • If Chart_depth is omitted, it is assumed to be 100, or it is unchanged if a value was previously set.

doughnut_size specifies the size of the hole in a doughnut chart. Can be a value from 10% - 90%. Default is 50%.

Axis_num is a number specifying whether to plot the chart on the primary axis or the secondary axis.

Drop corresponds to the Drop Lines check box. Drop is available only for area and line charts.

Hilo corresponds to the Hi-Lo Lines check box. Hilo is available only for 2-D line charts.

The next four arguments are logical values corresponding to check boxes in the Options tab of the Format (chart type) Group dialog box. If an argument is TRUE, Microsoft Excel selects the corresponding check box; if FALSE, Microsoft Excel clears the check box. If an argument is omitted, the setting is unchanged.

Up_down corresponds to the Up/Down Bars check box. Up_down is available only for 2-D line charts.

Series_line corresponds to the Series Lines check box. Series_line is available only for 2-D stacked bar and column charts.

Labels corresponds to the Radar Axis Labels check box. Labels is available only for radar charts.

Vary corresponds to the Vary Colors By Point check box. Vary applies only to charts with one data series and is not available for area charts.

Related Functions

FORMAT.MAIN Formats a chart according to the arguments you specify

FORMAT.OVERLAY Formats an overlay chart

List of Command-Equivalent Functions


FORMAT.FONT

Macro Sheets Only

Equivalent to choosing the Cells command from the Format menu, and then selecting Font tab from the Format Cells dialog box. This function is included for compatibility with Microsoft Excel 4.0. Use FONT.PROPERTIES to set various font properties. FORMAT.FONT has three syntax forms. Syntax 1 is for cells; syntax 2 is for text boxes and buttons; syntax 3 is used with all chart items (axes, labels, text, and so on).

Syntax 1

Cells

FORMAT.FONT(name_text, size_num, bold, italic, underline, strike, color, outline, shadow)
FORMAT.FONT?(name_text, size_num, bold, italic, underline, strike, color, outline, shadow)

Syntax 2

Text boxes and buttons on worksheets and macro sheets

FORMAT.FONT(name_text, size_num, bold, italic, underline, strike, color, outline, shadow, object_id_text, start_num, char_num)
FORMAT.FONT?(name_text, size_num, bold, italic, underline, strike, color, outline, shadow, object_id_text, start_num, char_num)

Syntax 3

Chart items including unattached chart text

FORMAT.FONT(color, backgd, apply, name_text, size_num, bold, italic, underline, strike, outline, shadow, object_id_text, start_num, char_num)
FORMAT.FONT?(color, backgd, apply, name_text, size_num, bold, italic, underline, strike, outline, shadow, object_id_text, start_num, char_num)

Arguments correspond to check boxes and list box items in the Font tab on the Format Cells dialog box. Arguments that correspond to check boxes are logical values. If an argument is TRUE, Microsoft Excel selects the check box; if FALSE, Microsoft Excel clears the check box. If an argument is omitted, the format is not changed.

Name_text is the name of the font as it appears in the Font tab. For example, Courier is a font name.

Size_num is the font size, in points.

Bold corresponds to the Bold item in the Font Style list box. Makes the selection bold, if applicable.

Italic corresponds to the Italicitem in the Font Style list box. Makes the selection italic, if applicable.

Underline corresponds to the Underline check box.

Strike corresponds to the Strikethrough check box.

Color is a number from 0 to 56 corresponding to the colors in the Font tab; 0 corresponds to automatic color.

Outline corresponds to the Outline check box. Outline fonts are available in Microsoft Excel for the Macintosh. For macro compatibility, this argument is ignored by Microsoft Excel for Windows.

Shadow corresponds to the Shadow check box. Shadow fonts are available in Microsoft Excel for the Macintosh. For macro compatibility, this argument is ignored by Microsoft Excel for Windows.

Note For macro compatibility with Microsoft Excel for the Macintosh, the presence of the outline and shadow arguments do not prevent the macro from working on Microsoft Excel for Windows, nor does their absence prevent it from working on the Macintosh.

Object_id_text identifies the text box you want to format (for example, "Text 1", "Text 2", and so on). You can also use the object number alone without the text identifier. For compatibility with earlier versions of Microsoft Excel. This argument is ignored in Microsoft Excel 5.0 or later.

Start_num specifies the first character to be formatted. If start_num is omitted, it is assumed to be 1 (the first character in the text box).

Char_num specifies how many characters to format. If char_num is omitted, Microsoft Excel formats all characters in the text box starting at start_num.

Backgd is a number from 1 to 3 specifying which type of background to apply to text in a chart.

Backgd Type of background applied

1 Automatic

2 Transparent

3 Opaque

Apply corresponds to the Apply To All check box. This argument applies to data labels only.

Remarks

Some extended TrueType styles do not have corresponding arguments to FORMAT.FONT. To access an extended TrueType font style, append the style name to the font name in name_text. For example, the font Taipei can be formatted in an upside-down style by specifying "Taipei Upside-down" as the name_text argument. For more information about TrueType, see your Microsoft Windows documentation.

Related Functions

ALIGNMENT Aligns or wraps text in cells

FONT.PROPERTIES Sets various font attributes

FORMAT.NUMBER Applies a number format to the selection

FORMAT.TEXT Formats a worksheet text box or a chart text item

List of Command-Equivalent Functions


FORMAT.TEXT

Macro Sheets Only

Equivalent to choosing the Object command from the Format menu, and then choosing the Alignment tab, when a text box or button is selected, or when a chart is made active. Formats the selected worksheet text box or button or any text item on a chart.

Syntax

FORMAT.TEXT(x_align, y_align, orient_num, auto_text, auto_size, show_key, show_value, add_indent)

FORMAT.TEXT?(x_align, y_align, orient_num, auto_text, auto_size, show_key, show_value, add_indent)

Arguments correspond to check boxes or options in the various tabs on Format Object dialog box. Arguments that correspond to check boxes are logical values. If an argument is TRUE, Microsoft Excel selects the check box; if FALSE, Microsoft Excel clears the check box; if omitted, the current setting is used.

X_align is a number from 1 to 4 specifying the horizontal alignment of the text.

X_align Horizontal alignment

1 Left

2 Center

3 Right

4 Justify

Y_align is a number from 1 to 4 specifying the vertical alignment of the text.

Y_align Vertical alignment

1 Top

2 Center

3 Bottom

4 Justify

Orient_num is a number from 0 to 3 specifying the orientation of the text.

Orient_num Text orientation

0 Horizontal

1 Vertical

2 Upward

3 Downward

Auto_text corresponds to the Automatic Text check box. If the selected text was created with the Data Labels command from the Insert menu and later edited, this option restores the original text. Auto_text is ignored for text boxes on worksheets and macro sheets.

Auto_size corresponds to the Automatic Size check box. If you have changed the size of the border around the selected text, this option restores the border to automatic size. Automatic size makes the border fit exactly around the text no matter how you change the text.

Show_key corresponds to the Show Legend Key Next to Label check box in the Data Labels dialog box. This argument applies only if the selected text is an attached data label on a chart.

Show_value corresponds to the Show Value option button in the Format Data Labels dialog box. This argument applies only if the selected text is an attached data label on a chart.

The following list summarizes which arguments apply to each type of text item.

Add_indent This argument is for only Far East versions of Microsoft Excel.

Text item Arguments that apply

Worksheet text box or button X_align, y_align, orient_num, auto_size

Attached data label All arguments

Unattached text label X_align, y_align, orient_num, auto_size

Tickmark label Orient_num

Related Functions

CREATE.OBJECT Creates an object

FONT.PROPERTIES Applies a font to the selection

FORMULA Enters values into a cell or range or onto a chart

List of Command-Equivalent Functions


CHART.TREND

Equivalent to choosing Trendline from the Insert menu when a chart is active. A trendline can be added to only to the these chart types: bar, column, stacked column, scatter, line, and area.

Syntax

CHART.TREND(type, ord_per, forecast, backcast, intercept, equation, r_squared, name)

Type is the type of trend or regression.

Number Type used

1 Linear

2 Logarithmic

3 Polynomial

4 Power

5 Exponential

6 Moving Average

Ord_per depends on type. If type is 3, then ord_per is the order of the polynomial. If type is 6, ord_per is the number of periods for the moving average. If type is neither 3 nor 6, then ord_per is ignored.

Forecast is the number of periods or units to extrapolate the trendline in the positive or forward direction. This argument is igonored for moving averages (type 6). The default is zero.

Backcast is a number specifying the number of periods or units to extrapolate the trendline in the negative or backward direction. This argument is ignored for moving averages (type 6). The default is zero.

Intercept is a number specifying the value of the the y-intercept of the trendline, if it is already known. If FALSE or omitted, Microsoft Excel will calculate the y-intercept . This argument is ignored for moving averages.

Equation is a logical value specifying whether the trend equation should be displayed on the chart. If TRUE, the equation will be displayed on the chart. If FALSE or omitted, the equation will not be displayed on the chart.

R_squared is a logical value specifying whether the r-squared equation should be displayed on the chart. If TRUE, the value will be displayed on the chart. If FALSE or omitted, the equation will not be displayed on the chart.

Name is a text string specifying the custom name of the trendline. Can also be a logical value. If TRUE or omitted, the automatic name will be used instead.

Remarks

  • A trendline can not be added to a 3-D chart, a stacked chart, or an 100% chart.
  • the linear model calculates the least squares fit for a line represented by the equation y = mx + b, where m is the sope and b is the intercept.
  • The logarithmic model calculates the least squares fit through points using the equation y = c*ln(x) + b, where c and b are constants.
  • The exponential model calculates the least squares fit through points using the following equation:

where c and b are constants.

  • The polynomial model calculates the least squares fit through points using the following equation:

where b, c1, c2, c3, etc. are constants.

  • The power model calculates the least squares fit through points using the following equation:

where b and c are constants.

Related Functions

CHART.WIZARD Equivalent to choosing the ChartWizard button on the standard or chart toolbar

List of Command-Equivalent Functions


FULL.SCREEN

Equivalent to choosing the Full Screen command from the View menu.

Syntax

FULL.SCREEN(logical)

Logical switches to fullscreen if TRUE or omitted; exits fullscreen mode if FALSE.

Related Functions

List of Command-Equivalent Functions


GET.CELL

Macro Sheets Only

Returns information about the formatting, location, or contents of a cell. Use GET.CELL in a macro whose behavior is determined by the status of a particular cell.

Syntax

GET.CELL(type_num, reference)

Type_num is a number that specifies what type of cell information you want. The following list shows the possible values of type_num and the corresponding results.

Type_num Returns

1 Absolute reference of the upper-left cell in reference, as text in the current workspace reference style.

2 Row number of the top cell in reference.

3 Column number of the leftmost cell in reference.

4 Same as TYPE(reference).

5 Contents of reference.

6 Formula in reference, as text, in either A1 or R1C1 style depending on the workspace setting.

7 Number format of the cell, as text (for example, "m/d/yy" or "General").

8 Number indicating the cell's horizontal alignment:
1 = General
2 = Left
3 = Center
4 = Right
5 = Fill
6 = Justify
7 = Center across cells

9 Number indicating the left-border style assigned to the cell:
0 = No border
1 = Thin line
2 = Medium line
3 = Dashed line
4 = Dotted line
5 = Thick line
6 = Double line
7 = Hairline

10 Number indicating the right-border style assigned to the cell. See type_num 9 for descriptions of the numbers returned.

11 Number indicating the top-border style assigned to the cell. See type_num 9 for descriptions of the numbers returned.

12 Number indicating the bottom-border style assigned to the cell. See type_num 9 for descriptions of the numbers returned.

13 Number from 0 to 18, indicating the pattern of the selected cell as displayed in the Patterns tab of the Format Cells dialog box, which appears when you choose the Cells command from the Format menu. If no pattern is selected, returns 0.

14 If the cell is locked, returns TRUE; otherwise, returns FALSE.

15 If the cell's formula is hidden, returns TRUE; otherwise, returns FALSE.

16 A two-item horizontal array containing the width of the active cell and a logical value indicating whether the cell's width is set to change as the standard width changes (TRUE) or is a custom width (FALSE).

17 Row height of cell, in points.

18 Name of font, as text.

19 Size of font, in points.

20 If all the characters in the cell, or only the first character, are bold, returns TRUE; otherwise, returns FALSE.

21 If all the characters in the cell, or only the first character, are italic, returns TRUE; otherwise, returns FALSE.

22 If all the characters in the cell, or only the first character, are underlined, returns TRUE; otherwise, returns FALSE.

23 If all the characters in the cell, or only the first character, are struck through, returns TRUE; otherwise, returns FALSE.

24 Font color of the first character in the cell, as a number in the range 1 to 56. If font color is automatic, returns 0.

25 If all the characters in the cell, or only the first character, are outlined, returns TRUE; otherwise, returns FALSE. Outline font format is not supported by Microsoft Excel for Windows.

26 If all the characters in the cell, or only the first character, are shadowed, returns TRUE; otherwise, returns FALSE. Shadow font format is not supported by Microsoft Excel for Windows.

27 Number indicating whether a manual page break occurs at the cell:
0 = No break
1 = Row
2 = Column
3 = Both row and column

28 Row level (outline).

29 Column level (outline).

30 If the row containing the active cell is a summary row, returns TRUE; otherwise, returns FALSE.

31 If the column containing the active cell is a summary column, returns TRUE; otherwise, returns FALSE.

32 Name of the workbook and sheet containing the cell If the window contains only a single sheet that has the same name as the workbook without its extension, returns only the name of the book, in the form BOOK1.XLS. Otherwise, returns the name of the sheet in the form "[Book1]Sheet1".

33 If the cell is formatted to wrap, returns TRUE; otherwise, returns FALSE.

34 Left-border color as a number in the range 1 to 56. If color is automatic, returns 0.

35 Right-border color as a number in the range 1 to 56. If color is automatic, returns 0.

36 Top-border color as a number in the range 1 to 56. If color is automatic, returns 0.

37 Bottom-border color as a number in the range 1 to 56. If color is automatic, returns 0.

38 Shade foreground color as a number in the range 1 to 56. If color is automatic, returns 0.

39 Shade background color as a number in the range 1 to 56. If color is automatic, returns 0.

40 Style of the cell, as text.

41 Returns the formula in the active cell without translating it (useful for international macro sheets).

42 The horizontal distance, measured in points, from the left edge of the active window to the left edge of the cell. May be a negative number if the window is scrolled beyond the cell.

43 The vertical distance, measured in points, from the top edge of the active window to the top edge of the cell. May be a negative number if the window is scrolled beyond the cell.

44 The horizontal distance, measured in points, from the left edge of the active window to the right edge of the cell. May be a negative number if the window is scrolled beyond the cell.

45 The vertical distance, measured in points, from the top edge of the active window to the bottom edge of the cell. May be a negative number if the window is scrolled beyond the cell.

46 If the cell contains a text note, returns TRUE; otherwise, returns FALSE.

47 If the cell contains a sound note, returns TRUE; otherwise, returns FALSE.

48 If the cells contains a formula, returns TRUE; if a constant, returns FALSE.

49 If the cell is part of an array, returns TRUE; otherwise, returns FALSE.

50 Number indicating the cell's vertical alignment:
1 = Top
2 = Center
3 = Bottom
4 = Justified

51 Number indicating the cell's vertical orientation:
0 = Horizontal
1 = Vertical
2 = Upward
3 = Downward

52 The cell prefix (or text alignment) character, or empty text ("") if the cell does not contain one.

53 Contents of the cell as it is currently displayed, as text, including any additional numbers or symbols resulting from the cell's formatting.

54 Returns the name of the PivotTable view containing the active cell.

55 Returns the position of a cell within the PivotTable View.

0 = row header
1 = Column header
2 = page header
3 = data header
4 = row item
5 = column item
6 = page item
7 = data item
8 = table body

56 Returns the name of the field containing the active cell reference if inside a PivotTable view.

57 Returns TRUE if all the characters in the cell, or only the first character, are formatted with a superscript font; otherwise, returns FALSE.

58 Returns the font style as text of all the characters in the cell, or only the first character as displayed in the Font tab of the Format Cells dialog box: for example, "Bold Italic".

59 Returns the number for the underline style:

1 = none
2 = single
3 = double
4 = single accounting
5 = double accounting

60 Returns TRUE if all the characters in the cell, or only the first characrter, are formatted with a subscript font; otherwise, it returns FALSE.

61 Returns the name of the PivotTable item for the active cell, as text.

62 Returns the name of the workbook and the current sheet in the form "[book1]sheet1".

63 Returns the fill (background) color of the cell.

64 Returns the pattern (foreground) color of the cell.

65 Returns TRUE if the Add Indent alignment option is on (Far East versions of Microsoft Excel only); otherwise, it returns FALSE.

66 Returns the book name of the workbook containing the cell in the form BOOK1.XLS.

Reference is a cell or a range of cells from which you want information.

  • If reference is a range of cells, the cell in the upper-left corner of the first range in reference is used.
  • If reference is omitted, the active cell is assumed.

Tip Use GET.CELL(17) to determine the height of a cell and GET.CELL(44) - GET.CELL(42) to determine the width.

Examples

The following macro formula returns TRUE if cell B4 on sheet Sheet1 is bold:

GET.CELL(20, Sheet1!$B$4)

You can use the information returned by GET.CELL to initiate an action. The following macro formula runs a custom function named BoldCell if the GET.CELL formula returns FALSE:

IF(GET.CELL(20, Sheet1!$B$4), , BoldCell())

Related Functions

ABSREF Returns the absolute reference of a range of cells to another range

ACTIVE.CELL Returns the reference of the active cell

GET.FORMULA Returns the contents of a cell

GET.NAME Returns the definition of a name

GET.NOTE Returns characters from a note

RELREF Returns a relative reference

List of Information Functions


GET.DOCUMENT

Macro Sheets Only

Returns information about a sheet in a workbook.

Syntax

GET.DOCUMENT(type_num, name_text)

Type_num is a number that specifies what type of information you want. The following lists show the possible values of type_num and the corresponding results.

Type_num Returns

1 Returns the name of the workbook and worksheet as text. If there is only one sheet in the workbook and the sheet name is the same as the workbook name less any extension, returns the name of the book. The book name does not include the drive, directory or folder, or window number. Otherwise, returns the book and sheet name in the form "[BOOK1.XLS]Sheet1". It is usually best to use GET.DOCUMENT(76) and GET.DOCUMENT(88) to return the name of the active worksheet and the active workbook.

2 Path of the directory or folder containing name_text, as text. If the workbook name_text hasn't been saved yet, returns the #N/A error value.

3 Number indicating the type of sheet. If name_text is a sheet, then the return value is one of the following numbers. If name_text is a book, then the return value is always 5. If name_text is omitted, then the sheet type is returned. If the book has one sheet that is named the same as the book, then the sheet type is returned.
1 = Worksheet
2 = Chart
3 = Macro sheet
4 = Info window if active
5 = Reserved
6 = Module
7 = Dialog

4 If changes have been made to the sheet since it was last saved, returns TRUE; otherwise, returns FALSE.

5 If the sheet is read-only, returns TRUE; otherwise, returns FALSE.

6 If the sheet is password protected, returns TRUE; otherwise, returns FALSE.

7 If cells in a sheet, the contents of a sheet, or the series in a chart are protected, returns TRUE; otherwise, returns FALSE.

8 If the workbook windows are protected, returns TRUE; otherwise, returns FALSE.

The next four values of type_num apply only to charts.

Type_num Returns

9 Number indicating the type of the main chart:
1 = Area
2 = Bar
3 = Column
4 = Line
5 = Pie
6 = XY (scatter)
7 = 3-D area
8 = 3-D column
9 = 3-D line
10 = 3-D pie
11 = Radar
12 = 3-D bar
13 = 3-D surface
14 = Donut

10 Number indicating the type of the overlay chart. Same as 1, 2, 3, 4, 5, 6, 11, and 14 for main chart above. If there is no overlay chart, returns the #N/A error value.

11 Number of series in the main chart.

12 Number of series in the overlay chart.

The next values of type_num apply to worksheets and macro sheets and to charts when appropriate.

Type_num Returns

9 Number of the first used row. If the document is empty, returns 0.

10 Number of the last used row. If the document is empty, returns 0.

11 Number of the first used column. If the document is empty, returns 0.

12 Number of the last used column. If the document is empty, returns 0.

13 Number of windows.

14 Number indicating calculation mode:
1 = Automatic
2 = Automatic except tables
3 = Manual

15 If the Iteration check box is selected in the Calculation tab of the Options dialog box, returns TRUE; otherwise, returns FALSE.

16 Maximum number of iterations.

17 Maximum change between iterations.

18 If the Update Remote References check box is selected in the Calculation tab of the Options dialog box, returns TRUE; otherwise, returns FALSE.

19 If the Precision As Displayed check box is selected in the Calculation tab of the Options dialog box, returns TRUE; otherwise, returns FALSE.

20 If the 1904 Date System check box is selected in the Calculation tab of the Options dialog box, returns TRUE; otherwise, returns FALSE.

Type_num values of 21 through 29 correspond to the four default fonts in previous versions of Microsoft Excel. These values are provided only for macro compatibility.

The next values of type_num apply to worksheets and macro sheets, and to charts if indicated.

Type_num Returns

30 Horizontal array of consolidation references for the current sheet, in the form of text. If the list is empty, returns the #N/A error value.

31 Number from 1 to 11, indicating the function used in the current consolidation. The function that corresponds to each number is listed under the CONSOLIDATE function. The default function is SUM.

32 Three-item horizontal array indicating the status of the check boxes in the Data Consolidate dialog box. An item is TRUE if the check box is selected or FALSE if the check box is cleared. The first item indicates the Top Row check box, the second the Left Column check box, and the third the Create Links To Source Data check box.

33 If the Recalculate Before Saving check box is selected in the Calculation tab of the Options dialog box, returns TRUE; otherwise, returns FALSE.

34 If the workbook is read-only recommended, returns TRUE; otherwise, returns FALSE.

35 If the workbook is write-reserved, returns TRUE; otherwise, returns FALSE.

36 If the document has a write-reservation password and it is opened with read/write permission, returns the name of the user who originally saved the file with the write-reservation password. If the file is opened as read-only, or if a password has not been added to the document, returns the name of the current user.

37 Number corresponding to the file type of the document as displayed in the Save As dialog box. See the SAVE.AS function for a list of all the file types that Microsoft Excel recognizes.

38 If the Summary Rows Below Detail check box is selected in the Outline dialog box, returns TRUE; otherwise, returns FALSE.

39 If the Summary Columns To Right Of Detail check box is selected in the Outline dialog box, returns TRUE; otherwise, returns FALSE.

40 If the Create Backup File check box is selected in the Save As dialog box, returns TRUE; otherwise, returns FALSE.

41 Number from 1 to 3 indicating whether objects are displayed:
1 = All objects are displayed
2 = Placeholders for pictures and charts
3 = All objects are hidden

42 Horizontal array of all objects in the sheet. If there are no objects, returns the #N/A error value.

43 If the Save External Link Values check box is selected in the Calculation tab of the Options dialog box, returns TRUE; otherwise, returns FALSE.

44 If objects in a document are protected, returns TRUE; otherwise, returns FALSE.

45 A number from 0 to 3 indicating how windows are synchronized:
0 = Not synchronized
1 = Synchronized horizontally
2 = Synchronized vertically
3 = Synchronized horizontally and vertically

46 A seven-item horizontal array of print settings that can be set by the LINE.PRINT macro function:

- Setup text

- Left margin

- Right margin

- Top margin

- Bottom margin

- Page length

- A logical value indicating whether output will be formatted (TRUE) or unformatted (FALSE) when printed

47 If the Transition Expression Evaluation check box is selected in the Transition tab of the Options dialog box, returns TRUE; otherwise, returns FALSE.

48 The standard column width setting.

The next values of type_num correspond to printing and page settings.

Type_num Returns

49 The starting page number, or the #N/A error value if none is specified or if "Auto" is entered in the First page Number text box on the Page tab of the Page Setup dialog box.

50 The total number of pages that would be printed based on current settings, excluding notes, or 1 if the document is a chart.

51 The total number of pages that would be printed if you print only notes, or the #N/A error value if the document is a chart.

52 Four-item horizontal array indicating the margin settings (left, right, top, bottom) in the currently specified units.

53 A number indicating the orientation:
1 = Portrait
2 = Landscape

54 The header as a text string, including formatting codes.

55 The footer as a text string, including formatting codes.

56 Horizontal array of two logical values corresponding to horizontal and vertical centering.

57 If row or column headings are to be printed, returns TRUE; otherwise, returns FALSE.

58 If gridlines are to be printed, returns TRUE; otherwise, returns FALSE.

59 If the sheet is printed in black and white only, returns TRUE; otherwise, returns FALSE.

60 A number from 1 to 3 indicating how the chart will be sized when it's printed:
1 = Size on screen
2 = Scale to fit page
3 = Use full page

61 A number indicating the pagination order:
1 = Down, then Over
2 = Over, then Down
Returns the #N/A error value if the document is a chart.

62 Percentage of reduction or enlargement, or 100% if none is specified. Returns the #N/A error value if not supported by the current printer or if the document is a chart.

63 A two-item horizontal array indicating the number of pages to which the printout should be scaled to fit, with the first item equal to the width (or #N/A if no width scaling is specified) and the second item equal to the height (or #N/A if no height scaling is specified). #N/A is also returned if the document is a chart.

64 An array of row numbers corresponding to rows that are immediately below a manual or automatic page break.

65 An array of column numbers corresponding to columns that are immediately to the right of a manual or automatic page break.

Note GET.DOCUMENT(62) and GET.DOCUMENT(63) are mutually exclusive. If one returns a value, then the other returns the #N/A error value.

The next values of type_num correspond to various document settings.

Type_num Returns

66 In Microsoft Excel for Windows, if the Transition Formula Entry check box is selected in the Transition tab of the Options dialog box, returns TRUE; otherwise, returns FALSE.

67 Microsoft Excel 5.0 or later always returns TRUE here.

68 Microsoft Excel 5.0 or later always returns the book name.

69 Returns TRUE if Automatic Page Breaks is chosen in the View tab of the Options dialog box; otherwise, returns FALSE.

70 Returns the names of all PivotTables in the current sheet as a horizontal array.

71 Returns an horizontal array of all the styles in a document.

72 Returns an horizontal array of all chart types displayed on the current sheet.

73 Returns an array of the number of series in each chart of the current sheet.

74 Returns the object id of the control that currently has the focus on a running user-defined dialog (based on the dialog sheet).

75 Returns the object id of the object that is the current default button on a running user-defined dialog (based on the dialog sheet).

76 Returns the name of the active sheet or macro sheet in the form [Book1]Sheet1.

77 In Microsoft Excel for Windows, returns the paper size, as integer:

1 = Letter 8.5 x 11 in

2 = Letter Small 8.5 x 11 in
5 = Legal 8.5 x 14 in
9 = A4 210 x 297 mm
10 = A4 Small 210 x 297 mm
13 = B5 182 x 257 mm
18 = Note 8.5 x 11 in

78 Returns the print resolution, as a horizontal array of two numbers.

79 Returns TRUE if the Draft Quality check box has been selected from the sheet tab in the Page Setup dialog box; otherwise, returns FALSE.

80 Returns TRUE if the Notes checkbox has been selected on the Sheet tab in the Page Setup dialog box; otherwise, returns FALSE.

81 Returns the print area from the Sheet tab of the Page Setup dialog box as a cell reference.

82 Returns the print titles from the Sheet tab of the Page Setup dialog box as an array of cell references.

83 Returns TRUE if the worksheet is protected for scenarios; otherwise, returns FALSE.

84 Returns the value of the first circular reference on the sheet, or #N/A if there are no circular references.

85 Returns the advanced filter mode state of the sheet. This is the mode without drop-down arrows on top. Returns TRUE if the list has been filtered by choosing Filter, then Advanced Filter from the Data menu. Otherwise, returns FALSE.

86 Returns the automatic filter mode state of the sheet. This is the mode with drop-down arrows on top. Returns TRUE if you have chosen Filter, then AutoFilter from the Data menu and the filter drop-down arrows are displayed. Otherwise, returns FALSE.

87 Returns the position number of the sheet. The first sheet is position 1. Hidden sheet are included in the count.

88 Returns the name of the active workbook in the form "Book1".

Name_text is the name of an open document. If name_text is omitted, it is assumed to be the active document.

Examples

The following macro formula returns TRUE if the contents of the active document are protected:

GET.DOCUMENT(7)

In Microsoft Excel for Windows, the following macro formula returns the number of windows in SALES.XLS:

GET.DOCUMENT(13, "SALES.XLS")

In Microsoft Excel for the Macintosh, the following macro formula returns 3 if the overlay chart on SALES CHART is a column chart:

GET.DOCUMENT(10, "SALES CHART")

To find out if SHEET1 is password-protected and if its contents and windows are protected, enter the following formula in a three-cell horizontal array:

GET.DOCUMENT({6, 7, 8}, "SHEET1")

Related Functions

GET.CELL Returns information about the specified cell

GET.WINDOW Returns information about a window

GET.WORKSPACE Returns information about the workspace

List of Information Functions


GET.PIVOT.FIELD

Macro Sheets Only

Returns information about a field in a PivotTable.

Syntax

GET.PIVOT.FIELD(type_num, pivot_field_name, pivot_table_name)

Type_num is a value from 1 to 17 that returns the following types of information:

Type_num Value

1 Returns an array of all the items which make up pivot_field_name. The array is made up of text constants, dates or numbers depending on the field.

2 Returns an array of all items which are set to show with the pivot_field_name. The array is made up of text constants, dates or numbers depending on the field. The array is returned in the order that the items are displayed in the PivotTable. If pivot_field_name is a page field, then the array contains only one element, the value corresponding to the active page (this could be all if the All item is showing).

3 Returns an array of all items which are hidden in the pivot_field_name. The array is made up of text constants, dates or numbers depending on the field. If pivot_field_name is a data field or the data header name, this function returns the #N/A! error value.

4 Returns an integer describing where the field is displayed in the active PivotTable (either row or column):
0 = Hidden
1 = Row
2 = Col
3 = Page
4 = Data

5 Returns an array of all items in pivot_field_name that are group parents. The array is made up of text constants, dates or numbers depending on the field. The array is returned in the order which these items appear in the PivotTable. Returns #N/A if there are no group parents and if the Pivot_field_name is a data field or the data field header.

6 Returns a number between 0 and 4095 which describes the subtotals attached to the field. The number is the sum of the values associated with each subtotal function. See PIVOT.FIELD.PROPERTIES for a list of all the values associated with subtotal calculations. If the field is showing as a data field or data field header, #N/A! is returned.

7 Returns an integer describing the type of data contained in the field:
0 = Text
1 = Number
2 = Date

8 Returns an array five columns wide and one row high describing the summary function's custom calculation shown with the specified field (Data field) in the PivotTable. The array will look as follows: {function, calculation, base Field, base item, number format}. If pivot_field_name is not showing in the active PivotTable as a data field, #N/A! is returned.

9 Returns a reference to all of pivot_field_name's items currently showing in the active PivotTable. If pivot_field_name is hidden, #N/A! is returned. If pivot_field_name is a page field, the reference to the currently showing page item is returned. If pivot_field_name is a data field, a reference to all the data for this field in the PivotTable body is returned. The references are returned as text.

10 Returns a reference to the header cell for pivot_field_name. If pivot_field_name is a data field, a reference to all the headers in the data row or column is returned. If pivot_field_name is hidden, #N/A! is returned. The reference is returned as text.

11 Returns the number of grouped fields in the grouped field set which includes pivot_field_name. If pivot_field_name is neither a parent field nor a child field, 1 is returned. If pivot_field_name is a data field or data header name, the function returns the #N/A! error value.

12 Returns the level of pivot_field_name in the grouped field set which includes pivot_field_name. Returns 1 for the highest level parent field, 2 for its child field, and so on. If pivot_field_name is neither a parent field nor a child field, 1 is returned. If pivot_field_name is a data field or data header name, the function returns the #N/A! error value.

13 Returns the name of the parent field for pivot_field_name as a text constant. If pivot_field_name is not a child field, #N/A! is returned.

14 Returns the name of the child field for pivot_field_name as a text constant. If pivot_field_name is not a parent field, #N/A! is returned.

15 Returns a text constant representing the original name of the field in the data source.

16 Returns the position of the field among all the other fields in its orientation. For instance, a 1 would be returned if the field was the first row field.

17 Returns an array of all items in pivot_field_name that are group children. The array is made up of text constants, dates or numbers depending on the field. The array is returned in the order which these items appear in the PivotTable. Returns #N/A if there are no group children, and if the Pivot_field_name is a data field or the data field header.

Pivot_field_name is the name of the field that you want information about. If there is no field named Pivot_field_name in the PivotTable, returns #VALUE!.

Pivot_table_name is the name of a PivotTablecontaining the field that you want information about. If omitted, the PivotTable containing the active cell is used. If the active cell is not in a PivotTable, the #VALUE! error value is returned.

Related Functions

GET.PIVOT.ITEM Returns information about an item in a PivotTable.

GET.PIVOT.TABLE Returns information about a PivotTable.

List of Information Functions


GET.PIVOT.ITEM

Macro Sheets Only

Returns information about an item in a PivotTable.

Syntax

GET.PIVOT.ITEM(type_num, pivot_item_name, pivot_field_name, pivot_table_name)

Type_num is a value from 1 to 9 the represents the type of information you want about an item in a PivotTable.

Type_num Information

1 Returns the position of the item in its field. Returns #N/A if pivot_field_name is a data field. Returns #N/A! if the item is hidden.

2 Returns the reference to all the cells in the PivotTable header currently containing pivot_item_name. This reference is returned as text. If pivot_item_name is currently not showing in the PivotTable, #N/A! is returned.

3 Returns the reference to all the data in the PivotTable body which is qualified by pivot_item_name. This reference is returned as text. If pivot_item_name is currently not showing in the PivotTable, #N/A! is returned.

4 Returns an array of text constants representing the children of pivot_item_name if pivot_item_name is a parent. Otherwise the function returns #N/A!.

5 Returns a text constant representing the parent of pivot_item_name, if pivot_item_name exists as part of a group. Otherwise the function returns #N/A!.

6 Returns TRUE if pivot_item_name is a member of a group which is currently expanded to show detail. Returns FALSE if pivot_item_name is a member of a group currently collapsed to hide detail. If item_name is not a member of a group, the function returns #N/A!.

7 Returns TRUE if pivot_item_name is expanded to show detail. Returns FALSE if pivot_item_name is collapsed to hide detail.

8 Returns TRUE if the item pivot_item_name is currently visible, FALSE if it is hidden.

9 Returns the name of the item as it appeared in the original ata source. This will differ from the current item name only if the user changes the name of the item after creating the PivotTable.

Pivot_item_name is the name of the item that you want information about. If there is no item named pivot_item_name in the PivotTable, returns #VALUE!.

Pivot_field_name is the name of the field that you want information about. If there is no field named pivot_field_name in the PivotTable, returns #VALUE!.

Pivot_table_name is the name of a PivotTable containing the field that you want information about. If omitted, uses the PivotTable containing the active cell. If the active cell is not in a PivotTable, the #VALUE! error value is returned.

Related Functions

GET.PIVOT.FIELD Returns information about an item in a PivotTable.

GET.PIVOT.TABLE Returns information about a PivotTable.

List of Information Functions


GET.PIVOT.TABLE

Macro Sheets Only

Returns information about a PivotTable.

Syntax

GET.PIVOT.TABLE(type_num,pivot_table_name)

Type_num is a value from 1 to 22 that represents a type of information you want about a PivotTable.

Type_num Information

1 Returns the name of the person who last updated the PivotTable, as a text constant.

2 Returns the date the PivotTablewas last updated, as a serial number.

3 Returns a horizontal array of text constants representing all the fields in the PivotTable.

4 Returns an integer representing the number of fields in the PivotTable.

5 Returns a horizontal array of text constants representing all the visible fields in the PivotTable(rows, columns, pages or data)

6 Returns a horizontal array of text constants representing all the hidden fields in the PivotTable. Return #N/A if no hidden fields.

7 Returns a horizontal arra of text constants representing the names of all the fields currently showing in the PivotTable as row fields. Returns #N/A if there are no row fields.

8 Returns a horizontal array of text constants representing all the fields currently showing in the PivotTable as column fields. Returns #N/A if no column fields exist.

9 Returns a horizontal arra of text constants representing all the fields currently showing in the PivotTable as page fields. Return #N/A if no page fields exist.

10 Returns a horizontal array of text constants representing all the fields currently showing in the PivotTable as data fields. Returns #N/A if there are no data fields.

11 Returns the smallest rectangular reference which bounds the PivotTable and all headers (not including the page header). This reference is returned as text.

12 Returns the smallest rectangular reference which bounds the PivotTable and all headers (including the page headers). This reference is returned as text.

13 Returns the reference to the row header area as text. The row header area includes each row field header along with all the items in each row field. Returns #N/A if there are no row headers.

14 Returns the reference to the column header area as text. The column header area includes each column field header along with all the items in each column field. Returns #N/A if there are no column headers.

15 Returns the reference to the data header area as text. The data header area includes the data field header along with all the headers in the data row/col. Returns #N/A if there is no data field.

16 Returns a reference to all the page headers as text.

17 Returns the reference to the PivotTable data area as text.

18 Returns TRUE if the PivotTable is set to show row grand totals.

19 Returns TRUE if the PivotTable is set to show column grand totals.

20 Returns TRUE if the user is saving data with the PivotTable.

21 Returns TRUE if the PivotTable is set up to Autoformat on pivoting.

22 Returns the data source of the PivotTable. The kind of information returned depends on the data source:
If the data source is a Microsoft Excel list or database, the cell reference is returned as text.
If the data source is an external data source, then an array is returned. Each row consists of a SQL connection string with the remaining elements as the query string broken down into 200 character segments.
If the data source is Multiple Consolidation ranges, then a two dimensional array is returned, each row of which consists of a reference and associated page field items.
If the data source is another PivotTable, then one of the above three kinds of information is returned.

Pivot_table_name is the name of a PivotTable containing the field that you want information about. If omitted, uses the PivotTable containing the active cell.

Remarks

Returns #VALUE! error value when pivot_table_name is not a valid PivotTable name on the active sheet and the active cell is not within a PivotTable.

Related Functions

GET.PIVOT.FIELD Returns information about an item in a PivotTable.

GET.PIVOT.ITEM Returns information about a PivotTable.

List of Information Functions


GET.WINDOW

Macro Sheets Only

Returns information about a window. Use GET.WINDOW in a macro that requires the status of a window, such as its name, size, position, and display options.

Syntax

GET.WINDOW(type_num, window_text)

Type_num is a number that specifies what type of window information you want. The following list shows the possible values of type_num and the corresponding results:

Type_num Returns

1 Name of the workbook and sheet in the window as text. For compatibility with Microsoft Excel 4.0, if the window contains only a single sheet that has the same name as the workbook without its extension, returns only the name of the book. Otherwise, returns the name of the sheet in the form "[Book1]Sheet1".

2 Number of the window.

3 X position, measured in points from the left edge of the workspace (in Microsoft Excel for Windows) or screen (in Microsoft Excel for the Macintosh) to the left edge of the window.

4 Y position, measured in points from the bottom edge of the formula bar to the top edge of the window.

5 Width, measured in points.

6 Height, measured in points.

7 If window is hidden, returns TRUE; otherwise, returns FALSE.

The rest of the values for type_num apply only to worksheets and macro sheets, except where indicated:

Type_num Returns

8 If formulas are displayed, returns TRUE; otherwise, returns FALSE.

9 If gridlines are displayed, returns TRUE; otherwise, returns FALSE.

10 If row and column headings are displayed, returns TRUE; otherwise, returns FALSE.

11 If zeros are displayed, returns TRUE; otherwise, returns FALSE.

12 Gridline and heading color as a number in the range 1 to 56, corresponding to the colors in the View tab of the Options dialog box; if color is automatic, returns 0.

Values 13 to 16 for type_num return arrays that specify which rows or columns are at the top and left edges of the panes in the window and the widths and heights of those panes.

  • The first number in the array corresponds to the first pane, the second number to the second pane, and so on.
  • If the edge of the pane occurs at the boundary between rows or columns, the number returned is an integer.
  • If the edge of the pane occurs within a row or column, the number returned has a fractional part that represents the fraction of the row or column visible within the pane.
  • The numbers can be used as arguments to the SPLIT function to split a window at specific locations.

Type_num Returns

13 Leftmost column number of each pane, in a horizontal numeric array

14 Top row number of each pane, in a horizontal numeric array.

15 Number of columns in each pane, in a horizontal numeric array.

16 Number of rows in each pane, in a horizontal numeric array.

17 Number indicating the active pane:
1 = Upper, left, or upper-left
2 = Right or upper-right
3 = Lower or lower-left
4 = Lower-right

18 If window has a vertical split, returns TRUE; otherwise, returns FALSE.

19 If window has a horizontal split, returns TRUE; otherwise, returns FALSE.

20 If window is maximized, returns TRUE; otherwise, returns FALSE.

21 Reserved

22 If the Outline Symbols check box is selected in the View tab of the Options dialog box, returns TRUE; otherwise, returns FALSE.

23 Number indicating the size of the window (including charts):
1 = Restored
2 = Minimized (displayed as an icon)
3 = Maximized

24 If panes are frozen on the active window, returns TRUE; otherwise, returns FALSE.

25 The numeric magnification of the active window (as a percentage of normal size) as set in the Zoom dialog box, or 100 if none is specified.

26 Returns TRUE if horizontal scrollbars are displayed in the active window; otherwise, returns FALSE.

27 Returns TRUE if vertical scrollbars are displayed in the active window; otherwise, returns FALSE.

28 Returns the tab ratio of workbook tabs to horizontal scrollbar, from 0 to 1. The default is .6.

29 Returns TRUE if workbook tabs are displayed in the active window; otherwise, returns FALSE.

30 Returns the title of the active sheet in the window in the form "[book1]sheet1".

31 Returns the name of a workbook only, without read/write indicated. For example, if Book1.xls is read only, then "Book.xls" will be returned without "[Read Only]" appended.

Window_text is the name that appears in the title bar of the window that you want information about. If window_text is omitted, it is assumed to be the active window.

Examples

If the active window contains the workbook Book1, then:

GET.WINDOW(1) equals "Book1"

If the title of the active window is Macro1:3, then:

GET.WINDOW(2) equals 3

In Microsoft Excel for Windows, the following macro formula returns the gridline and heading color of REPORT.XLS:

GET.WINDOW(12, "REPORT.XLS")

In Microsoft Excel for the Macintosh, the following macro formula returns the gridline and heading color of REPORT MASTER:

GET.WINDOW(12, "REPORT MASTER")

Related Functions

GET.DOCUMENT Returns information about a document

GET.WORKSPACE Returns information about the workspace

List of Information Functions


GET.WORKBOOK

Macro Sheets Only

Returns information about a workbook.

Syntax

GET.WORKBOOK(type_num, name_text)

Type_num is a number that specifies what type of workbook information you want.

Type_num Returns

1 The names of all sheets in the workbook, as a horizontal array of text values. Names are returned as [book]sheet.

2 This will always return the #N/A error value.

3 The names of the currently selected sheets in the workbook, as a horizontal array of text values.

4 The number of sheets in the workbook.

5 TRUE if the workbook has a routing slip; otherwise, FALSE.

6 The names of all of the document routing recipients who have not received the document, as a horizontal array of text values.

7 The subject line for the current routing slip, as text.

8 The message text for the routing slip, as text.

9 If the document is to be routed to recipients one after another, returns 1. If it is to be routed all at once, returns 2.

10 TRUE, if the Return When Done check box in the Routing Slip dialog box is selected; otherwise, FALSE.

11 TRUE, if the current recipient has already forwarded the current document; otherwise, FALSE.

12 TRUE, if the Track Status checkbox in the Routing Slip dialog box is selected; otherwise, FALSE.

13 Status of the workbook routing slip:
0 = unrouted
1 = routing in progress, or the workbook has been routed to a user
2 = routing is finished

14 TRUE, if the workbook structure is protected; otherwise, FALSE.

15 TRUE, if the workbook windows are protected; otherwise, FALSE.

16 Name of the workbook as text. The workbook name does not include the drive, directory or folder, or window number.This is the equivalent of GET.DOCUMENT(1).

17 TRUE if the document is read only; otherwise, FALSE. This is the equivalent of GET.DOCUMENT(34).

18 TRUE if sheet is write-reserved; otherwise, FALSE. This is the equivalent of GET.DOCUMENT(35).

19 Name of the user with current write permission for the document. This is the equivalent of GET.DOCUMENT(36).

20 Number corresponding to the file type of the document as displayed in the Save As dialog box. This is the equivalent of GET.DOCUMENT(37).

21 TRUE if the Create Backup File check box is selected in the Save As dialog box; otherwise, FALSE. This is the equivalent of GET.DOCUMENT(40).

22 TRUE if the Save External Link Values check box is selected in the Calculation tab of the Options dialog box. This is the equivalent of GET.DOCUMENT(43).

23 TRUE if the workbook has a PowerTalk mailer; otherwise, FALSE. Returns #N/A if no OCE mailer is installed.

24 TRUE if changes have been made to the workbook since the last time it was saved; FALSE if book is unchanged (or when closed, will not prompt to be saved).

25 The recipients on the To line of a PowerTalk mailer, as a horizontal array of text.

26 The recipients on the Cc line of a PowerTalk mailer, as a horizontal array of text.

27 The recipients on the Bcc line of a PowerTalk mailer, as a horizontal array of text.

28 The subject of the PowerTalk mailer, as text.

29 The enclosures of the PowerTalk mailer, as a horizontal array of text.

30 TRUE, if the PowerTalk mailer has been received from another user (as opposed to just being added but not sent). FALSE, if the mailer has not been received from another user.

31 The date and time the PowerTalk mailer was sent, as a serial number. Returns the #N/A error value if the mailer has not yet been sent.

32 The sender name of the PowerTalk mailer, as text. Returns the #N/A error value if the mailer has not yet been sent.

33 The title of the document as displayed in the Summary Info dialog box, as text.

34 The subject of the document as displayed in the Summary Info dialog box, as text.

35 The author of the document as displayed in the Summary Info dialog box, as text.

36 The keywords for the document as displayed in the Summary Info dialog box, as text.

37 The comments for the document as displayed in the Summary Info dialog box, as text.

38 The name of the active sheet.

Name_text is the name of an open workbook. If name_text is omitted, it is assumed to be the active workbook.

Example

The following macro formula returns the name of the active sheet in the workbook named SALES.XLS:

GET.WORKBOOK(38, "SALES.XLS")

Related Functions

GET.DOCUMENT Returns information about a document

WORKBOOK.SELECT Selects the specified documents in a workbook

List of Information Functions


GET.WORKSPACE

Macro Sheets Only

Returns information about the workspace. Use GET.WORKSPACE in a macro that depends on the status of the workspace, such as the environment, version number, and available memory.

Syntax

GET.WORKSPACE(type_num)

Type_num is a number specifying the type of workspace information you want. The following list shows the type_num values and their corresponding results.

Type_num Returns

1 Name of the environment in which Microsoft Excel is running, as text, followed by the environment's version number.

2 The version number of Microsoft Excel, as text (for example, "5.0").

3 If fixed decimals are set, returns the number of decimals; otherwise, returns 0.

4 If in R1C1 mode, returns TRUE; if in A1 mode, returns FALSE.

5 If scroll bars are displayed, returns TRUE; otherwise, returns FALSE. See also GET.WINDOW(26) and GET.WINDOW(27).

6 If the status bar is displayed, returns TRUE; otherwise, returns FALSE.

7 If the formula bar is displayed, returns TRUE; otherwise, returns FALSE.

8 If remote DDE requests are enabled, returns TRUE; otherwise, returns FALSE.

9 Returns the alternate menu key as text; if no alternate menu key is set, returns the #N/A error value.

10 Number indicating special modes:
1 = Data Find
2 = Copy
3 = Cut
4 = Data Entry
5 = Unused
6 = Copy and Data Entry
7 = Cut and Data Entry
If no special mode is set, returns 0.

11 X position of the Microsoft Excel workspace window, measured in points from the left edge of the screen to the left edge of the window. In Microsoft Excel for the Macintosh, always returns 0.

12 Y position of the Microsoft Excel workspace window, measured in points from the top edge of the screen to the top edge of the window. In Microsoft Excel for the Macintosh, always returns 0.

13 Usable workspace width, in points.

14 Usable workspace height, in points.

15 Number indicating maximized or minimized status of Microsoft Excel:
1 = Neither
2 = Minimized
3 = Maximized
Microsoft Excel for the Macintosh always returns 3.

16 Amount of memory free (in kilobytes).

17 Total memory available to Microsoft Excel (in kilobytes).

18 If a math coprocessor is present, returns TRUE; otherwise, returns FALSE.

19 If a mouse is present, returns TRUE; otherwise, returns FALSE. In Microsoft Excel for the Macintosh, always returns TRUE.

20 If a group is present in the workspace, returns a horizontal array of sheets in the group; otherwise returns the #N/A error value.

21 If the Standard toolbar is displayed, returns TRUE; otherwise, returns FALSE.

22 DDE-application-specific error code.

23 Full path of the default startup directory or folder.

24 Full path of the alternate startup directory or folder; returns the #N/A error value if no alternate path has been specified.

25 If Microsoft Excel is set for relative recording, returns TRUE; if set for absolute recording, returns FALSE.

26 Name of user.

27 Name of organization.

28 If Microsoft Excel menus are switched to by the transition menu or help key, returns 1; if Lotus 1-2-3 Help is switched to, returns 2.

29 If transition navigation keys are enabled, returns TRUE.

30 A nine-item horizontal array of global (default) print settings that can be set by the LINE.PRINT function:
- Setup text
- Left margin
- Right margin
- Top margin
- Bottom margin
- Page length
- Logical value indicating whether to wait after printing each page
- (TRUE) or use continuous form feeding (FALSE)
- Logical value indicating whether the printer has automatic line
- feeding (TRUE) or requires line feed characters (FALSE)
- The number of the printer port

31 If a currently running macro is in single step mode, returns TRUE; otherwise, returns FALSE.

32 The current location of Microsoft Excel as a complete path.

33 A horizontal array of the names in the New list, in the order they appear.

34 A horizontal array of template files (with complete paths) in the New list, in the order they appear (returns the names of custom template files and the #N/A error value for built-in document types).

35 If a macro is paused, returns TRUE; FALSE otherwise.

36 If the Allow Cell Drag And Drop check box is selected in the Edit tab of the Options dialog box that appears when you choose the Options command from the Tools menu, returns TRUE; otherwise, returns FALSE.

37 A 45-item horizontal array of the items related to country versions and settings. Use the following macro formula to return a specific item, where number is a number in the list below:

INDEX(GET.WORKSPACE(37), number)

These values apply to country codes:

1 Number corresponding to the country version of Microsoft Excel.
2 Number corresponding to the current country setting in the
Microsoft Windows Control Panel or the country number as
determined by your Apple system software

These values apply to number separators:

3 Decimal separator
4 Zero (or 1000) separator
5 List separator

These values apply to R1C1-style references:

6 Row character
7 Column character
8 Lowercase row character
9 Lowercase column character
10 Character used instead of the left bracket ([)
11 Character used instead of the right bracket (])

These values apply to array characters:

12 Character used instead of the left bracket ({)
13 Character used instead of the right bracket (})
14 Column separator
15 Row separator
16 Alternate array item separator to use if the current array separator is the same as the decimal separator

These values apply to format code symbols:

17 Date separator
18 Time separator
19 Year symbol
20 Month symbol
21 Day symbol
22 Hour symbol
23 Minute symbol
24 Second symbol
25 Currency symbol
26 "General" symbol

These values apply to format codes:

27 Number of decimal digits to use in currency formats
28 Number indicating the current format for negative currencies
0 = ($currency) or (currency$)
1 = -$currency or -currency$
2 = $-currency or currency-$
3 = $currency- or currency$-
where currency is any number and the $ represents the current currency symbol.

29 Number of decimal digits to use in noncurrency number formats
30 Number of characters to use in month names
31 Number of characters to use in weekday names
32 Number indicating the date order
0 = Month-Day-Year
1 = Day-Month-Year
2 = Year-Month-Day

These values apply to logical format values:

33 TRUE if using 24-hour time; FALSE if using 12-hour time.
34 TRUE if not displaying functions in English; otherwise, returns FALSE.
35 TRUE if using the metric system; FALSE if using the English measurement system.
36 TRUE if a space is added before the currency symbol; otherwise, returns FALSE.
37 TRUE if currency symbol precedes currency values; FALSE if it follows currency values.
38 TRUE if using minus sign for negative numbers; FALSE if using parentheses.
39 TRUE if trailing zeros are displayed for zero currency values; otherwise, returns FALSE.
40 TRUE if leading zeros are displayed for zero currency values; otherwise, returns FALSE.
41 TRUE if leading zero is displayed in months (when months are displayed as numbers); otherwise, returns FALSE.
42 TRUE if leading zero is shown in days (when days are displayed as numbers); otherwise, returns FALSE.
43 TRUE if using four-digit years; FALSE if using two-digit years.
44 TRUE if date order is month-day-year when displaying dates in long form; FALSE if date order is day-month-year.
45 TRUE if leading zero is shown in the time; otherwise, returns FALSE.

38 The number 0, 1, or 2 indicating the type of error-checking as set by the ERROR function. For more information, see ERROR.

39 A reference to the currently defined error-handling macro (set by the ERROR function), or the #N/A error value if none is specified.

40 If screen updating is turned on (set by the ECHO function), returns TRUE; otherwise, returns FALSE.

41 A horizontal array of cell ranges, as R1C1-style text, that were previously selected with the Goto command from the Edit menu or the FORMULA.GOTO macro function. If the book has multiple sheets, or if the single sheet in the workbook is named differently than the workbook itself, returns names as [book]sheet.

42 If your computer is capable of playing sounds, returns TRUE; otherwise, returns FALSE.

43 If your computer is capable of recording sounds, returns TRUE; otherwise, returns FALSE.

44 A three-column array of all currently registered procedures in dynamic link libraries (DLLs). The first column contains the names of the DLLs that contain the procedures (in Microsoft Excel for Windows) or the names of the files that contain the code resources (in Microsoft Excel for the Macintosh). The second column contains the names of the procedures in the DLLs (in Microsoft Excel for Windows) or code resources (in Microsoft Excel for the Macintosh). The third column contains text strings specifying the data types of the return values, and the number and data types of the arguments. For more information about DLLs and code resources and data types, see the "Using the CALL and REGISTER Functions" in the Appendix for the Microsoft Excel Worksheet Function Reference.

45 If Microsoft Windows for Pen Computing is running, returns TRUE; otherwise, returns FALSE.

46 If the Move Selection After Enter check box is selected in the Edit tab of the Options dialog box, returns TRUE; otherwise, returns FALSE.

47 Reserved.

48 Path to the library subdirectory for Microsoft Excel, as text.

49 MAPI session currently in use, returned as a string of hex digits encoding the mail session value.

50 If the Full Screen mode is on, returns TRUE; otherwise, FALSE.

51 If the the formula bar is displayed in Full Screen mode, returns TRUE; otherwise, FALSE.

52 If the status bar is displayed in Full Screen mode, returns TRUE; otherwise, FALSE.

53 The name of the topmost custom dialog sheet currently running in a modal window, or #N/A if no dialog sheet is currently running.

54 If the Edit Directly In Cell check box is selected on the Edit tab in the Options dialog box, returns TRUE; otherwise, returns FALSE.

55 TRUE if the Alert Before Overwriting Cells check box in the Edit tab on Options dialog box is selected; otherwise, FALSE.

56 Standard font name in the General tab in the Options dialog box, as text.

57 Standard font size in the General tab in the Options dialog box, as a number

58 If the Recently Used File list check box in the General tab on the Options dialog box is selected, returns TRUE; otherwise, FALSE.

59 If the Display Old Menus check box in the General tab on the Options dialog box is selected, returns TRUE; otherwise, FALSE.

60 If the Tip Wizard is enabled, returns TRUE; otherwise, FALSE.

61 Number of custom list entries listed in the Custom Lists tab of the Options dialog box.

62 Returns information about available file converters.

63 Returns the type of mail system in use by Excel:
0 = no mail transport detected
1 = MAPI based transport
2 = PowerTalk based transport (Macintosh only)

64 If the Ask to Update Automatic Links check box in the Edit tab of the Options dialog box is selected, returns TRUE; otherwise, FALSE.

65 If the Cut, Copy, and Sort Objects with Cells check box in the Edit tab on the Options dialog box is selected, returns TRUE; otherwise, FALSE.

66 Default number of sheets in a new workbook, as a number, from the General tab on Options dialog box.

67 Default file directory location, as text, from the General tab in the Options dialog box.

68 If the Show ToolTips check box on the Toolbars dialog box is selected, returns TRUE; otherwise, FALSE.

69 If the Large Buttons check box in the Toolbars dialog box is selected, returns TRUE; otherwise, FALSE.

70 If the Prompt for Summary Info check box in the General tab on the Options dialog box is selected, returns TRUE; otherwise, FALSE.

71 TRUE if Microsoft Excel is open for in-place object editing (OLE). If FALSE, it is opened normally.

72 TRUE if the Color Toolbars check box is selected in the Toolbars dialog box. FALSE if the Color Toolbars check box is not selected.

Related Functions

GET.DOCUMENT Returns information about a document

GET.WINDOW Returns information about a window

List of Information Functions


INSERT.PICTURE

Macro Sheets Only

Equivalent to choosing the Picture command from the Insert menu. This function is available for Microsoft Excel for Windows only .

Syntax

INSERT.PICTURE(file_name, filter_number)
INSERT.PICTURE?(file_name, filter_number)

File_name is the name, as text, of the file containing the picture that you want to insert into your workbook.

Filter_number is a number specifying which converter Microsoft Excel will use to open the file.

Convert_type Converter and filename extension

1 Windows Bitmaps (bmp)

2 Windows Metafile (wmf)

3 DrawPerfect (wpg)

4 Micrografix Designer/Draw (drw)

5 AutoCAD Format 2-D (dxf)

6 HP Graphics Language (hgl)

7 Computer Graphics Metafile (cgm)

8 Encapsulated Postscript (eps)

9 Tagged Image Format (tif)

10 PC PaintBrush (pcx)

11 Lotus 1-2-3 Graphic (pic)

12 AutoCAD Plot Files (plt)

13 Macintosh PICT (pct)

Related Functions

List of Information Functions


MAIL.ADD.MAILER

Macro Sheets Only

Equivalent to choosing the Add Mailer command from the Mail submenu on the File menu. Adds a new PowerTalk mailer to the active document. Use this command to add addressing or subject information to a document that you want to send to another user.

Note This function is available on Macintosh computers with Microsoft Excel and Apple PowerTalk only.

Syntax

MAIL.ADD.MAILER( )

Remarks

If there is already a mailer, this command fails and returns the #VALUE! error value.

Related Functions

MAIL.DELETE.MAILER Deletes an existing mailer from the active document

List of Command-Equivalent Functions


MAIL.DELETE.MAILER

Macro Sheets Only

Equivalent to choosing the Delete Mailer command from the Mail submenu on the File menu. Deletes an existing mailer from the active document.

Note This function is available on Macintosh computers with Microsoft Excel and Apple PowerTalk only.

Syntax

MAIL.DELETE.MAILER( )

Remarks

If there is no mailer, returns the #VALUE! error value.

Related Functions

MAIL.ADD.MAILER Adds a new PowerTalk mailer to the active document

List of Command-Equivalent Functions


MAIL.EDIT.MAILER

Macro Sheets Only

Equivalent to choosing the Mailer button when mailer is attached to the current document. Allows you to edit a PowerTalk mailer attached to the active document

Note This function is available on Macintosh computers with Microsoft Excel and Apple PowerTalk only.

Syntax

MAIL.EDIT.MAILER(to_recipients, cc_recipients, bcc_recipients, subject, enclosures, which_address)
MAIL.EDIT.MAILER?(to_recipients, cc_recipients, bcc_recipients, subject, enclosures, which_address)

To_recipients is the name of the person to whom you want to send the mail. The name should be given as text. To specify more than one name, give the list of names as an array.

Cc_recipients is the name of those recipients to be carbon copied. A single name should be given as text. To specify more than one name, give the list of names as an array.

Bcc_recipients is the name of the recipients to be added as blind carbon copies.

Subject is a text string containing the subject text for the mail messages.

Enclosures is an array of strings specifying enclosures as file names.

Which_address indicates which type of address to use, as a text string, specifying the address type for all recipients. For example, "Fax".

Remarks

If there is no mailer, returns the #VALUE! error value.

Related Functions

MAIL.DELETE.MAILER Adds a new PowerTalk mailer to the active document

MAIL.ADD.MAILER Adds a new PowerTalk mailer to the active document

List of Command-Equivalent Functions


MAIL.FORWARD

Macro Sheets Only

Equivalent to choosing the Forward command from the Mail submenu on the File menu. Creates a new mailer to replace the previous version and brings up the mailer dialog.

Note This function is available on Macintosh computers with Microsoft Excel and Apple PowerTalk only.

Syntax

MAIL.FORWARD( )

Remarks

  • Returns the #VALUE! error value or #N/A if the current document has no mailer.
  • This function is available only when the current document is open and has been received by PowerTalk with a piece of mail to forward.

Related Functions

MAIL.EDIT.MAILER Allows you to edit a PowerTalk mailer attached to the active document

MAIL.DELETE.MAILER Deletes a new PowerTalk mailer to the active document

MAIL.ADD.MAILER Adds a new PowerTalk mailer to the active document

List of Command-Equivalent Functions


MAIL.NEXT.LETTER

Macro Sheets Only

Equivalent to choosing the Next Letter command from the Mail submenu on the File menu. Opens the oldest unread Microsoft Excel document from the In Tray as a new window.

Note This function is available on Macintosh computers with Microsoft Excel and Apple PowerTalk only.

Syntax

MAIL.NEXT.LETTER( )

Remarks

Returns #VALUE! on error, and #N/A if there are no more letters in the In Tray to open.

Related Functions

MAIL.EDIT.MAILER Allows you to edit a PowerTalk mailer attached to the active document

MAIL.DELETE.MAILER Adds a new PowerTalk mailer to the active document

MAIL.ADD.MAILER Adds a new PowerTalk mailer to the active document

List of Command-Equivalent Functions


MAIL.REPLY

Macro Sheets Only

Equivalent to choosing the Reply command from the Mail submenu on the File menu. Replies to the sender of the current letter.

Note This function is available on Macintosh computers with Microsoft Excel and Apple PowerTalk only.

Syntax

MAIL.REPLY( )

Remarks

  • Returns the #VALUE! error value or #N/A if the current document has no mailer.
  • The letter must currently be open.

Related Functions

MAIL.EDIT.MAILER Allows you to edit a PowerTalk mailer attached to the active document

MAIL.DELETE.MAILER Deletes a new PowerTalk mailer to the active document

MAIL.ADD.MAILER Adds a new PowerTalk mailer to the active document

List of Command-Equivalent Functions


MAIL.REPLY.ALL

Macro Sheets Only

Equivalent to choosing the Reply All command from the Mail submenu on the File menu. Replies to the sender and all recipients of the current letter.

Note This function is available on Macintosh computers with Microsoft Excel and Apple PowerTalk only.

Syntax

MAIL.REPLY.ALL( )

Remarks

Returns the #VALUE! error value or #N/A if the current document has no mailer.

Related Functions

MAIL.EDIT.MAILER Allows you to edit a PowerTalk mailer attached to the active document

MAIL.DELETE.MAILER Deletes a new PowerTalk mailer to the active document

MAIL.ADD.MAILER Adds a new PowerTalk mailer to the active document

List of Command-Equivalent Functions


MAIL.ADD.MAILER

Macro Sheets Only

Equivalent to choosing the Send Mailer command from the Mail submenu on the File menu. Sends a PowerTalk mailer.

Note This function is available on Macintosh computers with Microsoft Excel and Apple PowerTalk only.

Syntax

MAIL.ADD.MAILER( )

Related Functions

List of Command-Equivalent Functions


OPEN.LINKS

Macro Sheets Only

Equivalent to choosing the Links command from the Edit menu. Use OPEN.LINKS with the LINKS function to open workbooks linked to a particular sheet.

Syntax

OPEN.LINKS(document_text1, document_text2, ..., read_only, type_of_link)
OPEN.LINKS?(document_text1, document_text2, ..., read_only, type_of_link)

Document_text1, document_text2, are 1 to 12 arguments that are the names of supporting documents in the form of text, or arrays or references that contain text.

Read_only is a logical value corresponding to the read/write status of the linked worksheet. If read_only is TRUE, the sheet can be modified but changes cannot be saved; if FALSE or omitted, changes to the sheet can be saved. Read_only applies only to Microsoft Excel, WKS, and SYLK documents.

Type_of_link is a number from 1 to 6 that specifies what type of link you want to get information about.

Type_of_link Link document type

1 Microsoft Excel link

2 DDE link

3 Reserved

4 Not applicable

5 Subscriber

6 Publisher

Remarks

You can generate an array of the names of linked workbooks with the LINKS function.

Related Functions

CHANGE.LINK Changes supporting workbook links

GET.LINK.INFO Returns information about a link

LINKS Returns the name of all linked workbooks

UPDATE.LINK Updates a link to another document

List of Command-Equivalent Functions


OPTIONS.CALCULATION

Macro Sheets Only

Equivalent to choosing the Options command from the Tools menu, and selecting the Calculation tab in the Options dialog box. Sets various worksheet calculation settings.

Syntax

OPTIONS.CALCULATION(type_num, iter, max_num, max_change, update, precision, date_1904, calc_save, save_values)
OPTIONS.CALCULATION?(type_num, iter, max_num, max_change, update, precision, date_1904, calc_save, save_values)

Arguments correspond to check boxes and options in the Calculation tab in the Options dialog box. Arguments that correspond to check boxes are logical values. If an argument is TRUE, Microsoft Excel selects the check box; if FALSE, Microsoft Excel clears the check box.

Type_num is a number from 1 to 3 indicating the type of calculation.

Type_num Type of calculation

1 Automatic

2 Automatic except tables

3 Manual

Iter corresponds to the Iteration check box. The default is FALSE.

Max_num is the maximum number of iterations. The default is 100.

Max_change is the maximum change of each iteration. The default is 0.001.

Update corresponds to the Update Remote References check box. The default is TRUE.

Precision corresponds to the Precision As Displayed check box. The default is FALSE.

Date_1904 corresponds to the 1904 Date System check box. The default is FALSE in Microsoft Excel for Windows and TRUE in Microsoft Excel for the Macintosh.

Calc_save corresponds to the Recalculate Before Save check box. If calc_save is FALSE, the workbook is not recalculated before saving when in manual calculation mode. The default is TRUE.

Save_values corresponds to the Save External Link Values check box. The default is TRUE.

Note Microsoft Excel for Windows and Microsoft Excel for the Macintosh use different date systems as their default. For more information, see NOW.

Related Functions

List of Command-Equivalent Functions


OPTIONS.CHART

Macro Sheets Only

Equivalent to choosing the Options command from the Tools menu and then selecting the Chart Tab in the Options dialog box when a chart is activated for editing. Sets various chart settings.

Syntax

OPTIONS.CHART(Display_Blanks, Plot_Visible, Size_With_Window)
OPTIONS.CHART?( Display_Blanks, Plot_Visible, Size_With_Window)

Display_Blanks is a number indicating how blank cells are plotted.

Number Blanks are displayed as

1 Not plotted (gaps are shown)

2 Zero values

3 interpolated

Plot_Visible is a logical value that if TRUE plots only visible data. If FALSE, all cells in the selection are plotted.

Size_With_Window is a logical value that if TRUE allows the chart to resize with window. If FALSE, chart will not size with window.

Remarks

If any of the arguments are omitted, then that setting is unchanged within the Options dialog box.

Related Functions

PREFERRED Changes the format of the active chart

SET.PREFERRED Changes the default chart format

List of Command-Equivalent Functions


OPTIONS.EDIT

Macro Sheets Only

Equivalent to choosing the Options command from the tools menu and then selecting the Edit tab in the Options dialog box. Sets various worksheet editing options.

Syntax

OPTIONS.EDIT(incell_edit, drag_drop, alert, entermove, fixed, decimals, copy_objects, update_links, move_direction, autocomplete, animations)
OPTIONS.EDIT?(incell_edit, drag_drop, alert, entermove, fixed, decimals, copy_objects, update_links, move_direction, autocomplete, animations)

Incell_edit is a logical value corresponding to the Edit Directly In Cell check box, which if TRUE allows In Cell Editing. If FALSE, editing directly in cells is not allowed. If omitted, the dialog box setting is not changed.

Drag_drop is a logical value corresponding to the Allow Cell Drag And Drop check box, which if TRUE allows drag and dropping on sheets. If FALSE, drag and drop is not allowed. If omitted, the dialog box setting is not changed.

Alert is a logical value corresponding to the Alert Before Overwriting Cells check box, which if TRUE displays an alert message warning you that cells containing values are about to be overwritten. If FALSE, an alert will not be displayed if your cells are about to overwritten. If omitted, the dialog box setting is not changed.

Entermove is a logical value corresponding to the Move Selection After Enter check box, which if TRUE moves the selection after the ENTER key is pressed. If FALSE, the selection is not moved. If omitted, the dialog box setting is not changed.

Fixed is a logical value corresponding to the Fixed Decimal check box, which if TRUE fixes the decimal place according to decimals. If FALSE, the decimal places are not fixed. If omitted, the dialog box setting is not changed.

Decimals is a number specifing the number of decimal places. Decimals is ignored if fixed is FALSE or omitted.

Copy_objects is a logical value corresponding to the Cut, Copy, and Sort objects with Cells check box. If TRUE allows objects to be cut, copied and sorted with their cells. If FALSE, objects are not cut, copied or sorted with cells. If omitted, the dialog box setting is not changed.

Update_links is a logical value corresponding to the Ask to Update Automatic Links check box, which if TRUE will prompt the user when the workbook is opened that has links to other documents. If FALSE, the prompt will not be displayed. If omitted, the dialog box setting is not changed.

Move_direction is a number specifying the direction to move the selection when the ENTER key is pressed and Entermove is TRUE. Setting this number to 1 moves down one cell, 2 moves right one cell, 3 moves up on cell, and 4 moves down one cell..

Autocomplete is a logical value corresponding to the Enable Autocomplete for Cell Values check box, which if TRUE will enable the AutoComplete feature of Microsoft Excel for Windows '95.

Animations is a logical value corresponding to the Animate Insertion and Deletion check box, which if TRUE will enable the worksheet Animations feature of Microsoft Excel for Windows '95. Deleted worksheet rows and columns will slowly disappear, and inserted worksheet rows and columns will slowly appear.

Related Functions

OPTIONS.GENERAL Sets various general Microsoft Excel settings

List of Command-Equivalent Functions


OPTIONS.GENERAL

Macro Sheets Only

Equivalent to choosing the Options command from the Tools menu and then selecting the General tab from the Options dialog box. Sets various general Microsoft Excel settings.

Syntax

OPTIONS.GENERAL(R1C1_mode, dde_on, sum_info, tips, recent_files, old_menus, user_info, font_name, font_size, default_location, alternate_location, sheet_num, enable_under)
OPTIONS.GENERAL?(R1C1_mode, dde_on, sum_info, tips, recent_files, old_menus, user_info, font_name, font_size, default_location, alternate_location, sheet_num, enable_under)

Arguments correspond to option buttons, check boxes and text boxes in the General dialog box. Arguments corresponding to check boxes are logical values. If an argument is TRUE, the check box is selected; if FALSE, the check box is cleared; if omitted, the current setting is not changed.

R1C1_mode is a number specifying the reference sytle. Use 1 for A1 style references; 2 for R1C1 style references.

Dde_on is a logical value corresponding to the Ignore Other Applications check box, which if TRUE ignores DDE request from other applications. If FALSE, DDE requests from other applications are allowed to happen.

Sum_info is a logical value corresponding to the Prompt for Summary Info check box, which if TRUE displays the summary information dialog box when a workbook is initially saved. If FALSE, the dialog box is not displayed.

Tips is a logical value corresponding to the Reset TipWizard check box, which if TRUE resets the TipWizard. If FALSE, the TipWizard will not be reset.

Recent_files is a logical value corresponding to the Recently Used File List check box, which if TRUE displays the four last opened files from the File menu. If FALSE, the file list will not be displayed.

Old_menus is a logical value corresponding to the Microsoft Excel 4.0 Menus check box, which if TRUE replaces the current menu bar with the Microsoft Excel 4.0 menu bar. If FALSE, the menu bar will not be replaced.

User_info corresponds to the Name text box, and is the name of the user of this copy of Microsoft Excel. By default it is the registered user, but can be changed to work on a network.

Font_name corresponds to the Standard Font text box, and is the name of the default font.

Font_size corresponds to the Size drop-down edit box, and is the size of the default font.

Default_location corresponds to the Default File Location text box, and is the default location that the File Open command displays. The Default is where Microsoft Excel is installed.

Alternate_location corresponds to the Alternate Startup File Location text box, and is the alternate startup directory.

Sheet_num corresponds to the Sheets in New Workbook spin control, and is the number of sheets in a new workbook. Default is 16. Can go up to 255.

Enable_under enables underlining of the menus. Used for only Microsoft Excel for the Macintosh. Ignored in Microsoft Excel for Windows.

Related Functions

OPTIONS.LISTS.DELETE Deletes a custom list

OPTIONS.LISTS.GET Returns contents of custom AutoFill lists

OPTIONS.VIEW Sets various view settings

List of Command-Equivalent Functions


OPTIONS.LISTS.ADD

Macro Sheets Only

This is the equivalent to choosing the Options command from the Tools menu and then selecting the Custom Lists tab in the Options dialog box. Used to add a new custom list.

Syntax

OPTIONS.LISTS.ADD(string_array)
OPTIONS.LISTS.ADD(import_ref, by_row)
OPTIONS.LISTS.ADD?(import_ref, list_num)

String_array is an array of strings or cell reference that contains the custom items in the list, a named cell reference, or an external reference containing the items of the custom list to add.

Import_ref is the reference to the cells that contain the members of the custom list. If A1:A12 contains the twelve signs of the Zodiac starting with Aquarius, then this function will add the contents of these twelve cells as a custom list.

By_row is a logical value that if TRUE, and if importing from cells, assumes that the list items are in sequential rows. If FALSE, assumes that the list items are in columns. If omitted, Microsoft Excel will try to determine the order of the custom lists according to the layout of the sheet.

List_num is a number specifying which list to activate. If omitted, then New List will be activated.

Remarks

  • To replace an existing custom list, you must first delete it and then add the new list to the end.
  • If the list already exists, then this function will do nothing. The list is not case sensitive, so "Scorpio" and "scorpio" are treated the same in custom lists.

Related Functions

OPTIONS.VIEW Sets various view settings

OPTIONS.LISTS.GET Returns contents of custom AutoFill lists

OPTIONS.LISTS.DELETE Deletes a custom list

List of Command-Equivalent Functions


OPTIONS.LISTS.DELETE

Macro Sheets Only

Equivalent to choosing the Options command from the Tools menu and then selecting the Delete button on the Custom Lists tab when a custom list is selected.

Syntax

OPTIONS.LISTS.DELETE(list_num)

List_num is the number of the custom list to delete. The first five lists (numbered zero through 4) cannot be deleted. If list_num doesn't exist, then FALSE is returned.

Related Functions

OPTIONS.LISTS.GET Returns contents of custom AutoFill lists

OPTIONS.LISTS.ADD Used to add a new custom list

List of Command-Equivalent Functions


OPTIONS.LISTS.GET

Macro Sheets Only

Returns contents of custom AutoFill lists as an array of text strings.

Syntax

OPTIONS.LISTS.GET(list_num)
OPTIONS.LISTS.GET(string_array)

List_num is a number specifying which list to return, as a horizontal string array. If list_num is zero, then FALSE is returned.

String_array is an array or cell reference to store the returned list.

Example

OPTIONS.LIST.GET(3) returns the twelve months of the year in the form {"Jan", "Feb", "Mar"}

Remarks

If list_num is zero or omitted, then FALSE is returned.

Related Functions

OPTIONS.LISTS.ADD Adds a new custom list

OPTIONS.LISTS.DELETE Deletes a custom list

OPTIONS.VIEW Sets various view settings

List of Information Functions


OPTIONS.TRANSITION

Macro Sheets Only

Equivalent to choosing the Options command from the Tools menu and then selecting the Transition tab in the Options dialog box. Sets options relating to compatibility with other spreadsheets.

Syntax

OPTIONS.TRANSITION(menu_key, menu_key_action, nav_keys, trans_eval, trans_entry )
OPTIONS.TRANSITION?(menu_key, menu_key_action, nav_keys, trans_eval, trans_entry )

Menu_key is text specifying which alternate menu key to use.

Menu_key_action is the number 1 or 2 specifying options for the alternate menu or Help key. In Microsoft Excel for the Macintosh, menu_key_action is ignored.

Menu_key_action Alternate menu or Help key activates

1 or omitted Microsoft Excel menus

2 Lotus 1-2-3 Help

Nav_keys is a logical value that corresponds to the Transition Navigation Keys check box, which if TRUE uses alternate navigation keys that correspond to the navigation keys for Lotus 1-2-3. In Microsoft Excel for the Macintosh, nav_keys is ignored.

Trans_eval is a logical value that corresponds to the Transition Formula Evaluation check box.

  • If trans_eval is TRUE, Microsoft Excel uses a set of rules compatible with that of Lotus 1-2-3 when calculating formulas. Text is treated as 0. TRUE and FALSE are treated as 1 and 0. Certain characters in database criteria ranges are interpreted the same way Lotus 1-2-3 interprets them.
  • If trans_eval is FALSE or omitted, Microsoft Excel calculates normally.
  • Trans_entry is a logical value that corresponds to the Transition Formula Entry check box.
  • This argument is available only in Microsoft Excel for Windows.
  • If trans_entry is TRUE, Microsoft Excel accepts formulas entered in
    Lotus 1-2-3 style.
  • If trans_entry is FALSE or omitted, Microsoft Excel only accepts formulas entered in Microsoft Excel style.

Related Functions

OPTIONS.LISTS.DELETE Deletes a custom list

OPTIONS.LISTS.GET Returns contents of custom AutoFill lists

OPTIONS.VIEW Sets various view settings

List of Command-Equivalent Functions


OPTIONS.VIEW

Macro Sheets Only

Equivalent to choosing the Options command from the Tools menu and then selecting the View tab in the Options dialog box. Sets various view settings.

Syntax

OPTIONS.VIEW(formula, status, notes, show_info, object_num, page_breaks, formulas, gridlines, color_num, headers, outline, zeros, hor_scroll, vert_scroll, sheet_tabs)
OPTIONS.VIEW?(formula, status, notes, show_info, object_num, page_breaks, formulas, gridlines, color_num, headers, outline, zeros, hor_scroll, vert_scroll, sheet_tabs)

Arguments correspond to check boxes and text boxes in the view tab on the options dialog box. Arguments corresponding to check boxes are logical values. If an argument is TRUE, the check box is selected; if FALSE, the check box is cleared; if omitted, the current setting is not changed.

Formula is a logical value corresponding to the Formula Bar check box. If TRUE, displays the formula bar. If FALSE, the formula bar is not displayed.

Status is a logical value corresponding to the Status Bar check box. If TRUE, the status bar is displayed. If FALSE, the status bar is not displayed.

Notes is a logical value corresponding to the Note Indicator check box. If TRUE, note indicators will be be displayed. If FALSE, note indicators will not be displayed.

Show_info is a logical value corresponding to the Info Window check box. If TRUE, displays the Info Window.

Object_num is a number from 1 to 3 corresponding to the display options in the Objects box.

Object_num Corresponds to

1 or omitted Show All

2 Show Placeholders

3 Hide

Page_breaks is a logical value corresponding to the Automatic Page Breaks check box.If TRUE, automatic page breaks will appear. If FALSE, automatic page breaks will not appear.

Formulas is a logical value corresponding to the Formulas check box. If TRUE, formulas will appear in the cells. If FALSE, formulas will not appear in the cells. The default is FALSE on worksheets and TRUE on macro sheets.

displayed. If FALSE, gridlines will not appear. The default is TRUE.

Color_num is a number from 0 to 56 corresponding to the gridline and heading. Zero corresponds to automatic color and is the default value.

Headings is a logical value corresponding to the Row & Column Headers check box. If TRUE, row and column headers will be displayed. If FALSE, they will not be displayed. The default is TRUE.

Outline is a logical value corresponding to the Outline Symbols check box. If TRUE, outline symbols will appear. If FALSE, they will not appear. The default is TRUE.

Zeros is a logical value corresponding to the Zero Values check box. If TRUE, zero values will appear, If FALSE, zero values will not appear. The default is TRUE.

Hor_scroll is a logical value corresponding to the Horizontal Scroll Bar checkbox. If TRUE, the horizontal scroll bar will be displayed. If FALSE, it will not be displayed. The default is TRUE.

Vert_scroll is a logical value corresponding to the Vertical Scroll Bar checkbox. If TRUE, the vertical scroll bar will be displayed. If FALSE, it will not be displayed. The default is TRUE.

Sheet_tabs is a logical value corresponding to the Sheet Tabs check box. If TRUE, sheet tabs will be displayed. If FALSE, sheet tabs will not be displayed. The default is TRUE.

Related Functions

OPTIONS.LISTS.GET Returns contents of custom AutoFill lists

OPTIONS.LISTS.DELETE Deletes a custom list

List of Command-Equivalent Functions


PASTE.LINK

Macro Sheets Only

Equivalent to choosing the Paste Special command from the Edit menu, and then choosing the Paste Link option from the Paste Special dialog box. Pastes copied data or objects and establishes a link to the source of the data or object. The source can be either another Microsoft Excel workbook or another application. Use PASTE.LINK when you want Microsoft Excel to automatically update the paste area with any changes that occur in the source.

Syntax

PASTE.LINK( )

Note To work properly, the application you are linking to must support dynamic data exchange (DDE) or object linking and embedding (OLE).

Related Functions

COPY Copies and pastes data or objects

CUT Cuts or moves data or objects

PASTE Pastes cut or copied data

PASTE.SPECIAL Pastes specific components of copied data

List of Command-Equivalent Functions


PASTE.SPECIAL

Macro Sheets Only

Equivalent to choosing the Paste Special command from the Edit menu. Pastes the specified components from the copy area into the current selection. The PASTE.SPECIAL function has four syntax forms.

Syntax 1 Pasting into a sheet or macro sheet

Syntax 2 Copying from a sheet and pasting into a chart.

Syntax 3 Copying and pasting between charts

Syntax 4 Pasting information from another application.


PASTE.SPECIAL Syntax 1

Macro Sheets Only

Equivalent to choosing the Paste Special command from the Edit menu. Pastes the specified components from the copy area into the current selection. The PASTE.SPECIAL function has four syntax forms. Use syntax 1 if you are pasting into a sheet or macro sheet.

Syntax

PASTE.SPECIAL(paste_num, operation_num, skip_blanks, transpose)
PASTE.SPECIAL?(paste_num, operation_num, skip_blanks, transpose)

Paste_num is a number from 1 to 6 specifying what to paste. Paste_num can also be quoted text of the object you want to paste.

Paste_num Pastes

1 All

2 Formulas

3 Values

4 Formats

5 Notes

6 All Except Borders

Operation_num is a number from 1 to 5 specifying which operation to perform when pasting.

Operation_num Action

1 None

2 Add

3 Subtract

4 Multiply

5 Divide

Skip_blanks is a logical value corresponding to the Skip Blanks check box in the Paste Special dialog box.

  • If skip_blanks is TRUE, Microsoft Excel skips blanks in the copy area when pasting.
  • If skip_blanks is FALSE, Microsoft Excel pastes normally.

Transpose is a logical value corresponding to the Transpose check box in the Paste Special dialog box.

  • If transpose is TRUE, Microsoft Excel transposes rows and columns when pasting.
  • If transpose is FALSE, Microsoft Excel pastes normally.

Related Functions

FORMULA Enters values into a cell or range or onto a chart

PASTE Pastes cut or copied data

PASTE.LINK Pastes copied data and establishes a link to its source

Syntax 2 Copying from a sheet and pasting into a chart.

Syntax 3 Copying and pasting between charts

Syntax 4 Pasting information from another application.

List of Command-Equivalent Functions


PASTE.SPECIAL Syntax 2

Macro Sheets Only

Equivalent to choosing the Paste Special command from the Edit menu on the Chart menu bar. Pastes the specified components from the copy area into a chart. The PASTE.SPECIAL function has four syntax forms. Use syntax 2 if you have copied from a sheet and are pasting into a chart.

Syntax

PASTE.SPECIAL(rowcol, titles, categories, replace, series)
PASTE.SPECIAL?(rowcol, titles, categories, replace, series)

Rowcol is the number 1 or 2 and specifies whether the values corresponding to a particular data series are in rows or columns. Enter 1 for rows or 2 for columns.

Titles is a logical value corresponding to the Series Names In First Column check box (or First Row, depending on the value of rowcol) in the Paste Special dialog box.

  • If series is TRUE, Microsoft Excel selects the check box and uses the contents of the cell in the first column of each row (or first row of each column) as the name of the data series in that row (or column).
  • If series is FALSE, Microsoft Excel clears the check box and uses the contents of the cell in the first column of each row (or first row of each column) as the first data point of the data series.

Categories is a logical value corresponding to the Categories (X Labels) In First Row (or First Column, depending on the value of rowcol) check box in the Paste Special dialog box.

  • If categories is TRUE, Microsoft Excel selects the check box and uses the contents of the first row (or column) of the selection as the categories for the chart.
  • If categories is FALSE, Microsoft Excel clears the check box and uses the contents of the first row (or column) as the first data series in the chart.

Replace is a logical value corresponding to the Replace Existing Categories check box in the Paste Special dialog box.

  • If replace is TRUE, Microsoft Excel selects the check box and applies categories while replacing existing categories with information from the copied cell range.
  • If replace is FALSE, Microsoft Excel clears the check box and applies new categories without replacing any old ones.

Series is a number specifying how cells are added to a chart.

Series Added as

1 New series

2 New point(s)

Related Functions

Syntax 1 Pasting into a sheet or macro sheet

Syntax 3 Copying and pasting between charts

Syntax 4 Pasting information from another application

List of Command-Equivalent Functions


PASTE.SPECIAL Syntax 3

Macro Sheets Only

Equivalent to choosing the Paste Special command from the Edit menu on the Chart menu bar. Pastes the specified components from the copy area into a chart. The PASTE.SPECIAL function has four syntax forms. Use syntax 3 if you have copied from a chart and are pasting into a chart.

Syntax

PASTE.SPECIAL(paste_num)
PASTE.SPECIAL?(paste_num)

Paste_num is a number from 1 to 3 specifying what to paste.

Paste_num Pastes

1 All (formats and data series)

2 Formats only

3 Formulas (data series) only

Related Functions

Syntax 1 Pasting into a sheet or macro sheet

Syntax 2 Copying from a sheet and pasting into a chart

Syntax 4 Pasting information from another application

List of Command-Equivalent Functions


PASTE.SPECIAL Syntax 4

Macro Sheets Only

Equivalent to choosing the Paste Special command from the Edit menu when pasting data from another application into Microsoft Excel. Use syntax 4 when pasting information from another application.

Syntax

PASTE.SPECIAL(format_text, pastelink_logical, display_icon_logical, icon_file, icon_number, icon_label)
PASTE.SPECIAL?(format_text, pastelink_logical, display_icon_logical, icon_file, icon_number, icon_label)

Format_text is text specifying the type of data you want to paste from the Clipboard.

  • The valid data types vary depending on the application from which the data was copied. For example, if you're copying data from Microsoft Word, some of the data types are "Microsoft Document Object", "Picture", and "Text".
  • For more information about object classes, see your Microsoft Windows or Apple system software documentation.

Pastelink_logical is a logical value specifying whether to link the pasted data to its source application.

  • If pastelink_logical is TRUE, Microsoft Excel updates the pasted information whenever it changes in the source application.
  • If pastelink_logical is FALSE or omitted, the information is pasted without a link.
  • If Microsoft Excel or the source application does not support linking for the specified format_text, then pastelink_logical is ignored.
  • Display_icon_logical is a logical value that specifies whether you want an application's icon to be displayed on the worksheet instead of the linked data. Equivalent to the Display as Icon check box on the Paste Special dialog box. If TRUE, the application's icon will be displayed. If FALSE or omitted, the application's icon will not be displayed.
  • Icon_file is the name of the file (with an .EXE or .DLL extension) that contains the icon. If display_icon_logical is FALSE, this argument is ignored.
  • Icon_number is the number associated with the icon and corresponds to the icon's relative position within the Icon Drop Down list box on the Change Icon Dialog box, which appears when you choose the Change Icon button from the Paste Special dialog box. If display_icon_logical is FALSE, this argument is ignored.
  • Icon_label is the caption that you want to appear below the icon, and is equivalent to the Caption text box on the Change Icon dialog box, which appears when you choose the Change Icon button from the Paste Special dialog box. If display_icon_logical is FALSE, this argument is ignored.

Related Functions

Syntax 1 Pasting into a sheet or macro sheet

Syntax 2 Copying from a sheet and pasting into a chart

Syntax 3 Copying and pasting between charts

List of Command-Equivalent Functions


PIVOT.ADD.DATA

Macro Sheets Only

Adds a field to a PivotTable.

Syntax

PIVOT.ADD.DATA(name, pivot_field_name, new_name, position, function, calculation, base_field, base_item, format_text)

Name is the name of the PivotTable to which the user wants to add as a data field. If name is omitted, Microsoft Excel will use the PivotTable containing the active cell.

Pivot_field_name is the name of a field which the user would like to add to his PivotTable as data or as text.

New_name is the name you would like to give to the new field once it is added to your PivotTable. If this argument is omitted, Microsoft Excel will pick a default name for you. This function returns new_name or the name Microsoft Excel chooses for the field.

Position is the position within all the Data fields you would like to place the new data field. If position is omitted, the field will be added as the last data field.

Function is a number from 2 to 2048 specifying how the new field is to be calculated. To compute the value to place in this column choose one value from the following table. If function is omitted, SUM will be used. If the field is a numeric field or text field, COUNTA will be used.

Value Function

2 SUM

4 COUNTA

8 COUNT

16 AVERAGE

32 MAX

64 MIN

128 PRODUCT

256 STDEV

512 STDEVP

1024 VAR

2048 VARP

Calculation is a number between 1 and 9 representing which custom calculation you would like to apply to this data field. This corresponds to the Show Data As drop-down box on the PivotTable Field dialog box. If this argument is omitted, no special calculation will be applied to the data field.

Value Calculation

1 Normal

2 Difference From

3 % Of Item

4 % Difference From

5 Running Total In

6 % of Row

7 % of Column

8 % of Total

9 Index

Base_Field is the field on which you want to base the Calculation.

Base_Item is the item within base_field on which you want to base the Calculation.

Format_text is the type of number format you want to apply to the PivotTable data. Corresponds to the number button in the PivotTable Field dialog box, which appears when you choose the PivotTable Field command from the Data menu when the selection is in a data field.

Remarks

  • If name is not a valid PivotTable name, then the #VALUE! error value is returned.
  • If field_name is not a valid field for the current PivotTable then the #VALUE! error value is returned.

Related Functions

PIVOT.ADD.FIELDS Adds fields to a PivotTable

PIVOT.FIELD Pivots fields within a PivotTable

PIVOT.FIELD.GROUP Creates groups within a PivotTable

PIVOT.FIELD.PROPERTIES Changes the properties of a field inside a PivotTable

PIVOT.FIELD.UNGROUP Ungroups all selected groups within a PivotTable

PIVOT.ITEM Moves an item within a PivotTable

PIVOT.ITEM.PROPERTIES Changes the properties of an item within a header field

PIVOT.REFRESH Refreshes a PivotTable

PIVOT.SHOW.PAGES Creates new sheets in the workbook containing the active cell

PIVOT.TABLE.WIZARD Creates an empty PivotTable

List of Command-Equivalent Functions


PIVOT.ADD.FIELDS

Macro Sheets Only

Add fields onto a PivotTable.

Syntax

PIVOT.ADD.FIELDS(name, row_array, column_array, page_array, add_to_table)

Name is the name of the PivotTable to which the user wants to add fields. If name is omitted, Microsoft Excel will use the PivotTable containing the active cell.

Row_array is an array of text constants consisting of the names of the fields which the user would like to add to the PivotTable as Row Fields.

Column_array is an array of text constants consisting of the names of the fields which the user would like to add to the PivotTable as Column Fields.

Page_array is an array of text constants consisting of the names of the fields which the user would like to add to the PivotTable as Page Fields.

Add_to_table is a logical value which if TRUE adds the fields specified by row_array, column_array and page_array to the exisiting fields on the PivotTable. If add_bool is FALSE, Microsoft Excel will replace the fields already along the rows, columns and pages with the fields specified by row_array, column_array and page_array.

Remarks

If name is not a valid PivotTable name, then the #VALUE! error value is returned.

Related Functions

PIVOT.ADD.DATA Adds a field to a PivotTable as a Data Field

PIVOT.FIELD Pivots fields within a PivotTable

PIVOT.FIELD.GROUP Creates groups within a PivotTable

PIVOT.FIELD.PROPERTIES Changes the properties of a field inside a PivotTable

PIVOT.FIELD.UNGROUP Ungroups all selected groups within a PivotTable

PIVOT.ITEM Moves an item within a PivotTable

PIVOT.ITEM.PROPERTIES Changes the properties of an item within a header field

PIVOT.REFRESH Refreshes a PivotTable

PIVOT.SHOW.PAGES Creates new sheets in the workbook containing the active cell

PIVOT.TABLE.WIZARD Creates an empty PivotTable

List of Command-Equivalent Functions


PIVOT.FIELD

Macro Sheets Only

Pivots a field within a PivotTable.

Syntax

PIVOT.FIELD(name, pivot_field_name, orientation, position)

Name is the name of the PivotTable in which the user wants to pivot fields. If name is omitted, Microsoft Excel will use the PivotTable containing the active cell.

Pivot_field_name is the name of the field which the user wishes to pivot to another part of the PivotTable. This argument is given as a text constant or a reference to a text constant. If field_name is omitted, Microsoft Excel uses the field containing the active cell.

Orientation is an integer representing the destination of the field which is being pivoted. If this argument is omitted, then the orientation remains unchanged. The integers refer to orientations as follows:

Value Orientation

0 Hidden

1 Row

2 Column

3 Page

4 Data

Position is an integer representing where in the orientation the fields will be positioned. Position 1 is the leftmost header position in the row header and the topmost position in the column header. This argument is ignored if orientation is set to 0. If the position argument is omitted, it will default to the last position in the field.

Remarks

  • The function returns TRUE if successful.
  • If name is not a valid PivotTable name then the #VALUE! error value is returned.
  • If pivot_field_name is not a text constant or contains text which is not a valid field name for the PivotTable then the #VALUE! error value is returned.
  • If destination is not an integer between 0 and 4, then the #VALUE! error value is returned.

Related Functions

PIVOT.ADD.DATA Adds a field to a PivotTable as a Data Field

PIVOT.ADD.FIELDS Adds fields to a PivotTable

PIVOT.FIELD.GROUP Creates groups within a PivotTable

PIVOT.FIELD.PROPERTIES Changes the properties of a field inside a PivotTable

PIVOT.FIELD.UNGROUP Ungroups all selected groups within a PivotTable

PIVOT.ITEM Moves an item within a PivotTable

PIVOT.ITEM.PROPERTIES Changes the properties of an item within a header field

PIVOT.REFRESH Refreshes a PivotTable

PIVOT.SHOW.PAGES Creates new sheets in the workbook containing the active cell

PIVOT.TABLE.WIZARD Creates an empty PivotTable

List of Command-Equivalent Functions


PIVOT.FIELD.GROUP

Macro Sheets Only

Creates groups within a PivotTable.

Syntax

PIVOT.FIELD.GROUP(start, end, by, periods)
PIVOT.FIELD.GROUP?(start, end, by, periods)

Start is the beginning date of the range to be grouped. If start is TRUE or omitted, it is assumed to be the first value in the field.

End is the ending date of the range to be grouped. If end is TRUE or omitted it is assumed to be the last value in the field.

By is the size of the groups to be created. If by is omitted, Microsoft Excel chooses a default group size. If grouping a date field and if periods is not 8(days) then by is ignored.

Periods is a number between 1 and 127. It is calculated by summing the values in the following table corresponding to the periods into which you want to group your dates. This argument is ignored if the field is not a date field. This argument takes precedence over By if they are both specified for a date field.

Value Periods

1 Seconds

2 Minutes

4 Hours

8 Days

16 Months

32 Quarters

64 Years

Remarks

  • This function returns TRUE if the grouping is successful. The #N/A error value is returned if the grouping failed.
  • If no arguments are specified and multiple items within the header field are selected then this function groups those selected items.
  • If no arguments are specified and a single item within the header field is selected then the #VALUE! error value is returned.

Related Functions

PIVOT.ADD.DATA Adds a field to a PivotTable as a Data Field

PIVOT.ADD.FIELDS Adds fields to a PivotTable

PIVOT.FIELD Pivots fields within a PivotTable

PIVOT.FIELD.PROPERTIES Changes the properties of a field inside a PivotTable

PIVOT.FIELD.UNGROUP Ungroups all selected groups within a PivotTable

PIVOT.ITEM Moves an item within a PivotTable

PIVOT.ITEM.PROPERTIES Changes the properties of an item within a header field

PIVOT.REFRESH Refreshes a PivotTable

PIVOT.SHOW.PAGES Creates new sheets in the workbook containing the active cell

PIVOT.TABLE.WIZARD Creates an empty PivotTable

List of Command-Equivalent Functions


PIVOT.FIELD.PROPERTIES

Macro Sheets Only

Changes the properties of a field inside a PivotTable.

Syntax

PIVOT.FIELD.PROPERTIES(name, pivot_field_name, new_name, orientation, function, formats)
PIVOT.FIELD.PROPERTIES?(name, pivot_field_name, new_name, orientation, function, formats)

Name is the name of the PivotTable containing the field which the user wants to edit. If name is omitted, Microsoft Excel will use the PivotTable containing the active cell.

Pivot_field_name is the name of a field in the PivotTable which the user would like to edit, as text. If it is omitted, Microsoft Excel uses the field containing the active cell.

New_name is the name which you would like to rename the current field. If it is omitted, the name of the current field will not change.

Orientation is a number between 0 and 4 specifying which area will show the field containing the active cell. If zero, then the field is deleted and all other arguments to this function are ignored. If this argument is omitted, the orientation of the field will not change.

Value Orientation

0 Delete

1 Display as Row

2 Display as Column

3 Display as Page

4 Display as Data

Function is a number between 0 and 4094 specifying which calculation or subtotals to apply to the field. If you will be showing the field in the header (orientation 1, 2, or 3), add up the values from the table corresponding to the subtotals you would like to show. If you will be showing the field as a data field (orientation 4), choose one value from the table. If an entry in this column is left blank, Microsoft Excel will not change the calculation or subtotal which are currently attached to the field.

Value Function

0 NO SUBTOTALS

1 AUTOMATIC

2 SUM

4 COUNTA

8 COUNT

16 AVERAGE

32 MAX

64 MIN

128 PRODUCT

256 STDEV

512 STDEVP

1024 VAR

2048 VARP

Formats is either a one or a two dimension array, depending on whether the field is a header field or a data field.

  • If the active field is a header field (orientation argument is 1, 2 or 3) then this is a two dimensional array. Each row of the array should consist of two entries. The first is a text string corresponding to the item whose property is being changed. The second element specifies whether the item will be hidden. If this argument is TRUE, the item will be hidden and therefore will not be displayed in the PivotTable. If the argument is FALSE, then the item will be displayed in the PivotTable.
  • If the active field is a data field, then the array is a one dimensional array with four elements. The first element is a number between 1 and 9 specifying which calculation you wish to apply to the current data field. This corresponds to the Show Data As drop-down box on the PivotTable Field dialog box.

Value Format

1 Normal

2 Difference From

3 %Of Item

4 %Difference From

5 Running Total In

6 %Of Row

7 %Of Column

8 %Of Subtotal

9 Index

  • The second element contains a text string representing the field to which your Data Field is related. This argument is not necessary for the Normal calculation. If omitted, Microsoft Excel will use the first field that would appear in the Base Field list box.
  • The third element must contain a text string representing an item in the base field on which to base your calculation. Note that this argument is not necessary for calculations like Running Total In which relies only on a Base Field. If omitted, Microsoft Excel will use the first item that would appear in the Base Item list box.
  • The fourth element is a text string representing the number format you wish to apply to the data field.

Remarks

  • If pivot_field_name is not a valid field name for the PivotTable then the #VALUE! error value is returned.
  • If name is not a valid PivotTable name, then the #VALUE! error value is returned.
  • If the orientation and function arguments do not contain numbers or if these arguments contain numbers which are out of range then the #VALUE! error value is returned.

Related Functions

PIVOT.ADD.DATA Adds a field to a PivotTable as a Data Field

PIVOT.ADD.FIELDS Adds fields to a PivotTable

PIVOT.FIELD Pivots fields within a PivotTable

PIVOT.FIELD.GROUP Creates groups within a PivotTable

PIVOT.FIELD.UNGROUP Ungroups all selected groups within a PivotTable

PIVOT.ITEM Moves an item within a PivotTable

PIVOT.ITEM.PROPERTIES Changes the properties of an item within a header field

PIVOT.REFRESH Refreshes a PivotTable

PIVOT.SHOW.PAGES Creates new sheets in the workbook containing the active cell

PIVOT.TABLE.WIZARD Creates an empty PivotTable

List of Command-Equivalent Functions


PIVOT.FIELD.UNGROUP

Macro Sheets Only

Ungroups all selected groups within a PivotTable.

Syntax

PIVOT.FIELD.UNGROUP( )

Remark

If the active cell is on a field header, then all the groups in that field are ungrouped and the field will be removed from the PivotTable. Similarly, if the last group in a Parent field is ungrouped, the entire field will be removed from the PivotTable.

Related Functions

PIVOT.ADD.DATA Adds a field to a PivotTable as a Data Field

PIVOT.ADD.FIELDS Adds fields to a PivotTable

PIVOT.FIELD Pivots fields within a PivotTable

PIVOT.FIELD.GROUP Creates groups within a PivotTable

PIVOT.FIELD.PROPERTIES Changes the properties of a field inside a PivotTable

PIVOT.ITEM Moves an item within a PivotTable

PIVOT.ITEM.PROPERTIES Changes the properties of an item within a header field

PIVOT.REFRESH Refreshes a PivotTable

PIVOT.SHOW.PAGES Creates new sheets in the workbook containing the active cell

PIVOT.TABLE.WIZARD Creates an empty PivotTable

List of Command-Equivalent Functions


PIVOT.ITEM

Macro Sheets Only

Moves an item within a PivotTable.

Syntax

PIVOT.ITEM(name, pivot_field_name, pivot_item_name,position)

Name is the name of the PivotTable within which an item will be repositioned. If name is omitted, Microsoft Excel will use the PivotTable containing the active cell.

Pivot_field_name is the name of the field within which an item will be repositioned, given as a text string. If pivot_field_name is omitted, Microsoft Excel will use the field containing the active cell. If the active cell is not within a field, then this argument is required.

Pivot_item_name is the name of the item to be repositioned in its field (given as a text constant). If it is omitted, Microsoft Excel uses the item containing the active cell. If the active cell is not contained within an item, then this argument is requiried.

Position is a number representing where in the field the items will be moved. Position 1 is the topmost position within the row field and the leftmost position within the column field and the highest position within the page field. If the position argument is omitted, it will default to the last position in the field.

Remarks

  • If an item is set to be visible, but its display is supressed because there is no data, this item still occupies a valid position.
  • If name is not a valid PivotTable name then the #VALUE! error value is returned.
  • If pivot_field_name is not a text string, or if pivot_field_name is not a text string within a valid field name, then #VALUE! is returned.
  • If pivot_item_name is an item which is not currently showing in the PivotTable because it does not exist in the field pivot_field_name, the #VALUE! error value is returned.

Related Functions

PIVOT.ADD.DATA Adds a field to a PivotTable as a Data Field

PIVOT.ADD.FIELDS Adds fields to a PivotTable

PIVOT.FIELD Pivots fields within a PivotTable

PIVOT.FIELD.GROUP Creates groups within a PivotTable

PIVOT.FIELD.PROPERTIES Changes the properties of a field inside a PivotTable

PIVOT.FIELD.UNGROUP Ungroups all selected groups within a PivotTable

PIVOT.ITEM.PROPERTIES Changes the properties of an item within a header field

PIVOT.REFRESH Refreshes a PivotTable

PIVOT.SHOW.PAGES Creates new sheets in the workbook containing the active cell

PIVOT.TABLE.WIZARD Creates an empty PivotTable

List of Command-Equivalent Functions


PIVOT.ITEM.PROPERTIES

Macro Sheets Only

Changes the properties of an item within a header field.

Syntax

PIVOT.ITEM.PROPERTIES(name, pivot_field_name, pivot_item_name, new_name, position, show, active_page)

Name is the name of the PivotTable containing the item which the user wants to edit.

Pivot_field_name is the name of a field in the PivotTable containing the item which the user would like to edit. If it is omitted, Microsoft Excel uses the field containing the active cell.

Pivot_item_name is the name of the item which the user would like to edit. If it is omitted, Microsoft Excel uses the item containing the active cell.

New_name is the name which you would like to rename the current item. If it is omitted, then the name of the current item will not change.

Position is a number representing where in the field the item will appear. Position 1 is the topmost position within the row field, the leftmost position within the column field, and the highest position within the page field. If the position argument is omitted, it will default to the last position in the field.

Show is a logical value which if TRUE causes the item to appear in the PivotTable. If FALSE, the item will be hidden.

Active_page is a logical value specifying whether item_name will become the active item in the page field. If TRUE then item_name will become the active item in the page field. If FALSE or omitted, the active item in the page field does not change. Applies to only page fields.

Remarks

  • If name is omitted, Microsoft Excel will use the PivotTable containing the active cell.
  • If pivot_field_name is not a header field, then this function will return the #VALUE! error value.

Related Functions

PIVOT.ADD.DATA Adds a field to a PivotTable as a Data Field

PIVOT.ADD.FIELDS Adds fields to a PivotTable

PIVOT.FIELD Pivots fields within a PivotTable

PIVOT.FIELD.GROUP Creates groups within a PivotTable

PIVOT.FIELD.PROPERTIES Changes the properties of a field inside a PivotTable

PIVOT.FIELD.UNGROUP Ungroups all selected groups within a PivotTable

PIVOT.ITEM Moves an item within a PivotTable

PIVOT.REFRESH Refreshes a PivotTable

PIVOT.SHOW.PAGES Creates new sheets in the workbook containing the active cell

PIVOT.TABLE.WIZARD Creates an empty PivotTable

List of Command-Equivalent Functions


PIVOT.REFRESH

Macro Sheets Only

Refreshes a PivotTable.

Syntax

PIVOT.REFRESH(name)

Name is the name of the PivotTable the user would like to refresh with current data. If name is omitted, Microsoft Excel will use the PivotTable containing the active cell.

Remarks

  • If the function is successful, it returns TRUE; otherwise, it returns the #VALUE! error value.
  • If name is not a valid PivotTable name, then the #VALUE! error value is returned.

Related Functions

PIVOT.ADD.DATA Adds a field to a PivotTable as a Data Field

PIVOT.ADD.FIELDS Adds fields to a PivotTable

PIVOT.FIELD Pivots fields within a PivotTable

PIVOT.FIELD.GROUP Creates groups within a PivotTable

PIVOT.FIELD.PROPERTIES Changes the properties of a field inside a PivotTable

PIVOT.FIELD.UNGROUP Ungroups all selected groups within a PivotTable

PIVOT.ITEM Moves an item within a PivotTable

PIVOT.ITEM.PROPERTIES Changes the properties of an item within a header field

PIVOT.SHOW.PAGES Creates new sheets in the workbook containing the active cell

PIVOT.TABLE.WIZARD Creates an empty PivotTable

List of Command-Equivalent Functions


PIVOT.SHOW.PAGES

Macro Sheets Only

Creates new sheets in the workbook containing the active cell. The function will iterate through each item in page_field and create a new PivotTable on a new sheet with the page field set to that particular item.

Syntax

PIVOT.SHOW.PAGES(name, page_field)

Name is the name of the target PivotTable. If name is omitted, Microsoft Excel will use the PivotTable containing the active cell.

Page_field is the name of a page field in the PivotTable specified by the name argument.

Remarks

If the function is successful, it returns TRUE; otherwise, it returns the #VALUE! error value.

If name is not a valid PivotTable name then the #VALUE! error value is returned.

Related Functions

PIVOT.ADD.DATA Adds a field to a PivotTable as a Data Field

PIVOT.ADD.FIELDS Adds fields to a PivotTable

PIVOT.FIELD Pivots fields within a PivotTable

PIVOT.FIELD.GROUP Creates groups within a PivotTable

PIVOT.FIELD.PROPERTIES Changes the properties of a field inside a PivotTable

PIVOT.FIELD.UNGROUP Ungroups all selected groups within a PivotTable

PIVOT.ITEM Moves an item within a PivotTable

PIVOT.ITEM.PROPERTIES Changes the properties of an item within a header field

PIVOT.REFRESH Refreshes a PivotTable

PIVOT.TABLE.WIZARD Creates an empty PivotTable

List of Command-Equivalent Functions


PIVOT.TABLE.WIZARD

Macro Sheets Only

Creates an empty PivotTable.

Syntax

PIVOT.TABLE.WIZARD(type, source, destination, name, row_grand, col_grand, save_data, apply_auto_format, autopage )
PIVOT.TABLE.WIZARD?(type, source, destination, name, row_grand, col_grand, save_data, apply_auto_format, autopage)

Type is a number specifying the type of source data used to create the PivotTable.

Value Type of source data

1 Microsoft Excel List or Database

2 External data source

3 Multiple consolidation ranges

4 Another PivotTable

Source can be one of four things. If type is one, then source is a cell reference or name to the range to be used as the PivotTable source. If type is two, then source is a one- dimensional array describing the external database to be used as the PivotTable source. If type is three, then source is a multi-dimensional array listing the cell ranges and associated page field items describing the consolidation PivotTable source. If type is four, then source is the name of another PivotTable with which to share its source.

Destination is a cell reference or name. The upper left corner of this range will act as the upper left corner of the PivotTable which will be created. If destination is omitted, Microsoft Excel will choose a default location for the PivotTable.

Name is the name of the PivotTable to be created given as a text. If name is omitted, Microsoft Excel will choose a default name.

Row_grand is a logical value which if TRUE displays a Grand Total for each row on the PivotTable. If FALSE, a Grand Total for each row is not displayed.

Col_grand is a logical value which if TRUE displays a Grand Total for each column. If FALSE, a Grand Total for each column is not displayed.

Save_data is a logical value which if TRUE causes the data for the PivotTable to be saved along with the PivotTable definition. If FALSE, the data is not saved along with the PivotTable definition.

Apply_auto_format is a logical value which if TRUE causes autoformatting upon pivotting or refreshing. If FALSE, the PivotTable will not be formatted automatically upon pivoting or refreshing.

Autopage Applies only to type 3. This argument is a logical value which if TRUE or omitted causes Microsoft Excel to create a page field automatically. If FALSE, the page field must be created manually.

Remarks

  • The function will return TRUE if successful; otherwise, returns the #VALUE! error value.
  • If destination is not a valid Microsoft Excel reference, then #VALUE! error value is returned.
  • If name is not a valid PivotTable name, then the #VALUE! error value is returned.

Related Functions

PIVOT.ADD.DATA Adds a field to a PivotTable as a Data Field

PIVOT.ADD.FIELDS Adds fields to a PivotTable

PIVOT.FIELD Pivots fields within a PivotTable

PIVOT.FIELD.GROUP Creates groups within a PivotTable

PIVOT.FIELD.PROPERTIES Changes the properties of a field inside a PivotTable

PIVOT.FIELD.UNGROUP Ungroups all selected groups within a PivotTable

PIVOT.ITEM Moves an item within a PivotTable

PIVOT.ITEM.PROPERTIES Changes the properties of an item within a header field

PIVOT.REFRESH Refreshes a PivotTable

PIVOT.SHOW.PAGES Creates new sheets in the workbook containing the active cell

List of Command-Equivalent Functions


QUERY.GET.DATA

Macro Sheets Only

Builds a new query using the supplied information. The application Microsoft Query nor any dialog boxes are displayed. Equivalent to choosing the Get External Data command from the Data menu when the Microsoft Query Add-in is installed.

Syntax

QUERY.GET.DATA(connection_string, query_text, keep_query_def, field_names, row_numbers, destination)
QUERY.GET.DATA?(connection_string, query_text, keep_query_def, field_names, row_numbers, destination)

Connection_string supplies information, such as the data source name, user ID, and passwords, necessary to making a SQL connection to an external data source. For example: "DSN=Myserver; Server=server1; UID=dbayer; PWD=buyer1; Database=nwind".

  • You must define the data source name (DSN) used in connection_string before you try to connect to it.
  • You can enter connection_string as an array or a string. If connection_string exceeds 250 characters, you must enter it as an array.
  • If QUERY.GET.DATA is unable to access the data source using connection_string, it returns the #N/A error value.

Query_text is the SQL language query to be executed on the data source.

Keep_query_def is a logical value that, if TRUE or omitted, preserves the query definition. If FALSE, the query definition is lost and the data from the query no longer constitutes a data range.

Field_names is a logical value that, if TRUE or omitted, places field names from Microsoft Query into the first row of the data range. If FALSE, the field names are discarded.

Row_numbers is a logical value that, if TRUE, places row numbers from Microsoft Query into the first column in the data range. If FALSE or omitted, the row numbers are discarded.

Destination is the location as a cell reference where you want the data placed. If destination is in a current data range then that data range is changed to reflect the new SQL statement. The default destination is the currently selected cell or range.

Remarks

  • If the information provided is not sufficient to create the query then the error value #REF! is returned.
  • If the Microsoft Query Tool is unavailable or can not be found, #N/A is returned.
  • If connection string is longer than 255 characters, the string will be truncated at the last semi-colon.

Related Functions

QUERY.REFRESH Refreshes the data in a data range returned by the Microsoft Query tool

List of Command-Equivalent Functions


QUERY.REFRESH

Macro Sheets Only

Refreshes the data in a data range returned by the Microsoft Query tool. This function acts exactly the same as the Refresh tool.

Syntax

QUERY.REFRESH(reference)

Reference is the reference to a single cell inside a data range. If reference is not in a data range then the error value #REF! is returned.

Related Functions

QUERY.GET.DATA Builds a new query using the supplied information

List of Command-Equivalent Functions


RENAME.OBJECT

Macro Sheets Only

Renames the selected object or group. This is useful for giving objects names more relevant to their usage. This is also useful if it is uncertain how the object may have been named.

Syntax

RENAME.OBJECT(new_name)

New_name is the new name to be given to the selected object.

Related Functions

GET.OBJECT Returns information about a specified object

INSERT.OBJECT Equivalent to choosing the Object command from the Insert menu

SELECT Syntax 2 Selects objects on worksheets

List of Command-Equivalent Functions


ROUTING.SLIP

Macro Sheets Only

Equivalent to choosing the Add Routing Slip command from the File menu. Adds or Edits the routing slip attached to the current workbook.

Syntax

ROUTING.SLIP(recipients,subject, message, route_num, return_logical, status_logical)
ROUTING.SLIP?(recipients,subject, message, route_num, return_logical, status_logical)

Recipients is the name of the person to whom you want to send the mail. The name should be given as text.

  • To specify more than one name, give the list of names as an array. For example, ROUTING.SLIP({"John", "Paul", "George", "Ringo"}) would send the active workbook to the four names in the array. You can also refer to a range on a sheet or macro sheet that contains a list of names to whom you want the mail to be sent.
  • Specifying recipients while a routing is in progress only modifies the non-grayed recipients (that is, those recipients who have not received the message yet). Recipients who have already received, reviewed and forwarded the routed document cannot be modified.

Subject is a text string containing the subject text used for the mail messages used to route the document. If omitted, the default subject line is "Routing: name", where name is the file name or title as displayed in the Summary Info dialog box, if available.

Message is a text string containing the body text used for the mail messages used to route the document.

Route_num is a number indicating the type of routing method.

Route_num Method

1 or omitted One after another routing

2 All at once routing

Return_logical is a logical value which, if TRUE or omitted, indicates that the routing should be returned to the originator when the routing is complete. If FALSE, the routing will end with the last recipient in the To list box in the Routing Slip Dialog box.

Status_logical is a logical value corresponding to the Track Status check box in the Routing Slip dialog box. If TRUE or omitted, status tracking messages for the routing are sent. FALSE means that no status tracking is performed.

Remarks

  • If this function is used on a document that is already being routed, the route_num, status_logical and return_logical arguments are ignored (they cannot be changed).
  • When arguments are omitted and a routing slip already exists, the omitted arguments are replaced by the current values of the routing slip.

Related Functions

ROUTE.DOCUMENT Routes the document using the defined routing slip information

SEND.MAIL Sends the active workbook using email

List of Command-Equivalent Functions


ROUTE.DOCUMENT

Macro Sheets Only

Routes the document using the defined routing slip information.

Syntax

ROUTE.DOCUMENT()

Remarks

If there is no routing slip, returns #N/A. If an error occurs or routing is not enabled for the system, returns #VALUE!.

Related Functions

SEND.MAIL Sends the active workbook using email

ROUTING.SLIP Adds or Edits the routing slip attached to the current workbook

List of Command-Equivalent Functions


SAVE.WORKSPACE

Macro Sheets Only

Equivalent to choosing the Save Workspace command from the File menu. Saves the currently opened workbook or workbooks as a workspace.

Syntax

SAVE.WORKSPACE(name_text)
SAVE.WORKSPACE?(name_text)

Name_text is the name of the workspace to save.

Related Function

SAVE.AS Specifies a new filename.

List of Command-Equivalent Functions


SCALE

Macro Sheets Only

Equivalent to choosing the Scale command from the Format menu, which is available when a chart is active. There are five syntax forms of this function.

Syntax 1 Changes the position, formatting, and scaling of the category axis in 2-D charts

Syntax 2 Changes the position, formatting, and scaling of the value axis in 2-D charts

Syntax 3 Changes the position, formatting, and scaling of the category axis in 3-D charts

Syntax 4 Changes the position, formatting, and scaling of the series axis in 3-D charts

Syntax 5 Changes the position, formatting, and scaling of the value axis in 3-D charts


SCALE

Macro Sheets Only

Equivalent to choosing the Selected Axis command from the Format menu when a chart's axis is selected, and then choosing the Scale tab. There are five syntax forms of this function. Syntax 1 of SCALE applies if the selected axis is a category (x) axis on a 2-D chart and the chart is not an xy (scatter) chart. Use this syntax of SCALE to change the position, formatting, and scaling of the category axis.

Syntax 1

SCALE(cross, cat_labels, cat_marks, between, max, reverse)
SCALE?(cross, cat_labels, cat_marks, between, max, reverse)

Arguments correspond to text boxes and check boxes in the Scale tab on the Format Axis dialog box. Arguments corresponding to check boxes are logical values. If an argument is TRUE, Microsoft Excel selects the check box; if FALSE, Microsoft Excel clears the check box.

Cross is a number corresponding to the Value (Y) Axis Crosses At Category number text box. The default is 1. Cross is ignored if max is set to TRUE.

Cat_labels is a number corresponding to the Number Of Categories Between Tick Mark Labels text box. The default is 1.

Cat_marks is a number corresponding to the Number Of Categories Between Tick Marks text box. The default is 1.

Between corresponds to the Value (Y) Axis Crosses Between Categories check box. This argument only applies if cat_labels is set to a number other than 1.

Max corresponds to the Value (Y) Axis Crosses At Maximum Category check box. If max is TRUE, it overrides any setting for cross.

Reverse corresponds to the Categories In Reverse Order check box.

Related Functions

AXES Controls whether axes on a chart are visible

GRIDLINES Controls whether chart gridlines are visible

Syntax 2 Changes the position, formatting, and scaling of the value axis in 2-D charts

Syntax 3 Changes the position, formatting, and scaling of the category axis in 3-D charts

Syntax 4 Changes the position, formatting, and scaling of the series axis in 3-D charts

Syntax 5 Changes the position, formatting, and scaling of the value axis in 3-D charts

List of Command-Equivalent Functions


SCALE

Macro Sheets Only

Equivalent to choosing the Selected Axes command from the Format menu when a chart's axis is selected, and then choosing the Scale tab. There are five syntax forms of this function. Syntax 2 of SCALE applies if the selected axis is a value (y) axis on a 2-D chart, or either axis on an xy (scatter) chart. Use this syntax of SCALE to change the position, formatting, and scaling of the value axis.

Syntax 2

SCALE(min_num, max_num, major, minor, cross, logarithmic, reverse, max)
SCALE?(min_num, max_num, major, minor, cross, logarithmic, reverse, max)

The first five arguments correspond to the five range variables on the Scale tab. Each argument can be either the logical value TRUE or a number:

  • If an argument is TRUE, Microsoft Excel selects the Auto check box.
  • If an argument is a number, that number is used for the variable.

Min_num corresponds to the Minimum check box and is the minimum value for the value axis.

Max_num corresponds to the Maximum check box and is the maximum value for the value axis.

Major corresponds to the Major Unit check box and is the major unit of measure.

Minor corresponds to the Minor Unit check box and is the minor unit of measure.

Cross corresponds to the Category (X) Axis Crosses At text box for the value (y) axis of a 2-D chart or the Value (Y) Axis Crosses At text box for the category (x) axis of an xy (scatter) chart.

The last three arguments are logical values corresponding to check boxes in the Scale tab . If an argument is TRUE, Microsoft Excel selects the check box; if FALSE, Microsoft Excel clears the check box.

Logarithmic corresponds to the Logarithmic Scale check box.

Reverse corresponds to the Values In Reverse Order check box.

Max corresponds to the Category (X) Axis Crosses At Maximum Value/Category check box.

Related Functions

Syntax 1 Changes the position, formatting, and scaling of the category axis in 2-D charts

Syntax 3 Changes the position, formatting, and scaling of the category axis in 3-D charts

Syntax 4 Changes the position, formatting, and scaling of the series axis in 3-D charts

Syntax 5 Changes the position, formatting, and scaling of the value axis in 3-D charts

List of Command-Equivalent Functions


SCALE

Macro Sheets Only

Equivalent to choosing the Selected Axes command from the Format menu when a chart's axis is selected, and then choosing the Scale tab. There are five syntax forms of this function. Syntax 3 of SCALE applies if the selected axis is a category (x) axis on a 3-D chart. Use this syntax of SCALE to change the position, formatting, and scaling of the category axis.

Syntax 3

SCALE(cat_labels, cat_marks, reverse, between)
SCALE?(cat_labels, cat_marks, reverse, between)

Cat_labels is a number corresponding to the Number Of Categories Between Tick Labels text box. The default is 1. Cat_labels can also be a logical value. If TRUE, an automatic setting will be used. If FALSE, or omitted, the number will be used.

Cat_marks is a number corresponding to the Number Of Categories Between Tick Marks text box. The default is 1. Cat_marks can also be a logical value. If TRUE, an automatic setting will be used. If FALSE, or omitted, the number will be used.

Reverse corresponds to the Categories in Reverse Order check box in the Scale tab. If reverse is TRUE, Microsoft Excel selects the check box; if FALSE, Microsoft Excel clears the check box.

Between corresponds to the Value (Z) Axis Crosses Between Categories check box. If between is TRUE, Microsoft Excel selects the check box and the data points appear between categories. If between is FALSE or omitted, Microsoft Excel clears the check box.

Related Functions

Syntax 1 Changes the position, formatting, and scaling of the category axis in 2-D charts

Syntax 2 Changes the position, formatting, and scaling of the value axis in 2-D charts

Syntax 4 Changes the position, formatting, and scaling of the series axis in 3-D charts

Syntax 5 Changes the position, formatting, and scaling of the value axis in 3-D charts

List of Command-Equivalent Functions


SCALE

Macro Sheets Only

Equivalent to choosing the Selected Axes command from the Format menu when a chart's axis is selected, and then choosing the Scale tab. There are five syntax forms of this function. Syntax 4 of SCALE applies if the selected axis is a series (y) axis on a 3-D chart. Use this syntax of SCALE to change the position, formatting, and scaling of the series axis.

Syntax 4

Series (y) axis, 3-D chart

SCALE(series_labels, series_marks, reverse)
SCALE?(series_labels, series_marks, reverse)

Series_labels is a number corresponding to the Number Of Series Between Tick Labels text box. The default is 1. Series_labels can also be a logical value. If TRUE, and automatic setting will be used. If FALSE, or omitted, the number will be used.

Series_marks is a number corresponding to the Number Of Series Between Tick Marks text box. The default is 1. Series_marks can also be a logical value. If TRUE, and automatic setting will be used. If FALSE, or omitted, the number will be used.

Reverse is a logical value that corresponds to the Series In Reverse Order check box in the Scale tab. If reverse is TRUE, Microsoft Excel displays the series in reverse order; if FALSE or omitted, Microsoft Excel displays the series normally.

Related Functions

Syntax 1 Changes the position, formatting, and scaling of the category axis in 2-D charts

Syntax 2 Changes the position, formatting, and scaling of the value axis in 2-D charts

Syntax 3 Changes the position, formatting, and scaling of the category axis in 3-D charts

Syntax 5 Changes the position, formatting, and scaling of the value axis in 3-D charts

List of Command-Equivalent Functions


SCALE

Macro Sheets Only

Equivalent to choosing the Selected Axes command from the Format menu when a chart's axis is selected, and then choosing the Scale tab. There are five syntax forms of this function. Syntax 5 of SCALE applies if the selected axis is a value (z) axis on a 3-D chart. Use this syntax of SCALE to change the position, formatting, and scaling of the value axis.

Syntax 5

SCALE(min_num, max_num, major, minor, cross, logarithmic, reverse, min)
SCALE?(min_num, max_num, major, minor, cross, logarithmic, reverse, min)

The first five arguments correspond to the five range variables in the Format Axis dialog box, as shown in the following list. Each argument can be either the logical value TRUE or a number.

  • If TRUE or omitted, the Auto check box is selected.
  • If a number, that number is used.

Min_num corresponds to the Minimum box and is the minimum value for the value axis.

Max_num corresponds to the Maximum box and is the maximum value for the value axis.

Major corresponds to the Major Unit box and is the major unit of measure.

Minor corresponds to the Minor Unit box and is the minor unit of measure.

Cross corresponds to the Floor (XY Plane) Crosses At box.

The last three arguments are logical values corresponding to check boxes in the Scale tab. If an argument is TRUE, Microsoft Excel selects the check box; if FALSE, Microsoft Excel clears the check box.

Logarithmic corresponds to the Logarithmic Scale check box.

Reverse corresponds to the Values In Reverse Order check box.

Min corresponds to the Floor (XY Plane) Crosses At Minimum Value check box.

Related Functions

Syntax 1 Changes the position, formatting, and scaling of the category axis in 2-D charts

Syntax 2 Changes the position, formatting, and scaling of the value axis in 2-D charts

Syntax 3 Changes the position, formatting, and scaling of the category axis in 3-D charts

Syntax 4 Changes the position, formatting, and scaling of the series axis in 3-D charts

List of Command-Equivalent Functions


SHOW.BAR

Macro Sheets Only

Displays the specified menu bar. Use SHOW.BAR to display a menu bar you have created with the ADD.BAR function or to display a built-in Microsoft Excel menu bar.

Syntax

SHOW.BAR(bar_num)

Bar_num is the number of the menu bar you want to display. It can be the number of one of the Microsoft Excel built-in menu bars, the number returned by a previously executed ADD.BAR function, or a reference to a cell containing a previously executed ADD.BAR function.

If bar_num is omitted, Microsoft Excel displays the appropriate menu bar for the active workbook as shown in the following table.

Bar_num Bar displayed

1 A sheet or macro sheet (Microsoft Excel 4.0)

2 A chart (Microsoft Excel 4.0)

3 No active window

4 The Info window

5 A sheet or macro sheet (short menus)

6 A chart (short menus)

7 Shortcut menus 1 (for Cells, Workbook tabs, Toolbars, VB Windows)

8 Shortcut menus 2 (for objects)

9 Shortcut menus 3 (for chart elements)

10 A sheet or macro sheet

11 A chart

12 A Visual Basic module

13-35 Reserved for use by shortcut menus. These numbers will return an error if a macro tries to do anything with them.

37-51 Custom menu bar for macro use

Remarks

  • When displaying a built-in menu bar, you can display only bars 1 or 5 if a sheet or macro sheet is active, bars 2 or 6 if a chart is active, and so on. If you try to display a chart menu bar while a sheet or macro sheet is active, SHOW.BAR returns an error and interrupts the current macro.
  • Displaying a custom menu bar disables automatic menu-bar switching when different types of sheets are selected. For example, if a custom menu bar is displayed and you switch to a chart, neither of the two chart menus is automatically displayed as it would be when you are using the built-in menu bars. Automatic menu-bar switching is reenabled when a built-in bar is displayed using SHOW.BAR.

Example

The following macro formula displays short menus on a worksheet or macro sheet:

SHOW.BAR(5)

Related Functions

ADD.BAR Adds a menu bar

DELETE.BAR Deletes a menu bar

SHOW.TOOLBAR Hides or displays a toolbar

List of Customizing Functions


SHOW.TOOLBAR

Macro Sheets Only

Equivalent to selecting the check box corresponding to a toolbar in the Toolbars dialog box, which appears when you select the Toolbars command from the View menu. Hides or displays a toolbar.

Syntax

SHOW.TOOLBAR(bar_id, visible, dock, x_pos, y_pos, width, protect, tool_tips, large_buttons, color_buttons)

Bar_id is a number or name of a toolbar corresponding to the toolbars you want to display. For detailed information about bar_id, see ADD.TOOL.

Visible is a logical value that, if TRUE, specifies that the toolbar is visible or, if FALSE, specifies that the toolbar is hidden.

Dock specifies the docking location of the toolbar.

Dock Position of toolbar

1 Top of workspace

2 Left edge of workspace

3 Right edge of workspace

4 Bottom of workspace

5 Floating (not docked)

X_pos specifies the horizontal position of the toolbar.

  • If the toolbar is docked (not floating), x_pos is measured horizontally from the left edge of the toolbar to the left edge of the toolbar's docking area.
  • If the toolbar is floating, x_pos is measured horizontally from the left edge of the toolbar to the right edge of the rightmost toolbar in the left docking area.
  • X_pos is measured in points. A point is 1/72nd of an inch.

Y_pos specifies the vertical position of the toolbar.

  • If the toolbar is docked, y_pos is measured vertically from the top edge of the toolbar to the top edge of the toolbar's docking area.
  • If the toolbar is floating, y_pos is measured vertically from the top edge of the toolbar to the top edge of the Microsoft Excel workspace.
  • Y_pos is measured in points.

Width specifies the width of the toolbar and is measured in points. If you omit width, Microsoft Excel uses the existing width setting.

Protect is a number specifying the degree to which you can modify a toolbar and its buttons. Each succeeding protect number retains the protection status of its previous numbers. For example, a protect status of 3 (a toolbar cannot become docked if it is floating) assumes the protection status of 0, 1, and 2 as well.

Protect Description

0 Default. Toolbars can be re-shaped, docked, and floating. Toolbar buttons can be removed from and moved to the toolbar.

1 Toolbars can be re-shaped, docked, and floating. Toolbar buttons can not be removed from nor moved to the toolbar.

2 A floating toolbar cannot be re-shaped. It can be docked.

3 A floating toolbar cannot be docked. If it is already docked, it cannot become floating.

4 The toolbar cannot be moved at all. If it is already floating, it cannot be re-shaped or moved. If it is docked, it cannot become un-docked.

Tool_tips is a logical value that corresponds to the Show ToolTips check box on the Toolbar dialog box. If TRUE, ToolTips will be displayed. If FALSE, ToolTips will not be displayed.

Large Buttons is a logical value that corresponds to the Large Buttons check box on the Toolbar dialog box. If TRUE, large buttons will be displayed. If FALSE, large buttons will not be displayed.

Color_buttons is a logical value that corresponds to the Color Toolbars check box. If TRUE, the toolbar buttons will be displayed in color. If FALSE, the toolbar buttons will not be displayed in color.

Related Function

ADD.TOOLBAR Creates a new toolbar with the specified tools

List of Customizing Functions


SORT

Macro Sheets Only

Equivalent to choosing the Sort command from the Data menu. Sorts the rows or columns of the selection according to the contents of a key row or column within the selection. Use SORT to rearrange information into ascending or descending order.

Syntax 1

For Worksheet and macro sheets

SORT(orientation, key1, order1, key2, order2, key3, order3, header, custom, case)
SORT?(orientation, key1, order1, key2, order2, key3, order3, header, custom, case)

Syntax 2

For PivotTables

SORT(orientation, key1, order1, type, custom)
SORT?(orientation, key1, order1, type, custom)

Orientation is a number specifying whether to sort by rows or columns. Enter 1 to sort top to bottom or 2 to sort left to right.

Key1 is a reference to the cell or cells you want to use as the first sort key. The sort key identifies which column to sort by when sorting rows or which row to sort by when sorting columns. For a PivotTable, if type is 1, then key1 is a cell reference which indicates what value to sort by. There are two ways to specify sort keys:

Type of key Examples

An external reference to the active worksheet. | !B:B or !Price
An R1C1-style reference in the form of text. If the reference is relative, it is assumed to be relative to the active cell in the selection. | "C2" or "C[1]" or "Price"

Order1 specifies whether to sort the row or column containing key1 in ascending or descending order. Enter 1 to sort in ascending order or 2 to sort in descending order.

Key2, order2, key3, and order3 are similar to key1 and order1. Key2 specifies the second sort key, and order2 specifies whether to sort the row or column containing key2 in ascending or descending order. Key3 and order3 work similarly.

Header is a number indicating how Microsoft Excel is to handle headers on list.

Header Defined

0 Microsoft Excel will guess if there is a header

1 Forces Microsoft Excel to assume there is a header

2 or omitted Forces Microsoft Excel to assume there is no header

Type is a number specifying whether to sort the field by labels or values. Use one to sort by values or two to sort by labels.

Custom is a number that specifies what kind of custom sorting you want. This corresponds to the First Key Sort Order drop-down box in the Sort Options dialog box. For a PivotTable, custom is a number indicating what custom sort order to use when sorting labels.

Number Type of sort

1 Normal

2 Weekdays in abbreviated form ("Sun", "Mon", and so on)

3 Weekdays

4 Months in abbreviated form ("Jan" "Feb", and so on)

5 Months

Case is a logical value that determines whether the sort is case sensitive. If TRUE, the sort is case sensitive. If FALSE or omitted, the sort will not be case sensitive.

Tip If you want to sort using more than three keys, then sort the data three keys at a time, starting with the least important group of keys and progressing to the most important group, but listing the most important key first within each group.

Remarks

In the dialog box form of this function, if the header argument is omitted, then Microsoft Excel will guess whether or not there are headers.

Related Functions

List of Command-Equivalent Functions


SPELLING

Macro Sheets Only

Equivalent to choosing the Spelling command from the Tools menu. Checks the spelling of words in the current selection.

Syntax

SPELLING(custom_dic, ignore_uppercase, always_suggest)

Custom_dic is the filename of the custom dictionary to examine if words are not found in the main dictionary. If custom_dic is omitted, the currently specified dictionary is used.

Ignore_uppercase is a logical value corresponding to the Ignore Words In Uppercase check box.

If ignore_uppercase is Microsoft Excel will

TRUE Ignore words in all uppercase letters

FALSE Check words in all uppercase letters

Omitted Use the current setting

Always_suggest is a logical value corresponding to the Always Suggest check box.

If always_suggest is Microsoft Excel will

TRUE Display a list of suggested alternate spellings when an incorrect spelling is found

FALSE Wait for user to input the correct spelling

Omitted Use the current setting

Related Function

SPELLING.CHECK Checks the spelling of a word

List of Command-Equivalent Functions


SQL.BIND

Macro Sheets Only

Specifies where results from a SQL query are placed when they are retrieved with SQL.RETRIEVE. If this function is not available, you must install the Microsoft ODBC add-in (XLODBC.XLA).

Syntax

SQL.BIND(connection_num, column, reference)

Connection_num is the unique connection ID of the data source for which you want to define storage.

  • Connection_num was returned by a previously executed SQL.OPEN function.
  • If connection_num is not valid, then SQL.BIND returns the #VALUE! error value.

Column is the number of the result column that is to be bound. Result columns are numbered from left to right starting with 1. If column is omitted then all bindings for connection_num are removed. Column number 0 contains row numbers for the result set. If column number 0 is bound then SQL.RETRIEVE will return row numbers in the bound location.

Reference is a single cell reference on the worksheet where the results should be placed. If reference is omitted, the binding is removed for the column.

When SQL.RETRIEVE is called, the result rows in this column will be placed in the reference cell and the cells immediately below reference. The number of rows that will be retrieved is one of the SQL.RETRIEVE arguments.

Remarks

  • If SQL.BIND is completed successfully then it will return a vertical array listing the bound columns on the current connection. If SQL.BIND is unable to bind the result column then it will return the error value #N/A. In such a case SQL.BIND will place error information in memory for the SQL.ERROR function, if such information is available.
  • SQL.BIND tells the ODBC interface where to place results when they are retrieved using SQL.RETRIEVE. Binding is not necessary but can be useful if you want the results from different columns to be placed in disjoint worksheet locations.
  • If bindings are used, SQL.BIND must be called once for each column in the result set. If a result column is not bound then it will not be returned. A binding remains valid for as long as connection_num is open.
  • Call SQL.BIND after calling SQL.OPEN and SQL.EXEC.QUERY, but before calling SQL.RETRIEVE or SQL.RETRIEVE.TO.FILE. Calls to SQL.BIND will not affect results that have already been retrieved.

Example

SQL.BIND(conn1,1,"[Book1]Sheet1!C1") stores data obtained fom the data source conn1 on Sheet1 from left to right in cell C1, starting with column1.

Related Functions

SQL.OPEN Establishes a connection with a data source

SQL.EXEC.QUERY Sends a query to a data source

SQL.RETRIEVE.TO.FILE Retrieves query results and places them in a file

SQL.RETRIEVE Retrieves query results

SQL.GET.SCHEMA Gets information about a connected data source.

SQL.CLOSE Closes a connection to a data source.

SQL.ERROR Returns detailed error information

List of Command-Equivalent Functions


SQL.CLOSE

Macro Sheets Only

Terminates a connection to an external data source. If this function is not available, you must install the Microsoft ODBC add-in (XLODBC.XLA).

Syntax

SQL.CLOSE(connection_num)

Connection_num is the unique connection ID of the data source from which you wish to disconnect.

  • Connection_num is returned by a previously executed SQL.OPEN function.
  • If connection_num is not valid, SQL.CLOSE returns the #VALUE! error value.

Remarks

  • If the connection is successfully terminated SQL.CLOSE will return zero and the connection ID number is then no longer valid.
  • If SQL.CLOSE is unable to disconnect with the data source then it will return the error value the #N/A error value. In such a case SQL.CLOSE will place error information in memory for the SQL.ERROR function, if such information is available.
  • SQL.CLOSE works with data sources in much the same manner as FCLOSE works with files. If the call is successful then SQL.CLOSE will terminate the specified data source connection.

Example

SQL.CLOSE(conn1) will close the connection with connection_num conn1

Related Functions

SQL.OPEN Establishes a connection with a data source

SQL.EXEC.QUERY Sends a query to a data source

SQL.BIND Specifies storage for a result column

SQL.RETRIEVE.TO.FILE Retrieves query results and places them in a file

SQL.RETRIEVE Retrieves query results

SQL.GET.SCHEMA Gets information about a connected data source.

SQL.ERROR Returns detailed error information

List of Command-Equivalent Functions


SQL.ERROR

Macro Sheets Only

Returns detailed error information when it is called after a previous XLODBC.XLA function call has failed. If this function is not available, you must install the Microsoft ODBC add-in (XLODBC.XLA).

Syntax

SQL.ERROR()

Calling SQL.ERROR returns detailed error information in a two dimensional array. Each row in the array describes exactly one error. If a function call generates multiple errors, a row will be created for each error.When SQL.ERROR is processed successfully, all SQL.ERROR information is cleared. Also, all SQL.ERROR information is automatically removed whenever an ODBC function completes successfully.

Each row will have exactly three fields. The information in these three fields is obtained through the SQLERROR API function call. These fields are:

  • A textual message describing the error.
  • The ODBC error class and subclass as a character string.
  • The data source native error code as a numeric value.

If one or more of these fields is not available for the type of error that was encountered, the field will be left blank. For more information on the meaning of these three fields, refer to Chapter 24, "ODBC Function Reference", in the Microsoft Open Database Connectivity Programmer's Reference for the SQLError API function. See also Appendix A, "ODBC Error Codes" in the same manual.

Remarks

  • SQL.ERROR cannot provide information on Excel errors.
  • If no error information is available when SQL.ERROR is called, then it well return the error value #N/A but does not post any error information to SQL.ERROR.
  • SQL.ERROR stores and returns error information by processing SQL.ERROR (in the ODBC API reference) in a loop until SQL_NO_DATA_FOUND is encountered. In the SQL.ERROR function, the error information is automatically defined and stored in memory whenever an XLODBC.XLA function fails. If the call is successful then SQL.ERROR will return the error information available. If SQL.ERROR fails, it will return the error value #N/A.

Example

When entered as an array formula, the following example will return error information about each argument in, for example, SQL.GET.QUERY.

SQL.ERROR()

Related Functions

SQL.OPEN Establishes a connection with a data source

SQL.EXEC.QUERY Sends a query to a data source

SQL.BIND Specifies storage for a result column

SQL.RETRIEVE.TO.FILE Retrieves query results and places them in a file

SQL.RETRIEVE Retrieves query results

SQL.CLOSE Closes a data source connection

List of Command-Equivalent Functions


SQL.EXEC.QUERY

Macro Sheets Only

Sends a query to a data source using an existing connection. If this function is not available, you must install the Microsoft ODBC add-in (XLODBC.XLA).

Syntax

SQL.EXEC.QUERY(connection_num, query_text)

Connection_num is the unique connection ID of the data source you want to query.

  • Connection_num is returned by a previously executed SQL.OPEN function.
  • If connection_num is not valid, SQL.EXEC.QUERY returns the #VALUE! error value.

Query_text is the SQL language query that is to be executed on the data source. The query must follow the SQL syntax guidelines in the appendix of the Microsoft Excel ODBC Developers Guide.

  • If SQL.EXEC.QUERY is unable to execute query_text on the specified data source, SQL.EXEC.QUERY returns the #N/A error value.
  • Excel limits strings to a length of 255 characters. If query_text needs to be longer than 255 characters then query_text should be a vertical array or vertical range of cells. The values in the array will be joined together to form the complete SQL query.

Remarks

  • Before calling SQL.EXEC.QUERY a connection must be established with a data source using SQL.OPEN. A successful call to SQL.OPEN returns a unique connection ID number. SQL.EXEC.QUERY uses that connection ID number to send SQL language queries to the data source.
  • Any results generated from the query will not be returned immediately-- SQL.EXEC.QUERY only executes the query. Retrieving results is handled by the functions SQL.RETRIEVE and SQL.RETRIEVE.TO.FILE.
  • If SQL.EXEC.QUERY is called using a previously used connection ID number, all pending results on that connection will automatically be discarded. The connection ID will then refer to the new query and its results.
  • If SQL.EXEC.QUERY is unable to successfully execute the query on the specified data source then an error value will be returned. In such a case SQL.EXEC.QUERY will place error information in memory for the SQL.ERROR function, if such information is available. If SQL.EXEC.QUERY is able to successfully execute the query on the specified connection it will return one of three values depending on the type of SQL statement that was executed.
    • If it was a SELECT statement then SQL.EXEC.QUERY will return the number of result columns available.
    • If it was an UPDATE, INSERT, or DELETE statement then SQL.EXEC.QUERY will return the number of rows affected by the statement.
    • If it was a legal SQL query that is not in one of the categories above, SQL.EXEC.QUERY will return 0 (zero).

Example

SQL.EXEC.QUERY(conn1, "SELECT Custmr_ID, Due_Date FROM Orders WHERE Order_Amt > 100") executes a SQL query from a SQL table named "Orders"

Related Functions

SQL.OPEN Establishes a connection with a data source

SQL.BIND Specifies storage for a result column

SQL.RETRIEVE.TO.FILE Retrieves query results and places them in a file

SQL.RETRIEVE Retrieves query results

SQL.GET.SCHEMA Gets information about a connected data source.

SQL.CLOSE Closes a data source connection

SQL.ERROR Returns detailed error information

List of Command-Equivalent Functions


SQL.GET.SCHEMA

Macro Sheets Only

Returns information about the structure of the data source on a particular connection. The return value from a successful call to SQL.GET.SCHEMA depends on the type of information that was requested. A list of the accepted requests and their respective return values is listed in the syntax section below.

If this function is not available, you must install the Microsoft ODBC add-in (XLODBC.XLA).

Syntax

SQL.GET.SCHEMA(connection_num, type_num, qualifier_text)

Connection_num is the unique connection ID of the data source you want information about.

  • Connection_num is returned by a previously executed SQL.OPEN function.
  • If connection_num is not valid, SQL.GET.SCHEMA returns the #VALUE! error value.

Type_num specifies the type of information you want returned. The following is a list of valid type_num values.

Type_num Returns

1 A list of available data sources, as a vertical array.

2 A list of databases on the current connection, as a vertical array .

3 A list of owners in a database on the current connection, as a vertical array.

4 A list of tables for a given owner and database on the current connection, as a vertical array.

5 A list of columns in a particular table and their data types, as a two-dimensional array. The returned array will have two fields and will have a row for each column in the table. The first field will be the name of the column. The second field is the data type of the column. The data type will be a number that corresponds to the ODBC C header file data types. These #define numbers are found in Microsoft Excel ODBC Developer Guide.

6 User ID of the current user

7 Name of the current database.

8 The name of the data source as given in the ODBC.INI file.

9 The name of the data source DBMS (i.e. Oracle, SQL Server, etc.).

10 The server name for the data source.

11 The terminology used by the data source to refer to owners ( i.e. "owner", "Authorization ID", "Schema", etc.).

12 The terminology used by the data source to refer to tables ( i.e. "table", "file", etc.).

13 The terminology used by the data source to refer to qualifiers (i.e. "database" or "directory").

14 The terminology used by the data source to refer to procedures (i.e. "database procedure", "stored procedure", or "procedure").

Qualifier_text is only included for type_num values of 3, 4 and 5. It is a text string used to qualify the search for the requested information and should be enclosed by quotation marks.

Type_num Qualifier_text

3 The value of qualifier_text should be the name of a database in the current data source. SQL.GET.SCHEMA will then only return the names of table owners in that database.

4 The value of qualifier_text should be both a database name and an owner name. The syntax of qualifier_text is "DatabaseName.OwnerName". A period is used to separate the two names. SQL.GET.SCHEMA will then return an array of table names that are located in the given database and owned by the given owner.

5 The value of qualifier_text should be the name of a table. Information about the columns in that table will be returned.

Remarks

  • If SQL.GET.SCHEMA is unable to find the requested information then it will return the error value #N/A. In such a case SQL.GET.SCHEMA will place error information in memory for the SQL.ERROR function, if such information is available.
  • SQL.GET.SCHEMA works with the ODBC functions SQLGetInfo and SQLTables to find the requested information. Refer to the Microsoft Excel ODBC Programmer Guide for more information on these two functions.

Example

SQL.GET.SCHEMA(conn1,7) returns the name of the current database.

SQL.GET.SCHEMA(conn1,9) returns the name of the DBMS used by the data source.

Related Functions

SQL.OPEN Establishes a connection with a data source

SQL.EXEC.QUERY Sends a query to a data source

SQL.BIND Specifies storage for a result column

SQL.RETRIEVE.TO.FILE Retrieves query results and places them in a file

SQL.RETRIEVE Retrieves query results

SQL.CLOSE Closes a data source connection

SQL.ERROR Returns detailed error information

List of Command-Equivalent Functions


SQL.OPEN

Macro Sheets Only

Establishes a connection with a data source. If the connection is successfully established SQL.OPEN will return a connection ID number. Use the connection ID number with other ODBC macro functions to identify a connection.

If this function is not available, you must install the Microsoft ODBC add-in (XLODBC.XLA).

Syntax

SQL.OPEN(connection_string, output_ref, driver_prompt)

Connection_string is a text string that contains the information necessary to establish a connection to a data source. Any data-source-name that is used in connection_string must be an existing data source name defined with ODBC Setup or the ODBC Administration Utility.

  • Connection_string must follow the format described in Chapter 24, "ODBC Function Reference", of the Microsoft Open Database Connectivity Programmer's Reference for SQLDriverConnect. In this string the user supplies the data source name, one or more user ID's, one or more passwords, and any other information necessary to successfully connect to a DBMS. An example of a SQL.OPEN connection_string entered would be: "DSN=MyServer; UID=dbayer; PWD=123; Database=pubs"
  • Enter the connection_string as an array when the length exceeds 255 characters. Or enter connection_string as an array of cells containing the same information. The connection string should be horizontal array.

Output_ref is a single cell reference where you want the completed connection string to be placed. Use output_ref when you want SQL.OPEN to return the completed connection string. If output_ref is omitted, a completed connection string will not be returned.

Driver_prompt is a number from 1 to 4 specifying if and how you want to be prompted by the driver. This sets the fDriverCompletion flag in ODBC's SQLDriverConnect.

Number Description

1 Always brings up a dialog box.

2 Bring up dialog only if there is not enough information to connect. The driver uses information from the connection string and from the data source specification as defaults.

3 Same as 2, but the driver grays and disables any prompts for information not needed.

4 If the connection string is unsuccessful, do not bring up a dialog box.

Remarks

  • If SQL.OPEN is unable to connect with the information provided then it will return the error value #N/A. In such a case, SQL.OPEN will place error information in memory for the SQL.ERROR function, if more information is available.
  • If the call is successful then SQL.OPEN will return a unique connection ID number that can be used in future function calls to identify the connection.
  • If connection_array does not allow SQL.OPEN to connect to a data source, then the error value #N/A will be returned.

Example

conn1=SQL.OPEN('DSN=NWind;DBQ=C:\MSQUERY;FIL=dBASE4',C15, 2) sets the name conn1 to the return value of SQL.OPEN, which connects to the NWind data source, specifies where to place the connection string, and displays the driver dialog box only if additional informaion is needed.

Related Functions

SQL.EXEC.QUERY Sends a query to a data source

SQL.BIND Specifies storage for a result column

SQL.RETRIEVE.TO.FILE Retrieves query results and places them in a file

SQL.RETRIEVE Retrieves query results

SQL.GET.SCHEMA Gets information about a connected data source.

SQL.CLOSE Closes a data source connection

SQL.ERROR Returns detailed error information

List of Command-Equivalent Functions


SQL.RETRIEVE

Macro Sheets Only

Retrieves all or part of the results from a previously executed query. The connection used must have already been established using the macro function SQL.OPEN. Also, a query must already have been executed using SQL.EXEC.QUERY and results must be pending.

If this function is not available, you must install the Microsoft ODBC add-in (XLODBC.XLA).

Syntax

SQL.RETRIEVE(connection_num, destination_ref, max_columns, max_rows, col_names_logical, row_nums_logical, named_rng_logical, fetch_first_logical)

Connection_num is the unique connection ID for a data source. The data source specified must have pending query results. Pending query results are generated by a call to SQL.EXEC.QUERY on the same connection.

  • If there are no pending results on the connection SQL.RETRIEVE returns the #N/A error value.
  • If connection_num is not valid, SQL.EXEC.QUERY returns the #VALUE! error value.

Destination_ref specifies where the results should be placed. It is either a reference to a single cell or it is omitted.

  • If destination_ref refers to a single cell then SQL.RETRIEVE will return all of the pending results in the cells to the right, below, and including destination_ref. This is the same convention used in Microsoft Excel when multiple cells are pasted into a single-cell selection. Any previous values contained in the destination cells will be overwritten without confirmation.
  • If destination_ref is omitted then the bindings established by previous calls to SQL.BIND will be used to return results. If no such bindings exist for the current connection then SQL.RETRIEVE will return the #REF! error value. If a particular result column has not been bound then its results will be discarded. Max_rows specifies the number of rows that will be returned under each bound column. The first row of results will be placed in the bound cell and any additional rows will be placed in the rows immediately under the bound cell.

Max_columns is the maximum number of columns to be retrieved. It is only used when destination_ref is not omitted.

  • If max_columns specifies more columns than are available in the results, SQL.RETRIEVE will place data in the columns for which data is available and clear the additional columns.
  • If max_columns specifies fewer columns than are available in the results, the rightmost result columns will be discarded to fit the chosen size. Column position will be determined by the order in which the data source returned them.
  • If max_columns is omitted then all of the result columns will be returned.

Max_rows is the maximum number of rows to be returned.

  • If max_rows specifies more rows than are available in the results, SQL.RETRIEVE will place data in the rows for which data is available and clear the additional rows.
  • If max_rows specifies fewer rows than are available in the results, SQL.RETRIEVE will place data in the selected rows but will not discard the additional rows. These extra rows can be retrieved via additional calls to SQL.RETRIEVE. This process is described in the fetch_first_logical argument description.
  • If max_rows is omitted then all rows in the result set will be returned.

Col_names_logical is a logical value which, if TRUE, causes the column names to be returned as the first row of results. It FALSE or omitted, the column names will not be returned.

Row_nums_logical is used only when destination_ref is included. If row_nums_logical is TRUE then the first column in the result set will contain row numbers. If FALSE then row numbers will not be returned. This column of row numbers will not have a column name and the column heading will be left blank. Row numbers can also be retrieved by binding column number 0 with SQL.BIND.

Named_rng_logical is a logical value which, if TRUE, sets each column of results to be declared as a named range on the worksheet. The name of the each range will be the result column name. The named range will only include the rows that were fetched with this SQL.RETRIEVE function call. If FALSE, the results will not be declared as a named range.

Fetch_first_logical is a logical value that allows you to request results from the beginning of the result set.

  • If the first call to SQL.RETRIEVE did not return all of the rows in the result set then SQL.RETRIEVE may be called again to return the next set of rows. This process can be repeated until no more result rows are available, at which time SQL.RETRIEVE will return the value 0 (zero). This will not halt the running of the macro. During each of these calls, including the first call, fetch_first_logical should be set to FALSE.
  • If you want to move the cursor back to the beginning of the result set then fetch_first_logical should be set to TRUE. This causes the same SQL query text to be executed again on the data source. The cursor will then be positioned at the top of the result set and SQL.RETRIEVE will fill destination_ref beginning with the first row of results. Further calls to SQL.RETRIEVE, for the purpose of retrieving additional rows, can then be made with fetch_first_logical set to FALSE .

Remarks

  • Before calling SQL.RETRIEVE a connection must be established with a data source using SQL.OPEN.
  • If SQL.RETRIEVE is unable to retrieve the results on the specified data source then an error value will be returned. In such a case SQL.RETRIEVE will place error information in memory for the SQL.ERROR function, if such information is available.
  • If SQL.RETRIEVE is able to successfully return rows of results on the specified connection it will return the number of rows that were actually returned. If there were no results pending on the connection then SQL.RETRIEVE will return the #N/A error value.If no data was found then SQL.RETRIEVE returns 0 (zero).
  • A successful call to SQL.OPEN returns a unique connection ID number, which is used in a call to SQL.EXEC.QUERY to send a SQL language query. Following this call to SQL.EXEC.QUERY, SQL.RETRIEVE uses the same connection ID number to retrieve query results.

Example

SQL.RETRIEVE(conn1,sheet1!C1,1) stores data obtained from the data source conn1 on Sheet1 from left to right in cell C1, using only column 1.

Related Functions

SQL.OPEN Establishes a connection with a data source

SQL.EXEC.QUERY Sends a query to a data source

SQL.BIND Specifies storage for a result column

SQL.RETRIEVE.TO.FILE Retrieves query results and places them in a file

SQL.GET.SCHEMA Gets information about a connected data source.

SQL.CLOSE Close a data source connection

SQL.ERROR Returns detailed error information

List of Command-Equivalent Functions


SQL.RETRIEVE.TO.FILE

Macro Sheets Only

Retrieves all of the results from a previously executed query and places them in a file. The connection used must have already been established using the macro function SQL.OPEN. Also, a query must already have been executed using SQL.EXEC.QUERY and results must be pending.

If this function is not available, you must install the Microsoft ODBC add-in (XLODBC.XLA).

Syntax

SQL.RETRIEVE.TO.FILE(connection_num, destination, col_names_logical, column_delimiter)

Connection_num is the unique connection ID for a data source. The data source specified must have query results pending. Pending results were generated by a previous call to SQL.EXEC.QUERY on the same connection.

  • If there are no pending results on the connection SQL.RETRIEVE.TO.FILE returns the #N/A error value. The file is not affected.
  • If connection_num is not valid, SQL.RETRIEVE.TO.FILE returns the #VALUE! error value.

Destination specifies the name and path of the file where the results should be placed. SQL.RETRIEVE.TO.FILE will open the specified file and fill it with the entire result set.

  • The format of the data in the file will be compatible with the Microsoft Excel ".CSV" format. The overall format will be that columns will be separated by the value in column_delimiter (see below) and the individual rows will be separated by a linefeed/carriage-return.
  • If the file specified by destination cannot be opened then the error value #N/A will be returned by SQL.RETRIEVE.TO.FILE.
  • If the file already exists its previous contents will be overwritten by SQL.RETRIEVE.TO.FILE.

Col_names_logical is a logical value that, if TRUE, allows the column names to be returned as the first row of data. If FALSE or omitted, the column names will not be returned.

Column_delimiter is the value that will be used to separate the elements in each row. If column_delimiter is omitted then a tab will be used. If another value is desired then it should be enclosed in quotation marks. Possible values for column_delimiter might be: "," or ";" or " ". The string "tab" can also be used to specify a tab separator (even though this is redundant, since a tab is the default).

Remarks

  • If SQL.RETRIEVE.TO.FILE is unable to retrieve the results on the specified connection then an error value will be returned. In such a case SQL.RETRIEVE.TO.FILE will place error information in memory for the SQL.ERROR function, if such information is available.
  • If SQL.RETRIEVE.TO.FILE is able to successfully return rows of results on the specified connection and place them in a file it will return the number of rows that were actually written to the file. If there were no results pending on the connection then SQL.RETRIEVE.TO.FILE will return the #N/A error value and the file will not be created or modified.
  • Before calling SQL.RETRIEVE.TO.FILE a connection must be established with a data source using SQL.OPEN.
  • A successful call to SQL.OPEN returns a unique connection ID number, which can be used in a call to SQL.EXEC.QUERY to send a SQL language query. Following this call to SQL.EXEC.QUERY, SQL.RETRIEVE.TO.FILE uses the same connection ID number to retrieve query results and place them in a file.

Example

SQL.RETRIEVE.TO.FILE(conn1,"C:\MSQUERY\RESULTS1.QRY",TRUE,",") retrieves the results of a previously executed query and places them in the file RESULTS1.QRY, with column names that are comma deliminated.

Related Functions

SQL.OPEN Establishes a connection with a data source

SQL.EXEC.QUERY Sends a query to a data source

SQL.BIND Specifies storage for a result column

SQL.RETRIEVE Retrieves query results

SQL.GET.SCHEMA Gets information about a connected data source.

SQL.CLOSE Closes a data source connection

SQL.ERROR Returns detailed errorinformation

List of Command-Equivalent Functions


SUBTOTAL.CREATE

Equivalent to choosing the Subtotals command from the Data menu. Generates a subtotal in a list or database.

Syntax

SUBTOTAL.CREATE(at_change_in, function_num, total, replace, pagebreaks, summary_below)
SUBTOTAL.CREATE?(at_change_in, function_num, total, replace, pagebreaks, summary_below)

At_change_in is a column offset corresponding to the At Each Change In text box on the Subtotal dialog box.

Function_Num is a number corresponding to the Use Function list box specifying which function you want to use in subtotaling your data.

Function Function_Num

SUM 1

COUNTA 2

AVERAGE 3

MAX 4

MIN 5

PRODUCT 6

COUNT 7

STDEV 8

STDEVP 9

VAR 10

VARP 11

Total is an Array of column offsets corresponding to the Add Subtotal To list box. Indicates which columns you want aggregated according to function_num; for example, {4,5}

Replace is a logical value which, if TRUE, causes any previous subtotals to be replaced by new subtotals. If FALSE or omitted, subtotals will not be replaced.

PageBreaks is a logical value corresponding to the Page Break Between Groups check box which, if TRUE, creates a page break below each subtotal. If FALSE or omitted, does not create a page break below each subtotal.

Summary_Below is a logical value corresponding to the Summary Below Data check box which, if TRUE, places subtotal rows below the data they refer to, and a grand total at the bottom of the list. If FALSE, places subtotal rows above the data they refer to, and a grand total just below the header.

Related Functions

SUBTOTAL.REMOVE Removes all previously existing subtotals and grand totals in a list

List of Command-Equivalent Functions


SUBTOTAL.REMOVE

Equivalent to choosing the Subtotal command from the Data menu, and then selecting the Remove All button in the Subtotal dialog box. Removes all previously existing subtotals and grand totals in a list. Any page breaks and outlines will also be removed.

Syntax

SUBTOTAL.REMOVE()

Related Functions

SUBTOTAL.CREATE Generates a subtotal in a list or database

List of Command-Equivalent Functions


SUMMARY.INFO

Equivalent to choosing the Summary Info command from the File menu. Generates the summary information for the active workbook.

Syntax

SUMMARY.INFO(title, subject, author, keywords, comments)
SUMMARY.INFO?(title, subject, author, keywords, comments)

The arguments correspond to the text boxes in the Summary Info dialog boxes. If any arguments are omitted, that text box is left empty.

Title specifies a title for the file, not necessarily a file name. Long names can be entered, up to 255 characters.

Subject is information pertaining to the subject matter of the workbook.

Author is initially the name specified in the General tab of the Options dialog box, which appears from the Options command from the Tools menu. If this is omitted, the registered user of the copy of Microsoft Excel will be used.

Keywords are keywords that can be later used in searching for the contents in the file.

Comments is a comment that can be entered to help a user learn more about the contents or subject matter of the workbook.

Related Functions

FIND.FILE Lets you search for files based on criteria such as author or creation date

GET.WORKBOOK Returns information about a workbook document

List of Command-Equivalent Functions


TEXT.TO.COLUMNS

Equivalent to choosing the Text To Columns command from the Data menu when a column of data is to be separated into multiple columns. Parses text into columns of data.

Syntax

TEXT.TO.COLUMNS(destination_ref, data_type, text_delim, consecutive_delim, tab, semicolon, comma, space, other, other_char, field_info)

The following arguments correspond to check boxes, option buttons and text buttons in the Text To Columns Wizard, which is started with the Text To Columns command on the Data menu.

Destination_Ref is a single cell reference to specifies where to place the converted text.

Data_Type is a number specifying whether that data is delimited (1) or fixed width (2)

Text_Delim denotes how text strings are represented, and can be one of the following values:

Number Text_Delim

1 "

2 '

3 none

Consecutive_delim is a logical value corresponding to the Treat Consecutive Delimiters as One check box which, if TRUE, allows consective delimiters (such as ",,,") to be treated as a single delimiter. If FALSE, all consecutive delimiters are considered separate column breaks.

Tab is a logical value which, if TRUE, specifies that the column has tab delimiters. If FALSE, the column does not have tab delimiters. Tab is ignored if data_type is 2.

Semicolon is a logical value which, if TRUE, specifies that the column has semicolon delimiters. If FALSE, the column does not have semicolon delimiters. Semicolon is ignored if data_type is 2.

Comma is a logical value which, if TRUE, specifies that the column has comma delimiters. If FALSE, the column does not have comma delimiters. Comma is ignored if data_type is 2.

Space is a logical value which, if TRUE, specifies that the column has space delimiters. If FALSE, the column does not have space delimiters. Space is ignored if data_type is 2.

Other is a logical value which, if TRUE, specifies that the column has custom delimiters. If FALSE, the column does not have custom delimiters. Other is ignored if data_type is 2.

Other_Char is a single character that specifies a delimiter not included in the list of delimiters. Other_Char is ignored if data_type is 2 and if the argument other is FALSE.

Field_Info is an array which consists of the following elements: "column number, data_format", if data_type is 1; or "start_pos, data_format" if data_type is 2. The second number defines the column's data format, and can be one of the following.

2nd Number Data Format

1 General

2 Text

3 Date, in the form MDY

4 Date, in the form DMY

5 Date, in the form YMD

6 Date, in the form MYD

7 Date, in the form DYM

8 Date, in the form YDM

9 Do not import column (skip)

Related Functions

List of Command-Equivalent Functions


TRACER.CLEAR

Macro Sheets Only

Equivalent to clicking the Remove All Arrows button on the Auditing toolbar on a worksheet. Clears all tracer arrows on the worksheet.

Syntax

TRACER.CLEAR()

Remark

Returns the #VALUE! error value if not available; for example, the selection is something other than worksheet.

Related Functions

TRACER.DISPLAY Allows tracer arrow to be displayed showing relationship among cells

List of Command-Equivalent Functions


TRACER.DISPLAY

Macro Sheets Only

Equivalent to clicking the Trace Precedents or Trace Dependents buttons on the Auditing toolbar on a worksheet. Allows tracer arrow to be graphically displayed showing relationship among cells.

Syntax

TRACER.DISPLAY(direction, create)

Direction is logical value which, if TRUE, displays tracer arrows for precedents. If FALSE tracer arrows for dependents are displayed.

Create is a logical value which, if TRUE displays the next level of tracer arrows in the direction specified by direction. If FALSE, removes the current level of tracer arrows in the direction specified by direction. A level is the number of "arrows" away from the source cell.

Remark

Returns the #VALUE! error value if not available; for example, the selection is something other than a worksheet, or the cell(s) cannot be traced.

Related Functions

TRACER.CLEAR Clears all tracer arrows on the worksheet

List of Command-Equivalent Functions


TRACER.ERROR

Macro Sheets Only

Equivalent to clicking the Tracer Error button on the Auditing toolbar on a worksheet. Allow tracer arrows to be graphically displayed showing which cells are generating an error value.

Syntax

TRACER.ERROR()

Returns TRUE if Microsoft Excel successfully found the cell at which the error occurred. Returns FALSE if an error is not found.

Remark

  • Returns the #VALUE! error value if not available; for example, the selection is something other than worksheet, or cell(s) that cannot be traced.
  • If you need to know if there is an error in a cell, use ISERROR().

Related Functions

TRACER.DISPLAY Allows tracer arrow to be displayed

TRACER.CLEAR Clears all tracer arrows on the worksheet

List of Command-Equivalent Functions


TRACER.NAVIGATE

Macro Sheets Only

Equivalent to double-clicking on a displayed tracer arrow. Moves the selection from one end of a tracer arrow to the other. If it is an error tracer arrow, then the selection goes to the end of the branch.

Syntax

TRACER.NAVIGATE(direction, arrow_num, ref_num)

Direction is a logical value which, if TRUE, moves the selection to the arrow endpoint in the precedents direction. If FALSE, moves the selection to the arrow endpoint in the dependents direction.

Arrow_num is a number specifying which reference a tracer arrow will follow. For example, a 1 indicates that the arrow will follow the first reference in the formula. 1 is the default.

Ref_num If the arrow is an external reference arrow with multiple links, this argument tells which of the links to follow. Refer to the Links dialog, which is displayed with the Links command from the Edit menu. If ref_num is 1, the link in the first reference in the Links dialog box wll be followed. The default is 1.

Remarks

  • Returns TRUE if successful. Returns FALSE if arrow_num exceeds the number of tracer arrows or if there are no tracer arrows.
  • Returns FALSE if ref_num exceeds the number of links.
  • Returns the #VALUE! error value if not available; for example, if the selection is something other than a worksheet, or the active cell does not contain an arrow.

Related Functions

TRACER.DISPLAY Allows tracer arrow to be displayed showing which cells formulas in other cells depend on

List of Command-Equivalent Functions


UNHIDE

Macro Sheets Only

Equivalent to choosing the Unhide command from the Window menu. Use UNHIDE to display hidden windows.

Syntax

UNHIDE(window_text)

Window_text is the name of the window to unhide. If window_text is not the name of an open workbook, an error value is returned and the macro is interrupted. You cannot unhide a window of an add-in workbook.

Tip You can use UNHIDE to activate an embedded chart in order to edit and format it. Use the HIDE function to de-activate the chart window.

Related Functions

GET.WINDOW Returns information about a window

HIDE Hides the active window

List of Command-Equivalent Functions


UPDATE.LINK

Macro Sheets Only

Equivalent to choosing the Links command from the Edit menu and choosing the Update Now button with a link selected in the Links dialog box. Updates a link to another document. Use UPDATE.LINK to get the newest information from a supporting document.

Syntax

UPDATE.LINK(link_text, type_of_link)

Link_text is a text string describing the full path of the link as displayed in the Links dialog box. If link_text is omitted, only links from the active workbook to other Microsoft Excel workbooks are updated.

Type_of_link is a number from 1 to 4 that specifies the type of link to update.

Type_of_link Link document type

1 or omitted Microsoft Excel link

2 DDE link

3 Not available

4 Not available

Related Functions

CHANGE.LINK Changes supporting links

GET.LINK.INFO Returns information about a link

OPEN.LINKS Opens specified supporting documents

List of Command-Equivalent Functions


WORKBOOK.ACTIVATE

Macro Sheets Only

Equivalent to activating a worksheet by clicking on its tab.

Syntax

WORKBOOK.ACTIVATE(sheet_name)

Sheet_name is the name of the document you want to activate within the active workbook.

Related Function

WORKBOOK.SELECT Selects one or more sheets for group editing

WORKBOOK.OPTIONS Changes the settings of a workbook document

List of Command-Equivalent Functions


WORKBOOK.ADD

Macro Sheets Only

Equivalent to choosing the Add button on the workbook contents window in Microsoft Excel version 4. Moves a sheet between workbooks. For Microsoft Excel version 5.0 or later use WORKBOOK.MOVE.

Syntax

WORKBOOK.ADD(name_array, dest_book, position_num)
WORKBOOK.ADD?(name_array, dest_book, position_num)

Name_array is the name of a sheet, or an array of names of sheets, that you want to move.

Dest_book is the name of the workbook to which you want to add name_array. If dest_book is omitted, it is assumed to be the active workbook.

Position_num is a number that specifies the position of the document within the workbook.

Related Function

WORKBOOK.MOVE Moves one or more sheets between workbooks or changes a sheet's position within a workbook

WORKBOOK.COPY Copies one or more documents from their current workbook to another workbook

List of Command-Equivalent Functions


WORKBOOK.COPY

Macro Sheets Only

Equivalent to choosing the Move or Copy Sheet command from the Edit menu. Copies one or more sheets from their current positions to the specified position in the same workbook or to another workbook.

Syntax

WORKBOOK.COPY(name_array, dest_book, position_num)
WORKBOOK.COPY?(name_array, dest_book, position_num)

Name_array is the name of a sheet, or an array of names of sheets, that you want to copy in the currently active workbook.

Dest_book is the name of the workbook to which you want to copy name_array. If dest_book is the current workbook, name_array is copied within the workbook. If dest_book is omitted, the copy of name_array becomes a separate workbook.

Position_num is a number that specifies the target position for the sheet within the new workbook. The first position is 1.

  • If position_num is specified, Microsoft Excel inserts the copy of the sheet at the specified position in the workbook.
  • If position_num is omitted, Microsoft Excel places the sheet at the last position in the workbook.
  • If dest_book is omitted, position_num is ignored.

Remarks

  • If the structure of the workbook is protected, you cannot copy sheets within the workbook or to another workbook.
  • You cannot copy a hidden sheet.

Related Function

WORKBOOK.MOVE Moves one or more documents from one workbook to another workbook or to another position in the same workbook

List of Command-Equivalent Functions


WORKBOOK.DELETE

Macro Sheets Only

Equivalent to choosing the Delete Sheet command from the Edit menu. Deletes a sheet or group of sheets from the current workbook.

Syntax

WORKBOOK.DELETE(sheet_text)

Sheet_text is the name of the sheet to delete. If omitted, the currently active sheet or sheets is deleted.

Remarks

  • This function prompts for confirmation. To suppress the prompt, use the ERROR function. For example, =ERROR(FALSE).
  • If the structure of the workbook is protected, you cannot delete any of its sheets.
  • If you want to delete Sheet1:Sheet10, you must select them first with WORKBOOK.SELECT(). You can also place the sheets in an array first, as in {"Sheet1", "Sheet2", "Sheet3",...}.
  • You cannot delete the last visible sheet in a workbook.

Related Functions

List of Command-Equivalent Functions


WORKBOOK.HIDE

Macro Sheets Only

Equivalent to choosing Sheet command from the Format menu, and then choosing Hide from the Sheet submenu. Hides sheets in the active workbook.

Syntax

WORKBOOK.HIDE(sheet_text, very_hidden)

Sheet_text is the name of the sheet to hide. If omitted, the currently selected sheet(s) are hidden.

Very_hidden specifies how the sheet is hidden. If TRUE, then the sheet name does not appear in the Unhide dialog box. After using this argument, use WORKBOOK.UNHIDE to unhide the sheet. If FALSE or omitted, hides the sheet but does not prevent the sheet's name from appearing in the Unhide dialog box.

Remarks

  • If the structure of the workbook is protected, you cannot hide any sheets in the workbook.
  • You cannot hide the last visible sheet in a workbook.
  • To hide Sheet1:Sheet10, select them first with the WORKBOOK.SELECT function. You can also place the sheets in an array first, as in {"Sheet1", "Sheet2", "Sheet3",...}.

Related Function

List of Command-Equivalent Functions


WORKBOOK.INSERT

Macro Sheets Only

Equivalent to choosing the Worksheet, Chart, or Macro commands from the Insert menu. Inserts one or more new sheets into the current workbook.

Syntax

WORKBOOK.INSERT(type_num)
WORKBOOK.INSERT?(type_num)

Type_num specifies the type of sheet to insert.

Type_num Type of sheet

1 Worksheet

2 Chart

3 Excel 4 Macro Sheet

4 Excel 4 International Macro Sheet

5 (Reserved)

6 Microsoft Excel Visual Basic Module

7 Dialog

quoted text Template

If omitted, the type of the active sheet is used.

If the current selection contains one sheet, then only one sheet is inserted. If the selection contains more than one sheet and the active sheet is a worksheet, then an equal number of sheets is inserted to the left of the selected group of sheets.

Remarks

The new sheets are always inserted to the left of the current selection.

If the workbook structure is protected, you cannot insert new sheets.

Related Function

List of Command-Equivalent Functions


WORKBOOK.MOVE

Macro Sheets Only

Equivalent to choosing the Move or Copy Sheet command from the Edit menu. Moves one or more sheets between workbooks or changes a sheet's position within a workbook.

Syntax

WORKBOOK.MOVE(name_array, dest_book, position_num)
WORKBOOK.MOVE?(name_array, dest_book, position_num)

Name_array is the name of a sheet, or an array of names of sheets, that you want to move.

Dest_book is the name of the workbook to which you want to move name_array. If dest_book is omitted, WORKBOOK.MOVE moves the sheet out of the workbook and puts it in a new separate workbook. If dest_book is the same as the current book, then the sheet is moved within the workbook.

Position_num is a number that specifies the target position for the sheet within dest_book. The first position is 1.

  • If position_num is specified, Microsoft Excel inserts the sheet at the specified position in the workbook.
  • If position_num is omitted, Microsoft Excel moves the sheet to the last position in the workbook.
  • If you move the last sheet out of a workbook, the workbook closes.

Related Functions

WORKBOOK.COPY Copies one or more documents from their current workbook into another workbook

List of Command-Equivalent Functions


WORKBOOK.NAME

Macro Sheets Only

Equivalent to choosing the Rename command on the Sheet submenu from the Format menu. Renames a sheet in a workbook.

Syntax

WORKBOOK.NAME(oldname_text, newname_text)
WORKBOOK.NAME?(oldname_text, newname_text)

Oldname_text is the name of the sheet that you want to rename.

Newname_text is the new name of the sheet.

Remarks

  • If you try to rename a sheet using a sheet name that already exists in the workbook, Microsoft Excel displays an error message and interrupts the macro.
  • If the structure of the workbook is protected, you cannot rename any of the sheets in the workbook.

Related Function

List of Command-Equivalent Functions


WORKBOOK.NEW

Macro Sheets Only

Adds a sheet to a workbook. This function is for compatibility with Microsoft Excel version 4.0. To add a new sheet to a workbook in Microsoft Excel version 5, use the WORKBOOK.INSERT function.

Syntax

WORKBOOK.NEW()
WORKBOOK.NEW?()

In both forms of this function, you will be prompted for the name of the workbooks.

Related Function

WORKBOOK.INSERT Adds sheets to workbooks

List of Command-Equivalent Functions


WORKBOOK.NEXT

Macro Sheets Only

Activates the next sheet in the active workbook.

Syntax

WORKBOOK.NEXT()

Remarks

If the last sheet in the workbook is active, this function has no effect.

This function skips over hidden sheets in the workbook.

Related Functions

List of Command-Equivalent Functions


WORKBOOK.OPTIONS

Macro Sheets Only

Equivalent to selecting the Options button in a workbook contents window in Microsoft Excel version 4. This function is for compatibility with Microsoft Excel version 4. To change the name of a sheet in Microsoft Excel version 5, use the WORKBOOK.NAME function.

Syntax

WORKBOOK.OPTIONS(sheet_name, bound_logical, new_name)

Sheet_name is the name of a sheet.

Bound_logical is for compatibility with Microsoft Excel version 4. In Microsoft Excel version 5, returns an error if FALSE.

New_name is the sheet name to assign to sheet_name. If new_name is omitted, then the sheet name is not changed.

Related Functions

GET.WORKBOOK Returns information about a workbook document

WORKBOOK.NAME Changes the name of a sheet in a workbook

WORKBOOK.SELECT Selects the specified documents in a workbook

List of Command-Equivalent Functions


WORKBOOK.PREV

Macro Sheets Only

Activates the previous sheet in the workbook.

Syntax

WORKBOOK.PREV()

Remarks

If the first sheet in the workbook is active, this function has no effect.

This function skips over hidden sheets in the workbook.

Related Functions

List of Command-Equivalent Functions


WORKBOOK.PROTECT

Equivalent to choosing the Protect Workbook command from the Protection submenu on the Tools menu. Controls protection of workbooks.

Syntax

WORKBOOK.PROTECT(structure, windows, password)
WORKBOOK.PROTECT?(structure, windows, password)

Structure specifies whether the structure of the workbook is protected. If TRUE, the structure is protected. If FALSE or omitted, the structure is not protected.

Windows specifes whether the windows of the workbook are protected. If TRUE, the windows are protected. If FALSE or omitted, the windows are not protected.

Password specifies whether to protect the workbook with a password. If omitted no password is used. When recording a macro, this argument is not recorded. In the dialog box form of this function, you can specify a password.

Remarks

To protect a sheet in a workbook, use the PROTECT.DOCUMENT function.

Related Functions

PROTECT.DOCUMENT Protects a sheet in a workbook

List of Command-Equivalent Functions


WORKBOOK.SCROLL

Macro Sheets Only

Scrolls through the sheets in a workbook.

Syntax

WORKBOOK.SCROLL(num_sheets, firstlast_logical)

Num_sheets. is a number specifying how many sheets to scroll and the direction of scrolling. Positive numbers scroll forward by that many sheets. Negative numbers scroll backward by that many sheets. Zero (0) does not scroll.

Firstlast_logical specifies whether to scroll to the first or last sheet in the workbook. If TRUE, scrolls to the last sheet in the workbook. If FALSE, scrolls to the first sheet in the workbook. If this argument is specified, then num_sheets is ignored.

Related Functions

List of Command-Equivalent Functions


WORKBOOK.SELECT

Macro Sheets Only

Equivalent to selecting a sheet or group of sheets in the active workbook. If you select a group of sheets, subsequent commands effect all the sheets in the group.

Syntax

WORKBOOK.SELECT(name_array, active_name, replace)

Name_array is a horizontal array of text names of sheets you want to select. If name_array is omitted, no sheets are selected.

Active_name is the name of a single sheet in the workbook that you want to be the active sheet. If active_name is omitted, the first sheet in name_array is made the active sheet.

Replace specifies whether the currrently selected sheets or macrosheets are to be replaced by name_array. If TRUE or omitted, then the current sheet selection is replaced by name_array. If FALSE, then name_array will be appended to the current sheet.

Related Functions

GET.WORKBOOK Returns information about a workbook

SELECT Selects a cell, worksheet object, or chart item

List of Command-Equivalent Functions


WORKBOOK.TAB.SPLIT

Macro Sheets Only

Sets the ratio of the tabs to the horizontal scrollbar.

Syntax

WORKBOOK.TAB.SPLIT(ratio_num)

Ratio_num is the ratio of tabs to horizontal scroll, as a decimal value between 0 and 1. If omitted defaults to .6.

Remarks

  • If the structure of the workbook is protected, you cannot use this function.
  • Use GET.WINDOW(28) to find out what the current ratio is.

Related Functions

GET.WINDOW Returns information about a

List of Command-Equivalent Functions


WORKBOOK.UNHIDE

Macro Sheets Only

Equivalent to choosing the Unhide command from the sheet submenu on the Format menu. Unhides one or more sheets in the current workbook.

Syntax

WORKBOOK.UNHIDE(sheet_text)
WORKBOOK.UNHIDE?(sheet_text)

Sheet_text. specifies the sheet that you want to unhide. If sheet_text is omitted, then this function unhides the sheets in the order that they would appear in the workbook.

Remarks

  • If the workbook is protected, you cannot unhide any sheets in the book.

Related Functions

WORKBOOK.HIDE Hides sheets in the active workbook

List of Command-Equivalent Functions


WORKGROUP

Macro Sheets Only

Equivalent to choosing the Group Edit command from the Options menu in Microsoft Excel version 4. Creates a group. This function is provided for compatibility only. In Microsoft Excel version 5, you can create a group by using the WORKBOOK.SELECT function.

Syntax

WORKGROUP(name_array)
WORKGROUP?(name_array)

Name_array is the list of workbooks or sheets in workbooks that you want grouped.

  • If name_array is omitted, the most recently created group is recreated.
  • If no group has been created during the current Microsoft Excel session, all open, unhidden worksheets are created as a group.
  • If you specify just the name of a workbook, WORKGROUP adds the first sheet of the workbook to the group.

Remarks

WORKGROUP returns the #VALUE! error value and interrupts the macro if it can't find any of the sheets in name_array or if any of the sheets is a chart or module.

Related Functions

FILL.GROUP Fills the contents of the active worksheet's selection to the same area on all other worksheets in the group

WORKBOOK.SELECT Selects one or more sheets in a workbook

List of Command-Equivalent Functions


WORKSPACE

Macro Sheets Only

Changes the workspace settings for a workbook. This function is provide for compatibility with Microsoft Excel version 4.0 only. In Microsoft Excel version 5, you can change workbook settings with OPTIONS.GENERAL function.

Syntax

WORKSPACE(fixed, decimals, r1c1, scroll, status, formula, menu_key, remote, entermove, underlines, tools, notes, nav_keys, menu_key_action, drag_drop, show_info)
WORKSPACE?(fixed, decimals, r1c1, scroll, status, formula, menu_key, remote, entermove, underlines, tools, notes, nav_keys, menu_key_action, drag_drop, show_info)

Arguments correspond to check boxes and text boxes in the Workspace dialog box. Arguments corresponding to check boxes are logical values. If an argument is TRUE, the check box is selected; if FALSE, the check box is cleared; if omitted, the current setting is not changed.

Fixed corresponds to the Fixed Decimal check box.

Decimals specifies the number of decimal places. Decimals is ignored if fixed is FALSE or omitted.

R1c1 corresponds to the R1C1 check box.

Scroll corresponds to the Scroll Bars check box.

Status corresponds to the Status Bar check box.

Formula corresponds to the Formula Bar check box.

Menu_key is a text value indicating an alternate menu key, and corresponds to the Alternate Menu Or Help Key box.

Remote corresponds to the Ignore Remote Requests check box.

Important Microsoft Excel for the Macintosh requires system software version 7.0 or later for this argument.

Entermove corresponds to the Move Selection After Enter/Return check box.

Underlines is a number corresponding to the Command Underline options as shown in the following table.

Note This argument is only available in Microsoft Excel for the Macintosh.

If underlines is Command underlines are

1 On

2 Off

3 Automatic

Tools is a logical value. If TRUE, the Standard toolbar is displayed; if FALSE, all visible toolbars are hidden. If omitted, the current toolbar display is not changed.

Notes corresponds to the Note Indicator check box.

Nav_keys corresponds to the Alternate Navigation Keys check box. In Microsoft Excel for the Macintosh, nav_keys is ignored.

Menu_key_action is the number 1 or 2 specifying options for the alternate menu or Help key. In Microsoft Excel for the Macintosh, menu_key_action is ignored.

Menu_key_action Alternate menu or Help key activates

1 or omitted Microsoft Excel menus

2 Lotus 1-2-3 Help

Drag_drop corresponds to the Cell Drag And Drop check box.

Show_info corresponds to the Info Window check box.

Related Function

GET.WORKSPACE Returns information about the workspace

List of Command-Equivalent Functions


ADD.LIST.ITEM

Macro Sheets Only

Adds an item in a list box or drop-down control on a worksheet or dialog sheet control.

Syntax

ADD.LIST.ITEM(text, index_num)

Text specifies the text of the item to be added. Instead of text, an empty string may be inserted.

Index_num is the list index to be used for the new item. Blank entries are created from the end of the current list to the new item index. If index_num is omitted the new item is appended to the list.

Remarks

If the list box or drop-down box was already filled using the LISTBOX.PROPERTIES function, then adding an item with ADD.LIST.ITEM causes the fillrange contents to be discarded in favor of the new list.

Related Functions

REMOVE.LIST.ITEM Removes an item in a list box or drop-down box

SELECT.LIST.ITEM Selects an item in a list box or in a group box

List of Customizing Functions


CHECKBOX.PROPERTIES

Macro Sheets Only

Equivalent to choosing the Object command from the Format menu when a check box or option button control is selected on a worksheet or dialog sheet. Sets various properties of check box and option box controls.

Syntax

CHECKBOX.PROPERTIES(value, link, accel_text, 3d_shading, accel_text2)
CHECKBOX.PROPERTIES?(value, link, accel_text, 3d_shading, accel_text2,)

Value is the value of the check box or option button setting that determines whether it is selected or not.

Value Box or Button Setting

0 or FALSE Off

1 or TRUE On

2 Mixed

Link is the cell on the sheet to which the check box or option button value is linked. Whenever one of these two controls is changed, the value of the control is entered into the cell. Similarly, whenever the value in the cell is changed, the setting for the corresponding check box or option button is also changed. To clear the link, set this value to an empty string. For example, entering "TRUE" into a cell linked to a check box will select that check box.

3d_shading is a logical value that specifies whether the check box appears as 3-D. If TRUE, the check box will appear as 3-D. If FALSE or omitted, the check box will not be 3-D. This argument is available for only worksheets.

Accel_text is a text string containing the character to use as the control's accelerator key on a dialog sheet. The character is matched against the text of the control, and the first matching character is underlined. When the user presses ALT+accel_text in Microsoft Excel for Windows or COMMAND+accel_text in Microsoft Excel for the Macintosh, the control is clicked.

Accel_text2 is a text string containing the second accelerator key on a dialog sheet. This argument is for only Far East versions of Microsoft Excel.

Remarks

Only controls on dialog sheets can have accelerator keys. Worksheet controls cannot have accelerator keys.

Related Functions

PUSHBUTTON.PROPERTIES Sets the properties of the push button control

EDITBOX.PROPERTIES Sets the properties of an edit box on a worksheet or dialog sheet

LABEL.PROPERTIES Sets the accelerator property of the label and group box control

LISTBOX.PROPERTIES Sets the properties of a list box and drop-down box controls on a worksheet or dialog sheet

List of Customizing Functions


EDITBOX.PROPERTIES

Macro Sheets Only

Equivalent to choosing the Object command from the Format menu when an edit box is selected. Sets the properties of an edit box on a dialog sheet.

Syntax

EDITBOX.PROPERTIES(validation_num, multiline_logical, vscroll_logical, password_logical)
EDITBOX.PROPERTIES?(validation_num, multiline_logical, vscroll_logical, password_logical)

Validation_num is the validation applied to the edit box when the dialog is dismissed. If the edit box contains a value other than the type specified (or validation), an error is returned.

Validation_num Type

1 Text

2 Integer

3 Number (allows floating point)

4 Reference

5 Formula

Multiline_logical is a logical value specifying whether word wrapping is allowed in the edit box control. If TRUE, word wrapping is allowed. If FALSE, word wrapping is not allowed

Vscroll_logical is a logical value specifying whether edit box displays a vertical scrollbar. If TRUE, a scrollbar is displayed. If FALSE, a scrollbar is not displayed.

Password_logical is a logical value specifying whether edit box displays characters as the user types. If TRUE, asterisks are displayed as the user types.

Related Functions

CHECKBOX.PROPERTIES Sets various properties of check box and option box controls

PUSHBUTTON.PROPERTIES Sets the properties of the push button control

List of Customizing Functions


ENABLE.OBJECT

Macro Sheets Only

Enables or disables a drawing object or the selected drawing object. A disabled object will not run any macro events assigned to it, and the controls will be grayed out.

Syntax

ENABLE.OBJECT(object_id_text, enable_logical)

Object_id_text is the name of the object(s) as text. If omitted, the selected object(s) are assumed.

Enable_logical is a logical value that specifies whether the object is to be enabled. If TRUE, the object is enabled. If FALSE, the object is disabled.

Examples

ENABLE.OBJECT("Button 2",FALSE) disables the button with object name Button 2 on the dialog box.

Related Functions

SET.CONTROL.VALUE Changes the value of the active control

List of Customizing Functions


HIDE.DIALOG

Macro Sheets Only

Closes the dialog box that has the current focus.

Syntax

HIDE.DIALOG(cancel_logical)

Cancel_logical is a logical value that specifies whether to close the dialog box and validate any edit boxes. If FALSE, the dialog box is closed and edit boxes are validated, or checked to determine if they contain a valid data type. If TRUE, the dialog box is closed and the edit boxes are not validated.

Remarks

If the edit box does not contain a valid data type when the dialog box is closed, the dialog will remain open. For example, if the edit box is supposed to contain integer values, and a text value is entered, the dialog box will not close. This applies to only those dialog boxes that must be closed before any further user action can happen.

Examples

HIDE.DIALOG(FALSE) closes the dialog box and checks to see if the edit box contains a valid data type (validated)

Related Functions

EDITBOX.PROPERTIES Sets the properties of an edit box on a worksheet or dialog sheet

SHOW.DIALOG Runs a dialog on a dialog sheet

List of Customizing Functions


LABEL.PROPERTIES

Macro Sheets Only

Equivalent to choosing the Object command from the Format menu when a label control is selected on a worksheet or dialog sheet. Sets the accelerator property of the label and group box controls.

Syntax

LABEL.PROPERTIES(accel_text, accel_text2, 3d_shading)
LABEL.PROPERTIES?(accel_text, accel_text2, 3d_shading)

Accel_text is a text string containing the character to use as the label's accelerator key on a dialog sheet. The character is matched against the text of the control, and the first matching character is underlined. When the user presses ALT+accel_text in Microsoft Excel for Windows or COMMAND+accel_text in Microsoft Excel for the Macintosh, the control is clicked. This argument is ignored for controls on worksheets.

Accel_text2 is a text string containing the second accelerator key on a dialog sheet. This argument is for only Far East versions of Microsoft Excel.

3d_shading is a logical value that specifies whether the list box appears as 3-D. If TRUE, the list box will appear as 3-D. If FALSE or omitted, the list box will not be 3-D. This argument is available for only worksheets.

Related Functions

CHECKBOX.PROPERTIES Sets various properties of check box and option box controls

SCROLLBAR.PROPERTIES Sets the properties of the scroll bar and spinner controls

PUSHBUTTON.PROPERTIES Sets the properties of the push button control

List of Customizing Functions


LINK.COMBO

Macro Sheets Only

Links an edit box and a list box control into a linked combination box group. The resulting linked controls track each other's selection and contents. Linked edit and list box combinations are similar to an editable drop-down list box, except that the list box is permanently visible and dropped down.

Syntax

LINK.COMBO(link_logical)

Link_logical is a logical value that specifies whether the controls are linked or unlinked. If TRUE, the controls will become linked. If FALSE, the controls will be unlinked.

Remarks

To use this function, first select the list box and edit box to be linked or unlinked. You can do this with SELECT("list box 1,Edit box 2").

Examples

LINK.COMBO(FALSE) will unlink a list box and an edit box.

Related Functions

ADD.LIST.ITEM Adds an item in a list box or drop-down control on a worksheet or dialog sheet control

SELECT.LIST.ITEM Selects an item in a list box or in a group box

List of Customizing Functions


LISTBOX.PROPERTIES

Macro Sheets Only

Equivalent to choosing the Object command from the Format menu when a list box or drop-down control is selected on a worksheet or dialog sheet. Sets the properties of a list box and drop-down controls on a worksheet or dialog sheet.

Syntax

LISTBOX.PROPERTIES(range, link, drop_size, multi_select, 3d_shading)
LISTBOX.PROPERTIES?(range, link, drop_size, multi_select, 3d_shading)

Range is the cell range that the initial contents of the list box are taken from. If blank (empty text), the list box is initially unfilled.

Link is the cell on the sheet to which the list box is linked, and indicates the numeric position of the currently selected item in the list box. Whenever an item in the list box is selected, its numeric position is entered into the linked cell on the sheet.

Drop_size is the number of lines shown when a drop-down control is dropped. This value is ignored when applied to a non-drop-down list box.

Multi_select is a number that specifies the selection mode of the list box. Zero is single selection. 1 is simple multi-select. 2 is extended multi-select.

3d_shading is a logical value that specifies whether the list box appears as 3-D. If TRUE, the list box will appear as 3-D. If FALSE or omitted, the list box will not be 3-D. This argument is available for only worksheets.

Related Functions

ADD.LIST.ITEM Adds an item in a list box or drop-down control on a worksheet or dialog sheet control

SELECT.LIST.ITEM Selects an item in a list box or in a group box

CHECKBOX.PROPERTIES Sets various properties of check box and option box controls

SCROLLBAR.PROPERTIES Sets the properties of the scroll bar and spinner controls

PUSHBUTTON.PROPERTIES Sets the properties of the push button control

List of Customizing Functions


ON.SHEET

Macro Sheets Only

Starts a macro whenever the specified sheet is activated from another sheet.

Syntax

ON.SHEET(sheet_text, macro_text, activate_logical)

Sheet_text is the name of the sheet that triggers a macro when it is activated, in the form "[Book1]Sheet1". If omitted, then when any sheet in any book is activated, macro_text will run.

Macro_text is the name of the macro to run when the specified sheet is activated. If omitted, then the triggering of a macro on the specified sheet is cancelled.

Activate_logical is a logical value that specifies if the macro is run when the sheet is activated or deactivated. If TRUE or omitted, the macro is run when the sheet is activated. If FALSE, the macro is run when the sheet is deactivated.

Examples

ON.SHEET("[STORE.XLS]Sheet1","WeeklyCalc") will run the macro "WeeklyCalc" when "[STORE.XLS]Sheet1" is activated.

ON.SHEET(,"WeeklyCalc") runs "WeeklyCalc" when any sheet in the book is activated.

ON.SHEET("[STORE.XLS]Sheet1") cancels the triggering of "WeeklyCalc" when Sheet1 in the book STORE.XLS is activated.

ON.SHEET("[STORE.XLS]","WeeklyCalc") runs "WeeklyCalc" when any sheet in the book STORE.XLS is activated

Related Functions

ON.WINDOW Runs a specified macro when you switch to a particular window.

List of Customizing Functions


OPEN.DIALOG

Macro Sheets Only

Displays the standard Microsoft Excel File Open dialog box with the specified file filters. When the user presses the button specified by button_text, the filename the user picks or types in will be returned.

Syntax

OPEN.DIALOG(file_filter, button_text, title, filter_index)

File_filter is the file filtering criteria to use, as text. For Microsoft Excel for Windows, file_filter consists of two parts, a descriptive phrase denoting the file type followed by a comma and then the MS-DOS wildcard file filter specification, as in "Text Files (*.TXT), *.TXT, Add-in Files (*.XLA), *.XLA". Groups of filter specifications are also separated by commas. Each separate pair is listed in the file type drop-down list box. File_filter can include an asterisk (*) to represent any sequence of characters and a question mark (?) to represent any single character. For Microsoft Excel for the Macintosh, file_filter consists of file type codes separated by commas, as in "TEXT,XLA ,XLS4". Spaces are signficant and should not be inserted before or after the comma separators unless they are part of the file type code.

Button_text is the text used for the Open button in the dialog. If omitted, "Open" will be used. Button_text is ignored on Microsoft Excel for Windows.

Title specifies the dialog window title. If omitted, "File Open" will be used as the default.

Filter_index specifies the index number of the default file filtering criteria from 1 to the number of filters specified in file_filter. If omitted or greater than the number of filters present, 1 will be used as the starting index number. The argument is ignored on Microsoft Excel for the Macintosh.

Remarks

  • To use multiple MS-DOS wildcard expressions within file_filter for a single file filter type, separate the wildcard expressions with semicolons, as in "VB Files (*.bas; *.txt), *.bas;*.txt"
  • If file_filter is omitted, "ALL Files (*.*), *.*" will be used as the default in Microsoft Excel for Windows. The default for Microsoft Excel for the Macintosh is all file types.
  • If the user cancels the dialog box, FALSE is returned.

Examples

OPEN.DIALOG("Text Files (*.TXT), *.TXT, Add-in Files (*.XLA), *.XLA,ALL FILES (*.*), *.*","FILE OPENER") opens a file open dialog box titled "FILE OPENER" with three file filter criteria in the drop-down list box.

Related Functions

SAVE.DIALOG Displays the standard Microsoft Excel File Save As dialog box and gets a file name from the user

List of Customizing Functions


PUSHBUTTON.PROPERTIES

Macro Sheets Only

Equivalent to choosing the Object command from the Format menu when a push button control is selected. Sets the properties of the push button control.

Syntax

PUSHBUTTON.PROPERTIES(default_logical, cancel_logical, dismiss_logical, help_logical, accel_text, accel_text2)
PUSHBUTTON.PROPERTIES?(default_logical, cancel_logical, dismiss_logical, help_logical, accel_text, accel_text2)

Default_logical is a logical value that determines whether the button is the default button for the dialog. If TRUE, the button is the default button. If FALSE, the button is not the default button for the control.

Cancel_logical is a logical value that determines whether the button is activated when the dialog is cancelled with the Close button or the ESC key. If TRUE, the button is activated when the dialog box is cancelled, and edit boxes are not checked to see if they contain valid data types. If FALSE, the button is not activated when the dialog box is cancelled.

Dismiss_logical is a logical value that determines whether the button dismissses the dialog when pressed, as when the user presses the box's OK button. If TRUE, the button dismisses the dialog box. If FALSE, the button does not dismiss the dialog box.

Help_logical is a logical value that determines whether the button is activated when the user presses the F1 key. If TRUE, the button is activated when the user presses the F1 key. If FALSE, the button is not activated when the user presses the F1 key.

Accel_text is a text string containing the character to use as the dialog button's accelerator key. The character is matched against the text of the control, and the first matching character is underlined. When the user presses ALT+accel_text in Microsoft Excel for Windows or COMMAND+accel_text in Microsoft Excel for the Macintosh, the control is clicked. This argument is ignored for push button controls on worksheets.

Accel_text2 is a text string containing the second accelerator key on a dialog sheet. This argument is for only Far East versions of Microsoft Excel.

Related Functions

CHECKBOX.PROPERTIES Sets various properties of check box and option box controls

SCROLLBAR.PROPERTIES Sets the properties of the scroll bar and spinner controls

EDITBOX.PROPERTIES Sets the properties of an edit box on a worksheet or dialog sheet

List of Customizing Functions


REMOVE.LIST.ITEM

Macro Sheets Only

Removes an item in a list box or drop-down box.

Syntax

REMOVE.LIST.ITEM(index_num, count_num)

Index_num specifies the index of the item to remove, from 1 to the number of items in the list. Specify zero to remove all items in the list.

Count_num Specifies the number of items to delete starting from index_num. If omitted, only one item is removed.

Remarks

If count_num + index_num is greater than the number of items in the list, all items starting with index_num to the end of the list are removed.

Examples

REMOVE.LIST.ITEM(3,2) removes two items starting with the third item

REMOVE.LIST.ITEM(3) removes only the third item

Related Functions

LISTBOX.PROPERTIES Sets the properties of a list box and drop-down controls on worksheet and dialog sheets

List of Customizing Functions


SAVE.DIALOG

Macro Sheets Only

Displays the standard Microsoft Excel File Save As dialog box and gets a file name from the user. This function returns the path and file name of the file that has been saved. Use SAVE.AS to automatically save a file with a particular format and other properties.

Syntax

SAVE.DIALOG(init_filename, title, button_text, file_filter, filter_index)

Init_filename Specifies the suggested filename for saving. If omitted, the active workbook's name is used, as returned by the GET.DOCUMENT(1) function.

Title Specifies the default window title on Microsoft Excel for Windows. For Microsoft Excel for the Macintosh, title specifies the prompt string. If omitted, "File Save As" will be used for Microsoft Excel for Windows, and "Save As:" For Microsoft Excel for the Macintosh.

Button_text is the text used for the save button in the dialog. If omitted, "Save" will be used as the default. This argument is ignored on the Microsoft Excel for Windows.

File_filter is the file filtering criteria to use, as text. For Microsoft Excel for Windows, file_filter consists of two parts, a descriptive phrase denoting the file type followed by a comma and then the MS-DOS wildcard file filter specification, as in "Text Files (*.TXT), *.TXT, Add-in Files (*.XLA), *.XLA". Groups of filter specifications are also separated by commas. Each separate pair is listed in the file type drop-down list box. File_filter can include an asterisk (*) to represent any sequence of characters and a question mark (?) to represent any single character. For Microsoft Excel for the Macintosh, file_filter consists of file type codes separated by commas, as in "TEXT,XLA ,XLS4". Spaces are signficant and should not be inserted before or after the comma separators unless they are part of the file type code.

Filter_index specifies the index number of the default file filtering criteria from 1 to the number of filters specified in file_filter. If omitted or greater than the number of filters present, 1 will be used as the starting index number. The argument is ignored on Microsoft Excel for the Macintosh.

Remarks

  • To use multiple MS-DOS wildcard expressions within file_filter for a single file filter type, separate the wildcard expressions with semicolons, as in "VB Filles (*.bas; *.txt), *.bas;*.txt".
  • If file_filter is omitted, "ALL Files (*.*), *.*" will be used as the default in Microsoft Excel for Windows. The default for Microsoft Excel for the Macintosh is all file types.
  • If the user cancels the dialog box, FALSE is returned.

Examples

SAVE.DIALOG("TRAVEL.XLS","How do you want to save this file?",,
"Text Files (*.TXT), *.TXT, Add-in Files (*.XLA), *.XLA, ALL FILES (*.*), *.*") opens a File Save As dialog box titled "How do you want to save this file?", with "TRAVEL.XLS" as the suggested file name, and with three file filter criteria in the drop-down list box.

Related Functions

OPEN.DIALOG Displays the standard Microsoft Excel File Open dialog box with the specified file filters

List of Customizing Functions


SCROLLBAR.PROPERTIES

Macro Sheets Only

Equivalent to choosing the Object command from the Format menu when an edit box is selected on a worksheet or dialog sheet. Sets the properties of the scroll bar and spinner button.

Syntax

SCROLLBAR.PROPERTIES(value, min, max, inc, page, link, 3d_shading)
SCROLLBAR.PROPERTIES?(value, min, max, inc, page, link, 3d_shading)

Value is the value of the control, and can range from min to max, inclusive. It designates where the scroll bar button is positioned along the scroll bar.

Min is a number specifying the minimum value that the scroll bar can have. This number ranges from 0 to 30,000, but cannot be greater than the maximum value given in max.

Max is a number specifying the maximum value that the scroll bar can have. This number ranges from 0 to 30,000.

Inc is a number specifying the increment that the value is adjusted by when the scrollbar arrow is clicked.

Page is a number specifying the increment that the value is adjusted by when the page scroll region of a scroll bar is clicked.

Link is the cell on the macro sheet to which the scroll bar value is linked. Whenever the scroll bar control is changed, the value of the control is entered into the cell. Similarly, whenever the value in the cell is changed, the setting for the scroll bar is also changed. To clear the link, set this value to an empty string.

3d_shading is a logical value that specifies whether the scroll bar or spinner button appears as 3-D. If TRUE, the scroll bar or spinner button will appear as 3-D. If FALSE or omitted, the scroll bar or spinner button will not be 3-D. The argument is available for only worksheets.

Related Functions

PUSHBUTTON.PROPERTIES Sets the properties of the push button control

EDITBOX.PROPERTIES Sets the properties of an edit box on a worksheet or dialog sheet

List of Customizing Functions


SCENARIO.MERGE

Macro Sheets Only

Equivalent to choosing the Scenarios command from the Tools menu and then selecting Merge. This function merges scenarios from other sheets onto the active sheet. A scenario is a set of values to be used as input for a model on your worksheet.

Syntax

SCENARIO.MERGE(source_file)
SCENARIO.MERGE?(source_file)

Source_file is the name of the book and sheet from which you want to merge scenarios onto the active sheet.

Related Functions

SCENARIO.GET Returns the specified information about the scenarios defined on your worksheet

List of Customizing Functions


SELECT.LIST.ITEM

Macro Sheets Only

Selects an item in a list box or in a group box.

Syntax

SELECT.LIST.ITEM(index_num, selected_logical)

Index_num is the index number of the item to select. Using zero will deselect all items. Adding 1 to the number of items in the list will select all the items specified.

Selected_logical is a number that specifies the selection mode of the list box. Zero is single selection. 1 is simple multi-select. 2 is extended multi-select.

Related Functions

ADD.LIST.ITEM Adds an item in a list box or drop-down control on a worksheet or dialog sheet control

REMOVE.LIST.ITEM Removes an item in a list box or drop-down box

List of Customizing Functions


SET.CONTROL.VALUE

Macro Sheets Only

Equivalent to choosing the Object command from the Format menu and changing the value for the active control, such as a list box, drop-down box, check box, option button, scroll bar, and spinner button.

Syntax

SET.CONTROL.VALUE(value)

Value is the value you want to change. The control interprets this value as follows:

Control Value is

List box The index of the selected item. If zero, then no item is selected.

Drop-down box The index of the selected item. If zero, then no item is selected.

Check box 0 = Off
1 = On
2 = Mixed

Option button 0= Off
1 = On

Scroll bar The numeric value of the control, between the maximum and minimum values

Spinner button The numberic value of the control, between the maximum and minimum values

Related Functions

ADD.LIST.ITEM Adds an item in a list box or drop-down control on a worksheet or dialog sheet control

REMOVE.LIST.ITEM Removes an item in a list box or drop-down box

SELECT.LIST.ITEM Selects an item in a list box or in a group box

CHECKBOX.PROPERTIES Sets various properties of check box and option box controls

SCROLLBAR.PROPERTIES Sets the properties of the scroll bar and spinner controls

List of Customizing Functions


SET.DIALOG.DEFAULT

Macro Sheets Only

Sets which button is automatically pressed (the default button) when the user presses ENTER. While running, this default button is visually recognized by its thick border. This function is used only with a dialog sheet active.

Syntax

SET.DIALOG.DEFAULT(object_id_text)

Object_id_text is the name of the button control to set as the default button, as in "Button 5".

Related Functions

SET.DIALOG.FOCUS Sets the focus of a dialog box

List of Customizing Functions


SET.DIALOG.FOCUS

Macro Sheets Only

Sets the focus of a dialog box. This function is used only with a dialog sheet active.

Syntax

SET.DIALOG.FOCUS(object_id_text)

Object_id_text the name of the control or object as text to give the focus to, as in "Check box 4".

Related Functions

SET.DIALOG.DEFAULT Sets which button is automatically pressed (the default button) when the user presses ENTER

List of Customizing Functions


SET.LIST.ITEM

Macro Sheets Only

Sets the text of an item in a list box or drop-down box control.

Syntax

SET.LIST.ITEM(text, index_num)

Text specifies the text of the item to be added. Instead of text, an empty string may be inserted.

Index_num is the list index of the item to be changed, from 1 to the number of items in the list.

Remarks

If the list box or drop-down box was already filled using the LISTBOX.PROPERTIES function, then changing an item with SET.LIST.ITEM causes the fillrange contents to be discarded, leaving a list with one non-blank element and index_num entries.

Related Functions

REMOVE.LIST.ITEM Removes an item in a list box or drop-down box

SELECT.LIST.ITEM Selects an item in a list box or in a group box

List of Customizing Functions


SHOW.DIALOG

Macro Sheets Only

Runs a dialog on a dialog sheet.

Syntax

SHOW.DIALOG(dialog_sheet)

Dialog_sheet is the name of the dialog sheet to run. If omitted, the active sheet will be the sheet that is run. If this function is run on a sheet other than a dialog sheet, this function returns the #VALUE error value.

Remarks

Returns TRUE if the dialog box is closed by the user choosing an OK button. Returns FALSE if the dialog box is cancelled by choosing the Cancel button or the ESC key, or in Microsoft Excel for the Macintosh by pressing COMMAND+. (period).

Related Functions

HIDE.DIALOG Closes the dialog box that has the current focus

List of Customizing Functions


TAB.ORDER

Macro Sheets Only

Equivalent to choosing the Tab Order command from the Tools menu. This function determines the order in which dialog controls will be selected when the user presses the TAB key.

Syntax

TAB.ORDER?()

Remarks

  • This function brings up the Tab Order dialog box and allows the user to select the order in which buttons will be selected when the TAB key is pressed.
  • The BRING.TO.FRONT and SEND.TO.BACK macro functions can also be used to programmatically set up the tab order.

Related Functions

BRING.TO.FRONT Puts the selected object or objects on top of all other objects

SEND.TO.BACK Puts the selected object or objects behind all other objects

List of Customizing Functions


APP.ACTIVATE.MICROSOFT

Macro Sheets Only

Activates a Microsoft application. If the application is not already activated, this function will load the application into memory. Equivalent to choosing one of the toolbar buttons on the Microsoft Toolbar.

Syntax

APP.ACTIVATE.MICROSOFT(app_id)

App_id is the id number associated with the Microsoft Application.

App_id Application

1 Microsoft Word

2 Microsoft Powerpoint

3 Microsoft Mail

4 Microsoft Access (for Microsoft Windows only)

5 Microsoft Fox Pro

6 Microsoft Project

7 Microsoft Schedule +

Remarks

Returns TRUE if the application is activated successfully. Returns FALSE if the application is not activated successfully.

Related Functions

APP.ACTIVATE Switches to an application.

List of DDE/External Functions


FONT.PROPERTIES

Equivalent to choosing the Cells command from the Format menu. Applies a font and other attributes to the selection. Applies to cells, charts, and text boxes and buttons on worksheets and macro sheets.

Syntax

FONT.PROPERTIES(font, font_style, size, strikethrough, superscript, subscript, outline, shadow, underline, color, normal, background, start_char, char_count)

FONT.PROPERTIES?(font, font_style, size, strikethrough, superscript, subscript, outline, shadow, underline, color, normal, background, start_char, char_count)

Arguments correspond to check boxes or options in the Font tab on the Format Cells dialog box. Arguments that correspond to check boxes are logical values. If an argument is TRUE, Microsoft Excel selects the check box; if FALSE, Microsoft Excel clears the check box. If an argument is omitted, the format is not changed.

Font is the name of the font as it appears in the Font tab. For example, Courier is a font name.

Font_style is the name of the font style as it appears in the Font tab. For example, Bold Italic is a font style.

Size is the font size, in points.

Strikethrough corresponds to the Strikethrough check box.

Superscript corresponds to the Superscript check box

Subscript corresponds to the Subscript check box

Outline corresponds to the Outline check box. Outline fonts are available in Microsoft Excel for the Macintosh. For macro compatibility, this argument is ignored by Microsoft Excel for Windows..

Shadow corresponds to the Shadow check box. Shadow fonts are available in Microsoft Excel for the Macintosh. For macro compatibility, this argument is ignored by Microsoft Excel for Windows.

Note For macro compatibility with Microsoft Excel for the Macintosh, the presence of the outline and shadow arguments do not prevent the macro from working on Microsoft Excel for Windows, nor does their absence prevent it from working on the Macintosh.

Underline corresponds to the Underline Drop-down box.

Underline Type applied

0 None

1 Single

2 Double

3 Single Accounting

4 Double Accounting

Color is a number from 0 to 56 corresponding to the colors in the Font tab; 0 corresponds to automatic color.

Normal corresponds to the Normal Font check box. Applies the default font for your system

Background is a number from 1 to 3 specifying which type of background to apply to text in a chart.

Backgd Type of background applied

1 Automatic

2 Transparent

3 Opaque

Start_char specifies the first character to be formatted. If start_char is omitted, it is assumed to be 1 (the first character in the cell or text box).

Char_count specifies how many characters to format. If char_count is omitted, Microsoft Excel formats all characters in the cell or text box starting at start_char.

Remarks

Some extended TrueType styles do not have corresponding arguments to FONT.PROPERTIES. To access an extended TrueType font style, append the style name to the font name in the font argument. For example, the font Taipei can be formatted in an upside-down style by specifying "Taipei Upside-down" as the font argument. For more information about TrueType, see your Microsoft Windows documentation.

Related Functions

ALIGNMENT Aligns or wraps text in cells

FORMAT.NUMBER Applies a number format to the selection

FORMAT.TEXT Formats a worksheet text box or a chart text item

List of Command-Equivalent Functions


ACTIVE.CELL.FONT

Macro Sheets Only

Equivalent to formatting individual characters in a cell.

Syntax

ACTIVE.CELL.FONT(font, font_style, size, strikethrough, superscript, subscript, outline, shadow, underline, color, normal, background, start_char, char_count)

The arguments for this function are the same as those for FONT.PROPERTIES.

Related Functions

FONT.PROPERTIES Applies a font and other attributes to the selection

List of Command-Equivalent Functions


ADDIN.MANAGER

Macro Sheets Only

Equivalent to choosing the Add-Ins command from the Tools menu. Adds or removes an add-in from the working set.

Syntax

ADDIN.MANAGER(operation_num, addinname_text, copy_logical)
ADDIN.MANAGER?(operation_num, addinname_text, copy_logical)

Operation_num determines the operation that the add-in manager will perform.

Operation_num Operation

1 Install an add-in, using the descriptive name in the add-in manager dialog.

2 Uninstall an add-in, using the descriptive name in the add-in manager dialog.

3 Adds a new add-in to the list of add-ins that Excel knows about. Equivalent to clicking on the Browse button in the add-in manager and choosing a file. The add-in is not installed by default.

Addinname_text specifies the name of the add-in. If operation_num is 1 or 2, use the descriptive name of the add-in, such as "SOLVER". If operation_num is 3, this contains the filename of the add-in.

Copy_logical specifies whether the add-in should be copied to the library directory. This argument is only used if operation_num is 3. If omitted, and the file is on removable media, the user will be asked if they want to copy it to removable media.

Related Functions

List of Command-Equivalent Functions


ATTACH.TOOLBARS

Macro Sheets Only

Displays the Attach Toolbars dialog box from the Tools menu, which you use to attach or associate toolbars with documents.

Syntax

ATTACH.TOOLBARS?( )

Related Functions

List of Command-Equivalent Functions


AUTO.OUTLINE

Macro Sheets Only

Equivalent to choosing the Auto Outline command from the Group and Outline submenu on the Data menu. Creates an outline within the selection. If a single cell is selected, creates an outline for the whole sheet.

Syntax

AUTO.OUTLINE( )

Related Functions

CLEAR.OUTLINE Removes outlining from the current sheet

OUTLINE Creates an outline and defines settings for automatically creating outlines

List of Command-Equivalent Functions


CHART.ADD.DATA

Equivalent to dragging data from a worksheet onto a chart. Adds data to an existing chart.

Syntax

CHART.ADD.DATA(ref, rowcol, titles, categories, replace, series)

Ref is the cell reference for the data that is being dragged onto the chart

Rowcol is the number 1 or 2 and specifies whether the values corresponding to a particular data series are in rows or columns. Enter 1 for rows or 2 for columns.

Titles is a logical value corresponding to the Series Names In First Column check box (or First Row, depending on the value of rowcol) in the Paste Special dialog box.

  • If titles is TRUE, Microsoft Excel selects the check box and uses the contents of the cell in the first column of each row (or first row of each column) as the name of the data series in that row (or column).
  • If titles is FALSE, Microsoft Excel clears the check box and uses the contents of the cell in the first column of each row (or first row of each column) as the first data point of the data series.

Categories is a logical value corresponding to the Categories (X Labels) In First Row (or First Column, depending on the value of rowcol) check box in the Paste Special dialog box.

  • If categories is TRUE, Microsoft Excel selects the check box and uses the contents of the first row (or column) of the selection as the categories for the chart.
  • If categories is FALSE, Microsoft Excel clears the check box and uses the contents of the first row (or column) as the first data series in the chart.

Replace is a logical value corresponding to the Replace Existing Categories check box in the Paste Special dialog box.

  • If replace is TRUE, Microsoft Excel selects the check box and applies categories while replacing existing categories with information from the copied cell range.
  • If replace is FALSE, Microsoft Excel clears the check box and applies new categories without replacing any old ones.

Series is a number specifying how cells are added to a chart.

Series Added as

1 New series

2 New point(s)

Related Functions

List of Command-Equivalent Functions


CLEAR.OUTLINE

Macro Sheets Only

Equivalent to choosing the Clear Outline command from the Group and Outline submenu on the Data menu. Clears the outline within the selection. If a single cell is selected, it clears the outline from the whole sheet.

Syntax

CLEAR.OUTLINE()

Related Functions

AUTO.OUTLINE Creates an outline

OUTLINE Creates an outline and defines settings for automatically creating outlines

List of Command-Equivalent Functions


EDIT.TOOL

Macro Sheets Only

Displays the Button Editor dialog, which you use to change the appearance of a button on a toolbar.

Syntax

EDIT.TOOL(bar_id, position)

Bar_id is the number of the toolbar containing the button you want to edit. For a list of toolbar numbers, see ADD.TOOL. Use the GET.TOOLBAR function to return the information about a toolbar.

Position is the position on the toolbar of the button you want to edit. Buttons are numbered from the left starting at 1. Gaps between buttons are counted as positions.

Related Functions

ADD.TOOL Adds a button to a toolbar

GET.TOOLBAR Returns information about a toolbar

List of Command-Equivalent Functions


ENABLE.TIPWIZARD

Macro Sheets Only

Turns on or off the Tip Wizard.

Syntax

ENABLE.TIPWIZARD(state)

State is a logical value specifying whether the Tip Wizard is on: use TRUE to turn it on, FALSE to turn it off.

Related Functions

List of Command-Equivalent Functions


ERRORBAR.XERRORBAR.Y

ERRORBAR.X
ERRORBAR.Y

Macro Sheets Only

Adds error bars to the selected series in a chart. ERRORBAR.X adds bars showing the error factor for the X (category) axis and works for XY (scatter) charts only. ERRORBAR.Y adds bars showing the error factor for the Y (value) axis for all charts.

Syntax

ERRORBAR.X(include, type, amount, minus)
ERRORBAR.Y(include, type, amount, minus)

Include specifies the type of error value to include:

Include Type of error value

1 or omitted Plus and minus

2 Plus

3 Minus

4 None

Type specifies the type of error bars to display:

Type Type of error displayed

1 or omitted Fixed amount

2 Percent

3 Multiplying factor standard deviation (default value is 1)

4 Standard error

5 Custom

Amount is the range of error values to display. This argument depends on the value of type:

If type is then amount

1 or omitted can be any number greater than 0

2 can be any number greater than 0

3 can be any number greater than or 0

4 not required

5 is the positive amount for custom error bars

Minus is the negative amount for custom error bars. Applicable only if type is 5.

Remarks

For the amount argument, standard deviation(s) can be calculated using this equation:

The standard deviation is multiplied by the value specified by amount and the error bars are placed this distance from the arithmetic mean. Therefore, these error bars are plotted along the arithmetic mean, not attached to data series.

Microsoft Excel calculates the standard error using the following equation:

Both the standard deviation and standard error functions use the following variables:

Variable Equals

s series number

i point number in series s

m number of series for point y in chart

n number of points in each series

Yi data value of series s and the ith point

Ny total number of data values in all series

M arithmetic mean

Related Functions

List of Command-Equivalent Functions


FORMAT.CHARTTYPE

Macro Sheets Only

Changes the chart type for a selected data series, a group of data series, or an entire chart.

Syntax

FORMAT.CHARTTYPE(apply_to, group_num, dimension, type_num)
FORMAT.CHARTTYPE?(apply_to, group_num, dimension, type_num)

Apply_to is a number from 1 to 3 specifying what part of a chart the new chart type effects.

Value Part of chart

1 Selected data series

2 Group of data series

3 Entire chart

Group_num corresponds to the number of the group you want to change as listed in the Group list box of the Chart Type dialog box, which appears when you choose Chart Type from the Format menu while a chart is active. Groups are numbered starting with 1 for the group at the top of the list. This argument is required if apply_to equals 2; otherwise it is ignored.

Dimension specifies whether to apply a 2D- or 3D-chart type. Use 1 for a 2D chart type or 2 for a 3D chart type. If omitted, uses the same dimension as the series, group, or chart to be changed.

Type_num specifies the chart type to apply. Meaning of type_num varies depending on the value of dimension:

Type_num Chart type if dimension is 1 Chart type if dimension is 2

1 | Area | 3D area
2 | Bar | 3D bar
3 | Column | 3D column
4 | Line | 3D line
5 | Pie | 3D pie
6 | Doughnut | 3D surface
7 | Radar |
8 | XY (scatter) |

Related Functions

FORMAT.CHART Formats the selected chart

List of Command-Equivalent Functions


FUNCTION.WIZARD

Macro Sheets Only

Displays the Function Wizard dialog box, which you can use to enter functions into cells.

Syntax

FUNCTION.WIZARD?( )

Remarks

If you know the function or formula that you want to insert into a cell, use the FORMULA function.

Related Functions

FORMULA Enters values into a cell or range or onto a chart

List of Command-Equivalent Functions


INSERT.TITLE

Macro Sheets Only

Equivalent to the Titles command on the Insert menu when a chart is active. Attaches text to various parts of a chart.

Syntax

2D charts

INSERT.TITLE(chart, y_primary, x_primary, y_secondary, x_secondary)

3D charts

INSERT.TITLE(chart, z_primary, x_primary, y_primary)

Chart is a logical value specifying whether to attach a title to the chart.

Y_primary is a logical value specifying whether to attach a title to the value (y) axis of a 2D chart or the series (y) axis of a 3D chart.

X_primary is a logical value specifying whether to attach a title to the category (x) axis of the chart.

Z_primary is a logical value specifying whether to attach a title to the value (z) axis of a 3D chart.

Y_secondary is a logical value specifying whether to attach a title to the second value (y) axis of a chart containing more than one chart type.

X_secondary is a logical value specifying whether to attach a title to the second category (x) axis of a chart containing more than one chart type.

Remarks

To change the text in a selected title, use the FORMULA function.

Related Functions

FORMULA Enters formulas in a chart

List of Command-Equivalent Functions


JUSTIFY

Macro Sheets Only

Equivalent to choosing the Justify command on the Fill submenu on the Edit menu. Rearranges the text in a range so that it fills the range evenly.

Syntax

JUSTIFY()

Related Functions

ALIGNMENT Aligns the contents of the selected cells

List of Command-Equivalent Functions


LINK.FORMAT

Macro Sheets Only

Equivalent to the Linked to Source checkbox in the Number tab of the Format Data Label dialog box. Links the number format of the selected data label to the worksheet cell or range containing the data label text.

Syntax

LINK.FORMAT( )

Related Functions

List of Command-Equivalent Functions


MAIL.LOGOFF

Macro Sheets Only

Ends the current mail session.

Important To use MAIL.LOGOFF in Microsoft Excel for Windows, you must be using a mail client that supports the Messaging Applications Programming Interface (MAPI) or Vendor-Independent Messaging (VIM). The function is available for only Microsoft Excel for Windows.

Syntax

MAIL.LOGOFF( )

Remarks

Returns TRUE if the session was ended, or #VALUE! if there was no session.

Related Functions

List of Command-Equivalent Functions


MAIL.LOGON

Macro Sheets Only

Starts a mail session.

Important To use MAIL.LOGON in Microsoft Excel for Windows, you must be using a mail client that supports the Messaging Applications Programming Interface (MAPI) or Vendor-Independent Messaging (VIM). The function is available for only Microsoft Excel for Windows.

Syntax

MAIL.LOGON(name_text, password_text, download_logical)
MAIL.LOGON?(name_text, password_text, download_logical)

Name_text is the username of the mail account or Microsoft Exchange profile name. If omitted, prompts for username.

Password_text is the password for the account. If omitted, prompts for password. Ignored when the dialog box form is used. This argument is ignored in Microsoft Exchange.

Download_logical specifies whether to download new mail. Use TRUE to download new mail; use FALSE or leave blank to skip downloading new mail.

Remarks

Returns FALSE if you cancel the dialog box or #VALUE! if you can't log on.

If you omit both name_text and password_text, Microsoft Excel tries to log on using an existing mail session.

Related Functions

MAIL.LOGOFF Ends the current mail session

List of Command-Equivalent Functions


MENU.EDITOR

Macro Sheets Only

Displays the Menu Editor dialog box, which you use to create custom commands and menus to use with your Visual Basic procedures.

Syntax

MENU.EDITOR?( )

Related Functions

List of Command-Equivalent Functions


OPEN.TEXT

Macro Sheets Only

Equivalent to using the Text Import Wizard to open a text file in Microsoft Excel.

Syntax

OPEN.TEXT(file_name, file_origin, start_row, file_type, text_qualifier, consecutive_delim, tab, semicolon, comma, space, other, other_char, {field_info1; field_info2;...})

File_name is the full pathname of the text file you want to open.

File_origin specifies the operating environment the text file was created in.

File_origin Operating system

1 Macintosh

2 Windows (ANSI)

3 MS DOS (PC-8)

omitted Current operating environment

Start_row is a number greater than or equal to one, specifying the row in the text file where you want to start importing into Microsoft Excel. This number should be less than the number of lines in the text file.

File_type specifies the type of delimited text file to import:

File_type Type of file

1 or omitted Delimited

2 Fixed Width

Text_qualifier indicates the character-enclosing text fields in the text file:

Text_qualifer value Qualifer

1 or " " (double quotation mark)

2 or ' ' (single quotation mark)

3 or {None} No text qualifier

Consecutive_delim is a logical value corresponding to the Treat Consecutive Delimiters as One check box which, if TRUE, allows consective delimiters (such as ",,,") to be treated as a single delimiter. If FALSE, all consecutive delimiters are considered separate column breaks.

Tab, semicolon, comma, space are logical values corresponding to the check boxes in the Column Delimiters group. If an argument is TRUE, the check box is selected. These arguments apply only when the file_type argument is 1 or omitted (delimited file type).

Other is a logical value indicating a custom delimiter to use in opening the text file.

Other_char specifies the custom delimiter to use or FALSE if no custom delimiter is used.

Field_info is an array which consists of the following elements: "column number, data_format", if file_type is 1; or "start_pos, data_format" if file_type is 2.

Related Functions

TEXT.TO.COLUMNS Parses text, as in a text file, into columns of data

List of Command-Equivalent Functions


OVERLAY

Macro Sheets Only

Equivalent to choosing the Overlay command from the Format menu in Microsoft Excel version 2.2 or earlier. This function is included only for macro compatibility. To format chart types in Microsoft Excel version 5.0 or later, use the FORMAT.CHART function.

Syntax

OVERLAY(type_num, stack, 100, vary, overlap, drop, hilo, overlap%, cluster, angle, series_num, auto)

Related Functions

FORMAT.CHART Formats the chart according to the arguments you specify.

List of Command-Equivalent Functions


REPLACE.FONT

Macro Sheets Only

Replaces one of the four built-in fonts in Microsoft Excel for Windows version 2.1 or earlier with a new font and style. This function is included only for macro compatibility. To change the font of the selected cell or range as part of a macro, use the FONT.PROPERTIES function.

Syntax

REPLACE.FONT(font_num, name_text, size_num, bold, italic, underline, strike, color, outline, shadow)

Related Functions

FONT.PROPERTIES Sets various font attributes

List of Command-Equivalent Functions


SAVE.COPY.AS

Macro Sheets Only

Saves a copy of the current document using a different name but all the current document settings, such as passwords and file protection. Does not affect the current document. Use this command if you need a temporary copy of the current document; for example, to include in an electronic mail message.

Syntax

SAVE.COPY.AS(document_text)

Document_text is the name you want to give the copy of the workbook.

Example

Suppose that you are creating a macro that makes changes to a file called BUDGET95.XLS. Use the following function to save a copy of this file called TEMP.XLS without affecting BUDGET95.XLS:

SAVE.COPY.AS("temp.xls")

Related Functions

List of Command-Equivalent Functions


SELECT.ALL

Macro Sheets Only

Equivalent to selecting all the sheets in a workbook.

Syntax

SELECT.ALL( )

Related Functions

List of Command-Equivalent Functions


SERIES.AXES

Macro Sheets Only

Equivalent to the Axis Tab in the Format Data Series dialog box. Changes the axis on which a series is plotted.

Syntax

SERIES.AXES(axis)

Axis is a number specifying on which axis to plot the data series: use 1 for primary axis, 2 for secondary axis.

Related Functions

List of Command-Equivalent Functions


SERIES.X

Macro Sheets Only

Equivalent to the X Values tab in the Format Data Series dialog box. Specifies the category labels (x values) for a data series.

Syntax

SERIES.X(x_ref)
X-ref is an external reference in the form of text specifying the range containing the category labels (or x values for a scatter (xy) chart) you want to use.

Related Functions

SERIES.Y Specifies the name and values for a data series

List of Command-Equivalent Functions


SERIES.Y

Macro Sheets Only

Equivalent to the Name and Values tab in the Format Data Series dialog box. Specifies the name and values for a data series.

Syntax

SERIES.Y(name_ref, y_ref)

Name_ref is text or an external reference in the form of text specifying the name for the data series that appears in the legend for the chart.

Y_ref is an external reference in the form of text specifying the range containing the values for the data series.

Related Functions

SERIES.X Specifies the category labels (x values) for a data series

List of Command-Equivalent Functions


SERIES.ORDER

Macro Sheets Only

Changes the order of series in a chart.

Syntax

SERIES.ORDER(chart_num, old_series_num, new_series_num)

Chart_num is the number of the group containing the series you want to change

Old_series_num is the current number of the series in the group.

New_series_num is the new number you want for the series in the group.

Related Functions

List of Command-Equivalent Functions


STANDARD.FONT

Macro Sheets Only

Sets the attributes of the standard font in Microsoft Excel version 2.2 and earlier. This function is included only for macro compatibility. To define and apply a style in Microsoft Excel 5.0 or later, use the APPLY.STYLE and DEFINE.STYLE functions.

Syntax

STANDARD.FONT(name_text, size_num, bold, italic, underline, strike, color, outline, shadow)

The arguments for this function are the same as those for FORMAT.FONT.

Related Functions

APPLY.STYLE Applies a style to the selection

DEFINE.STYLE Defines a cell style

FORMAT.FONT Applies a font to the selection

List of Command-Equivalent Functions


STANDARD.WIDTH

Macro Sheets Only

Sets the default width used for all columns in a worksheet.

Syntax

STANDARD.WIDTH(standard_num)

Standard_num specifies how wide you want the columns to be in units of one character of the font corresponding to the Normal cell style.

Related Functions

List of Command-Equivalent Functions


VBA.MAKE.ADDIN

Macro Sheets Only

Converts a workbook containing Visual Basic procedures into an add-in.

Syntax

VBA.MAKE.ADDIN(filename_text)

Filename_text is the name of the workbook that you want to convert to an add-in.

Remarks

For information about creating add-ins with Visual Basic, see Chapter 13, "Creating Automatic Procedures and Add-in Applications" in the Visual Basic User's Guide.

Related Functions

List of Command-Equivalent Functions


VBA.INSERT.FILE

Macro Sheets Only

Inserts a text file containing code directly into your Visual Basic module.

Syntax

VBA.INSERT.FILE(filename_text)

Filename_text is the name of a text file that contains Microsoft Visual Basic code that is inserted into the currently active module.

Related Functions

List of Command-Equivalent Functions


Developing Microsoft(R) Excel 5 Solutions

Developing Microsoft® Excel 5 Solutions

Excerpted from Developing Microsoft® Excel 5 Solutions: Expert Development Strategies Using the Microsoft Excel 5 Object Model and Visual Basic® for Applications

This excerpt consists of Part One, "Introduction to Excel Objects and VBA," and includes the three chapters found in this section of the Development Library.

Developing Microsoft® Excel 5 Solutions is available wherever computer books are sold and through the CompuServe® Electronic Mall—GO MSP. Call (800) MSPRESS or (615) 793-5090 for more information or to place a credit card order.

PUBLISHED BY
Microsoft Press
A Division of Microsoft Corporation
One Microsoft Way
Redmond, Washington 98052-6399

Copyright © 1995 by Eric Wells

All rights reserved. No part of the contents of this book may be reproduced or transmitted in any form or by any means without the written permission of the publisher.

Library of Congress Cataloging-in-Publication Data
Wells, Eric, 1962–
Developing Microsoft Excel solutions / by Eric Wells.
p. cm.
Includes index.
ISBN 1-55615-684-7
1. Computer software--Development. 2. Microsoft Excel (Computer
file) I. Title.
QA76.76.D47W46 1994
005.369--dc20 94-24467
CIP

Printed and bound in the United States of America.

1 2 3 4 5 6 7 8 9 MLML 0 9 8 7 6 5

Distributed to the book trade in Canada by Macmillan of Canada, a division of Canada Publishing Corporation.

A CIP catalogue record for this book is available from the British Library.

Microsoft Press books are available through booksellers and distributors worldwide. For further information about international editions, contact your local Microsoft Corporation office. Or contact Microsoft Press International directly at fax (206) 936-7329.

Apple, Macintosh, and PowerTalk are registered trademarks of Apple Computer, Inc. dBASE is a registered trademark of Borland International, Inc. FoxPro, Microsoft, Microsoft Access, the Microsoft logo, MS, PowerPoint, and Visual Basic are registered trademarks and ODBC, PivotTable, Visual C++, Windows, Windows NT, and the Windows operating system logo are trademarks of Microsoft Corporation. All other trademarks and service marks are the property of their respective owners.

Acquisitions Editor: Dean Holmes
Project Editor: Jack Litewka
Manuscript Editor: Barbara Olsen Browne
Technical Editor: Kurt T. Meyer


Chapter 1 Excel Objects

Click to open or copy the sample files for this book

This chapter provides an overview of the Microsoft Excel object model. An object in Excel is something that can be programmed or, in essence, controlled. Excel's object model contains 128 different objects, ranging from simple objects such as rectangles and textboxes to complicated objects such as pivottables and charts. Before you can create Excel applications, you must have not only a good understanding of the functionality that various Excel objects offer but also a firm knowledge of the structure of the Excel object model.

Excel objects are discrete entities that offer various pieces of data analysis functionality. You create applications in Excel by tying these objects together using Visual Basic for Applications (VBA), Excel's new macro language. (Chapter 2 gives you a complete overview of the VBA language.) The end of this chapter focuses on showing you how to begin building custom applications with four commonly used Excel objects: Application, Workbook, Worksheet, and Range. Additional objects are discussed in detail throughout the course of this book. Note that all Excel objects are fully documented in the online VBA Help that comes with Excel 5—and documented in printed form in the Microsoft Excel Visual Basic for Applications Reference (Microsoft Press).

Objects and Their Properties and Methods

All objects in Excel have what are known as "properties" and "methods." VBA is a tool through which you can control Excel objects by manipulating their properties and methods. To develop custom applications in Excel, you must understand the concepts of objects, properties, and methods as well as know the specific details about the properties and methods of Excel's objects.

F Y I

VBA Naming Conventions

In VBA code, the name of an object, a property, or a method is written as one word (for example, the OptionButton object). In addition, all such names begin with a capital letter, and if a name consists of two concatenated words, the first letter of the second word is capitalized as well (for example, the HasPassword property or the PrintPreview method).

A Real-World Example

Let's take a look at a real-world example of an object and its properties and methods. Think of everything that you encounter in your daily life that can be controlled: your car, your phone, your television, your microwave, and even your computer. Just about everything you encounter can be controlled in some way. Even the earth is subject to the gravitational control of the sun and the other planets. These are all objects in the true definition of the word. In fact, every definable thing is an object. So, in essence, an object can be defined as some "thing."

In addition, all objects can be described. For each object, there is a set of associated adjectives that represent various measurable aspects of the object. A property is a measurable aspect of an object. Take a car as an example. It is an object that has properties of color (red), year (1990), make (Nissan), number of seats (two), and top speed (145 mph), and numerous other measurable aspects. Properties represent all aspects of an object. If you measure all the properties of an object, you'll have a complete and accurate description of that object.

Properties
Color: | Red
Year: | 1990
Make: | Nissan 300ZX
Number of seats: | Two
Top speed: | 145 mph

As properties are adjectives, methods are, in effect, verbs that represent actions that can be performed on or by an object. If we look again at the example of a car, the car's methods would include start, accelerate, decelerate, and stop.

Methods

Start

Accelerate

Decelerate

Stop

Examples of Excel Workbook Properties

Excel objects are similar to real-world objects in the sense that each Excel object has a unique set of properties used to describe it and a unique set of methods representing the actions that can be performed on or by it. Let's take a look at the workbook as an example of an Excel object. Workbooks are simply Excel files. When describing a Workbook object, we're simply talking about the characteristics of an Excel file. The following is a partial list of the properties of an Excel Workbook object:

Author | The name of the person who created the workbook
Creator | The name of the application (Excel) that was used to create the workbook
HasPassword | True if the workbook has a password; False if not
Name | The name of the workbook
Path | The path that describes where the workbook is saved on disk
ReadOnly | True if the workbook has been saved as read only; False if not

As we review this set of properties, a couple of important facts come to light. First, all properties have values associated with them—be they string values (as in Workbook Name), Boolean values (as in the Workbook HasPassword property), numeric values, or some other kind. Second, properties can be specific to a single object, or they can apply to several different objects. For example, the Workbook object is the only Excel object that has a HasPassword property; it is also the only object that has a ReadOnly property. On the other hand, 58 Excel objects have a Name property. In fact, Name is one of the most prevalent properties in Excel, which makes sense because most real-life objects have names.

Getting and Setting Properties

When dealing with properties using VBA in Excel, you can perform two types of actions: You can set a property, or you can get a property setting. When doing either, you must reference both the object name and the property name, separating the two with the dot operator (.). In addition, you set or get a property by using the equals operator (=). For example, to set the Author property of the workbook named BOOK1.XLS, you would use the following VBA syntax:

Workbooks("BOOK1.XLS").Author = "Jane Smith"

The five parts of the line of code above are as follows:

Object name | Workbooks("BOOK1.XLS")
Dot operator | .
Property name | Author
Equals operator | =
Property value | "Jane Smith"

Note When writing VBA code to set property values, you must include all of the elements listed above. The Workbook object here is specified using an index to the Workbooks collection object. You'll find an explanation of this kind of reference in the section "Referencing Objects: Singular Objects vs. Objects in Collections," beginning on page 10. We'll go into more detail about each of the elements and the various ways you can reference them later in this book.

F Y I

Using This Code in a VBA Macro

To write an entire VBA macro that sets the Author property of the Workbook object, include the keyword Sub followed by the macro name on the first line of the macro and the keywords End Sub on the last line of the macro, as in the following example:

Sub SetAuthorName()
Workbooks("BOOK1.XLS").Author = "Jane Smith"
End Sub

Getting property settings works in much the same way as does setting them except that the elements in the VBA command appear in the reverse order. Also, when getting a property setting, you usually use a variable to hold the value of the property. The line of code below assigns the value of the Author property of the Workbook object to a string variable named AuthorName:

AuthorName = Workbooks("BOOK1.XLS").Author

The parts of the line of VBA code used to get a property are similar to those used to set a property:

Variable | AuthorName
Equals operator | =
Object name | Workbooks("BOOK1.XLS")
Dot operator | .
Property name | Author

Note If you haven't yet saved your workbook, its name is still simply Book1. If you don't specify a new name using the Save As command, Excel adds the file extension .XLS when it saves the file, and the name becomes BOOK1.XLS. (For Macintosh users, the default name of a new file is WORKBOOK1, and a file extension is not automatically added.)

Examples of Excel Workbook Methods

Excel's Workbook object also has many methods that represent actions that can be performed on or by the workbook. Here are a few of these methods:

Activate | Activates the first window associated with the workbook
Close | Closes the workbook
PrintPreview | Displays a preview of the workbook as it would be printed
Protect | Protects a workbook with a password
Save | Saves the workbook
SendMail | Sends the workbook as an embedded object in an e-mail message
Unprotect | Unprotects the workbook

Calling Methods

The VBA syntax for calling a method differs from that of setting or getting properties. All that is required for a method call is a reference to the object and the method. In addition, each method in Excel has a set of "arguments," or additional pieces of information, that can be specified to indicate how the method is to be carried out. In VBA, many methods have optional arguments—that is, depending on how you want a particular method to be executed, you can specify all, some, or none of the method's arguments. For example, the Close method of the Workbook object has three arguments:

saveChanges | Either True (save changes to the file) or False (don't save changes)
fileName | The filename under which the workbook will be saved if saveChanges is True
routeWorkbook | Either True (route the workbook through e-mail) or False (don't route the workbook before closing)

Note The first letter of an argument name is most often lowercase. And if an argument name is made up of two concatenated words, the first letter of the second word is usually but not always capitalized.

Passing Arguments to Methods

Here is an example of the VBA syntax you would use to call the Close method without passing any arguments:

Workbooks("BOOK1.XLS").Close

If you call the Close method without passing any arguments, the arguments take on default values. For example, if you omit the first argument, saveChanges, and changes have been made to the file, Excel by default asks the user whether the file should be saved:

The default for the fileName argument is the file's current name, and the default for the routeWorkbook argument is False. This example shows the VBA syntax for calling the Close method while passing all three arguments:

Workbooks("BOOK1.XLS").Close True, "MYBOOK.XLS", False

When passing the arguments, you merely append them to the method call and separate multiple argument values with commas; be certain the arguments are in the proper order. For Close, for example, the appropriate order is saveChanges, fileName, and routeWorkbook. Also be aware that two different methods of passing arguments are available when you call a method. You can pass arguments "by name," or you can pass arguments "by order," as in the example above. When you pass an argument by name, you must specify three elements: the name of the argument (for example, saveChanges), followed by the colon-equals assignment operator (:=), and then the value for the argument. The example below shows the appropriate VBA syntax for executing the Close method while passing all arguments by name:

Workbooks("BOOK1.XLS").Close saveChanges:=True, _
  fileName:="BOOK1.XLS", routeWorkbook:=False

When you pass arguments by name in VBA, you need not pass them in order. For example, you can accomplish the same method call as the one shown above by passing the arguments by name in a different order:

Workbooks("BOOK1.XLS").Close routeWorkbook:=False, _
  saveChanges:=True, fileName:="BOOK1.XLS"

F Y I

The Line Continuation Character

The underscore character (_) at the end of a line in VBA indicates that the code is continued on the next line; you must precede the underscore with a space. In VBA, one line of code can contain up to 1024 characters, but breaking up a line can make your code more readable. We'll use the continuation character in this book to break up long lines of code in order to fit them on the page.

To call the Close method and pass only the first argument, saveChanges, you could pass the argument by order using the following:

Workbooks("BOOK1.XLS").Close True

Or you could pass the argument by name using the following:

Workbooks("BOOK1.XLS").Close saveChanges:=True

To pass the first and third arguments, you could do so by order by leaving a blank for the second argument:

Workbooks("BOOK1.XLS").Close True, , False

Or you could do so by name:

Workbooks("BOOK1.XLS").Close saveChanges:=True, routeWorkbook:=False

Referencing Objects: Singular Objects vs. Objects in Collections

The examples above showed that when you reference a property or method of a particular object, you simply append the name of the property or method to the object reference using the dot operator (.). You can reference objects, though, in two different ways: You can reference the name of a single object directly, or you can reference an index in a collection of objects. To understand these two ways of referencing objects, it's important that you have a clear understanding of collections. A collection, in its simplest definition, is a group of like objects. All Excel objects fall into two classes: singular objects and objects in a collection. Singular objects are referenced directly by name. Objects in a collection are referenced by an index in the collection. Approximately half of the objects in Excel are singular objects, and the other half are objects in collections.

Note Three objects in Excel—Range, Sheets, and DrawingObjects—deviate slightly from this classification scheme. The Range object is classified as a singular object, yet it assumes characteristics of both a singular object and an object in a collection. Sheets and DrawingObjects are both collections that contain collections of several other objects. Range, Sheets, and DrawingObjects are discussed in the following sections: "The Range Object—An Exception," beginning on page 15 in this chapter; "Multi-Sheet Workbooks," beginning on page 39 in Chapter 2; and "The DrawingObjects Collection," beginning on page 135 in Chapter 3.

F Y I

Collections Are Also Objects

Although a collection contains groups of objects, a collection itself is also an object—a singular object. It is an object that contains a group of like objects. This concept might be difficult to grasp at first, but it will be easier to understand as you become more familiar with the Excel object model. Perhaps an example would best illustrate the point.

The Worksheets collection contains all Worksheet objects. Each Worksheet object in the collection has properties and methods associated with it. It just so happens that the Worksheets collection also has a different set of properties and methods associated with it. You could say that there are three types of objects in Excel: singular objects, objects in collections, and collections. But technically speaking, collections are really singular objects. We won't dwell on the point, however; simply remember that collections are objects themselves and as such are associated with their own set of properties and methods.

Which Objects Are Singular, and Which Are Objects in Collections?

Of the 128 objects in Excel, you might wonder which are singular objects and which are objects in collections. You could memorize the names of all the objects as well as whether each object is singular or in a collection. Or you could apply two simple rules of intuition and avoid the work of memorization:

RULE 1 A singular object has only one instance in a given context. That is, it is a unique object—there is only one of this type of object in this object's context.

RULE 2 An object in a collection has multiple instances in a given context. That is, there are several of this type of object in the same context.

Applying these rules does require that you understand the 128 objects in Excel, and you will likely understand them after you read this book. In the meantime, let's look at a few simple examples. Excel has an object named Application. The Application object is a singular object that represents the Excel application. It is singular because Excel has only one Application object. The Font object is another example of a singular object. For any given cell on an Excel worksheet, only one instance of the Font object exists. Font does have multiple properties, including Name (Courier, Times New Roman, Helvetica, and so on), Bold (True or False), Italic (True or False), and Size (the size of the font in points). Yet, for a particular cell, there is only one Font object. Therefore, Font is a singular object.

The Worksheet object, on the other hand, is an object in a collection. Any Excel workbook file can have multiple worksheets and, therefore, multiple instances of the Worksheet object. For example, if you open a new workbook file in Excel, by default 16 worksheets are included in the workbook file—or 16 instances of the Worksheet object. Because the Worksheet object can exist in multiple instances within the same context, it is, by definition, an object in a collection. The Chart object provides another example. In an Excel workbook file, you can have multiple charts and, therefore, multiple instances of a Chart object. As such, the Chart object is an object in a collection. Figure 1-1 on the next page displays a collection of Chart objects.

Figure 1-1. A collection of Chart objects.

Referencing Objects Directly or by Collection Index

As mentioned, singular objects are referenced directly, and objects in collections are referenced by specifying an index in the collection in which the object exists. Let's take a look first at an example of referencing a singular object. The Application object, which is singular, has several properties, including the following:

Caption | A string that is displayed in the application title bar
DisplayAlerts | True (allows display of built-in Excel alerts) or False (prevents their display)
ScreenUpdating | True (Excel updates screen during macro execution) or False (Excel waits until macro completes before updating screen)

To set the Caption property, you reference the Application object directly:

Application.Caption = "My Custom Application"

Note

Macintosh users should use the following:

ActiveWindow.Caption = "My Custom Application"

Below you see the result of setting the Caption property of the Application object:

To turn off screen updating during macro execution, you set the ScreenUpdating property to False, again referencing the Application object directly:

Application.ScreenUpdating = False

Now let's take a look at referencing an object in a collection. Because the Worksheet object is an object in a collection, you must reference the Worksheet object by specifying an index in the Worksheets collection. To set the Name property of the Worksheet object that corresponds to the first worksheet, for example, you use the following code:

Worksheets(1).Name = "My First Worksheet"

The following screen example shows the result of setting the Name property of the Worksheet object:

And to set the name of the third worksheet, you use the following VBA code:

Worksheets(3).Name = "My Third Worksheet"

Note When you index the Worksheets collection to reference a specific Worksheet object, be sure to use the plural "Worksheets." You must do so for most collections in Excel, with only two exceptions—Range and SeriesCollection.

Indexing Collections by Number or by Name

You can specify an index in a collection by number (as shown in the examples above) or by name. When writing VBA code, you'll encounter times when using one or the other indexing scheme is advantageous. For example, it is usually easiest to process the items in a collection one by one using a numeric index. If you have a specific item (such as a "totals" worksheet), however, you can use a name index to jump directly to it without having to keep track of its numeric position in the collection.

Keep in mind when indexing by number that worksheets are numbered according to the order in which they are added to the workbook file. If you try to reference a Worksheet object by specifying an index number that is higher than the number of worksheets in the Worksheets collection, you will receive an error message at runtime. For example, if only 16 worksheets exist in the active workbook, any attempt to set properties of or call methods on Worksheets(17) will fail.

If you don't know the index number for an object in a collection, you can reference it by name instead. Each Worksheet object in a Worksheets collection has a name associated with it. These are the names displayed on the worksheet tabs at the bottom of the Excel screen. Let's assume you want to set the Visible property of a worksheet. The Visible property can take a value of True or False; if Visible is True, the worksheet is displayed, and if Visible is False, the worksheet is hidden from view. If the worksheet is named My Worksheet, for example, you might have no idea what numeric place that particular Worksheet object occupies in the Worksheets collection. Therefore, you could index the Worksheets collection by name instead of by number, as in the following example:

Worksheets("My Worksheet").Visible = False

Tip When indexing a collection by name, you must indicate the particular object name in double quotation marks within the parentheses. Also, VBA ignores case when indexing objects by name. For example, Worksheets("MY WORKSHEET") is the same as Worksheets("my worksheet").

F Y I

Beware of Changing the Name Property

Take care when you set the Name property of objects in collections because the Name property affects the way in which an object is referenced when indexed by name. For example, when the following two lines of code are executed, the second line generates an error message:

Worksheets("My Worksheet").Name = "New Worksheet Name"
Worksheets("My Worksheet").Visible = False

It generates an error message because the first line changes the name of the My Worksheet worksheet to New Worksheet Name. When VBA attempts in the second line to index the Worksheets collection by name using the worksheet's old name, it cannot find any Worksheet object in the collection by that name, and execution fails.

Let's look at some other examples of indexing collections by name. The Chart object has a property named HasLegend that can take a value of True or False. If HasLegend is True, a legend appears on the chart; if it is False, no legend appears. The Chart object is an object in a collection. Therefore, if you have a chart named Chart1 and you want to have a legend displayed on the chart, you index the Charts collection by name, as in the following code sample:

Charts("Chart1").HasLegend = True

The example chart below shows the result of setting the HasLegend property of the Chart object to True:

Let's suppose you have an application that opens and closes several Excel workbooks, one of which is named BOOK2.XLS. The Workbook object is an object in a collection. So to close BOOK2.XLS, you index the Workbooks collection by name and call the Close method, as in the following example:

Workbooks("BOOK2.XLS").Close

The Range Object--An Exception

We've seen the differences between referencing singular objects and referencing objects in collections and looked at examples of how objects in collections can be indexed either by number or by name. One Excel object—the Range object—falls into the gray area between singular objects and objects in collections. The Range object is used to reference a cell or a group of cells on an Excel worksheet. It is, by definition, a singular object; however, it also exhibits some of the behavior of an object in a collection. For example, to reference a specific range on a worksheet, you must index the Range object by address or by name in a manner similar to the way in which you index an object in a collection.

Suppose you wanted to change the contents of a particular cell. Range has a property named Value that represents the value contained in a cell or a group of cells. In addition, each cell on an Excel worksheet has an address that is specified by combining the column letter displayed at the top of the worksheet and the row number displayed on the left side of the worksheet. For example, the address of the first cell in a worksheet is A1. To set the Value property of the first cell on a worksheet, you could index the Range object using an address, as in the following example:

Range("A1").Value = 1

Here you see the result of setting the Value property of the Range object corresponding to the address A1:

Worksheet ranges can also have names. You can therefore index the Range object using the name of a cell or group of cells instead of an address. In the following code example, the first line sets the Name property of the first cell, referencing the Range object by address. The second line sets the Value property of the same cell, this time referencing the Range object by name:

Range("A1").Name = "FirstCell"
Range("FirstCell").Value = 1

Note

Cells that have names still retain their addresses. In the second line of code above, therefore, an index to the Range object by address would still execute properly. You should be aware, though, that you cannot index the Range object by number. For example, the following code example generates an error message:

Range(1).Value = 1

When you set properties of or call methods on the Range object, you can use an address index that contains multiple cells. For example, the following code sets the Value property of all the cells that fall into the address A1:F20.

Range("A1:F20").Value = 1

The Excel Object Hierarchy

Of the 128 different objects in Excel 5, not all exist on the same level—that is, some objects are contained within others. You can think of these levels as tiers in a hierarchy. (See Figure 1-2, beginning on page 18.) You need to understand this hierarchy and become familiar with the different tiers at which each object exists if you are to reference Excel objects effectively in your VBA code.

The Tiers of the Hierarchy

The topmost tier of the Excel object hierarchy is occupied by a single object: Application. The Application object represents Excel itself, and all other Excel objects fall under Application.

Seven objects are included in the second tier:

Workbook | The Excel file
AddIn | An Excel add-in file (discussed in chapters 7 and 12)
Debug | An object that represents the Excel Debug window
Dialog | An object that represents built-in Excel dialog boxes
MenuBar | An object used to access one of the many menubars in Excel
Toolbar | An object used to access one of the many toolbars in Excel
Window | An object used to access different windows in Excel

The third, fourth, and fifth tiers of the hierarchy include a variety of additional objects used to access functionality that the second tier objects contain. The Excel object hierarchy has a treelike structure. For example, if we descend from the Workbook object on the second tier down to the third tier of the hierarchy, we encounter the Worksheet, Chart, Module, DialogSheet, Style, Window, Name, RoutingSlip, and Mailer objects. Or if we descend from the Toolbar object on the second tier down to the third tier of the hierarchy, we encounter only one object, ToolbarButton.

The diagram in Figure 1-2 shows the Microsoft Excel 5 object model hierarchy. In the diagram, collections appear in boxes, with the names of the objects in the collection in parentheses. Although Excel has 128 objects, a different number of nodes are shown in this diagram. That's because each collection can itself be treated as an individual object. Also, certain objects—such as Font, Border, and Interior—are repeated in several places. The total number of objects does come out to 128.

Refer to the object model diagram shown in Figure 1-2 on the next page when you need help with the hierarchy of Excel 5's objects. For example, if you are writing code to set a property of the Range object, you can see from the diagram that the Range object falls under the Worksheet object in the hierarchy, which in turn falls under the Workbook object, which itself falls under the Application object. Or if you are writing code to call a method on the Legend object, you can see from the diagram that you have to descend from the Application object to the Workbook object and then to the Chart object before you finally reach the Legend object.

Figure 1-2. The Excel object hierarchy.

Using the Excel Object Hierarchy

How does the Excel object hierarchy affect you when you are writing VBA code? To manipulate the properties and methods of an object, you must sometimes reference all objects that lie on the hierarchical path to that object. You traverse that path down to a specific object by using the dot operator (.).

For example, let's suppose you are writing a VBA macro to set the Value property of a Range object that represents the first cell in the first worksheet of the first workbook in Excel. Using the full hierarchical path, the reference to Range appears as follows:

Application.Workbooks(1).Worksheets(1).Range("A1").Value = 1

Referencing the Application object implicitly

Although the code above executes properly in Excel, it is not always necessary to traverse the entire hierarchical object path when setting a property of or calling a method on a particular object. How far from the top of the hierarchy you must begin depends on the context in which the property setting or method call is made. The code example above, which starts at Application and steps all the way down to Range, could be executed anywhere in Excel under any circumstances and will always assign 1 to the Value property of the Range("A1") object on the first worksheet in the first workbook (provided a workbook is open). If this code is executed in Excel, as it would usually be, there is no need to reference the Application object. Application refers to Excel, so in the absence of an explicit reference to the Application object—and as long as the code is executed inside of Excel—VBA understands that the code is to be executed on Excel's Application object. Therefore, we can remove the reference to Application, as shown here:

Workbooks(1).Worksheets(1).Range("A1").Value = 1

Executing this line of code in Excel has the exact same effect as does executing the earlier line of code, which includes the reference to Application.

Referencing the active workbook implicitly

It is possible in Excel to have several workbook files open at one time. However, only one workbook can be active at a time—that is, a user can enter or manipulate data in only one workbook at any given time. The active workbook is displayed in front of all other open workbooks so that the active workbook window is on top in the Excel work area; the inactive workbook windows are displayed behind the active workbook. The preceding line of code uses an index to the Workbooks collection to reference the first workbook in the collection. Let's assume that instead of setting the property of the first workbook, the goal is to set the property of the active workbook. To do so, you use a Workbook object reference named ActiveWorkbook.

Object references such as ActiveWorkbook and ThisWorkbook are explained thoroughly in the "FYI" titled "Accessing Objects Through Properties and Methods," beginning on page 23. For now, here is an example:

ActiveWorkbook.Worksheets(1).Range("A1").Value = 1

This code executes on the workbook that is currently active, which might not be the same as Workbooks(1).

Tip You can also use ThisWorkbook to reference a Workbook object. ThisWorkbook, however, always refers to the workbook that actually holds the code being executed and not necessarily to the active workbook.

If only one workbook is open and that workbook is the one for which you want to set the property, you need not include the workbook reference in the hierarchical object path. VBA implicitly determines that the property setting is to occur on the one open workbook. You could therefore eliminate the workbook reference and use the shortened code shown here:

Worksheets(1).Range("A1").Value = 1

Note If the code above is executed while multiple workbooks are open, the property setting takes place in the active workbook.

Referencing the active sheet implicitly

In the same way that the ActiveWorkbook reference accesses the active workbook, a reference named ActiveSheet accesses the active sheet. If the property setting were to occur on the active worksheet, the preceding line of code could be changed to the following:

ActiveSheet.Range("A1").Value = 1

Here is the result of the altered line of code:

In addition, if the workbook has only one worksheet or if the context is such that the property setting is, by default, to occur on the active worksheet, the worksheet reference could be removed entirely:

Range("A1").Value = 1

This line of code sets the Value property of Range("A1") equal to 1 on the active worksheet. Note, though, that some objects in Excel have what is known as a "default property." Value is the default property of the Range object. That being the case, the line of code above could be shortened even further:

Range("A1") = 1

As mentioned, ActiveWorkbook and ActiveSheet can be used to reference the active workbook and the active worksheet. The active range—those cells on the worksheet that have been selected—can also be referenced by using the Application object's Selection property. Selection, however, can refer to other objects in addition to the Range object. During execution, VBA determines what type of object has been selected and evaluates Selection to the appropriate object. When using Selection, you cannot use default properties, so if Selection is used to set the Value property of a Range object, a specific reference to the Value property must be included, as the following code example shows:

Selection.Value = 1

Executing this code assigns 1 to the Value property of the currently selected range, be it Range("A1") or Range("A1:Z256").

At Which Level Should Object References Begin?

Looking back at the preceding discussion, you can see that—assuming the proper context—all of the following lines of code produce the same result:

Application.Workbooks(1).Worksheets(1).Range("A1").Value = 1
Workbooks(1).Worksheets(1).Range("A1").Value = 1
ActiveWorkbook.Worksheets(1).Range("A1").Value = 1
Worksheets(1).Range("A1").Value = 1
ActiveSheet.Range("A1").Value = 1
Range("A1").Value = 1
Range("A1") = 1
Selection.Value = 1

So at which level on the hierarchical object path should object references begin? If you were to play it safe, you would start all object references at the Application object. By doing so, you would always be certain about the objects in the path, and your code would always execute without error (assuming proper syntax). You would also find yourself typing an enormous amount of code. You should, therefore, try to keep track of the context in which object references are made and traverse the hierarchical object path accordingly, using longer paths where needed to avoid any errors that might arise when you are unsure of the context in which the code will execute. You can, however, abbreviate object references to take advantage of longer object references without having to type so much code; you do so by using object variables and With statements, both of which are covered in Chapter 2.

F Y I

Accessing Objects Through Properties and Methods

Before moving on, let's clarify two points about references to objects. As mentioned, singular objects are referenced by name, and objects in collections are referenced by an index in the collection. When you reference a singular object by name, you are actually using a property that points to the singular object. For example, Legend is a singular object that is contained in the Chart object. The VBA reference to the Legend object in a chart appears as follows:

Charts(1).Legend

In the above line of code, Legend is actually a property of the Chart object—a property that can be used to reference the Legend object associated with that particular chart.

When you specify an index in a collection to reference an object in a collection, you are making a method call; you pass an argument of either an integer or a string that corresponds to the object in the collection that you want returned. This example is used to reference the first worksheet in the first workbook:

Application.Workbooks(1).Worksheets(1)

The reference to Worksheets is actually a call to a method named Worksheets—a method of the Workbook object. The reference to Workbooks is, in turn, a call to a method of the Application object.

This distinction—that singular-object references are actually properties and that object-in-a-collection references are actually methods—is important to understand when you search for help on particular objects in Excel's online VBA Help. For example, if you look up the VBA Help topic for the Chart object, you find a property named Legend. This property returns the Legend object that's contained in the Chart object. On the other hand, if you look up the VBA Help topic for the Workbook object, you find a method named Worksheets. You can pass an argument to this method so that one Worksheet object is returned from the Worksheets collection that is contained in the Workbook object.

In addition, references to ActiveWorkbook, ThisWorkbook, ActiveSheet, and Selection are actually properties. For example, the Application object has a property named ActiveWorkbook that represents the currently active Workbook object. The following line of code calls the Close method on the active workbook:

ActiveWorkbook.Close

You could produce the same result using the full hierarchical object path:

Application.ActiveWorkbook.Close

When you use the ActiveWorkbook property and omit the reference to Application, VBA implicitly determines that the property is that of the Application object. The same holds true for ThisWorkbook, ActiveSheet, and Selection; for these as well, VBA determines the appropriate object by the context of the reference.

This use of properties and methods to reference objects runs counter to the definitions of properties and methods provided at the beginning of this chapter. Don't let this fact alter your view of the overall structure of the object model; it is relevant only to how the object model is documented in Excel.

Online VBA Help

Full online help is available for all objects, properties, and methods in Excel. After you start writing code in VBA, you will find the online reference an invaluable tool. By choosing Contents from the Help menu in Excel and then selecting Programming With Visual Basic, you can access help topics on all Excel objects as well as on their associated properties and methods. You can also get a listing of all Excel objects by selecting Objects from the main Visual Basic Reference Contents screen. And to search for a particular object, you simply choose the Search button and then enter the name of the object.

Help screens for all Excel objects are structured in the same manner. The top of the screen displays the name of the object, and the body of the screen presents a description of the object. Under the name of the object, the headings Properties and Methods, shown in the following illustration, are displayed in green:

By clicking either heading, you can access lists of the properties or methods for the displayed object. In the Properties and Methods lists, you can click a particular property or method name to access a help screen. All property and method help screens are structured in the same manner, as described below and as shown on the sample screen at the top of the next page. The top of the screen displays the name of the property or method, and the body of the screen is broken up into the following sections:

Applies To | Lists the objects to which the property or method applies
Description | Describes the property or method
Syntax | Provides the appropriate syntax to be used when setting the property or calling the method
Elements | Describes each of the syntactical elements of the property setting or method call; for a method, includes a full description of all arguments
Remarks | Provides any additional information about how to use the property or method and references to any associated properties or methods (see sample screen at top of next page)

At the top of the help screen, under the property or method name, you'll find two green labels: "See Also" and "Example." By clicking See Also, you can access other help topics related to the displayed property or method, and by clicking Example, you can view an example of syntactically correct code that shows the property being set or the method being called. Note that on the Example screen you also have the option of copying the code example to the clipboard so that you can paste it directly to your VBA module.

For a printed version of the VBA Help file, see the Microsoft Excel Visual Basic for Applications Reference, available from Microsoft Press.

The Application, Workbook, Worksheet, and Range Objects

The remainder of this book focuses on how to build custom applications using Excel objects. Although this book provides information about nearly every object in Excel, some objects are discussed at great length, and others because of space constraints are mentioned only briefly. Here we take a look at four Excel objects: Application, Workbook, Worksheet, and Range. These are four of the most commonly used objects in Excel, and gaining a basic understanding of them now will help you as you continue to read this book.

The diagram below shows the hierarchical structure of these four objects:

Figure 1-3 on the facing page displays these four objects as they appear in Excel.

The Application Object

Application is the topmost object in the Excel object hierarchy and represents Excel itself. Because Excel VBA applications run in Excel, you can think of the

Figure 1-3. The Application, Workbook, Worksheet, and Range objects as they appear in Excel.

Application object as representing the environment in which VBA applications run. Any property settings or method calls made on the Application object affect all of Excel and thereby also affect all VBA applications that run in the Excel environment.

The next two sections follow a format that is repeated for each object introduced here. A partial list of properties presents a short description of a property, the type of values the property can hold, information about whether the property is read/write or read only, and a segment of VBA code that shows how the value of the property can be set or retrieved. A partial list of methods gives a description of a method, the arguments that can be passed to the method, and an example of how the method can be called.

Only a few of the more important properties and methods are listed. For example, the Application object has over 100 properties and over 60 methods, but only a few of the more important ones are described here. For a complete list of properties and methods or for more information about a particular property or method, see Excel's online VBA Help.

Properties of the Application object

Caption: The Caption property is the caption that is displayed in the Excel title bar. String; read/write. Not available on the Macintosh.

Application.Caption = "My Custom Application"

DisplayAlerts: If DisplayAlerts is True, built-in Excel alerts are displayed. If it is False, alerts are not displayed. True or False; read/write.

Application.DisplayAlerts = False

Path: The Path property is the path to the directory in which Excel is installed. String; read only.

ExcelPath = Application.Path

ScreenUpdating: If ScreenUpdating is True, Excel updates the screen display as macros execute. If it is False, the screen display is not updated during execution. This property is True by default; it remains set only during execution of the macro in which the setting is made. True or False; read/write.

Application.ScreenUpdating = False

WindowState: The WindowState property is the state of the Application window. WindowState can take three different values:

xlNormal | Window in normal state
xlMaximized | Window maximized
xlMinimized | Window minimized; this argument not available on the Macintosh

Read/write.

Application.WindowState = xlNormal

Methods of the Application object

Calculate: The Calculate method forces all formulas in all worksheets in all open workbooks to be recalculated. Arguments: none.

Application.Calculate

Help: The Help method displays a help topic from a specified help file. Arguments:

helpFile | String that represents path to file
helpContextId | Integer that represents context ID number for help topic

Application.Help helpFile:="MAINXL.HLP", helpContextId:=100

Quit: The Quit method closes the Excel application. Note that if the DisplayAlerts property is set to False when the Quit method is called, Excel does not prompt the user to save any open workbook files. Arguments: none.

Application.Quit

Run: The Run method is used to execute an XLM macro. XLM is the Excel 4.0 macro language. Arguments: The first argument of Run is a string that represents the name of the macro to be run. Run can take additional arguments; the number and type depends on the number and type of arguments the macro expects.

Application.Run macro:="OldMacro", arg1:=100, arg2:="Revenue"

The Workbook Object

The Workbook object falls directly below the Application object in the Excel object hierarchy and represents an Excel workbook file. In terms of application development, think of the Workbook object as the delivery mechanism, or the container, of any VBA application that you create in Excel. A VBA application can span more than one workbook. Generally speaking, however, a single application can be characterized as existing in a single workbook. Any property setting or method call that you perform on the Workbook object affects your entire application.

A workbook can come in two forms: an .XLS file (or what is characterized as a standard Excel workbook) or an .XLA file (known as an Excel "add-in file"; .XLA files are fully compiled and hidden VBA applications). You can compile VBA code without creating an .XLA file; however, if you create an .XLA file, you will be certain that your code is, indeed, fully compiled. Also, .XLAs allow you to hide your code from users. Topics related to .XLA files are discussed in greater depth in Chapter 12. The following two sections describe some of the Workbook object's more commonly used properties and methods. For more information about these properties and methods, see Excel's online VBA Help.

Properties of the Workbook object

HasRoutingSlip: If HasRoutingSlip is True, a routing slip is added to the workbook. If it is False, any existing routing slips are removed from the workbook. A routing slip is used to route a workbook to several recipients through a MAPI compatible e-mail network. True or False; read/write.

Workbooks("BOOK1.XLS").HasRoutingSlip = True

Name: The Name property is the name of the workbook. Note that Name is a read-only property; to change the name of a workbook file, you must save the file with a new name using the SaveAs method. String; read only.

WorkbookName = ThisWorkbook.Name

Path: The Path property is the path to the workbook file. String; read only.

WorkbookPath = ActiveWorkbook.Path

Saved: If Saved is True, no changes have been made to the workbook since it was last saved. If it is False, changes have been made to the workbook since it was last saved. True or False; read only.

If Not(ActiveWorkbook.Saved) Then
  ActiveWorkbook.Save
End If

Methods of the Workbook object

Activate: The Activate method activates the first window associated with the workbook and makes the specified workbook active. Arguments: none.

Workbooks("MYAPP.XLS").Activate

Close: The Close method closes the workbook. Arguments:

saveChanges | If True, workbook saved before closing; if False, workbook not saved
fileName | String that represents name of file to which workbook is to be saved if saveChanges argument is True
routeWorkbook | If True and workbook has routing slip, workbook routed before it is closed

ActiveWorkbook.Close saveChanges:=False

Protect: The Protect method protects the workbook so that no changes can be made to it. Arguments:

password | String that represents password for workbook
structure | If True, worksheet structure of workbook protected
windows | If True, window structure of workbook protected; if False, window structure not protected

Workbooks(1).Protect "password", True, True

Save: The Save method saves the workbook. Arguments:

filename

String that represents name of file to which workbook is to be saved

ActiveWorkbook.Save

The Worksheet Object

The Worksheet object is contained in the Workbook object and serves several purposes in a VBA application in Excel. Its most important purpose perhaps is as the basis for designing forms; the majority of custom forms in Excel are designed using the Worksheet object. Worksheets also provide a powerful grid that can be used to display and manipulate data. In addition, worksheets contain over 400 built-in Excel functions that can perform advanced numeric calculations at lightning speed. And worksheets can serve as miniature databases. Their tablelike structure makes them ideal for storing, summarizing, and even performing lookup functions on small data sets.

Here we discuss a few of the Worksheet object's more commonly used properties and methods. For more information about these properties and methods, see Excel's online VBA Help. Worksheets themselves are discussed in greater detail in Chapter 5, which provides information about designing forms. In addition, Chapter 8 covers the different ways in which you can handle data on a worksheet. Recall that a worksheet can be referenced either by an index in the Worksheets collection or by using the Application object's ActiveSheet property.

Properties of the Worksheet object

Index: This is the numeric index of the specified worksheet object in the Worksheets collection. Integer; read only.

ActiveSheet.Name = "WkSheet" & ActiveSheet.Index

Name: This is the name of the worksheet. String; read/write.

Worksheets(1).Name = "My Worksheet"

UsedRange: The UsedRange property returns a Range object that references the range on the worksheet that contains data. Range object; read only.

Dim Range1 As Range
Set Range1 = Worksheets(1).UsedRange

Visible: If Visible is True, the worksheet is displayed. If Visible is False, the worksheet is hidden from view, but the user can restore the worksheet to view by choosing the Sheet command from the Format menu. If Visible is xlVeryHidden, the worksheet is hidden from view and can be restored to view only through a macro. True, False, or xlVeryHidden; read/write.

Worksheets("Main").Visible = xlVeryHidden

Methods of the Worksheet object

Activate: The Activate method activates the specified worksheet. Arguments: none.

Worksheets("My Worksheet").Activate

Calculate: The Calculate method forces all formulas on the worksheet to be recalculated. Arguments: none.

Worksheets(1).Calculate

Delete: The Delete method deletes the worksheet from the workbook. Arguments: none.

Worksheets("My Worksheet").Delete

Protect: The Protect method protects the worksheet so that no changes can be made to it. Arguments:

password | String to be used as password for worksheet
drawingObjects | If True, all graphical objects on worksheet protected; if False, unprotected
contents | If True, cells on worksheet protected; if False, unprotected
scenarios | If True, scenarios on worksheet protected; if False, unprotected

Worksheets("My Sheet").Protect "password"

The Range Object

The Range object is contained in the Worksheet object and is used to represent one or more cells on a worksheet. The Range object's primary purpose is to hold and display individual pieces of data: integers, strings, or formulas. The worksheet cells that a Range object represents actually possess a degree of intelligence. From a cell, you can access over 400 built-in Excel functions; you can call VBA functions; and you can even establish links to other cells that exist on the same worksheet, on other worksheets, or in other workbooks. Understanding the flexibility and power of the Range object allows you to tap into the power of Excel's built-in calculation engine and to create more powerful data analysis applications. We touch here on a few of the most commonly used properties and methods associated with the Range object, but we will deal with Range in greater detail in the section titled "Using the Range Object to Create Forms," beginning on page 246 in Chapter 5. For more information about these properties and methods, see Excel's online VBA Help.

Properties of the Range object

Count: The Count property is the number of cells in a range. Integer; read only.

NumOfCells = Worksheets(1).UsedRange.Count

Dependents: The Dependents property returns a range that contains all the dependents of the referenced range. Dependents are cells that reference the range in a formula. Range object; read only.

Dim Range1 As Range
Set Range1 = Worksheets(1).Range("A1").Dependents
MsgBox Range1.Address

Name: The Name property is the name of a range. String; read/write.

Worksheets(1).Range("A1").Name = "FirstCell"

Value: The Value property is the value contained in a range. If the range contains multiple cells, the Value property is an array that contains values for all the cells. Boolean, Integer, Long, Single, Double, Currency, Date, or String; read/write.

Worksheets(1).Range("FirstCell").Value = 1

Methods of the Range object

Calculate: The Calculate method forces all formulas in the range to be recalculated. Arguments: none.

Worksheets(1).Range("A1:F20").Calculate

ClearContents: The ClearContents method clears all values from the range. Arguments: none.

Worksheets(1).Range("A1:F20").ClearContents

Copy: The Copy method copies the values in the range either to another range or to the clipboard. Argument:

destination

Range to which values are to be copied (if nothing passed for destination argument, values copied to clipboard)

Worksheets(1).Range("A1").Copy

S U M M A R Y

This chapter has covered the concepts of objects, properties, and methods. You'll want to remember these important points:

  • Excel 5 is made up of 128 objects. Each object represents a feature or a piece of functionality in Excel.
  • Every Excel object has a unique set of properties and methods. You program Excel by using Visual Basic for Applications (VBA) to manipulate the properties and methods of Excel objects.
  • A property represents a value or a setting that describes an object. VBA can be used to either set or get a property setting.
  • A method represents an action that can be taken by or on an object. A method usually has a set of arguments associated with it that specify information about how the method is to be carried out. When using VBA to call a method, passing arguments is in most cases optional; you can pass all arguments, only some, or none. If arguments are used, however, they can be passed by order or by name.
  • Objects come in two different forms: singular objects and objects in collections. A singular object is a unique object only one instance of which occurs in a given context. An object in a collection is an object multiple instances of which occur in the same context.
  • You reference singular objects directly. You reference objects in collections by indexing the appropriate collection either by name or by number.
  • The Range object is by definition a singular object, but it is referenced in a manner similar to that of a collection: by indexing Range by name or by address.
  • Excel objects are arranged in a hierarchical structure; some objects are contained in others.
  • In setting a property of or calling a method on an Excel object, it is sometimes necessary to specify the entire hierarchical path for the object. The starting position on the hierarchical object path, however, depends on the context in which the property setting or the method call is made, and the path can sometimes be shortened.
  • Full online VBA Help is available in Excel for all objects, properties, and methods. You access VBA Help by choosing Contents from the Help menu in Excel and then selecting Programming With Visual Basic. Excel's online VBA Help is an excellent source of information about VBA, Excel objects, properties, and methods—as is the Microsoft Excel Visual Basic for Applications Reference (Microsoft Press).
  • The Application object exists at the top of the Excel object hierarchy and represents the environment in which VBA applications are run.
  • The Workbook object is contained in the Application object. The Workbook object represents an Excel file and serves as the container or delivery mechanism for VBA applications.
  • The Worksheet object is contained in the Workbook object and serves as the basis for designing custom forms in Excel.
  • The Range object is contained in the Worksheet object and serves a variety of purposes that involve data handling and data display.


Chapter 2 Visual Basic for Applications

The previous chapter introduced you to Microsoft Excel objects and explained properties and methods. This chapter focuses on the language that you use to manipulate Excel objects, Visual Basic for Applications (VBA). VBA is an implementation of Microsoft's award-winning visual programming tool Visual Basic, embedded in Excel. It is the glue that binds Excel objects together when you create custom applications. This chapter explains the most important VBA concepts, including subroutines, variables, data types, arrays, constants, functions, scoping, control structures, and VBA editing and debugging tools.

Although this chapter is comprehensive, its explanation of VBA moves at a rapid pace. This chapter will not necessarily serve well as a tool for learning everything about VBA. The purpose here is to give you as much information as is necessary to create powerful applications in Excel. After this chapter covers the fundamentals of the VBA language, the rest of this book focuses on using VBA with Excel objects to create custom applications.

Note Microsoft Excel Visual Basic for Applications Step by Step by Reed Jacobson (Microsoft Press, 1994) thoroughly explains all aspects of coding VBA modules.

If You Already Know Visual Basic

If you are already familiar with Visual Basic, you might want to merely skim some of this chapter because many of the syntax constructs used in VBA are identical to those used in Visual Basic. You should, however, read the sections that focus on those areas in which VBA differs from Visual Basic.

  • Variable scoping: VBA differs slightly from Visual Basic in this area. (See the section titled "Scoping of Variables, Constants, Subroutines, and Functions," page 77.)
  • The For-Each-Next control structure: This is a new control structure in VBA. (See the section titled "Using VBA's For-Each-Next Control Structure," page 101.)
  • The With statement: This is a new statement in VBA. (See the section titled "The With Statement," page 108.)
  • VBA editing and debugging tools: The tools for creating and testing VBA code are part of the Excel environment and are slightly different from Visual Basic's tools. (See the sections titled "The Structure of Excel Workbook Files," page 38; "Inserting a VBA Module," page 41; "Entering and Executing VBA Macros," page 42; and "VBA Editing and Debugging Tools," page 112.)

You should also review the summary list titled "Differences Between VBA and Visual Basic" on page 124 of this chapter.

F Y I

Where to Find the VBA Macro Code Examples

This book includes numerous examples of VBA macro code. You can find all of the code examples in the files on the companion disk packaged with this book. You might want to start Excel, open the appropriate file, and step through the code examples in the file as you read. (For Chapter 2, for example, the file is named CHAP02.XLS.) Note that the name of each macro in a file follows a predefined naming convention. For example, the first macro for this chapter is named Chap02aMacro1_SetRangeValue. The name has three components:

Chap02a: The name of the VBA module in which the macro resides in the CHAP02.XLS file

Macro1: An indication of the sequential order of the macro in this chapter

_SetRangeValue: A description of what the macro does

This naming convention helps you find a specific code example. Thus, the macro named Chap02fMacro59_IfThenElse resides in the VBA module named Chap02f, is the 59th macro in the chapter, and demonstrates the use of the If-Then-Else control structure. In the text, we abbreviate macro names by using, for example, simply "Macro59."

VBA Subroutines

VBA code is contained in what is called a "VBA macro." There are two types of macros: subroutines and functions. We discuss VBA subroutines first in this chapter. VBA functions, which are simply subroutines that return values, are discussed in detail in the section titled "Function Macros," beginning on page 74.

The VBA subroutine is the basic building block of all VBA applications. A subroutine is simply a stand-alone segment of code that holds a series of VBA commands. A VBA application can be defined as consisting of at least one VBA subroutine, although VBA applications generally consist of several subroutines (and functions). Let's take a look at a simple VBA macro:

Sub Chap02aMacro1_SetRangeValue()
    Workbooks(1).Worksheets(1).Range("A1").Value = 1
End Sub

In specifying a VBA subroutine, you must use certain keywords. In Macro1 above, for example, the word Sub on the first line and the words End Sub on the last line are the keywords that define the VBA subroutine. (All VBA subroutines begin with Sub and end with End Sub.)

Note The Sub and End Sub keywords in the example code above are formatted in boldface. In a VBA module in Excel, however, they usually appear on the screen in blue. (They appear in boldface in this example and in the code examples throughout the remainder of this book to make them stand out.) Excel colors all VBA keywords blue to show you as you write code that it recognizes the keywords you have entered. If you ever enter a keyword in Excel and Excel does not color it blue, go back and check your spelling. You will most likely have made an error in typing the keyword. You will find as you read this chapter that keywords are an integral part of the various features of VBA.

A subroutine in its simplest form can be defined as any segment of VBA code that contains the word Sub as the first word in the first line and the words End Sub in the last line. The subroutine example above assigns the number 1 to the Value property of the upper left cell on the first worksheet of the first workbook. Let's look at a few other simple examples of VBA subroutines. The following subroutine closes the active workbook:

Sub Chap02aMacro2_CloseWorkbook()
    ActiveWorkbook.Close
End Sub

The example subroutine below sets the Name property of the first worksheet in the first workbook to "My First Worksheet" and then sets the Visible property of the same worksheet to False, hiding the worksheet from view:

Sub Chap02aMacro3_SetWorksheetProperties()
    Workbooks(1).Worksheets(1).Name = "My First Worksheet"
    Workbooks(1).Worksheets("My First Worksheet").Visible = False
End Sub

Macro4 below resets the Visible property of the first worksheet to True:

Sub Chap02aMacro4_SetVisibleProperty()
    Workbooks(1).Worksheets(1).Visible = True
End Sub

As Macro3 showed, VBA subroutines can contain multiple VBA commands or, in this case, property assignments; a single VBA subroutine can contain thousands of lines of VBA commands. It is a good idea, however, to keep VBA subroutines short and concise so that they are easy to edit and understand.

How do you create and use the above VBA macros in Excel? Before you can write VBA macros, you must understand the structure of Excel workbook files and the process of inserting a VBA module in a workbook file. Let's deviate here from our discussion of VBA code to briefly cover these topics.

The Structure of Excel Workbook Files

After you start Excel, you see a screen similar to the one shown in Figure 2-1.

Figure 2-1. The Excel startup screen.

One of Excel 5's most distinguishing characteristics is that its files can contain multiple spreadsheets, or "worksheets," as they are called in Excel. In fact, a single Excel 5 workbook file can contain hundreds, even thousands, of worksheets. (In past versions of Excel, one Excel file corresponded to one Excel worksheet.) You access the different worksheets in an Excel workbook file by clicking the tabs located along the bottom border of the workbook file window. If you are running Excel as you read this book, try clicking the different tabs. As you click a tab, the corresponding worksheet is displayed in the workbook file window.

Note If no workbook file is displayed after you start Excel, you can open a new default workbook file by choosing the New command from the File menu.

Multi-Sheet Workbooks

An Excel workbook file can include five different types of sheets: worksheets, charts, Excel 4 Macro sheets, dialogsheets, and VBA modules. (Each is described below.) You must understand the multi-sheet architecture of the Excel workbook file if you are to understand how to enter and edit VBA code and even how to design VBA applications.

Worksheet: A standard Excel spreadsheet that contains a grid of cells in which numbers and data can be entered. In the Excel object model, the Worksheet object is used to refer to a worksheet. Figure 2-1 shows a worksheet.

Chart sheet: A sheet that contains a chart. A chart sheet does not contain grids of cells; it contains a chart only. Note that a chart in Excel can exist either in a chart sheet or as a graphical image floating on a worksheet—this second type of chart is referred to as an "on-sheet chart," meaning "a chart on a worksheet." It is easy to confuse "chart sheets" and "on-sheet charts." Simply remember that a chart sheet is a chart that is on a separate sheet by itself. Note that in the Excel object model, the Chart object is used to refer to chart sheets. Figure 2-2 on the next page displays a chart sheet.

Excel 4 Macro sheet: A sheet that contains Excel 4 XLM macros. If you have used Excel macros in earlier versions of Excel, you are familiar with the XLM macro language and how XLM macros are written and edited on separate sheets. An Excel 4 Macro sheet is not used to create VBA applications and exists in Excel 5 only for backward compatibility with applications that were developed in earlier versions of Excel. You can access an Excel 4 Macro sheet with VBA, however, by using the Excel4MacroSheets method, which returns a Worksheet object.

Figure 2-2. A chart sheet.

Dialogsheet: A sheet that holds a graphical display of a dialog box. You use dialogsheets to design dialog boxes that you then incorporate in VBA applications. (In Chapter 5, you'll find information about designing dialog boxes.) In the Excel object model, the DialogSheet object is used to refer to dialogsheets. Figure 2-3 displays a dialogsheet.

Figure 2-3. A dialogsheet.

Module: A sheet that contains VBA code. Modules are used to enter, edit, and store VBA code. As you write VBA applications, you will spend a good deal of time in VBA modules, so learning as much as you can about VBA modules and the VBA editing environment will make the job of creating and debugging code easier. Note that in the Excel object model hierarchy, the Module object is used to refer to VBA modules. The following section describes how to insert a VBA module. Figure 2-4 displays a VBA module.

Figure 2-4. A VBA module.

Inserting a VBA Module

To create a VBA application, you need to add code to a module, but when you first start Excel, a default workbook file contains only worksheets. (Click the tabs at the bottom of the workbook window, and you will see that this is the case.) You can insert a VBA module in a workbook in one of two ways. The first way is straightforward: From the Insert menu, choose the Macro command, and then select Module.

The second way involves using an Excel shortcut menu:

1. Point to any of the worksheet tabs at the bottom of the workbook window, and click the right mouse button to display the shortcut menu.

Note

If you are running Excel for the Macintosh, hold down the Option and Command keys while you click the mouse button to display the shortcut menu.

2. From the shortcut menu, select Insert to display the Insert dialog box. In the Insert dialog box, you have the choice of inserting any of the five kinds of sheets described on pages 39 and 40.

3. Select Module to insert a VBA module.

You now have a blank VBA module in which you can enter VBA code. You could save the workbook file that contains the VBA module and reopen it later to continue to write and edit VBA code in the same module. For now, though, keep the workbook file open so that you can enter and run a VBA macro.

Entering and Executing VBA Macros

To enter a macro in a VBA module, you simply begin typing at the top of the module. Remember that a VBA macro must begin with the keyword Sub and end with the keywords End Sub. Try entering the following macro:

Sub Chap02aMacro5_DisplayMsgBox()
    MsgBox "Hello World"
End Sub

This macro uses a built-in VBA function named MsgBox, which displays a message box on the screen. The MsgBox function takes as its first argument a string (up to 256 characters long) that is displayed in the body of the message box. MsgBox can also take several other arguments that govern how the resulting message box is displayed (the types of buttons used, the title, and so forth); however, the first argument is all that is necessary to display a simple box that includes the message and an OK button. MsgBox is one of several built-in VBA functions that allow you to perform an action aside from manipulating properties and methods of Excel objects.

After you enter Macro5 in your VBA module, the next step is to execute it. You can execute a macro in one of four ways:

  • Position the mouse cursor anywhere in the body of the macro, and choose the Start command from the Run menu.
  • From the Tools menu, choose the Macro command. Next select the name of the macro you want to run from the list of available macros, and then choose the Run button.
  • Position the mouse cursor anywhere in the body of the macro, and click the Run Macro button on the Visual Basic toolbar. (If the Visual Basic toolbar is not displayed, choose the Toolbars command from the View menu, select Visual Basic from the list of toolbars, and then choose OK.)

  • Position the mouse cursor anywhere in the body of the macro, and press the F5 key.

Run Macro5. If the macro executes successfully, a message box is displayed in the middle of the screen. Choosing OK closes the message box and causes the macro to finish executing.

F Y I

More Ways to Run Macros

You can also run a macro by attaching it to a menuitem or a shortcut key or by referencing a VBA function in a spreadsheet formula. These topics are covered in the "FYI" titled "Executing a Function by Calling It from a Worksheet Cell," beginning on page 76, and in the section titled "The Menu Editor Button," beginning on page 112.

Now try entering and executing the following macro:

Sub Chap02aMacro6_SetRangeValue()
    Worksheets(1).Visible = True
    Worksheets(1).Range("A1:B1").Value = 1
    Worksheets(1).Select
End Sub

After you execute Macro6 above, the first worksheet of the active workbook is displayed, and the value 1 appears in the cells that correspond to the range A1:B1 on the worksheet. Next try making a minor change to the macro by specifying a new range address of A1:F20.

Sub Chap02aMacro7_SetRangeValue()
    Worksheets(1).Range("A1:F20").Value = 1
    Worksheets(1).Select
End Sub

By running the above macro, you can set the value of a block of cells in a worksheet all in one command.

Variables

Variables are used to hold and manipulate values, or data, when a macro is executing. Using variables saves you time and effort in coding and makes your macros run faster. Variables can assume several different data types (see the next section), including various numeric types, strings, objects, variants, and user-defined types. Before you use a variable in your code, it is often a good idea to "dimension," or declare, the variable to set aside space in memory for holding the variable during execution. To dimension a variable, you include a simple statement at the top of your VBA macro, as explained in the section titled "Dimensioning a Variable," beginning on page 46.

Data Types for VBA Variables

The types of values that variables can hold are referred to as "data types." The following is a list of the data types that VBA variables can accommodate. For each data type, the list includes the amount of memory (in parentheses) required to hold a single variable for each data type and a definition.

Boolean: (2 bytes) True or False.

Integer: (2 bytes) Integer between -32,768 and 32,767.

Long: (4 bytes) Integer between -2,147,483,648 and 2,147,483,647.

Single: (4 bytes) Single precision floating-point (real number):

Negative single numbers: -3.042823E38 to -1.401298E-45.
Zero.
Positive single numbers: 1.401298E-45 to 3.042823E38.

Double: (8 bytes) Double precision floating-point (real number):

Negative double numbers: -1.79769313486232E308 to -4.94065645841247E-324.
Zero.
Positive double numbers: 4.94065645841247E-324 to 1.79769313486232E308.

Currency: (8 bytes) Currency; useful for fixed-point calculations in which accuracy is imperative:

-922,337,203,685,477.5808 to 922,337,203,685,477.5808.

Date: (8 bytes) Date values between January 1, 100, and December 31, 9999.

Object: (4 bytes) Object variable that can be used to refer to any Excel object.

String: (1 byte per character) String of text characters from 0 to 2 billion characters, depending on the operating system in which you are running Excel. (In Microsoft Windows 3.1, the upper limit on string variables is 65,535 characters.)

Variant: (16 bytes + 1 byte for each character if the variant holds a string) Can be used to represent any VBA data type (except a user-defined type). Occasionally you will need to store a piece of data in a variable and will be uncertain of the data's type. In such a situation, the variant data type is useful.

User-defined: (dependent on definition) Similar to data structures in other programming languages. User-defined types allow you to store multiple values of different data types in a single variable.

It is probably a good idea to know the names of the different data types listed above as well as the types of data they represent. For the numeric data types, however, you need not memorize the exact upper and lower bounds of the numbers they represent. Instead, you might want to remember these general definitions:

Integer | Medium-size integer numbers up to roughly 32,000
Long | Large integer numbers
Single | Very large floating-point numbers
Double | Very, very large floating-point numbers

Dimensioning a Variable

You dimension, or declare, a variable in a VBA macro to tell VBA to set aside extra memory to hold the variable while the macro executes. The amount of memory that VBA sets aside is determined by the variable's data type (as shown in the preceding list). You dimension a variable before it is used by placing a Dim statement for the variable at the beginning of a VBA macro or VBA module. Although you need not dimension variables before they are used, by doing so you can improve the performance of your macros and make them easier to debug. (You'll read more about the performance costs of undeclared variables in the section titled "The Pros and Cons of Using Variants," beginning on page 54.) Here is an example Dim statement for dimensioning a variable:

Dim Var1 As Integer

The above statement declares Var1 as a variable of the Integer data type and, by doing so, sets aside 2 bytes of memory for Var1. Three keywords are included in the statement above: Dim, As, and Integer. Let's take a look at each of the components:

Dim | Keyword that indicates a variable declaration (abbreviation for "dimension")
Var1 | Name of the variable
As | Keyword used as a qualifier to separate the variable name from the data type
Integer | Keyword that represents the name of the data type; can be any one of Integer, Long, Single, Double, Currency, Date, Object, String, Variant, or user-defined types

Here are some other examples of variable declarations:

Dim Var2 As Double
Dim Var3 As Date
Dim Var4 As Currency
Dim Var5 As Variant

It is possible to declare more than one variable in a single Dim statement. For each variable that you declare, however, you must use the As keyword, specify the appropriate data type, and include a comma to separate one variable from the next. The following is an example:

Dim Var2 As Double, Var3 As Date, Var4 As Currency, Var5 As Variant

Using Variables in Macros

Now let's take a look at using a variable in a macro. Macro8 uses an Integer variable to set the Value property of a Range object:

Sub Chap02aMacro8_UseIntegerVariable()
    Dim Num1 As Integer
    Num1 = 5
    Worksheets(1).Range("A1").Value = Num1
    Worksheets(1).Select
End Sub

This macro sets the Value property of range A1 on the first worksheet to the value stored in Num1, which in this case is 5. In the third line of the macro, an Integer value is assigned to the Num1 variable. Num1 then holds that value while the macro executes. In the fourth line of the macro, we use Num1 to set the Value property of the specified Range object. Let's look at an example in which a variable is assigned the value of a range:

Sub Chap02aMacro9_GetRangeValue()
    Dim Num1 As Integer
    Num1 = Worksheets(1).Range("A1").Value
    MsgBox Num1
End Sub

Macro9 above uses Num1 to get the setting of the Value property of the specified Range object. Assuming that Macro9 is run in the same workbook as the previous Macro8, the statement in the third line of Macro9 returns the value 5 and assigns it to the Num1 variable. Num1 then holds the value and is used again in the fourth line of the macro to display the value in a message box:

Macro9 above merely displays in a message box the setting for the Value property of range A1 on the worksheet. The same result can be accomplished easily without using a variable, as the following example shows:

Sub Chap02aMacro10_DisplayRangeValue()
    MsgBox Worksheets(1).Range("A1").Value
End Sub

Advantages of Variables

After reviewing the above example, you might be asking yourself, "Why use variables at all?" One good reason to use variables is if you need to use a specific value numerous times. For example, let's say you need to write a macro that assigns the Value property of range A1 in the active workbook's second, third, and fourth worksheets to the same setting as the Value property of range A1 in the first worksheet. If you do not use variables, you must write the following macro:

Sub Chap02aMacro11_SetValues()
    Worksheets(2).Range("A1").Value = Worksheets(1).Range("A1").Value
    Worksheets(3).Range("A1").Value = Worksheets(1).Range("A1").Value
    Worksheets(4).Range("A1").Value = Worksheets(1).Range("A1").Value
End Sub

If you use variables, however, you can write the same macro in fewer keystrokes and produce a macro that is easier to read and understand:

Sub Chap02aMacro12_UseIntegerVariable()
    Dim Num1 As Integer
    Num1 = Worksheets(1).Range("A1").Value
    Worksheets(2).Range("A1").Value = Num1
    Worksheets(3).Range("A1").Value = Num1
    Worksheets(4).Range("A1").Value = Num1
End Sub

In addition to offering fewer keystrokes and code that's easier to read, using variables makes your code execute faster. Macro12, for example, executes faster than does Macro11. We will look further at speed issues later in this section. For now, however, remember that every property or method reference and every hierarchical object reference requires a certain amount of processing by Excel and therefore a certain amount of time. In Macro11 above, you can count the number of object and property references by counting the number of times the dot operator (.) is used. In lines 2, 3, and 4 of Macro11, the dot operator is used four times in each line, for a total of twelve times in the whole macro. In Macro12, the dot operator is used two times in each of lines 3, 4, 5, and 6 for a total of eight times in the macro. If we think of the dot operator as representing a unit of processing time, Macro12 should take roughly two-thirds the time to execute that Macro11 does, which is indeed the case. With macros this simple, you cannot see the speed difference on your computer. With larger and more complicated macros, however, the difference becomes apparent.

Let's look at another example, this time using a variable of a data type other than Integer:

Sub Chap02aMacro13_DisplayString()
    Dim String1 As String
    String1 = "Hello World"
    MsgBox String1
End Sub

Macro13 assigns a value to the String variable String1 and then displays the value in a message box. And, in one more example, the macro below transfers a value from a String variable to the Value property of the Range object:

Sub Chap02aMacro14_UseStringVariable()
    Dim String1 As String
    String1 = "Important Data"
    Worksheets(1).Range("A1").Value = String1
    Worksheets(1).Select
End Sub

Object Variables

An object variable is a variable that is used to refer to an object. As you become a VBA expert, you will find that object variables are of tremendous use because they reduce the number of keystrokes required to write your VBA code. They make your code easier to read, and they improve the performance of your macros. Throughout the pages that follow, several examples demonstrate these advantages.

Setting an object variable

You declare and assign values to object variables in a slightly different way from that for other variables. Let's take a look at a code segment that shows how you make these declarations and assignments:

Dim Range1 As Object
Set Range1 = Worksheets(1).Range("A1")

You will notice that the declaration statement in the first line above is much like declarations for other variables. As you'll see shortly, however, in the declaration for an object variable you can actually specify the type of object being declared. But for now, focus on the second line, in which an object is assigned to the variable. Note that when you assign an object to an object variable, you must always use the Set keyword. If you look at the example above, for instance, the components of a statement that involves the assignment of an object variable are as follows:

Set | Keyword that indicates the assignment of an object variable
Range1 | Name of the object variable
= | Assignment operator
Worksheets(1).Range("A1") | Object assigned to the variable

Using object variables

What can you do with an object variable? Let's take a look at an example. The macro on the next page uses an Integer variable and an object variable to set the Value property of a Range object.

Sub Chap02aMacro15_UseObjectVariable()
    Dim Num2 As Long
    Num2 = 100000
    Dim Range1 As Object
    Set Range1 = Worksheets(1).Range("A1")
    Range1.Value = Num2
    MsgBox Range1.Value
End Sub

Macro15 above shows that we can use the object variable Range1 to set the Value property of the object Worksheets(1).Range("A1")—and then display the setting for that Value property in a message box:

Using specific object variables

As mentioned, you can use the exact name of the type of object when you declare a variable. For example, it is possible to dimension a Range object in the following manner:

Dim Range1 As Range

In this example, we use the specific name of the object, "Range," as the type of the object variable as opposed to the generic Object type. Here are a few other examples of object variable declarations in which the names of the objects are used as types when the variables are declared:

Dim Workbook1 As Workbook
Dim MyWorksheet As Worksheet
Dim XL As Application

You might wonder how you will know the name of the type of object to use when declaring object variables. Object types are simply the names of the objects in Excel—the same names that appear in the Excel object model hierarchy diagram in Chapter 1 (Figure 1-2, page 18) and the same names that are used for Excel objects throughout this book. After you become familiar with the 128 objects in Excel, you will know their names well.

Note that it is possible to make the same three object variable declarations shown above by using the generic Object type instead of the specific names of objects, as the example on the next page shows.

Dim Workbook1 As Object
Dim MyWorksheet As Object
Dim XL As Object

So, if it's possible to use the generic Object type when declaring object variables, why bother with declaring variables by using specific object names? If you declare object variables by using specific object names, you see better performance in your macros than if you use the generic Object type. When VBA performs a property setting or a method call on an Excel object via an object variable, VBA must first determine the type of object that the variable represents. If the generic Object type is used to declare the variable, VBA must do some extra work to determine the specific object type to which the variable refers. If the object variable is declared by specifying the name of the object to which the variable refers, however, VBA does not have to do that extra work. For simple macros, either approach will do. But for large and complicated applications, you can see measurable improvements in performance if you use object names to declare object variables rather than the generic Object type.

Let's take a look at an example in which declaring an object variable as a specific object type improves performance. Macro16 below uses two object variables that are declared with the generic Object type to exchange values between cells A1 and A2 on the first worksheet. The macro uses a For-Next loop to execute the operation 1000 times and the VBA Timer function to keep track of how much time is required for the macro to execute:

Sub Chap02aMacro16_UseGenericObjectType()
    Dim Range1 As Object
    Dim Range2 As Object
    Dim StartTime As Variant
    Dim x As Integer
    Set Range1 = Worksheets(1).Range("A1")
    Set Range2 = Worksheets(1).Range("A2")
    StartTime = Timer
    For x = 1 To 1000
        Range1.Value = 5
        Range2.Value = Range1.Value
    Next
    MsgBox (Timer – StartTime) & " seconds."
End Sub

After you run Macro16, a message box indicates how much time it took the macro to execute:

You can rewrite the same macro using the Range type to declare the two Range object variables:

Sub Chap02aMacro17_UseSpecificObjectType()
    Dim Range1 As Range
    Dim Range2 As Range
    Dim StartTime As Variant
    Dim x As Integer
    Set Range1 = Worksheets(1).Range("A1")
    Set Range2 = Worksheets(1).Range("A2")
    StartTime = Timer
    For x = 1 To 1000
        Range1.Value = 5
        Range2.Value = Range1.Value
    Next
    MsgBox (Timer – StartTime) & " seconds."
End Sub

Macro17 should run faster than Macro16 because VBA has to spend less time evaluating the types of objects to which the variables Range1 and Range2 refer. Here is the message box displayed by Macro17; when you compare the Macro16 and Macro17 times, it is apparent that Macro17 is faster:

F Y I

The Ampersand Operator (&)

In Macro16 and Macro17, we've introduced the ampersand operator (&). Ampersands are used to concatenate the contents of variables with strings—or even strings with strings. In the preceding two macros, VBA evaluates the elapsed time and then combines it with the literal string to form a single string that is passed to the MsgBox function.

A closer look at the advantages of using object variables

As we've seen, using object variables cuts down on the time required to write code, makes code easier to read, and makes your macros run faster. You save time writing your code by using object variables because object variables allow you to represent hierarchical object references with a single word (the name of the variable). For example, the following macro sets the Value, RowHeight, and ColumnWidth properties of the Range object; displays the setting for the Value property in a message box; and then calls the ClearContents method. Hierarchical object references starting at the Worksheet object are used to access the properties and methods of the Range object in this example:

Sub Chap02aMacro18_RangeObject()
    Worksheets(1).Range("A1").Value = 25
    Worksheets(1).Range("A1").RowHeight = 50
    Worksheets(1).Range("A1").ColumnWidth = 50
    MsgBox Worksheets(1).Range("A1").Value
    Worksheets(1).Range("A1").ClearContents
End Sub

You could rewrite this macro using an object variable to refer to the Range object, as the following example shows:

Sub Chap02aMacro19_RangeObjectVariable()
    Dim Range1 As Range
    Set Range1 = Worksheets(1).Range("A1")
    Range1.Value = 25
    Range1.RowHeight = 50
    Range1.ColumnWidth = 50
    MsgBox Range1.Value
    Range1.ClearContents
End Sub

Macro19 appears more concise than Macro18, and, in fact, fewer keystrokes were required to write Macro19. Using object variables also makes code easier to read; when you look at the statements in Macro19, you can easily see that actions are being performed on the same object throughout.

The third advantage of using object variables is improved performance. Object references take a certain amount of processing time in VBA, which you can approximate by counting the number of occurrences of the dot operator (.). Compare Macro19 with Macro18 above, and you will see that using an object variable results in fewer dot operators in Macro19 (five) than in Macro18 (ten). In fact, Macro19 runs roughly twice as fast as Macro18. Although it is difficult to measure the time differences between these two macros, such time differences become obvious, for example, when you are dealing with looping structures that execute hundreds of times.

Optional Variable Declaration and Variants

VBA has an interesting feature that is well appreciated by the renegade developer but scorned by those who are more organized in their code-writing habits. The feature is called "optional variable declaration." You've probably noticed that in all the macros that have been presented in this section on variables, each variable used has first been declared with a Dim statement. In reality, however, Dim statements are optional. If you fail to use a Dim statement to declare a variable, VBA simply dimensions the variable for you. For example, let's look at one of the macros presented earlier:

Sub Chap02aMacro13_DisplayString()
    Dim String1 As String
    String1 = "Hello World"
    MsgBox String1
End Sub

You can write this macro without the Dim statement; it executes in the same way as Macro13, even though the Dim statement for the variable String1 is omitted:

Sub Chap02aMacro20_NoVariableDeclaration()
    String1 = "Hello World"
    MsgBox String1
End Sub

When a Dim statement for a variable is omitted, the variable assumes the default data type—in this case, it's the Variant data type. In essence, therefore, String1 in Macro20 above is a variable of the Variant data type. Because variants can take on values of any data type, the macro runs without problem. In the following example, Macro20 has been rewritten to explicitly declare the variable as a variant:

Sub Chap02aMacro21_UseVariant()
    Dim String1 As Variant
    String1 = "Hello World"
    MsgBox String1
End Sub

The Pros and Cons of Using Variants

When a value is assigned to a Variant variable, VBA evaluates the value and coerces the variable to match the value's data type. Because VBA's default data type is Variant, a variable assumes the Variant data type if you omit a Dim statement for that variable. (It is possible to change the default data type to a different type, as you'll see in the following pages.) Omitting Dim statements and assuming the default data type for variables reduces the number of keystrokes required to write your code. Some developers will appreciate being able to use a variable whenever and wherever they want without having to worry about whether it is properly declared.

Using a default Variant data type, however, presents three disadvantages, and programmers who are concerned about structure and organization are probably aware of these problems. First, the Variant data type requires more memory. If you look back to the section titled "Data Types for VBA Variables," beginning on page 44, you'll see that variables of the Variant type require more memory than variables of any other data type, with the possible exception of user-defined variables (covered later in this chapter). Variant variables require 16 bytes (plus 1 byte per character for strings)—at least twice as much memory as is required for the other data types that also demand lots of memory: Currency, Date, and Double. For small macros, the memory demands present little problem, but with large and complicated macros that have lots of variables, you could definitely see performance problems; your application might even eat up all available memory.

The second disadvantage also involves performance. VBA is required to coerce a variable of the Variant type to meet the data type of any value being assigned to it. This process takes time. You see the results of these time demands most clearly when assignments to variants occur multiple times in a loop; each time the assignment occurs in each loop, VBA must perform the coercion.

The third disadvantage deals with keeping track of the data that variants contain. You can never be certain what type of data is contained in a Variant variable because a Variant can hold anything. Variants make debugging code and successfully implementing error-checking routines a cumbersome process. For example, if you always declare variables to be of specific data types, no question ever arises about the type of data a variable contains. If you use variants, however, you will often have to build checks into your code to determine whether the data held in the variant is of the proper type.

Let's take as an example a subroutine that performs a mathematical calculation on a variable. If the subroutine is called and an Integer variable is passed to the subroutine, no code need be implemented in the subroutine to determine that the data in the variable is numeric. If a Variant variable is passed to the same subroutine, however, error checking must be implemented to be sure that the variable contains numeric data and not a string, a date, or even an object reference. This error checking requires time and degrades performance further.

Despite the disadvantages mentioned here, variants do serve a purpose. In fact, variants are useful whenever you are uncertain about the type of data you are dealing with. For example, suppose you have written a subroutine that prompts a user to enter an integer. You can never be entirely certain that the user will actually enter an integer—perhaps the user will mistakenly enter a text string or a real number instead. Your subroutine must be able to accept the user's input and check the data before manipulating the data further. Variants are well suited to accepting user input because they can accept any type of input. Therefore, you would likely use a variant to accept the user input and then, after performing error checking, pass the value to another variable of the appropriate data type before manipulating the data further.

Forced Variable Declaration

VBA offers a feature called "forced variable declaration" that can keep you from inadvertently omitting variable declarations and thus protect you from the potential disadvantages of using variants. You can impose forced variable declaration in one of two ways: You can place the Option Explicit statement at the top of each VBA code module. (This statement must be included at the top of the module, before any subroutines or function macros.) Or you can choose the Options command from the Tools menu and, in the Options dialog box, click the Module General tab and check the Require Variable Declaration check box. When this check box is checked, Excel inserts the Option Explicit statement at the beginning of any new VBA module. Note that checking the Require Variable Declaration check box has no effect on existing VBA modules.

The following is an example of a macro that includes the Option Explicit statement:

Option Explicit
Sub Chap02bMacro22_UseString()
    Dim String1 As String
    String1 = "Hello World"
    MsgBox String1
End Sub

Again, the Option Explicit statement must reside at the beginning of the VBA module, before any subroutines.

If you remove the Dim statement but retain the Option Explicit statement, Excel generates an error message when you attempt to run this macro:

Option Explicit
Sub Chap02cMacro23_NoVariableDeclaration()
    String1 = "Hello World"
    MsgBox String1
End Sub

In Macro23 above, execution halts immediately, and Excel displays an error message:

You can circumvent this error message either by including a Dim statement for the String1 variable or by removing the Option Explicit statement.

Default Data Types

It is possible in VBA to change the default data type to something other than Variant. To do so, place a DefType declaration at the beginning of a VBA module. For example, if you want all undeclared variables to default to an Integer data type, place the following statement at the beginning of a VBA module, before any subroutines:

DefInt A-Z

The arguments A–Z after the DefInt keyword indicate that all undeclared variables that have names starting with any letter from A through Z (irrespective of case) should assume the Integer data type. Because DefType declarations take starting letters as arguments, it is possible for different undeclared variables in a module to take different data types, depending on each variable's first letter. For example, the following statements at the beginning of a VBA module force all undeclared variables that begin with the letter "I" to assume an Integer data type, all that begin with the letter "S" to assume a String data type, and all that begin with the letter "C" to assume a Currency data type:

DefInt I
DefStr S
DefCur C

In the absence of any DefType statements at the top of a VBA module, all undeclared variables assume the Variant data type by default.

Note You can place multiple VBA statements on a single line of code by separating the statements with a colon (:), as in the following example:

DefInt I: DefStr S: DefCur C

User-Defined Data Types

VBA allows you to create your own user-defined data types. Such user-defined data types are synonymous with structures found in other programming languages and can be defined simply as data types that form some combination of the other available data types in VBA. Using user-defined variables, you can group multiple values of different data types all in a single variable. Declaring a variable as a user-defined data type is a little more complicated than declaring a variable as another data type. Before you can declare a variable as a user-defined data type, you must first give a definition of the type. Definitions of user-defined types are always placed at the beginning of a VBA module.

Type PersonalData
    Dim PName As String
    Dim PAge As Integer
    Dim PBirthDate As Date
End Type

Let's look at the different components of the above user-defined type definition:

Type | Keyword that indicates a user defined data type definition
PersonalData | Name of the user defined data type
Dim PName As String | First element of the user defined data type
Dim PAge As Integer | Second element of the user defined data type
Dim PBirthDate As Date | Third element of the user defined data type
End Type | Keywords that indicate the end of the user defined data type definition

When placed at the top of a VBA module, the above user-defined data type definition creates a data type named PersonalData that contains three elements: a string represented by PName, an integer represented by PAge, and a date represented by PBirthDate. But how would you use a variable of the PersonalData type? Let's take a look at an example:

Type PersonalData
    Dim PName As String
    Dim PAge As Integer
    Dim PBirthDate As Date
End Type

Sub Chap02dMacro24_UserDefinedType()
    Dim User1 As PersonalData
    User1.PName = "Billijean"
    User1.PAge = 32
    User1.PBirthDate = #2/23/64#
    MsgBox User1.PName & ", Age " & User1.PAge & _
            ", Born " & User1.PBirthDate & "."
End Sub

In line 2 of Macro24 above, a variable named User1 is declared as type PersonalData. Then, in lines 3, 4, and 5, values are assigned to the different elements that are contained in the PersonalData type structure for User1: "Billijean" is assigned to PName, 32 is assigned to PAge, and #2/23/64# is assigned to PBirthDate. Line 6 of the macro then displays values of User1's elements in a message box:

F Y I

Date Literals

The macro above also introduces date literals. In line 5 of Macro24, an assignment is made to User1.PBirthDate by specifying a date that is enclosed in number signs (#). Number signs are required whenever you assign a literal date value to a Date variable. Literal dates are similar to literal strings—except that you enclose them in number signs instead of in double quotation marks.

Using VBA Arrays

VBA arrays offer a powerful approach to dealing with large amounts of data; you use VBA arrays much as you use arrays in other programming languages. An array is a variable that contains multiple values—in the simplest definition, it is an indexed group of values that all have the same data type. Whereas a non-array variable is useful in dealing with a single value of a particular data type, an array is useful in dealing with multiple values of a particular data type.

In reality, arrays are more complex than you might gather from the definition just given because they are multidimensional. All dimensions of an array are indexed numerically. A one-dimensional array is simply a single, indexed list of values. The list has a starting point (the first item) and an ending point (the last item), and each item in the list falls in line between the starting and ending points; no two items overlap, so each item has a unique index.

A two-dimensional array is a bit more complicated and is a group of lists that are all the same length. Such a group of lists is more commonly known as a "table" or a "matrix." It contains rows and columns, much as a spreadsheet does, and each value in the table occupies a position that represents the intersection of a certain row with a particular column. Figure 2-5 shows a simple example of a two-dimensional array.

Figure 2-5. A two-dimensional array is commonly called a "table" or a "matrix."

A three-dimensional array can be characterized as a group of tables in which each table has the same number of rows and the same number of columns. The concept of a three-dimensional array is similar to an Excel workbook, which contains multiple worksheets. You can access any value in a three-dimensional array by specifying three pieces of information: the row, the column, and the table.

Taking this discussion even further, we see that a four-dimensional array can be characterized as a larger group that contains groups of tables in which each group has the same number of tables and each table has the same number of rows and the same number of columns. Again using the Excel workbook example, a four-dimensional array is analogous to a directory of Excel workbook files: You can access any value in a four-dimensional array by specifying a row, a column, a table, and a directory.

VBA arrays can have up to 60 dimensions. Consider the possibilities entailed in using 60-dimensional arrays, and you can come up with some very complex sets of data. For the most part, however, in VBA you use either one- or two-dimensional arrays; three-dimensional arrays are rare. Arrays of greater than three dimensions are extremely rare and, depending on their size, could require more memory than is usually available on a personal computer.

Declaring an Array

Arrays operate in much the same way as do variables. Before you use an array, you must first declare it and specify the data type for the values that the array is to hold. Note that an array can hold values only of a single data type. It is easy to get around this limitation, however, by declaring an array to be of the Variant data type, which allows the array to hold any type of data. Array data types are exactly the same as the variable data types discussed in the section titled "Data Types for VBA Variables," beginning on page 44. Let's take a look at an example of an array declaration. This example declares a one-dimensional array of the Integer data type:

Dim NumberArray(10) As Integer

You'll notice that this array declaration is similar to the variable declarations discussed previously, with one exception: A number is enclosed in parentheses after the name used in the declaration. The number in parentheses indicates that this declaration is for an array and not for a single-value variable. The value (or values) enclosed in parentheses after the name provides information about the architecture of the array. In the example above, the presence of only one number indicates that NumberArray is a one-dimensional array, and the number 10 indicates that the size of the array is 10—or that the array can hold up to 10 integer values. That number actually refers to the upper bound of the array; when you state that the array can hold up to 10 values, it is assumed that the lower bound is 1.

F Y I

The Option Base Statement

Note that VBA allows lower bounds of arrays to start at either 0 or 1 by default, as governed by an Option Base statement at the beginning of a VBA module. Option Base 0 makes the default lower bound of the array 0, and Option Base 1 makes the default lower bound of the array 1. In the absence of an Option Base statement, array lower bounds are 0 by default. For the sake of simplicity, the examples that follow assume Option Base 1. Option Base statements are discussed in greater detail in the section titled "Option Base and Array Bounds," beginning on page 65.

A declaration for a two-dimensional array appears as follows:

Dim TableArray(10, 20) As String

TableArray above consists of 10 rows and 20 columns, which means it is capable of holding a total of 200 string values. And here's one more example. The following is a declaration for a three-dimensional array of variants:

Dim BigArray(50, 100, 5) As Variant

BigArray is composed of 5 tables, each of which consists of 50 rows and 100 columns, which means the array can hold up to 25,000 variants.

You can see from these examples that as you increase the number of dimensions of an array, its size (and therefore the number of values it can hold) grows quickly. After you declare an array, VBA sets aside enough memory to accommodate the array; how much memory must be allocated depends on the array's size and data type. Declaring a one-dimensional Integer array of size 10 requires 20 bytes because each Integer value occupies 2 bytes. BigArray declared above—the three-dimensional array of variants—requires at least 400,000 bytes (25,000 × 16). Take care if you plan to declare arrays of greater than two dimensions because they can eat up a lot of memory and negatively impact performance. The amount of memory allocated for an array depends on the amount of RAM available on your computer and the operating system under which you are running Excel. If you try to declare an array whose size will exceed the amount of available memory, you get an "Out of Memory" message.

Using an Array

After you declare an array, how exactly do you use it? Let's take a look at an example. Macro25 uses a three-element array of integers:

Sub Chap02dMacro25_IntegerArray()
    Dim Vals(3) As Integer
    Vals(1) = Int(100 * Rnd())
    Vals(2) = Int(100 * Rnd())
    Vals(3) = Int(100 * Rnd())
    MsgBox "Lottery Numbers: " & Vals(1) & ", " & _
            Vals(2) & ", " & Vals(3)
End Sub

In this macro, after the Vals array is declared in line 2 (a one-dimensional, three-element array of integers), assignments are made to the three elements in Vals in lines 3, 4, and 5. An assignment to an array element is similar to an assignment to a variable; however, for an array element, you must specify the index of the element to which the assignment is being made. In lines 3, 4, and 5, the index is specified in the parentheses that follow Vals.

Also notice an interesting formula that appears on the right side of the assignment statements in lines 3, 4, and 5. This formula uses two built-in VBA functions, Rnd and Int, to create a randomly generated integer between 0 and 100. The Rnd function generates real random numbers between 0 and 1. Rnd can take one argument, which can be used as a seed number. (See Excel's online VBA Help for details.) The Int function converts real numbers to integers by removing all numbers to the right of the decimal point (effectively, always rounding down). By multiplying the value returned by Rnd by 100 and then using the Int function to convert the product of this multiplication to an integer, we arrive at a random integer between 0 and 100. And by using the same formula three times to make assignments to the three elements of the Vals array, we end up with an array that contains three random integers. In line 6 of Macro25, you'll find a reference to each element by its index number, causing the values the array contains to be displayed in a message box:

The next example shows the use of an array of variants:

Sub Chap02dMacro26_VariantArray()
    Dim Data(3) As Variant
    Data(1) = "Johann"
    Data(2) = 84
    Data(3) = #3/21/12#
    MsgBox Data(1) & ", age " & Data(2) & ", born " & Data(3)
End Sub

In the example above, values of different data types have been assigned to the different elements of the array: a string to the first element, an integer to the second element, and a date to the third element. Because Data is an array of variants, values of any type can be assigned to any of its elements. Line 6 of Macro26 displays the values held by the elements of the array in a message box. We could extend the above example and create a two-dimensional array that might hold name, age, and birth date data for, say, 10 people:

Sub Chap02dMacro27_2DVariantArray()
    Dim Data2(10, 3) As Variant
    Data2(1, 1) = "Johann"
    Data2(1, 2) = 84
    Data2(1, 3) = #3/21/12#
    MsgBox Data2(1, 1) & ", age " & Data2(1, 2) & _
           ", born " & Data2(1, 3)
End Sub

If we look at the Data2 array in Macro27 above as a table, the code assigns values to those elements in the first row of the table. Additional code could be written to provide data for nine more people. Note that we can rewrite Macro27 to take advantage of the PersonalData user-defined type explained earlier in this chapter. In fact, we can achieve the same functionality as that in Macro27 by using a one-dimensional array of the PersonalData type, as the following example shows. Remember, the user-defined type definition must occur at the top of the VBA module.

Type PersonalData
    Dim PName As String
    Dim PAge As Integer
    Dim PBirthDate As Date
End Type

Sub Chap02dMacro28_UserDefinedTypeArray()
    Dim Data3(10) As PersonalData
    Data3(1).PName = "Johann"
    Data3(1).PAge = 84
    Data3(1).PBirthDate = #3/21/12#
    MsgBox Data3(1).PName & ", age " & Data3(1).PAge
End Sub

Below is the message box displayed by Macro28:

Dynamic Arrays

VBA actually provides two different types of arrays: dynamic arrays and fixed-size arrays. All of the examples we have looked at so far in this section have been fixed-size arrays, in which the size of the array is specified in the array's declaration statement. When you declare a dynamic array, the size of the array is not specified. In fact, the size of a dynamic array can be specified at any time the code is executing.

Dynamic arrays are useful when you know that the size of the array you are working with is going to change during code execution. If you are concerned about conserving memory, you can adjust the sizes of any arrays you use to meet your immediate needs; otherwise, you might have arrays in your code that are doing nothing but taking up memory, which can have a negative impact on performance. Let's take a look at a dynamic array. Macro29 below uses the ReDim statement to dimension Data4 first as a one-dimensional, two-element array and then as a two-dimensional, thirty-element array:

Sub Chap02dMacro29_UseDynamicArray()
    Dim Data4() As Variant
    ReDim Data4(2)
    Data4(1) = Int(100 * Rnd())
    Data4(2) = Int(100 * Rnd())
    MsgBox "Lottery Numbers: " & Data4(1) & ", " & Data4(2)
    ReDim Data4(10, 3)
    Data4(1, 1) = "Johann"
    Data4(1, 2) = 84
    Data4(1, 3) = #3/21/12#
    MsgBox Data4(1, 1) & ", age " & Data4(1, 2) & _
           ", born " & Data4(1, 3)
End Sub

In line 2 of Macro29 above, we start by dimensioning an array, Data4, as a variant, without specifying the number of dimensions or the number of elements. This statement declares a dynamic array, yet it does not allocate any memory to the array. It is not until the ReDim statement in line 3 that memory is allocated for the array. The ReDim statement declares a one-dimensional, two-element array. Lines 4 and 5 are then used to assign random integer values to the two elements of the array, and line 6 of the macro displays the values held by the elements of the array in a message box. In line 7, we use the ReDim statement again to change the array to a two-dimensional array that contains 30 elements. We then assign values to the elements in the first row of the array and display the values in a message box. This example shows how you can conserve memory during code execution by using dynamic arrays and the ReDim keyword to redimension arrays as the code executes. For more information about using ReDim and dynamic arrays, see Excel's online VBA Help.

Option Base and Array Bounds

In the examples of arrays given so far, all numeric indexing of array dimensions has started at 1. As mentioned earlier, you can make numeric indexing for an array dimension start at 0, 1, or any number you choose. Many developers prefer to have array indexing start at 0, and some prefer 1. VBA makes it easy to choose either 0 or 1 as the basis for starting array indexing by using an Option Base statement at the beginning of a VBA module. If you don't specify Option Base at the beginning of a VBA module, VBA defaults to Option Base 0.

If you want array indexing to begin at a number other than 0 or 1, you must specify the lower and upper bounds of the index in the declaration of the array. The following is an example:

Sub Chap02dMacro30_UseArrayBounds()
    Dim Data5(4 To 5) As Integer
    Data5(4) = Int(100 * Rnd())
    Data5(5) = Int(100 * Rnd())
    MsgBox "Lottery Numbers: " & Data5(4) & ", " & Data5(5)
End Sub

In Macro30 above, Data5 is a one-dimensional, two-element array. In the declaration of the array, however, the numbers enclosed in parentheses after the array name specify the lower and upper bounds of the array. In essence, Data5 is a two-element array that has number indexing beginning at 4 and ending at 5.

Five Array Functions

Five functions are used often with arrays in VBA; these are Array, Erase, IsArray, LBound, and UBound. Let's take a brief look at each of these functions.

The Array function

The Array function allows you to create an array during code execution without having to first dimension the array, as the following example shows:

Sub Chap02dMacro31_ArrayFunction()
    Data6 = Array("Johann", 84, #3/21/12#)
    MsgBox Data6(1) & ", age " & Data6(2) & ", born " & Data6(3)
End Sub

Line 2 of Macro31 above uses the Array function to create a fixed-size, one-dimensional, three-element array of variants. Well, that's not exactly correct, although it seems it should be. Data6 is not actually an array; it is a variant that contains an array—the array that the Array function returns. Even though Data6 is not really an array, it acts like one, so we won't bother getting caught up in the technical details here. Suffice it to say, the above code works. Note that the Array function always returns an array of variants and conforms to the numeric indexing specified by the Option Base statement at the beginning of the VBA module.

The Erase function

The Erase function can be used to erase the data that an array holds. With fixed-size arrays, Erase erases the values held by all the elements of the array without deallocating any memory that the array occupies. For a dynamic array, however, Erase not only erases values but also deallocates all of the memory assigned to the array. Here's an example of using Erase to eliminate the values in a fixed-size array:

Sub Chap02dMacro32_EraseFunction()
    Dim Data7(2) As Integer
    Data7(1) = Int(100 * Rnd())
    Data7(2) = Int(100 * Rnd())
    MsgBox "Lottery Numbers: " & Data7(1) & ", " & Data7(2)
    Erase Data7
    MsgBox "Lottery Numbers: " & Data7(1) & ", " & Data7(2)
End Sub

Macro32 above assigns values to a one-dimensional, two-element array and then displays them in a message box. Then, by using the Erase function, the macro eliminates the values in the array. The second call to the MsgBox function in line 7 of the macro displays the value 0 for the elements of the array. The following is an example of calling Erase on a dynamic array:

Sub Chap02dMacro33_EraseDynamicArray()
    Dim Data8() As Integer
    ReDim Data8(2)
    Data8(1) = Int(100 * Rnd())
    Data8(2) = Int(100 * Rnd())
    MsgBox "Lottery Numbers: " & Data8(1) & ", " & Data8(2)
    Erase Data8
    MsgBox "Lottery Numbers: " & Data8(1) & ", " & Data8(2)
End Sub

Executing Macro33 above results in a runtime error in Excel; the macro fails in line 8. When the Erase function is called in line 7, it wipes out all memory allocated to the dynamic array, Data8. After the array's memory is deallocated, VBA has no way to evaluate the array indices that are specified in the call to MsgBox in line 8, which causes the macro to fail and VBA to generate an error message.

When Macro33 causes an error, a VBA Error dialog box is displayed telling you which error occurred. The error in this case is "Subscript out of range." At this point, you can choose to take one of four actions: End the execution of Macro33 (choose End), go directly to the line of code that caused the problem (choose Goto), access a help screen that describes the error and its probable cause (choose Help), or debug your code (choose Debug). If you choose Debug, a new window is displayed, from which you can step through your code, examine the contents of variables, or even execute single VBA instructions. For more information about using the Debug window, see the section titled "The Instant Watch Button," beginning on page 117.

Tip You can also get to the Debug window by choosing the Debug Window command from the View menu whenever a VBA module is active. The Immediate tab of the Debug window offers a great way to try out single instructions as you enter and edit your code. The Debug window's Immediate tab is also covered more thoroughly in the section titled "The Instant Watch Button," beginning on page 117.

The IsArray function

IsArray is a built-in VBA function that allows you to test a variable to determine whether it is indeed an array. IsArray takes one argument and returns either True (if it is an array) or False (if it is not). IsArray is useful when you call a function that is supposed to return an array; you can use IsArray to verify that the value returned is indeed an array. The following example demonstrates IsArray:

Sub Chap02dMacro34_IsArrayFunction()
    Dim Data9(2) As Integer
    Dim ArrayBool As Boolean
    ArrayBool = IsArray(Data9)
    If ArrayBool = True Then
        MsgBox "Data9 is an array."
    End If
End Sub

Although the above example is not practical in a real-world sense, it does demonstrate the functionality of IsArray. In line 2 of the macro, an array is declared, and in line 3, a Boolean variable (ArrayBool) is declared. IsArray is then used to make an assignment to ArrayBool (either True or False). An If statement next determines whether the value in ArrayBool is True; if it is True, a message is displayed in a message box. (The syntax of the If statement is covered in detail, in the section titled "Altering Flow Using the If-Then-Else Control Structure," beginning on page 85.)

The LBound and UBound functions

You can use the LBound and UBound functions to determine the lower bound and upper bound indices of an array. Here's an example:

Sub Chap02dMacro35_LBoundAndUBound()
    Dim Data10(4 To 15) As Integer
    MsgBox "The lower bound is " & LBound(Data10) & "."
    MsgBox "The upper bound is " & UBound(Data10) & "."
End Sub

VBA Constants

A constant is a value that does not change during the execution of a macro. VBA constants are similar to constants found in other programming languages, and, in fact, constants represent exactly what their name implies: constant values. You use constants, therefore, when dealing with a value that you know will not change or that you do not want to change during the execution of a macro.

You declare constants in a manner that is similar to the way in which you declare variables, with one exception: Constants are assigned values in the same statement in which they are declared. After the declaration, constants cannot be changed. Any effort to change the value of a constant causes an error. Here's an example of a constant declaration:

Const MinVal As Integer = 1

As the example shows, you declare constants by using the Const keyword, followed by the name of the constant, the data type, and the value assigned to the constant. Constant data types are the same as those for variables, with one exception: You cannot declare a constant of a user-defined type. If you omit the data type for a constant in its declaration, the constant is given a data type that matches the value assigned to it. Note that expressions can also be used to assign values to constants, as in the following example:

Const TwoSquared As Integer = 2 * 2

You can also include multiple constant declarations in a single Const statement by separating the declarations with commas, as shown in the following example:

Const Con1 As Integer = 5, Con2 As Integer = 6, Con3 As Integer = 7

Constants do not come in the form of arrays, but you can use constants like you use a variable, provided you do not try to change the constant's value.

Calling One Macro from Another

In VBA, it's possible to call, or execute, one macro from another macro. This capability allows you to separate your code into logical segments. You gain two advantages by separating code into multiple subroutines. First, if you want to use a VBA routine repeatedly, you need only write this routine once and store it in a macro that can be called by any macro that requires it. Doing so also makes editing this shared routine easier because you have to make changes in only one place. Second, you can separate your VBA code into discrete, logical segments that are easy to code, debug, and maintain. If you could not call one subroutine from another, your VBA macros would be extremely long and difficult to edit and debug.

Use logic, however, when breaking up your application into separate macros. A single macro should represent a single functional operation. Be careful not to go overboard in this respect; you could potentially write a separate macro for each VBA command in your application. Deciding when a particular operation should stand alone functionally is largely a matter of preference and experience. Let's take a look at an example. Macro36 calls the DisplayMessage macro to display a message:

Sub Chap02dMacro36_CallSecondMacro()
    Dim Range1 As Range
    Set Range1 = Worksheets(1).Range("A1")
    Range1.Value = 500
    DisplayMessage
End Sub

Sub DisplayMessage()
    MsgBox "Data has been entered."
End Sub

This macro enters data in range A1 of the first worksheet. Then, in line 5, the macro makes a call to the second macro, DisplayMessage. The DisplayMessage macro executes, displaying a message before returning control to Macro36.

The DisplayMessage macro above is perhaps not practical; the call to the MsgBox function could just as easily have been placed in the body of Macro36. If you had several macros that involved entering data in some way, however, and all of them displayed a message box that indicated that data was entered, you could see how the DisplayMessage macro would be useful—ensuring that all macros displayed the same message. Also, using the DisplayMessage macro simplifies the process of changing the message displayed. By including the message in only one macro, you have to change it only once, rather than having to make the change in several places.

Passing Data When You Call a Macro

When you call one macro from another, it's possible to pass variables or data to the macro being called. This capability gives you greater power in separating your code into multiple subroutines by allowing a single routine to act on different inputs. Take as an example the DisplayMessage macro. It displays a message box that simply states "Data has been entered." Let's suppose you want the message box to display the actual value that has been entered instead—something like "The value 500 has been entered." The easiest way to do so is to specify an argument when calling the DisplayMessage macro. (You can pass a variable from one macro to another in two ways—see the next section.) In the following example, Macro37 calls and passes arguments to DisplayMessage2:

Sub Chap02dMacro37_PassArgumentToMacro()
    Dim Range1 As Range
    Set Range1 = Worksheets(1).Range("A1")
    Range1.Value = 500
    DisplayMessage2 Range1.Value
End Sub

Sub DisplayMessage2(Value1)
    MsgBox "The value " & Value1 & " has been entered."
End Sub

Two items of interest occur in the two macros above. First, in Macro37, the call to DisplayMessage2 contains an argument: Range1.Value. Second, in line 1 of the DisplayMessage2 macro, Value1 appears in the parentheses that follow the macro name. In this case, Value1 serves as a variable. And, in fact, Value1 assumes the value of the argument that is specified when the call to DisplayMessage2 is made. Value1 is then used in DisplayMessage2 to display the appropriate value in the message box:

Macro38 below shows another example of passing arguments when calling a macro. This macro passes elements of a user-defined type variable as arguments to DisplayMessage3:

Type PersonalData
    Dim PName As String
    Dim PAge As Integer
    Dim PBirthDate As Date
End Type

Sub Chap02dMacro38_PassUserDefinedElements()
    Dim User2 As PersonalData
    User2.PName = "Jane"
    User2.PAge = 35
    User2.PBirthDate = #3/31/61#
    DisplayMessage3 User2.PName, User2.PAge
End Sub

Sub DisplayMessage3(UserName, UserAge)
    MsgBox UserName & ", Age " & UserAge & "."
End Sub

In Macro38 above, two values are passed to DisplayMessage3: User2.PName and User2.PAge. DisplayMessage3 then displays both of those values in a message box.

Passing a variable by reference or by value

You can pass a variable from one subroutine to another in two ways: by reference or by value. When a variable is passed by reference, the variable itself is actually passed to the macro that is called, and the called macro can change the variable. When a variable is passed by value, however, the variable's value—and not the variable itself—is passed to the macro that is called, and the called macro cannot change the variable.

How do you pass a variable by reference or by value? You do so by specifying either the ByRef or the ByVal keyword in the parentheses that follow the macro name in the macro that is being called.

Note If you fail to specify either the ByRef or the ByVal keyword, variables are by default passed by reference.

Macro39 below calls the ChangeName macro and passes the UserName variable by reference:

Sub Chap02dMacro39_PassArgumentByReference()
    Dim UserName As String
    UserName = "Jeff"
    ChangeName UserName
    MsgBox UserName
End Sub

Sub ChangeName(ByRef UserName)
    UserName = "Dave"
End Sub

In the first line of the ChangeName macro above, the ByRef keyword and the name of the variable are specified in the parentheses that follow the macro name, indicating that the variable is being passed by reference—that is, the actual variable is being passed to the subroutine. In addition, a new value is assigned to the UserName variable in ChangeName. In fact, when the ChangeName macro finishes executing and returns to the calling macro, Macro39, the new value of UserName, which is "Dave," is displayed in a message box:

Note that in the macros above, the original name of the variable used in Macro39 is the same as that used in the ChangeName macro: UserName. You are not required, however, to use the same name in both instances. For example, the two macros below have the same effect even though they use two different variable names:

Sub Chap02dMacro40_ByRefDifferentVariableNames()
    Dim UserName As String
    UserName = "Jeff"
    ChangeName2 UserName
    MsgBox UserName
End Sub

Sub ChangeName2(ByRef NewName)
    NewName = "Dave"
End Sub

Passing a variable by value does not involve passing the variable itself but rather the value of the variable. Therefore, changes to the variable in the called subroutine cannot affect the value of the variable in the calling routine. You pass a variable by value in the same manner as you pass a variable by reference except that you use the ByVal keyword:

Sub Chap02dMacro41_PassArgumentByValue()
    Dim UserName As String
    UserName = "Jeff"
    ChangeName3 UserName
    MsgBox "Yet remains as " & UserName & " in the original macro."
End Sub

Sub ChangeName3(ByVal UserName)
    MsgBox "The original name is " & UserName & "."
    UserName = "Dave"
    MsgBox "The name is changed to " & UserName & _
           " in the called macro."
End Sub

The original value of UserName is passed to the ChangeName3 macro above, and the value is displayed in a message box. ChangeName3 then changes the value of UserName and displays the new value in a second message box. Because the argument was passed to ChangeName3 by value, the UserName variable still retains its original value when ChangeName3 finishes executing and returns control to Macro41. The value is displayed in a message box in the last line of Macro41.

Specifying Optional and ParamArray arguments

Two additional keywords can be used when passing arguments from one macro to another: Optional and ParamArray. The argument list of a called macro uses the Optional keyword to specify those arguments that are optional. After you declare an argument in an argument list as optional, all remaining arguments must be optional as well. In addition, all optional arguments are evaluated as variants.

Here's an example of an argument list that uses the Optional keyword:

Sub OptionalExample(ByVal Arg1, Optional ByRef Arg2, _
                    Optional ByVal Arg3)

A ParamArray argument will accept an arbitrary number of arguments from the calling macro and package them into an array of variants. (In the absence of any Option Base statement, the array is base 0.) You can use ParamArray only with the last argument in an argument list. Here is an example of an argument list that uses the ParamArray keyword:

Sub ParamArrayExample(ByVal Arg1, ParamArray Arg2())

For more information about the Optional and ParamArray keywords, see Excel's online VBA Help.

Function Macros

As mentioned, VBA uses two types of macros: subroutines and function macros. The first half of this chapter focused on subroutines; we'll look now at function macros.

Function macros are similar to subroutines; in fact, there are only three main differences between a function macro and a subroutine:

  • All function macros begin with the Function keyword and end with the End Function keywords.
  • Although you can run a subroutine in a stand-alone fashion—executing a macro in one of the ways explained earlier in this chapter—you cannot run a function macro stand-alone. Function macros must be called by subroutines or as part of a formula in a cell.
  • A function macro returns a value to the subroutine or formula expression that calls it.

Let's take a look at an example of a function that returns the product of two numbers:

Sub Chap02dMacro42_CallFunction()
    Dim Var1 As Integer
    Dim Var2 As Integer
    Dim Var3 As Integer
    Var1 = 5
    Var2 = 10
    Var3 = Multiply(Var1, Var2)
    MsgBox Var3
End Sub

Function Multiply(ByVal Var1, ByVal Var2)
    Multiply = Var1 * Var2
End Function

The Multiply function shown above is a simple function that merely returns the product of its two arguments. Notice that in line 2 of the Multiply function, the product of the two arguments is assigned to the name of the function. Such a statement in a function macro—where an assignment is made to the function name—specifies the return value of the function.

Note

You can specify the data type of each argument and of a function's return type, as in the following example:

Function Multiply (ByVal Var1 As Integer, _
ByVal Var2 As Integer) As Integer

Arguments and return types are variants by default if no data type is specified.

You might have noticed something interesting about the way in which Macro42 calls the Multiply function. The call is made by using an assignment statement in which a variable appears on the left side of the statement and the function name, along with a parameter list enclosed in parentheses, appears on the right side of the statement. This assignment statement assigns the return value of the Multiply function to the Var3 variable. In addition, the argument list for the function is enclosed in parentheses. In earlier examples of calling one subroutine from another, we saw that when arguments are passed to a subroutine, they are not enclosed in parentheses. You'd do well to remember the following general rules about passing arguments to functions or subroutines:

RULES

  1. Because a function returns a value, you can use a function in an expression—that is, you can use a function anywhere that you might normally use a variable or a literal value. When a function is used in an expression on the right side of an assignment statement or as an argument to some other macro, you must enclose any arguments to that function in parentheses.

  2. You can also call either a function or a subroutine using the Call keyword, in which case you must again enclose any arguments in parentheses. See Excel's online VBA Help for more information about using the Call keyword.

  3. If the function or subroutine is called by itself—not as part of an expression and without using the Call keyword—you must not enclose arguments in parentheses.

F Y I

Executing a Function by Calling It from a Worksheet Cell

You can execute a function macro by calling it directly from a worksheet cell—in the same way that you can call one of Excel's built-in worksheet functions. For example, by entering the Multiply function in a VBA module, you can access the function through a formula in a worksheet cell, as the following example shows:

=Multiply(50,100)

Also note that when calling a function macro from a cell formula, instead of passing values to the function, you can also pass range addresses. The function accepts the addresses as arguments and evaluates the values they contain. Here is an example:

=Multiply(A1,B1)

This call to Multiply returns the product of the values in cells A1 and B1.

Scoping of Variables, Constants, Subroutines, and Functions

All VBA variables, constants, subroutines, and functions have what is called "scope," which refers to the area in the VBA application in which a specific variable, constant, subroutine, or function can be accessed. For example, let's suppose that you declare a variable named Var1 in a macro named Macro1. Then suppose that you write a second macro named Macro2 in which you want to access the variable declared previously in Macro1—that is, Var1. If Var1 is declared in the body of Macro1 using the Dim keyword (shown in numerous examples in this chapter), Var1 has what is known as "procedure-level scope." That is, its scope is bounded by the procedure, or subroutine, in which it is declared. Therefore, you cannot access Var1 from Macro2—unless you expand the scope of Var1.

Let's take a different example—a function named Function1 that has been written in a VBA module named Module1. Suppose you want to call Function1 from a macro that resides in a different module—specifically, Module2. If Function1 was written using the Function keyword (as described in the previous section, titled "Function Macros"), Function1 has what is known as "project-level scope," meaning its scope is bounded by the workbook that contains the function. Because it has project-level scope, you can call Function1 from any macro in any VBA module in the workbook. If for some reason you wanted to prevent Function1 from being called by macros in other modules, you would have to limit the scope of Function1.

To get a more complete picture of scope, let's look at the scoping issues and at the ways you set scope for each of the main VBA elements we've discussed thus far: variables, constants, subroutines, and functions.

Scope of Variables

Although the scope of a variable refers to the area in your VBA application in which the variable can be accessed, the scope of a variable is also sometimes referred to as that area of the application in which the variable "stays alive" or retains the value that has been assigned to it. VBA provides three different levels of variable scope:

  • Procedure-level scope
  • Module-level scope
  • Project-level scope

These levels apply to arrays as well as to single-value variables. Also note that user-defined type definitions, which must occur at the top of a VBA module, by default have project-level scope. That is, after a user-defined type definition has been entered, you can declare a variable of that type anywhere in the workbook.

The following sections look at each of these levels of scope in more detail.

Variables: Procedure-level scope

A variable has procedure-level scope if it is declared using the Dim keyword in the body of a subroutine. In this example, Var1 has procedure-level scope:

Sub Chap02eMacro43_ProcedureLevelVariable()
    Dim Var1 As Integer
    Var1 = 55
    MsgBox Var1
End Sub

Any attempt to access Var1 from another macro will fail. Let's suppose that you write a second macro in the same module as Macro43 above and that in this second macro an attempt is made to access Var1. Let's also suppose that you change Macro43 by inserting a line at the end of the macro that calls this second macro. The resulting two macros would appear as follows:

Sub Chap02eMacro43ProcedureLevelVariable()
    Dim Var1 As Integer
    Var1 = 55
    MsgBox Var1
    Chap02eMacro44
End Sub

Sub Chap02eMacro44()
    MsgBox Var1
End Sub

Now, when you execute Macro43, the Var1 variable is declared and the value 55 is assigned to it and then displayed in a message box, as in the original macro. After the initial message box is displayed, however, the macro calls Macro44. Macro44 also attempts to display the value held by Var1 in a message box, but a blank message box is displayed instead of "55." Because Var1 has procedure-level scope, it does not retain its value outside of the macro (Macro43) in which it was declared. When Macro44 tries to access the value of Var1, VBA assumes that the Var1 variable referenced in Macro44 is an undeclared variant to which no value has been assigned and therefore displays an empty string in the message box. Figure 2-6 illustrates procedure-level scope.

If you want to be able to access the original value of Var1 (55) from Macro44, you could do so in one of two ways: As already discussed, you could pass Var1 from Macro43 to Macro44. Or you could change Var1 to module-level scope, which is described in the next section.

Figure 2-6. Var1, declared with procedure-level scope, is available only in Macro43. The shaded area represents the scope of Var1.

Variables: Module-level scope

A variable with module-level scope can be accessed by any subroutine or function macro that resides in the module in which the variable is declared. To declare a module-level variable, you place the declaration at the beginning of the VBA module, before any subroutines or function macros, as in this example:

Dim Var2 As String

Sub Chap02eMacro45_ModuleLevelVariable()
    Var2 = "Hello World"
    Chap02eMacro46
End Sub

Sub Chap02eMacro46()
    MsgBox Var2
End Sub

In the example above, Macro46 successfully accesses the correct value of Var2 as set in Macro45 because Var2 has been declared as a module-level variable and therefore retains its value throughout the VBA module. Figure 2-7 on the next page illustrates module-level scope.

Let's consider another case, in which a module-level variable named Var3 is declared and assigned a value in Module1. Suppose, however, that you have a macro in Module2 that must have access to this variable. Because a module-level variable retains its value only in the module in which it is declared, you must change the scope of the variable to be able to access it from different modules, as the next section explains.

Figure 2-7. Var2, declared with module-level scope, is available in all of module Chap02e. The shaded area represents the scope of Var2.

Variables: Project-level scope

A variable that has project-level scope can be accessed from and retains its value in any module in the workbook file in which it is declared. You declare variables of project-level scope by using the Public keyword; again, the declaration must occur at the beginning of any VBA module in the workbook, before any subroutines or function macros. Let's assume that we have two macros that exist in two different modules. One macro sets the value of a project-level variable, and the other displays the value in a message box. Here's an example:

Public Var3 As String

Sub Chap02fMacro47()
    Var3 = "This variable was declared and set in module Chap02f."
End Sub

Sub Chap02eMacro48_ProjectLevelVariable()
    Chap02fMacro47
    MsgBox Var3
End Sub

In the example above, Macro48 calls Macro47 in a separate module, which in turn sets the value of the project-level variable Var3. Macro48 then displays the value of Var3 in a message box. Figure 2-8 illustrates project-level scope.

Figure 2-8. Var3, declared with project-level scope, is available in all modules in the workbook. The shaded area represents the scope of Var3.

Static Variables

We have seen how the Dim and Public keywords can be used to declare variables; however, the Static keyword can also be used to declare variables—at the procedure level only. Normally, if a procedure-level variable is declared with Dim, the variable ceases to retain its value after the subroutine in which it is declared finishes executing—when execution encounters the End Sub or End Function statement at the end of the macro. Declaring a variable as Static extends the life of the variable until execution of all macros, including the macro in which the variable is declared, is finished, as shown in this example:

Sub Chap02fMacro49_StaticVariable()
    Chap02fMacro50
    Chap02fMacro50
End Sub

Sub Chap02fMacro50()
    Static Var1 As String
    Dim Var2 As String
    If Var1 = "" Then
        Var1 = "Var1: Static Value"
        Var2 = "Var2: Non-Static Value"
    End If
    MsgBox Var1
    MsgBox Var2
End Sub

Macro49 calls Macro50 twice. The first time it calls Macro50, the macro declares Var1 as a static variable and Var2 as a non-static variable. Execution then flows into an If statement, which compares Var1 to an empty string. The If statement evaluates to True because no value has yet been assigned to Var1. In the If statement, strings are assigned to both Var1 and Var2, and before the macro finishes executing, the values of Var1 and Var2 are displayed in message boxes. Macro50 returns control to Macro49, which then calls Macro50 a second time. Because Var1 was declared as a static variable, this time it retains its value and continues to retain its value until execution stops. The If statement evaluates to False because Var1 has retained its value; consequently, the assignment statements in the If clause are not executed. Finally, the values of Var1 and Var2 are displayed in message boxes a second time. Because Var1 has retained its value, we see the value of Var1 displayed, but because Var2 is non-static, it has not retained its value from the first time Macro50 executed. Therefore, when Var2 is displayed in a message box, we see only an empty string.

F Y I

A Few Words About Project-Level and Module-Level Variables and Compilation

After an assignment is made to a project-level or module-level variable, that variable maintains its value until a new assignment is made or until the user closes the Excel workbook file that contains the application. There is one other circumstance in which module-level and project-level variables lose the values they contain: when the VBA module in which those variables exist reaches an uncompiled state. A VBA module reaches an uncompiled state whenever a change is made to the module—specifically, whenever the macro is edited. The first time a macro in the affected module is executed, the whole module is compiled. After this first execution, the module remains in a compiled state until any changes are made to it. To ensure that all modules are compiled at the time you save and distribute a VBA application, be sure to run at least one macro in each module to force compilation. You can also force all VBA modules to be compiled by creating what is called an "XLA Add-In." These topics are discussed in greater detail later in this book. For now, remember that if you edit a module, data held by any module or project-level variables in that module is lost, and you will be forced to run code to re-initialize the variables.

Scope of Constants

Constants have the same three levels of scope as do variables: procedure, module, and project. The way in which constants are declared with each level, however, differs slightly from that of variables. Constants that have procedure-level scope can be accessed only from within the subroutine in which they are declared. The following is an example:

Sub Chap02fMacro51_ProcedureLevelConstant()
    Const USCapitalCity As String = "Washington, D.C."
    MsgBox "The capital of the U.S. is " & USCapitalCity & "."
End Sub

You declare constants of module-level scope by using the Const keyword at the beginning of a VBA module, as shown in the following examples:

Const MoonLandingDate As Date = #7/20/69#
Sub Chap02fMacro52_ModuleLevelConstant()
    MsgBox "People first walked on the moon on " & _
           MoonLandingDate & "."
End Sub

Sub Chap02fMacro53_ModuleLevelConstant()
    MsgBox "I was in Los Angeles on " & MoonLandingDate & "."
End Sub

As the above examples show, module-level constants can be accessed by any macros that reside in the module. Note also that a module-level constant can be declared with the keyword Private, as in the following example:

Private Const MoonLandingDate As Date = #7/20/69#

Using the Private keyword in a declaration of a module-level constant makes the constant available in that particular module only. All module-level constants are private by default, however, so you need not be concerned about including the Private keyword.

To declare project-level constants, you include the Public and Const keywords at the beginning of a VBA module, as in the following example:

Public Const ColorOfSky As String = "Blue"

You can access project-level constants from anywhere in the workbook file in which they are declared.

Scope of Subroutines and Function Macros

Subroutines and function macros have only two levels of scope: module-level scope and project-level scope. Macros have, by default, project-level scope; they can be called by any macro in any module in the workbook. It is possible to declare a subroutine or function by using a Public keyword, as in the examples on the next page.

Public Sub Chap02fMacro54_ProjectLevelMacro()
    Dim Var1 As Integer
    Var1 = 1
    MsgBox AddOne(Var1)
End Sub

Public Function AddOne(ByRef Var1)
    AddOne = Var1 + 1
End Function

Because all macros by default have project-level scope, the only reason to use the Public keyword is to make those macros easily identifiable as being at the project level. Omitting the Public keyword, however, has no functional effect.

To make a macro module-level in scope, you use the Private keyword before the subroutine or function declaration. Note that declaring a macro by using the Private keyword makes it impossible for the macro to run stand-alone; private macros can be called only from other macros. The following is an example:

Sub Chap02fMacro55_ModuleLevelMacro()
    Var1 = GetRand
    Chap02fMacro56 Var1
End Sub

Private Sub Chap02fMacro56(ByVal Var1)
    MsgBox Var1 * GetRand
End Sub

Private Function GetRand()
    GetRand = Int(100 * Rnd())
End Function

In the example above, Macro55 first calls the GetRand function to get a random integer between 1 and 100 and then calls Macro56, passing the integer. Macro56 then multiplies its argument by the result of another call to GetRand before it displays the product in a message box.

Static Subroutines and Function Macros

You can declare subroutines and function macros as static, and when you do so, all variables in those subroutines and functions become static also. The following provides an example:

Sub Chap02fMacro57_StaticMacro()
    Chap02fMacro58
    Chap02fMacro58
End Sub

Static Sub Chap02fMacro58()
    Dim Var1 As String
    If Var1 = "" Then
        Var1 = "Var1 is not yet proven to be static."
    Else
        Var1 = "Var1 is static."
    End If
    MsgBox Var1
End Sub

Var1 in the example above is declared and set in Macro58 and is static because Macro58 is static. When you run Macro57, it calls Macro58 twice and displays a message box both times, the second time confirming that Var1 is indeed static.

Control Structures

VBA provides several control structures that you can use to control the flow of execution of your macros. You will find that these control structures give you a great deal of power and flexibility in creating complex routines. These control structures are functionally equivalent to those generally found in other programming languages, with the exception of one new structure in VBA—the For-Each-Next structure. The following list describes the most commonly used VBA control structures:

If-Then-Else | Tests a condition and alters execution flow based on the results of the test
For-Next | Carries out a repetitive action a specific number of times
While-Wend | Carries out a repetitive action while a specific condition is True
Do-Loop | Carries out a repetitive action either while a specific condition is True or until a specific condition becomes True
Select Case | Branches to one of several possible code segments based on the value of a variable or the outcome of a specific test
For-Each-Next | Performs a repetitive action on each object in a collection or on each item in an array

The following sections take a closer look at each of these control structures.

Altering Flow Using the If-Then-Else Control Structure

You use the If-Then-Else control structure to alter the flow of execution based on the evaluation of what is referred to as a "test condition." The code on the next page provides an example.

Sub Chap02gMacro59_IfThenElse()
    Dim Num1 As Integer
    Num1 = GetRandomNumber
    If Num1 = 7 Then
        MsgBox "Congratulations! You received the winning " & _
               Num1 & "."
    Else
        MsgBox "I'm sorry; you lose. Your number was " & _
               Num1 & "."
    End If
End Sub

Function GetRandomNumber()
    GetRandomNumber = Int(10 * Rnd())
End Function

Macro59 above starts by calling the GetRandomNumber function to set Num1 to a random integer between 1 and 10. The macro then uses an If statement to evaluate a test condition, Num1 = 7. If the test condition evaluates to True (Num1 is equal to 7), VBA executes the first MsgBox statement and displays a message announcing that the winning number has been received:

If the test condition in Macro59 evaluates to False (Num1 is not equal to 7), however, VBA executes the second MsgBox statement and displays a message stating that a losing number has been received.

Let's look at the individual elements that make up the above If-Then-Else statement:

If | A keyword that indicates the start of an If-Then-Else statement.
Num1 = 7 | The test condition. The initial test condition always follows the If keyword and is used to determine the flow of execution through the If-Then-Else statement. The evaluation of the test condition can result in only one of two values—either True or False—and the execution flow is altered based on the result. If the test condition evaluates to True, execution flows to the line immediately after the If statement and continues until an Else statement is encountered. After the Else statement is encountered, execution jumps to the line that contains the End If keywords. If the test condition evaluates to False, execution jumps immediately to the line that contains the Else statement and continues until the End If statement is encountered.
Then | A keyword that signals the end of the test condition.
MsgBox "Congratulations! You received the winning" & Num1 & "." | The statement that is executed if the test condition (Num1 = 7) evaluates to True.
Else | A keyword that indicates where execution should stop if the test condition evaluates to True and where execution should start if the test condition evaluates to False.
MsgBox "I'm sorry; you lose. Your number was " & Num1 & "." | The statement that is executed if the test condition (Num1 = 7) evaluates to False
End If | Keywords that indicate the end of the If-Then-Else control structure.

In an If-Then-Else statement, the Else keyword and the code segment that follows it are optional. If both are omitted and the test condition evaluates to False, execution flows immediately to the End If keywords and exits the If-Then-Else control structure.

Providing an alternative test condition by using ElseIf

As shown previously in Macro59, the If-Then-Else control structure is useful for executing statements selectively, depending on the evaluation of a test condition. Let's take a look at another example of If-Then-Else—one that contains the ElseIf keyword. Macro60 below prompts the user for a password. Depending on the password entered, the macro grants certain worksheet access and displays a message box that indicates the level granted:

Sub Chap02gMacro60_IfThenElseIf()
    Dim Password As String
    Password = GetPassword
    If Password = "level1" Then
        For Each Sheet In ActiveWorkbook.Sheets
            Sheet.Visible = True
            Sheet.Unprotect
        Next
        MsgBox "You have read/write access to all sheets."
    ElseIf Password = "level2" Then
        ActiveWorkbook.Worksheets(1).Visible = True
        ActiveWorkbook.Worksheets(1).Unprotect
        MsgBox "You have read/write access to one worksheet."
    ElseIf Password = "level3" Then
        ActiveWorkbook.Worksheets(1).Visible = True
        MsgBox "You have read-only access to one worksheet."
    Else
        MsgBox "Password incorrect. Please try again."
    End If
End Sub

Function GetPassword()
    GetPassword = LCase(InputBox("Enter Password:", "Password"))
End Function

In Macro60, the If-Then-Else statement contains two instances of an ElseIf keyword followed by a condition. The ElseIf keyword provides an alternative test condition if the previous test condition evaluates to False. The first test condition in Macro60 comes immediately after the If keyword: Password = "level1". If this initial test condition evaluates to False, execution jumps immediately to the first ElseIf keyword, at which point a new test condition is introduced: Password = "level2". From here on, VBA ignores the original condition and concentrates solely on the new one. If the new test condition evaluates to False, execution again jumps to the next ElseIf keyword, where the process continues.

Looking at Macro60, you might have noticed a few other items of interest. The segment that immediately follows the If statement includes a For-Each-Next loop. (For-Each-Next is discussed in greater detail in the section titled "Using VBA's For-Each-Next Control Structure," beginning on page 101.) The For-Each-Next loop in this macro goes through all the sheets in the active workbook and performs the same two actions on each sheet: It sets the Visible property of each sheet to True so that the user can see the sheets, and it calls the Unprotect method on each sheet. (Individual sheets in an Excel workbook can be password protected; calling the Unprotect method unprotects a sheet.) Unprotect takes a single argument—a string that represents a password. It is possible to protect a sheet without a password. Let's assume that the worksheets don't have a password in this example; therefore, no password argument is passed to Unprotect. As you look at the other code segments that follow the ElseIf keywords, you can see that, depending on the evaluation of each test condition, the Visible property of the first worksheet is selectively set to True, and the Unprotect method of the same worksheet is selectively called.

F Y I

Using the LCase and InputBox Functions to Get Lowercase User Input

Line 3 of the preceding Macro60 calls a function named GetPassword, in which you might have noticed a few new items. Let's take a look at this function again:

Function GetPassword()
GetPassword = LCase(InputBox("Enter Password:", "Password"))
End Function

GetPassword uses two built-in VBA functions—LCase and InputBox. LCase takes one string argument and returns the same string with all letters converted to lowercase. InputBox displays a box on the screen that requests input from the user. InputBox takes several optional arguments, although here we will concern ourselves only with the first two arguments. The first argument is a string that will be displayed to the user as a prompt in the body of the input box. The second argument is a string that will be displayed at the top of the input box in the title bar. When the InputBox function is called, an input box is displayed that includes the appropriate prompt string and title bar string as well as an empty edit box in which the user can type a value. If the user chooses OK in the input box, the string value that the user has entered is returned. (If the user chooses the Cancel button, however, an empty string is returned.) In the GetPassword function, the string is then passed to the LCase function, which converts it to lowercase.

Using the For-Next Control Structure to Repeat an Action

The For-Next control structure lets you execute the same action a certain number of times. Let's take a look at an example in Macro61 below, which raises the number contained in the variable Base to the power of the number contained in the variable Power:

Sub Chap02gMacro61_ForNext()
    Dim Base As Integer
    Dim Power As Integer
    Dim Result As Integer
    Dim Count1 As Integer
    Base = 4
    Power = 5
    Result = 1
    For Count1 = 1 To Power Step 1
        Result = Result * Base
    Next
    MsgBox Base & " raised to the " & Power & "th power = " & Result
End Sub

This macro determines the result of the value of 4 raised to the fifth power by using a For-Next loop. VBA has a built-in exponent operator (^) that can easily perform this calculation for you. To assign the value of 4 raised to the fifth power to variable Num2, you execute the following statement:

Num2 = 4 ^ 5

We are using the For-Next loop in this circumstance, however, as an example only. Macro61 above uses four integer variables to perform the calculation: Base, which holds the value 4; Power, which holds the value 5; Result, which holds the result of 4 raised to the fifth power; and Count1, which is used as the counter in the For-Next loop. Let's look at the individual components of the For-Next loop:

For | Keyword that indicates the start of the For-Next loop.
Count1 = 1 To Power | Expression that contains a counter variable as well as start and end values that determine the number of times the loop is executed. In this case, a variable named Count1 is used as the counter variable. The To keyword is used to separate the start value from the end value. With 1 as the start value and Power as the end value, the loop begins executing by setting the counter variable equal to 1.
Step 1 | Keyword used to specify the value by which the counter variable is incremented or decremented with each loop execution. In the majority of For-Next loops, the step value is 1. It is possible, however, for the step value to be any real number, and it can even be a negative number (in which case the counter variable is decremented with each loop execution). At the beginning of every loop execution, the counter variable is compared with the end value. If the step value is positive and the counter variable is greater than the end value, execution flows out of the loop and on to the statements that follow the For-Next loop. On the other hand, if the step value is negative and the counter variable is less than the end value, execution also flows out of the loop. Specifying the Step keyword and the step value is optional; if you omit them, VBA assumes Step 1.
Result = Result * Base | Statement that is executed with each loop. The body of a For-Next loop can contain multiple statements.
Next | Keyword that indicates the end of the For-Next loop. Each time execution encounters the Next keyword, the step value is added to the counter variable, and execution flows back to the top of the For-Next loop. There the counter variable is once more compared with the end value to determine whether the loop should be executed again.

Macro62 below includes another example of the For-Next loop. The macro uses the InputBox function to prompt the user to enter a number and then employs a For-Next loop, along with two nested If-Then-Else control structures, to calculate the factorial of the number. (The factorial of n is the product of all the integers from 1 to n; the factorial of 0 is defined as 1, and n must be greater than or equal to 0.)

Sub Chap02gMacro62_ForNextIfThenElse()
    Dim NumberString As String
    Dim Num As Integer
    Dim Factorial As Double
    Dim Count1 As Integer
    NumberString = InputBox("Enter Number:", "Calculate Factorial")
    If IsNumeric(NumberString) Then
        Num = Val(NumberString)
        If Num >= 0 Then
            Factorial = 1
            For Count1 = 1 To Num
                Factorial = Factorial * Count1
            Next
            MsgBox "The factorial of " & Num & " is " & Factorial
        Else
            MsgBox "Factorials cannot be calculated on negative numbers."
        End if
    Else
        MsgBox "The factorial could not be calculated.  Please try again."
    End If
End Sub

Again, we calculate the factorial as shown in Macro62 above for example purposes only. (Excel has a built-in worksheet function that calculates the factorial with much greater ease.) In Macro62, we combine two If-Then-Else statements with a For-Next loop. The test condition of the first If-Then-Else statement introduces a built-in VBA function—IsNumeric. The IsNumeric function takes a single argument and returns True if the argument is numeric or False if it is not. If the user enters a number, the test condition evaluates to True, and execution flows into the code segment that follows the If statement. Another built-in VBA function, Val, is included in the first line of the code segment after the If statement. The Val function takes a string, converts it to a number, and, in this case, assigns it to Num. The Val function is required here because the value that InputBox returns is always a string, and the string must be converted to a number before its factorial can be calculated.

Execution next flows into a second If-Then-Else statement, in which a test condition is used to determine whether the Num variable is greater than or equal to 0. If this second test condition evaluates to True, execution flows to the code segment after the second If statement and enters a For-Next loop in which the factorial is calculated and assigned to the Factorial variable. (Note that the factorial of 0 is indeed 1.) If the test condition of the second If statement evaluates to False, the macro displays a message to indicate that factorials cannot be calculated for negative numbers; if the user enters a non-numeric string, the test condition of the first If statement evaluates to False, and a message box explains that the factorial could not be calculated and that the user should try again. But if the user enters a numeric value, a message displays its factorial:

Although we have included two If-Then-Else statements in Macro62 to do some error checking, Macro62 will still, in some instances, break. For example, if the user enters a value greater than 170, Macro62 generates an "Overflow" error message because factorials of numbers greater than 170 exceed the upper bound of a Double variable (roughly 1.79E308). Macro62 also fails to check whether the user has entered a real number that contains values to the right of the decimal point. VBA automatically converts any numeric input to an integer if you assign the result of the Val function to an Integer variable, so Macro62 simply truncates real number input and acts as if it had been given an integer.

Using the While-Wend Control Structure to Loop Based on a Test Condition

While-Wend is another VBA looping structure; it is similar in concept to the For-Next control structure. Instead of looping a set number of times, however, While-Wend loops as long as a specified test condition evaluates to True. Let's look at a simple example. Macro63 uses a While-Wend loop to obtain a specific number from the Rnd function:

Sub Chap02gMacro63_WhileWend()
    Dim LotteryEntry As Integer
    LotteryEntry = 0
    While LotteryEntry <> 7
        LotteryEntry = Int(10 * Rnd())
        Beep
    Wend
    MsgBox "Your number is " & LotteryEntry & ". You Win!!"
End Sub

Macro63 provides a foolproof way of ensuring that the Rnd function always returns a 7. The macro uses a While-Wend loop along with a test condition that causes the loop to continue executing until the value of the variable LotteryEntry is equal to 7. The test condition compares LotteryEntry with the integer 7 by using a not-equals operator (<>). You read the test condition statement above, therefore, as "LotteryEntry not equal to 7." With each loop that is executed, a new random integer is assigned to LotteryEntry. You will also notice that the macro uses the VBA Beep function to tell the computer's internal speaker to beep every time the loop executes—this is purely for effect. If you run this macro multiple times on your computer, you hear a different number of beeps with each execution because the series of numbers generated by successive calls to the Rnd function is random.

Tip Use the Randomize statement in your applications to force Rnd to generate a different sequence of random numbers each time the application is run. Otherwise, Rnd generates the same sequence of numbers each time you open the application's workbook file. For more information about random number sequences, see the topic titled "Rnd Function" in Excel's online VBA Help.

Let's take a closer look at the elements of the above While-Wend loop:

While | Keyword that indicates the start of the While-Wend loop.
LotteryEntry <> 7 | Test condition used to determine whether the loop should execute. If this condition is True, the loop executes. If it is False, execution flows to the Wend keyword at the end of the loop and continues with the rest of the macro.
LotteryEntry = Int(10 * Rnd( )) | First statement executed with each loop.
Beep | Second statement executed with each loop.
Wend | Keyword that signals the end of the While-Wend loop.

Using While-Wend in a geography quiz application

Macro64 below shows a more realistic example of using While-Wend. The macro and the accompanying GeoQuiz function form the basis of a geography quiz application. Macro64 makes repetitive calls to the GeoQuiz function, which prompts the user to enter the name of the country that corresponds to a specified capital city:

Sub Chap02gMacro64_GeographyApplication()
    Dim GeoResult As Boolean
    Dim GeoCount As Integer
    Dim GeoArray(3,2) As String
    GeoArray(1, 1) = "Copenhagen"
    GeoArray(1, 2) = "Denmark"
    GeoArray(2, 1) = "Beijing"
    GeoArray(2, 2) = "China"
    GeoArray(3, 1) = "Cairo"
    GeoArray(3, 2) = "Egypt"
    GeoResult = True
    GeoCount = 1
    While GeoResult And GeoCount <= UBound(GeoArray, 1)
        GeoResult = GeoQuiz(GeoArray(GeoCount, 1), _
                            GeoArray(GeoCount, 2))
        GeoCount = GeoCount + 1
    Wend
    If GeoResult Then
        MsgBox "Congratulations.  All of your answers are correct."
    End If
End Sub

Function GeoQuiz(ByVal Capital, ByVal Country)
    Dim CountryName As String
    Dim PromptString As String
    PromptString = Capital & " is the capital of which country?"
    GeoQuiz = True
    While (CountryName <> UCase(Country)) And GeoQuiz
        CountryName = UCase(InputBox(PromptString, "GeoQuiz"))
        If CountryName = "" Then
            'User chose Cancel or OK with no input.
            GeoQuiz = False
        Else
            PromptString = CountryName & _
              " is not correct. Try again." & Chr(13) & _
              Capital & " is the capital of which country?"
        End If
    Wend
    If GeoQuiz Then
        MsgBox Country & " is the correct answer."
    End If
End Function

Macro64 and the GeoQuiz function combine—in several ways—many of the components that this book has already discussed and also introduce several new items. Let's step through the macro and take a look at what it shows.

At the beginning of Macro64, two variables—GeoResult and GeoCount—and one array—GeoArray—are declared. GeoArray is a two-dimensional array that, if we look at it as a table, has two columns of data in each row: the name of a capital city in the first column and the name of the corresponding country in the second column. After the array is initialized, execution in Macro64 flows into the While-Wend loop. The loop has a test condition that evaluates two expressions that are joined by an And operator; both expressions must be True for the test condition to be True. GeoResult is a Boolean variable that is used to capture the return value from the GeoQuiz function. The first time the While-Wend loop executes, GeoResult is True. GeoCount is a counter that is used to loop through the array's rows. The test condition for the While-Wend loop checks for two items: that GeoResult is True and that GeoCount is less than or equal to the upper bound of the first dimension of GeoArray. If both expressions in the test condition evaluate to True, execution enters the loop's body.

A call is made in the body of the loop to the GeoQuiz function. The macro passes two arguments to GeoQuiz: a capital city name and a corresponding country name from GeoArray. Using GeoCount, we can specify which row of the array is current. In short, GeoQuiz takes the first argument (the capital city), displays it in an input box, and asks the user to enter the corresponding country:

If the user enters the correct answer, GeoQuiz returns a value of True, which is assigned to GeoResult. The second statement in the While-Wend loop in Macro64 is used to increment GeoCount to move to the next row of the array. Execution then goes back to the beginning of the While-Wend loop, where the process begins again. If the user enters all country names correctly, GeoCount eventually becomes greater than the upper bound of GeoArray, causing the test condition to evaluate to False and execution to exit the loop. Execution then flows to the If statement at the end of Macro64, which displays the message box at the top of the next page if all answers are correct.

The GeoQuiz function takes two arguments: a capital city name and a corresponding country name. In the While-Wend loop in GeoQuiz, the InputBox function is first invoked; it displays the capital city's name and asks the user to enter the corresponding country. If the user chooses Cancel in the input box or leaves the edit box blank, the function's return value is set to False, causing the loop to end. A comment explains what part of the code is executed when the user chooses Cancel or leaves the edit box blank.

If the user enters a value in the input box and chooses OK, execution flows to the start of the While-Wend loop, where the test condition is evaluated again. If the user has entered the incorrect country, the test condition evaluates to True, and the loop executes again. If the user enters at least one character and chooses OK, the function return value retains the value of True. The test condition evaluates to False when the user enters the correct country, and execution flows to the end of the While-Wend loop. Because the function's return value is still True, a message box tells the user that the correct answer has been entered:

F Y I

Comments in Code Listings

A comment begins with an apostrophe ('); everything to the right of the apostrophe is part of the comment. A comment can be on a line by itself as in the GeoQuiz function, or it can be at the end of a line of code. If you use comments on the same lines as your code, use tabs to align the comments; comments should make your code more—not less—readable.

In the GeoQuiz function, review the assignment statement for the PromptString variable at the end of the While-Wend loop. The statement involves building a string that says something along the lines of "The country name you entered is not correct. Please enter another country name." At the end of the first line of the assignment statement, the line continuation character (_) is used to continue the statement on a second line. In addition, on the following line, we see a built-in VBA function called Chr. The Chr function takes one argument—a number from 0 through 255—and returns the ASCII character that corresponds to the argument. In GeoQuiz, Chr(13) evaluates to a linefeed character, which causes the prompt displayed in the input box to wrap around to a new line. Calling Chr(13) twice inserts two linefeed characters in the prompt.

Note Chr(13) produces a linefeed character when used with the MsgBox or InputBox functions whether running in Windows or on the Macintosh. In Windows, Chr(10) will also generate a linefeed for these two functions. To produce a linefeed in the text of a TextBox object, however, you must use Chr(10) in Windows and Chr(13) on the Macintosh.

Macro64 and the GeoQuiz function are perhaps the most complicated macros encountered so far in this book. They could easily form the basis of a geography quiz application that could be used in a real-life educational setting. You would simply have to retrieve the names of all the countries in the world and their corresponding capital cities from a database or an Excel worksheet. And you would probably want to improve the user interface by using custom graphics and perhaps dialog boxes, which offer more flexibility than do input boxes. As this example shows, input boxes are limited. Chapter 5 includes a discussion of designing dialog boxes. Because you can add many features to a dialog box, you can create a user interface that is custom designed.

The Do-Loop Control Structure Offers Two Additional Features

The Do-Loop control structure is similar to While-Wend. Do-Loop, however, provides two important features that While-Wend does not. First, Do-Loop lets you choose whether to specify the test condition at the beginning or at the end of the loop. With While-Wend, you can specify the test condition only at the beginning of the loop. Placing the test condition at the end of the loop, however, guarantees that the loop will always execute at least one time. Second, Do-Loop allows you to specify that execution of the loop should continue either while the test condition is True or until the test condition becomes True. This second feature, however, is achievable with While-Wend; by using the VBA Not operator, you can easily transform a test condition that allows execution while it is True into a test condition that executes until it is True.

Let's take a look at some examples. We saw that Macro63 employed While-Wend to retrieve random integers until a 7 was returned. Here's how the same macro would be written using Do-Loop:

Sub Chap02gMacro65_DoWhileLoop()
    Dim LotteryEntry As Integer
    LotteryEntry = 0
    Do While LotteryEntry <> 7
        LotteryEntry = Int(10 * Rnd())
        Beep
    Loop
    MsgBox "Your number is " & LotteryEntry & ". You Win!!"
End Sub

If we compare Macro65 above with Macro63 on page 93, we see only two subtle differences: The keyword Do appears before the keyword While in Macro65, and the keyword Loop replaces the keyword Wend. We can rewrite the above macro in several different ways, however, using Do-Loop. In Macro66 below, the While keyword is replaced with the Until keyword, and the not-equals operator (<>) that compares the LotteryEntry variable to the value 7 is replaced with an equals operator (=):

Sub Chap02gMacro66_DoUntilLoop()
    Dim LotteryEntry As Integer
    LotteryEntry = 0
    Do Until LotteryEntry = 7
        LotteryEntry = Int(10 * Rnd())
        Beep
    Loop
    MsgBox "Your number is " & LotteryEntry & ". You Win!!"
End Sub

By using Do-Loop, we can continue to make changes to this macro. In Macro67 below, for example, we keep the Do keyword at the top of the loop but move the Until keyword and the test condition to the end of the loop after the Loop keyword. Making this change ensures that the loop will execute at least one time because the test condition is not evaluated until the end of the loop. As a result, we no longer need to initialize LotteryEntry before entering the loop.

Sub Chap02gMacro67_DoLoopUntil()
    Dim LotteryEntry As Integer
    Do
        LotteryEntry = Int(10 * Rnd())
        Beep
    Loop Until LotteryEntry = 7
    MsgBox "Your number is " & LotteryEntry & ". You Win!!"
End Sub

We can make one final change to show the last permutation of Do-Loop: Substitute the While keyword for the Until keyword at the end of the loop. In doing so, we must change the equals operator (=) back to a not-equals operator (<>):

Sub Chap02gMacro68_DoLoopWhile()
    Dim LotteryEntry As Integer
    Do
        LotteryEntry = Int(10 * Rnd())
        Beep
    Loop While LotteryEntry <> 7
    MsgBox "Your number is " & LotteryEntry & ". You Win!!"
End Sub

Using the Select Case Control Structure to Selectively Alter the Flow of Execution

The Select Case control structure alters the flow of execution to one of several possible code segments, depending on the value of a variable or the evaluation of an expression. Using Select Case is similar to using multiple ElseIf statements to redefine a test condition in an If-Then-Else control structure. Earlier, Macro60 used an If-Then-Else statement to prompt a user for a password and then, depending on the password entered, provided a certain level of access privilege to an Excel workbook. Let's rewrite Macro60 using a Select Case statement:

Sub Chap02gMacro69_SelectCase()
    Dim Password As String
    Dim Sheet As Object
    Password = LCase(InputBox("Enter Password:", "Password"))
    Select Case Password
        Case "level1"
            For Each Sheet In ActiveWorkbook.Sheets
                Sheet.Visible = True
                Sheet.Unprotect
            Next
            MsgBox "You have read/write access to all sheets."
        Case "level2"
            ActiveWorkbook.Worksheets(1).Visible = True
            ActiveWorkbook.Worksheets(1).Unprotect
            MsgBox "You have read/write access to one worksheet."
        Case "level3"
            ActiveWorkbook.Worksheets(1).Visible = True
            MsgBox "You have read-only access to one worksheet."
        Case Else
            MsgBox "Password incorrect. Please try again."
    End Select
End Sub

The following list describes the components of the Select Case control structure used above in Macro69:

Select Case | Keywords that indicate the beginning of the Select Case control structure.
Password | Test expression—can be a variable or an expression. The test expression is evaluated, and execution flows to the Case statement that contains an expression equal to the test expression. If no such Case statement exists, execution flows to a Case Else statement. If no Case Else statement exists, execution flows to the End Select statement at the end of the control structure.
Case "level1" | First Case expression. If the test expression is equal to the Case expression listed here, execution flows to the code segment that starts on the following line and continues until another Case statement is encountered, at which time execution flows to the End Select statement. If the test expression is not equal to the Case expression listed here, execution flows to the next Case statement.
Case "level2" | Second Case expression—handled in the same way as Case "level1".
Case "level3" | Third Case expression—handled in the same way as Case "level1".
Case Else | Evaluates to True if all of the other Case expressions evaluate to False. If Case Else evaluates to True, execution flows to the code segment that follows the Case Else statement.
End Select | Keywords that signal the end of the Select Case control structure.

Macro70 below also uses a Select Case control structure, but the one it uses differs slightly from the original Select Case control structure we looked at in Macro69:

Sub Chap02gMacro70_SelectCase()
    Dim Score As Integer
    Score = Int(100 * Rnd())
    Select Case Score
        Case 0 To 33
            MsgBox "Score: " & Score & Chr(13) & _
                   "You're in the first third."
        Case 34 To 66
            MsgBox "Score: " & Score & Chr(13) & _
                   "You're in the second third."
        Case 67 To 100
            MsgBox "Score: " & Score & Chr(13) & _
                   "You're in the last third."
    End Select
End Sub

In Macro70, the Case expressions cover a range of values. Each Case expression specifies a starting value, followed by the To keyword, and then an ending value. If the test expression for the control structure is equal to a value that falls within one of the ranges specified, the appropriate Case expression evaluates to True, and the code segment that corresponds to that Case expression is executed.

Using VBA's For-Each-Next Control Structure

For-Each-Next is perhaps the most powerful looping control structure in VBA. In fact, few programming languages provide such a powerful control structure. For-Each-Next allows you to loop through all of the objects in a collection or all of the elements in an array and perform the same action on each object or element. The following is a simple example of the For-Each-Next control structure:

Option Base 1
Sub Chap02gMacro71_ForEachNext()
    Dim CountryArray(5) As String
    Dim Country As Variant
    CountryArray(1) = "India"
    CountryArray(2) = "Peru"
    CountryArray(3) = "Greece"
    CountryArray(4) = "Canada"
    CountryArray(5) = "Kenya"
    For Each Country In CountryArray
        MsgBox Country
    Next
End Sub

Macro71 above assigns country names to the five elements of the array CountryArray and then uses the For-Each-Next control structure to display the value of each element in the array in a message box:

Note that a loop is executed a certain number of times exactly as in the For-Next control structure. The benefit of For-Each-Next, however, is that you don't have to worry about trying to figure out how many times the loop should execute; it executes as many times as there are elements in the array (or objects in the collection). For example, we could rewrite Macro71 and use a standard For-Next loop, as shown in Macro72 below:

Sub Chap02gMacro72_ForNext()
    Dim CountryArray(5) As String
    Dim Count1 As Integer
    CountryArray(1) = "India"
    CountryArray(2) = "Peru"
    CountryArray(3) = "Greece"
    CountryArray(4) = "Canada"
    CountryArray(5) = "Kenya"
    For Count1 = 1 to UBound(CountryArray)
        MsgBox CountryArray(Count1)
    Next
End Sub

With the For-Next loop in Macro72 above, however, we've had to use a counter variable—Count1—to count from 1 to the upper bound of the array. Note also that in the body of the For-Next loop we've had to index CountryArray to retrieve values from the array. The For-Each-Next loop in Macro71 did not require a counter variable; nor did it require that the array be indexed in the body of the loop. Let's take a look at the elements of the For-Each-Next loop shown in Macro71:

For Each | Keywords that indicate the start of a For-Each-Next loop.
Country | Variable to which all the elements in the group will be assigned. The group can be either an array or a collection of objects. If the group is an array, this variable must be of the Variant data type. If the group is a collection, this variable must be of the Variant data type, of the generic Object data type, or of the specific object data type that corresponds to the objects in the collection.
In | Keyword that separates the variable from the group.
CountryArray | The group—can be either an array or a collection of objects. The loop executes as many times as there are items in the group. With the first loop, the variable is set to the value of the first item in the group; with each successive loop, the variable is set to the value of each successive item.
MsgBox Country | Action that is performed in the body of the loop.
Next | Keyword that indicates the end of the loop. After reaching Next, execution flows back to the start of the loop, where the For Each keywords appear. If, after reaching Next, the variable is equal to the last element of the group, execution breaks out of the loop and continues with the rest of the macro.

Note If the group in a For-Each-Next statement is an array, the values of the array elements can only be retrieved; you cannot use For-Each-Next to change the items in an array. If the group is a collection, however, you can use For-Each-Next to display or change the properties of the objects in the collection.

Using For-Each-Next with multidimensional arrays

Let's take a look at what happens when For-Each-Next is used with a two-dimensional array. Note how For-Each-Next allows access to each element in the array, regardless of dimension:

Sub Chap02gMacro73_ForEachNext2DArray()
    Dim StudentNames(2, 2) As String
    Dim NameVar As Variant
    StudentNames(1, 1) = "Nancy"
    StudentNames(1, 2) = "Tim"
    StudentNames(2, 1) = "Margie"
    StudentNames(2, 2) = "Louie"
    For Each NameVar In StudentNames
        MsgBox NameVar
    Next
End Sub

For-Each-Next visits all elements in all dimensions in Macro73 above. Accomplishing the same using For-Next instead would require two For-Next loops—one nested in the other. Macro74 below uses a For-Each-Next loop to go through all of the elements in a six-dimensional array, incrementing a counter with each element encountered:

Sub Chap02gMacro74_ForEachNext6DArray()
    Dim BigArray(5, 5, 5, 5, 5, 5) As Boolean
    Dim Var1 As Variant
    Dim Var2 As Integer
    Var2 = 0
    For Each Var1 In BigArray
        Var2 = Var2 + 1
    Next
    MsgBox Var2
End Sub

Accessing every element of a multidimensional array using standard For-Next loops would be much more difficult.

Using For-Each-Next with collections

Although For-Each-Next loops are powerful with arrays, their real power comes when you use them with collections of objects. Let's take a look at a simple example:

Sub Chap02gMacro75_ForEachNextWorksheet()
    Dim SheetVar As Worksheet
    For Each SheetVar In ActiveWorkbook.Worksheets
        MsgBox SheetVar.Name
    Next
End Sub

Macro75 above uses a For-Each-Next loop to access each Worksheet object in the ActiveWorkbook's Worksheets collection, displaying the value of the Name property for each worksheet in a message box:

It is possible to change the value of the Name property of each worksheet, as the following example shows:

Sub Chap02gMacro76_ForEachNextWorksheet()
    Dim SheetVar As Worksheet
    For Each SheetVar In ActiveWorkbook.Worksheets
        SheetVar.Name = "Work" & SheetVar.Name
        MsgBox SheetVar.Name
    Next
End Sub

Macro76 above changes the Name property of each worksheet in the workbook by attaching the string "Work" to the front of each name. To reinstate the names, you could use the following:

Sub Chap02gMacro77_ForEachNextWorksheet()
    Dim SheetVar As Worksheet
    Dim x As Integer
    x = 1
    For Each SheetVar In ActiveWorkbook.Worksheets
        SheetVar.Name = "Sheet" & x
        x = x + 1
        MsgBox SheetVar.Name
    Next
End Sub

Macro78 below sets the Visible property of all worksheets in the ActiveWorkbook to False, effectively hiding every worksheet from view:

Sub Chap02gMacro78_ForEachNextWorksheet()
    Dim SheetVar As Worksheet
    For Each SheetVar In ActiveWorkbook.Worksheets
        SheetVar.Visible = False
    Next
End Sub

Macro79, on the other hand, restores all worksheets to view:

Sub Chap02gMacro79_ForEachNextWorksheet()
    Dim SheetVar As Worksheet
    For Each SheetVar In ActiveWorkbook.Worksheets
        SheetVar.Visible = True
    Next
End Sub

You can also use For-Each-Next to call methods on objects in a collection. Macro80 adds 10 new workbooks, arranges all of the workbooks in a tiled fashion in the Excel work area, and then deletes all the workbooks except the workbook in which the code is being run:

Sub Chap02gMacro80_ForEachNextWorkbook()
Dim x As Integer
Dim Book As Workbook
    For x = 1 To 10
        Workbooks.Add
    Next
    Windows.Arrange
    MsgBox "Workbooks have been arranged."
    For Each Book In Application.Workbooks
        If Book.Name <> ThisWorkbook.Name Then
            Book.Close
        End If
    Next
    ActiveWindow.WindowState = xlMaximized
End Sub

This macro first uses a For-Next loop to add 10 new workbooks; it does so by calling the Add method on the Workbooks collection. Then, by calling the Arrange method on the Windows collection, the macro arranges all of the workbooks in a tiled fashion on the screen. A message box pauses execution so that you can see the result:

Next a For-Each-Next loop is used to test the value of each Workbook object's Name property. If the name does not match the name ThisWorkbook, the Close method is called on the Workbook object. Last, the macro sets the WindowState property of the ActiveWindow object to the constant xlMaximized, which adjusts the window size so that it fills the entire Excel work area.

Using For-Each-Next with the Range object

You might recall that the Range object can act like a collection of objects, so you can use the For-Each-Next loop to set properties and call methods on Range objects. The following is an example:

Sub Chap02gMacro81_ForEachNextRange()
    Dim SheetVar As Worksheet
    Dim Cell As Range
    For Each SheetVar In ActiveWorkbook.Worksheets
        SheetVar.Select
        For Each Cell In Range("A1:F20")
            Cell.Value = 25
        Next
    Next
End Sub

Macro81 uses a For-Each-Next loop nested in another For-Each-Next loop to set the Value property of all cells in Range("A1:F20") for each worksheet in the ActiveWorkbook object. The first For-Each-Next loop scrolls through all the worksheets in the Worksheets collection, calling the Select method on each worksheet object.

Macro81 can be made more interesting if you change it to set the ColorIndex property of each cell's Interior object. (Interior is an object that exists inside the Range object.) By setting the ColorIndex property of the Interior object to 15, for example, you can make the interior of each cell light gray:

Sub Chap02gMacro82_ForEachNextRange()
    Dim SheetVar As Worksheet
    Dim Cell As Range
    For Each SheetVar In ActiveWorkbook.Worksheets
        SheetVar.Select
        For Each Cell In Range("A1:F20")
            Cell.Interior.ColorIndex = 15
        Next
    Next
End Sub

Previously, Macro81 set the Value property of each cell in Range("A1:F20") equal to 25. Let's use Macro83 to create a few minor deviations in this range of cells on the first worksheet.

Sub Chap02gMacro83_SetDeviations()
    Worksheets(1).Select
    Range("B5") = 24
    Range("C2") = 26
    Range("D10") = 27
    Range("E18") = 22
End Sub

Looking at the range of cells that contains these minor deviations from 25, it is difficult to see which cells in the range differ. We need a macro that will go through the range, identify the cells that contain deviations, and make them stand out. Such a macro would be useful, for example, in a quality control application or in a financial application in which deviant values of grave importance must stand out. Macro84 accomplishes the task:

Sub Chap02gMacro84_ForEachNextRange()
    Dim Cell As Range
    Worksheets(1).Select
    For Each Cell In Range("A1:F20")
        If Cell.Value <> 25 Then
            Cell.Font.Size = 18
            Cell.Font.Bold = True
            Cell.Interior.ColorIndex = 3
        End If
    Next
End Sub

This macro first calls the Select method on the first worksheet in the workbook. Then it uses a For-Each-Next loop to scroll through all of the cells in Range("A1:F20"). An If statement tests whether the Value property of each Range object is equal to 25. If the Value property is not equal to 25, the Size property of the Font object (in the Range object) is set to 18, the Bold property of the Font object is set to True, and the ColorIndex property of the Interior object (in the Range object) is set to 3 (equal to Red). Macro84 successfully identifies all of the Range objects in Range("A1:F20") on the first worksheet that have a Value property not equal to 25 and makes those objects stand out so that they are easily identifiable:

The With Statement

The With statement is new to VBA in Excel 5—it allows you to abbreviate object references. Using With statements provides three main advantages: They reduce the amount of code you have to type, make your code easier to read, and improve your code's performance. Perhaps the best way to see the advantages that With statements offer is to take a look at two different macros that accomplish the same task—one that does not use the With statement and one that does. Macro85 does not use With:

Sub Chap02hMacro85_NonWith()
    ActiveWorkbook.Worksheets(2).Range("A1").Font.Bold = True
    ActiveWorkbook.Worksheets(2).Range("A1").Font.Italic = True
    ActiveWorkbook.Worksheets(2).Range("A1").Font.Size = 22
    ActiveWorkbook.Worksheets(2).Range("A1").Font.Name = "Times New Roman"
    ActiveWorkbook.Worksheets(2).Range("A1").Font.ColorIndex = 3
    Worksheets(2).Select
End Sub

The above macro contains five statements that set five properties of the Font object contained in the second worksheet's cell A1. Approximately 360 keystrokes were required to write the macro. As it is currently written, Macro85 contains 21 object and property references (as indicated by the number of instances of the dot operator [.]), each one of which requires time to evaluate. The same macro can be rewritten using the With statement:

Sub Chap02hMacro86_With()
    With ActiveWorkbook.Worksheets(2).Range("A1").Font
        .Bold = True
        .Italic = True
        .Size = 22
        .Name = "Times New Roman"
        .ColorIndex = 3
    End With
    Worksheets(2).Select
End Sub

Macro86 required 202 keystrokes and contains nine object and property references. That's roughly 56 percent of the keystrokes and 43 percent of the object and property references used in Macro85. You could argue that by using With you can enter your code in half the time and make it run twice as fast. The example comparison that Macro85 and Macro86 provide is a fabrication; object references in Macro85 could have been shortened, improving performance and reducing keystrokes. But this fabrication clearly illustrates the advantages of using the With statement. Although not all code benefits from using With to as great a degree as is shown here, code benefits often enough that you should remember the following rule:

Rule Use the With statement whenever and wherever you can to shorten code, make code easier to read, and improve performance.

It probably doesn't make sense to use With when you are setting a single property or calling a single method; it does make sense to use With, however, if you are setting more than one property or calling more than one method. The examples on the next page illustrate further.

Sub Chap02hMacro87_NestedWith()
    With ActiveWorkbook.Worksheets(3)
        .Select
        .Unprotect
        With .Range("A1")
            MsgBox .Value
            .Value = 200
            .RowHeight = 60
            .ColumnWidth = 20
            .Font.Size = 20
            .Interior.ColorIndex = 3
        End With
    End With
End Sub

Macro87 above uses two With statements—one nested in the other. The macro first calls the Select and Unprotect methods on the third worksheet and then displays the setting of the Value property of Range("A1") in a message box. Next Macro87 changes the Value property to 200, sets the RowHeight and ColumnWidth properties, and then sets the Size property of the Font object and the ColorIndex property of the Interior object.

Macro88 uses a For-Next loop to slowly shrink the size of the active window, uses four additional For-Next loops to move the shrunken window along the four borders of the screen, and then restores the window to its normal size:

Sub Chap02hMacro88_With()
    Application.Windows.Arrange
    With ActiveWindow
        For x = 1 To 25
            .Height = .Height - 10
            .Top = .Top + 5
            .Width = .Width - 20
            .Left = .Left + 10
        Next
        .Top = 0
        .Left = 0
        For x = 0 To 250 Step 5
            .Top = x
        Next
        For x = 0 To 400 Step 5
            .Left = x
        Next
        For x = 250 To 0 Step -5
            .Top = x
        Next
        For x = 400 To 0 Step -5
            .Left = x
        Next
    End With
    Application.Windows.Arrange
    ActiveWindow.WindowState = xlMaximized
End Sub

You can see in Macro88 that by using the With statement, you can abbreviate numerous property references throughout the body of the macro.

Other VBA Functions and Statements You'll Find Useful

Although this chapter has covered most of the functions and statements you will use to design applications in VBA, it is not possible or practical to cover in detail in this book all VBA functions and statements. A few additional VBA functions and statements deserve mention, however, and they are listed here:

Abs | Returns the absolute value of a number
CurDir | Returns the current MS-DOS or Macintosh path
Date | Returns the current system date
Exit Do | Causes execution to break out of a Do-Loop
Exit For | Causes execution to break out of a For-Next or For-Each-Next loop
Exit Function | Causes execution to break out of a function macro
Exit Sub | Causes execution to break out of a subroutine
Fix | Returns the integer portion of a number, rounding appropriately
Int | Returns the integer portion of a number, always rounding down
IsArray | Returns True if an expression is an array
IsDate | Returns True if an expression is a date
IsEmpty | Returns True if no value has been assigned to a variable
IsError | Returns True if an expression is an error value
IsNull | Returns True if an expression evaluates to Null
IsNumeric | Returns True if an expression evaluates to a number
IsObject | Returns True if an expression represents an object
Len | Returns the length of a string
Now | Returns the current date and time
Shell | Runs an executable program
Sqr | Returns the square root of a number
Str | Returns a string representation of a number
StrComp | Performs a string comparison
Time | Returns the current system time
TypeName | Returns the data type of a variable

For more information about other VBA functions and statements not covered here, see Excel 5's online VBA Help or the Microsoft Excel Visual Basic for Applications User's Guide that's shipped with Excel 5.

VBA Editing and Debugging Tools

VBA comes with several advanced editing and debugging tools that will be of great help when you write code. You access most of the debugging tools from the Visual Basic toolbar, shown below. Here we take a look at the buttons on the Visual Basic toolbar and briefly discuss the functions they serve.

To display the Visual Basic toolbar, choose the Toolbars command from the View menu, select Visual Basic, and then choose OK.

The Insert Module Button

The Insert Module button is the first button on the left on the Visual Basic toolbar:

Simply click the Insert Module button to insert a new VBA module.

The Menu Editor Button

The Menu Editor button is the second button from the left on the Visual Basic toolbar. Clicking the button displays the Menu Editor dialog box, shown on the next page. The Menu Editor is an easy-to-use tool for editing Excel menubars and menus. You can save menu changes with a workbook; menu settings are file-specific. Also note that you can manipulate menus with VBA through the Menu, MenuBar, and MenuItem objects.

The Menu Editor dialog box provides access to all seven menubars in Excel, and you can use it to delete menus from or add menus to any menubar.

You access different menubars in the Menu Editor by selecting them from the Menu Bars drop-down list box. To delete a menu, select the menu name from the Menus list box, and choose the Delete button. To add a menu, select the location on the appropriate menubar where you want to insert the new menu, and choose the Insert button; then type the caption for the new menu in the Caption edit box.

Note If you are running Microsoft Windows, you can specify a command underline by inserting an ampersand (&) in the menu caption before the appropriate letter. A command underline represents a key that the user presses to choose the menu. (This option is not available on the Macintosh.)

You can also delete or add menuitems on any menu. To delete a menuitem, select the appropriate entry from the Menu Items list box, and choose the Delete button. To add a menuitem, from the Menu Items list box, select the item before which you want to insert the new item, choose the Insert button, and enter a caption (use an ampersand [&] if you want to specify a command underline). Finally, from the Macro drop-down list box, select a macro to assign to the menuitem you are adding. You insert and delete menuitems in a submenu in much the same way as you do menuitems in a regular menu.

Tip You can restore all of Excel's default menus at any time by choosing the Restore All button.

The Object Browser Button

The Object Browser button is the third button from the left on the Visual Basic toolbar:

Clicking the Object Browser button displays the Object Browser dialog box, which shows you all of the programmable objects that are installed and registered on your system—along with their associated properties and methods:

This dialog box is divided into three main sections: the Libraries/Workbooks drop-down list box, the Objects/Modules list box, and the Methods/Properties list box. You can select different libraries or workbooks from the Libraries/Workbooks drop-down list box. The following items appear in this drop-down list box: libraries that are installed on your system (including Excel and VBA); all workbooks that are currently open in Excel; any add-in files for which you have established a reference; and any applications that use VBA (such as Project 4) for which you have established a reference. (References are explained in detail in Chapter 7, beginning on page 392.)

Selecting Excel from the Libraries/Workbooks drop-down list box displays 127 Excel objects and an entry named Constants in the Objects/Modules list box. (The Excel Debug object is the only object not listed by the Object Browser.) And after you select an object in the Objects/Modules list box, you can view all the properties and methods for that object in the Methods/Properties list box. For example, select VBA from the Libraries/Workbooks drop-down list box, and then select Interaction from the Objects/Modules list box; the Properties/Methods list box displays a list of interactive VBA functions, including InputBox and MsgBox. Now try selecting Constants from the Objects/Modules list box; the Properties/Methods list box displays a list of VBA constants. Or select an Excel workbook from the Libraries/Workbook drop-down list box to view all the modules in each open workbook and all the macros available in each module.

After you select a property or method from the Methods/Properties list, the Paste button in the Object Browser dialog box becomes active. You can choose the Paste button to paste the property or method directly into your code. Also, selecting a property or method displays the name of the property or method in the lower portion of the dialog box. (For a method, the names of any arguments that must be passed to the method are also displayed.) Clicking the question mark button at the bottom of the dialog box immediately displays an online VBA Help topic for the selected property or method.

Note The Help button in the Object Browser dialog box provides help on how to use the Object Browser; it does not provide help on the selected item.

If you select an Excel workbook from the Libraries/Workbooks drop-down list box and then select a module from the Object/Modules list box, a list of all the subroutines and functions in the module is displayed in the Methods/Properties list box. If you then select a subroutine or function from the Methods/Properties list, the Show and Options buttons in the dialog box become active. Choose the Show button to see the section of the VBA module in which the selected subroutine or function resides. Or choose the Options button to specify numerous macro options for the selected subroutine or function.

The Run Macro Button

The Run Macro button is the fourth button from the left on the Visual Basic toolbar, as shown on the next page.

If you select any macro in a VBA module and then click the Run Macro button, the macro is executed.

The Step Macro, Step Into, Step Over, Resume Macro, and Stop Macro Buttons

The Step Macro, Step Into, Step Over, Resume Macro, and Stop Macro buttons on the VBA toolbar are all used in conjunction with the VBA Debug window. You click the Step Macro button to execute subroutines in debug mode. If you select a macro in a VBA module and then click the Step Macro button, the VBA Debug window immediately appears, and the first line of the selected macro is highlighted:

To execute a macro one statement at a time, click the Step Into button one time for each line of code. Clicking Step Into steps through a macro line by line when the Debug window is displayed—Step Into even steps through other subroutines or functions that the macro calls.

Tip Pressing the F8 key on your keyboard has the same effect as does clicking the Step Into button.

If you do not want to see the line-by-line execution of macros or functions that the original macro calls, you can click the Step Over button when those calls occur. Clicking the Step Over button executes called macros or subroutines without stepping through them. If at any time while the Debug window is displayed you want to resume normal macro execution and exit debug mode, click the Resume Macro button. And if you want to stop execution while in debug mode, click the Stop Macro button. Stop Macro stops macro execution and closes the Debug window.

The Toggle Breakpoint Button

The Toggle Breakpoint button allows you to establish breakpoints in your code where execution will stop and the Debug window will be displayed. Breakpoints are useful for investigating problems in your code; they allow you to stop code execution at a specific point and then step through the code line by line. To establish a breakpoint in your code, select the line in the macro where you want the break to occur, and then click the Toggle Breakpoint button, which highlights in red the selected line of code. When you execute the macro, execution breaks at this point, and the Debug window is displayed. To remove a breakpoint, select the line that contains the breakpoint and then click the Toggle Breakpoint button again.

Tip You can remove all breakpoints from all VBA modules by choosing the Clear All Breakpoints command from the Run menu.

The Instant Watch Button

You use the Instant Watch button to establish Watch variables in your code. Watch variables are used in conjunction with the Debug window as powerful tools for debugging code. Watch variables are simply variables or expressions from your code that are added to the Debug Watch window. To specify a Watch variable, select any variable or expression in your code and then click the Instant Watch button, which displays the Instant Watch dialog box. This dialog box displays the name of the macro, the selected expression, and the current value of the selected expression:

The Instant Watch dialog box includes an Add button; by choosing Add, you can add the selected expression to the Watch list, which is displayed under the Watch tab of the Debug window. Let's use the following example macro to look at how you specify a Watch variable:

Sub Chap02hMacro89_WatchVariables()
    Dim Num1 As Integer
    Dim x As Integer
    For x = 1 To 10
        Num1 = Num1 + x
    Next
End Sub

Before you execute Macro89, add the variable Num1 to the Watch list by highlighting the variable in Macro89, clicking the Instant Watch button, and then choosing the Add button in the Instant Watch dialog box:

Now execute the macro in debug mode by placing the cursor in Macro89 and clicking the Step Macro button, which displays the Debug window. You will notice that the top half of the Debug window is blank and that two tabs above this blank area are displayed. One tab is labeled "Watch," and the other is labeled "Immediate," corresponding to the Watch and Immediate panes. These panes allow you to work with variable values in real time, which is of major benefit when you are debugging and diagnosing problems in your code. Click the Watch tab now to see the Watch list in the Watch pane, as shown here:

Now click the Step Into button to begin stepping through the macro. Continue to click the Step Into button to see the macro execute line by line in the lower portion of the Debug window; you see the value of the Num1 Watch variable change in the Watch list in the upper portion of the Debug window. As you loop through the code, the value of Num1 grows with increasing speed. You can add more Watch variables while the Debug window is displayed by selecting the appropriate expression, clicking the Instant Watch button, and then choosing the Add button. For example, try adding the variable x to the Watch list. You can now watch both variables change as you step through the macro. To remove a Watch variable from the Watch list, select the variable and then press the Del key on your keyboard.

The Immediate tab allows you to access the Immediate pane, in which you can type VBA statements directly so that they can be executed on a stand-alone basis in real time. For example, display the Debug window, click the Immediate tab, and enter the following statement in the Immediate pane:

MsgBox "Hello World"

The statement is executed in real time, and you see a message box that displays the message "Hello World." You can also use the Immediate pane to change the values of variables as your code executes.

The Record Macro Button

Clicking the Record Macro button starts the Excel macro recorder. (You can also access the macro recorder from the Tools menu.) Using the macro recorder can help you to learn VBA and to become familiar with Excel objects, properties, and methods. If you don't know what objects are involved in performing a certain action in Excel, for example, you can turn on the macro recorder, perform the action manually, and then look at the recorded code.

When you record a macro, Excel records all of your actions and writes VBA code that corresponds to those actions. Excel continues to record your actions until you turn off the macro recorder. When you start recording a new macro, Excel by default inserts a new VBA module to hold the recorded macro. You can, however, tell Excel to place recorded macro code anywhere in any VBA module. To do so, select where you want the code to be placed, choose the Record Macro command from the Tools menu, and then select Mark Position For Recording. Next choose the Record Macro command from the Tools menu again, and then select Record At Mark. This will cause Excel to insert the recorded code at the marked position. Excel will not prompt you for a macro name, and it will not add the Sub and End Sub keywords around the recorded code. If you want Excel to record a complete macro, follow the above procedure but select Record Macro instead of Record At Mark. Excel will then add the complete macro at the bottom of the active module.

Let's experiment by recording one macro. First click the Record Macro button to start the macro recorder and display the Record New Macro dialog box. Choose the Options button to display the expanded dialog box, as shown on the facing page. Type a name for your macro in the Macro Name box. (The macro name must be one contiguous string of characters.) In the Description box, type This macro enters data in Range("A1").

In the Assign To box, you can tell VBA to add a menuitem to the Tools menu from which the macro can be called. To add the menuitem, check the Menu Item On Tools Menu check box, and then type a caption for the menuitem. You can also assign a shortcut key for the macro by checking the Shortcut Key check box. In the Store In box, you can specify where you would like the recorded macro to be placed—in your Personal Macro Workbook, in the current workbook, or in a new workbook.

Note The Personal Macro Workbook is a hidden workbook that holds macros that are loaded each time you start Excel. It is saved in Excel's startup directory as PERSONAL.XLS in Windows and as PERSONAL MACRO WORKBOOK on the Macintosh.

For our example, select This Workbook. Last, in the Language box, you can tell Excel in which macro language to record the macro—either in Visual Basic for Applications or in Excel 4's macro language. For our example, select Visual Basic, and then choose OK. A Stop Macro toolbar appears at the top of the screen, and if the status bar is displayed, "Recording" appears at the bottom of the screen.

Now let's record entering data in Range("A1") of Worksheets("Sheet1"). First click the Sheet1 tab at the bottom of the screen to display Sheet1. Type the value 100 in Range("A1"), and then press Enter. After you finish recording the macro, click the Stop Macro button to turn off the macro recorder. If you now select the module in which Excel has stored the recorded macro, you see something similar to Macro90 on the next page.

'
' Chap02hMacro90 Macro
' This macro enters data in Range("A1").
'
'
Sub Chap02hMacro90_RecordedMacro()
    ActiveWindow.ScrollWorkbookTabs Position:=xlFirst
    Sheets("Sheet1").Select
    Range("A1").Select
    ActiveCell.FormulaR1C1 = "100"
    Range("A2").Select
End Sub

If you run Macro90, it performs the same actions that you performed while the macro recorder was on. You've probably noticed that the code the macro recorder generates is not necessarily the most efficient code possible. For example, the most efficient way to set the Value property of Range("A1") on Worksheets("Sheet1") to 100 is as follows:

Sub Chap02hMacro91()
    Worksheets("Sheet1").Range("A1").Value = 100
End Sub

Tip Excel's macro recorder often goes a bit overboard in recording macro code, recording every property setting for an object, for example, even if only one property setting was changed while the macro recorder was on. That being the case, you'll want to be careful about incorporating recorded macro code directly in your VBA applications. Before you do so, ensure optimal performance by first editing the code to remove any unnecessary statements.

Other VBA Editing Tools and Features

In addition to the tools that you access from the Visual Basic toolbar, VBA provides several other editing tools and features that will help you write code efficiently. We'll take a brief look at those here.

VBA Online Help

As mentioned in Chapter 1, complete online help is available for VBA in Excel. You access VBA Help by choosing the Contents command from the Help menu and then selecting Programming With Visual Basic. Note, however, that you can jump immediately to VBA Help by pressing the F1 key while a VBA module is active. In fact, if you select any VBA keyword, function, object, method, or property in a VBA module and press F1, the help topic for the selected item is displayed immediately. From the main Contents screen of VBA Help, you can access lists of Excel objects, methods, and properties as well as information about VBA functions, statements, and keywords. To search quickly for help on a specific topic, choose the Search button in VBA Help.

Tip Help topics for all properties and methods provide code examples to demonstrate how to set each property and call each method correctly. If you want, you can copy and paste these code examples directly into a VBA module to incorporate them in your own macros.

Syntax Checking

If you are typing VBA code as you read this chapter, you might have already encountered VBA's syntax checking feature, which checks your syntax as you type keywords for variable declarations, constant declarations, control structures, and functions. If your code's syntax is not correct, VBA alerts you by displaying an error message. If you ignore the error and keep on typing, VBA colors the erroneous code red to signal that it has been entered incorrectly.

VBA also recognizes object, property, and method names as you type them. If you enter such names correctly, VBA follows a standard capitalization scheme to format these names for you. The first letter of object, property, and method names is always capitalized, and if a property or method name is formed from two words, the first letter of the second word is capitalized as well (as in ReadOnly). All other letters are lowercase. Because VBA formats your object, property, and method names as you type them, you can check the accuracy of your code as you work. For example, if you enter a property name and VBA does not capitalize the first letter, you have likely misspelled the name and will need to go back and correct it.

Module Options

By choosing the Options command from the Tools menu, you can access several option settings that affect the way code in VBA modules is entered, executed, and displayed. Under the Module General tab, you can specify options for indenting code, displaying syntax errors, breaking on errors, requiring variable declarations, setting tab width, and specifying international language settings. Under the Module Format tab, you can select the font and font size for your VBA code. You can also select the foreground and background colors for various components of VBA code, including keywords, comments, erroneous code, and plain code. By default, keywords are displayed in blue, comments in green, breakpoints in white on a red background, and erroneous code in red.

Differences Between VBA and Visual Basic

VBA is built on top of Visual Basic—it is a superset of Visual Basic. Although the two languages are similar, they differ in some areas. The following list briefly explains the differences between VBA and Visual Basic:

For-Each-Next control structure: VBA includes the For-Each-Next control structure (described in the section titled "Using VBA's For-Each-Next Control Structure," beginning on page 101), which you can use to access all of the elements in an array or all of the objects in a collection. Visual Basic does not have this feature. (Version 4 of Visual Basic will incorporate this control structure.)

With statement: VBA includes the With statement (described in the section titled "The With Statement," beginning on page 108), which you can use to abbreviate object references for property settings or method calls. Visual Basic does not currently have this feature. (Version 4 of Visual Basic will incorporate the With statement.)

Custom controls: VBA does not support VBX custom controls; Visual Basic does.

Creating executables: You cannot create stand-alone executable files in VBA as you can in Visual Basic. Because VBA is embedded in a host application (in this case, in Excel), you must run the host application to execute a VBA program.

Line continuation character: VBA offers a new line continuation character that allows you to extend a single statement to multiple lines. To use the character, enter a space followed by an underscore (_) at the end of the statement that you want to continue. Visual Basic does not currently have this feature. (Version 4 of Visual Basic will allow line continuation.)

Forms design: Designing forms in VBA is slightly different from designing forms in Visual Basic. Excel's VBA relies on dialog boxes and Excel worksheets and chart sheets for its user interface, instead of on the kinds of forms found in Visual Basic. Chapter 5 explains form design in detail.

Events: VBA's Event model is vastly different from Visual Basic's. Chapter 8 discusses VBA events in detail.

Editing and debugging tools: VBA's editing and debugging tools (described in the section titled "VBA Editing and Debugging Tools," beginning on page 112) differ slightly from those found in Visual Basic.

Although Visual Basic for Applications and Visual Basic differ in these areas today, the languages will converge in the future. Today, VBA is available only in Excel 5 and in Project 4, but it is Microsoft's goal to make VBA available in all Microsoft Office applications.

S U M M A R Y

Visual Basic for Applications is a powerful programming language. This chapter has briefly summarized the language, introducing you to its basic components. The rest of this book builds from the material introduced here by explaining how you can use VBA to control Excel objects.

Let's quickly summarize the main aspects of the VBA language here before you move on to Chapter 3 and begin learning about using objects to create applications:

  • VBA supports variables of numerous data types: Boolean, Integer, Long, Single, Double, Currency, Date, Object, String, Variant, and user-defined.
  • VBA supports arrays, which are single-dimensional or multidimensional groups of data that are all of the same data type.
  • VBA constants are used to hold constant values during macro execution.
  • VBA provides two different types of macros: subroutines, which can run on a stand-alone basis; and functions, which must be called by subroutines, functions, or cell formulas and can return values.
  • VBA variables, constants, and macros can have different levels of scope: Variables and constants can have procedure-level, module-level, or project-level scope; macros can have module-level or project-level scope.
  • VBA offers several powerful control structures, including If-Then-Else, For-Next, While-Wend, Do-Loop, Select-Case, and For-Each-Next.
  • The VBA With statement is a powerful tool that you use to abbreviate object references.
  • VBA offers numerous debugging and editing tools, including a Menu Editor, an Object Browser, breakpoints, Watch variables, an interactive Debug window, and full online help.

After mastering the material in this chapter, you are now ready to move on and learn more about Excel objects. VBA is often referred to as the "glue" by which Excel objects are attached to each other in creating VBA applications. You have learned most of what there is to know about the glue. Now comes the task of learning how to apply the glue to the objects.


Chapter 3 Sample Application 1: West Coast Airways

In this chapter, we take the concepts that the first two chapters covered and use them to build an application in Microsoft Excel. Let's start by taking a glance at what the completed application will look like. If you have access to a computer as you read, start Excel and open the file named CHAP03-1.XLS on the companion disk packaged with this book.

What the Application Does

The sample application we're looking at uses as its subject a fictitious airline named West Coast Airways. West Coast Airways does business in the western United States, serving Arizona, California, Colorado, Idaho, Montana, Nevada, Oregon, Utah, Washington, and Wyoming. The application was developed solely in Excel 5 and is used by the company and specifically by its president to track summary financial data for each of the West Coast Airways sales offices—the company has one sales office in each state in which it does business. The application presents revenue and profit data in various formats for analysis, a few of which are shown in Figure 3-1 on the next page.

Users move from one format to another by choosing buttons to move to different Excel sheets, which we refer to as "forms." (The pictures and maps you see on these forms were created in drawing programs and imported as bitmaps.)

Figure 3-1. Some of the formats in which the West Coast Airways application displays data.

The Control Form

As soon as CHAP03-1.XLS is opened, Excel displays the main form of the application, the Control form. The Control form is used to access the various forms in the application and has several elements: a title box, some graphics, a listbox, and some buttons on a blue background.

Here is a list of the objects required to create these elements:

Worksheet object: This object serves as the basis for the form; the whole area that makes up the form is, indeed, an Excel worksheet.

TextBox object: The title at the top of the screen, "West Coast Airways," is an Excel TextBox object.

Picture objects: Four Picture objects appear on the main form; these are the four small airplanes below the title.

ListBox object: The ListBox object appears in the lower left portion of the form and displays a list of the states in which the company does business. The user can select a state from the list to display sales information about that state.

Button objects: Three Button objects appear in the lower right portion of the screen: Map Sheet, Summary Data, and Quit. The user can choose these buttons either to see color-coded maps that show financial information at a glance or to quit the application.

Range object: It isn't obvious, but the Range object has been used to design this form. The blue background is a range of worksheet cells that have been colored blue so that the screen looks like a form instead of a spreadsheet.

The State Forms

Each state form shows summary financial information about a specific state. To display a state form, select a state from the listbox on the Control form. Selecting California from the list, for example, runs a Visual Basic for Applications (VBA) macro that activates the California form. A state form contains several Excel objects:

Button object: The button at the top of the sheet is the Control button; choosing it activates the Control form.

Picture object: Each state form includes a map of the selected state in the form of an imported bitmap. The maps contained in this application were created in a product called MapLand by Software Illustrated. The user can click this map to activate the map form. (See the next section.)

Rectangle object: Behind the state map is a dark gray area; this is an Excel Rectangle object that has been colored gray.

TextBox object: Beneath the map, an Excel TextBox object displays the name of the state.

Range objects: In the upper right portion of the screen, a table displays financial data specific to the selected state. This table is merely a range of cells in which data has been entered; the cells have been formatted using various colors and special effects to make them visually appealing. Note that a range of cells lies behind the other objects on the form; the gridlines have been removed to give the cells the appearance of plain white space.

ChartObject object: Below the table is a ChartObject object—or what is known as an on-sheet chart. As mentioned earlier, Excel uses two types of objects for charts: a chart that floats as a graphical object on a sheet—known as a ChartObject object—and a chart that exists on a separate sheet by itself—known as a Chart object. The ChartObject object in this case graphically displays the data from the range of cells above it and is actually linked to the cells. If the data in the cells changes, the ChartObject object is automatically updated.

Worksheet object: Again, the Worksheet object is the basis for this form.

The California form shows summary financial data for West Coast Airways business in the state of California. You'll notice that the table in the upper right displays data for the years 1993 and 1994 along with the percentage difference for various values between those two years. The chart in the lower right is linked to the table. The map of California and the textbox under the map visually key the user to the category of data being displayed on the form—namely, that for California. You'll notice that the map is color coded based on the percentage change in revenue from 1993 to 1994. If the revenue decreases by more than 20 percent, the map is red; if the change is between -20 percent and 20 percent, the map is green; if the change is greater than 20 percent, the map is blue. After reviewing the data for California, you can choose the Control button to run a macro that activates the Control form. On the Control form, try selecting some of the other states from the listbox. You'll see that each of the state forms is constructed in the same manner.

The Map Form

On the Control form, choose the Map Sheet button to display the map form. The map form shows a color-coded map of the western United States, which gives the user a quick view of how West Coast Airways is doing throughout the region. The map form contains these objects:

Button object: Choosing the Control button activates the Control form.

Picture objects: Ten Picture objects appear on this form; they are bitmaps, each of which depicts a state in which West Coast Airways does business. Together, they form a map of the western United States.

OptionButton objects: Two OptionButton objects—Revenue and Net Income— are displayed on the left side of the form below the Control button.

TextBox object: Under the optionbuttons, a TextBox object displays a legend for the colors in the map.

Range object: A range of gray cells that lies behind the other objects.

Worksheet object: Again, the Worksheet object is the basis for this form.

The map form gives the user an immediate impression of how the company is doing in the different states—in terms of either revenue or net income (profit). By selecting either the Revenue or the Net Income optionbutton, the user launches a macro that updates the map with the appropriate data. The macro retrieves the numbers for percentage changes in revenue (growth) or net income from the state forms and colors the individual states appropriately. Try selecting the Revenue and Net Income optionbuttons now, and notice how the states change color. The user can choose the Control button to activate the Control form or click any of the individual states on the map to run a macro that activates the state form for the selected state. Try clicking some of the states on the map form now to activate the respective state forms. Recall that you can return to the map form from a state form by clicking the state map. After viewing data in the map and state forms, choose the Control button to return to the Control form.

The SummaryData Form

The second button on the Control form is the Summary Data button. Choose this button now to run a macro that activates the SummaryData form, which summarizes data for all of the states served by the company. The SummaryData form contains a number of objects:

Button object: Choosing the Control button activates the Control form.

OptionButton objects: The Revenue and Net Income OptionButton objects control which type of data is displayed in the chart.

Range objects: A Range object holds the cells in the table that summarizes the data for the whole company. The table contains formulas that are linked to the individual state forms; if the data on one of the state forms changes, Excel automatically updates the table on the SummaryData form. A range of gray cells also lies behind the other objects.

ChartObject object: The on-sheet chart displays the data from the table in the form of a three-dimensional pie chart. The chart also includes a legend and a title and is automatically updated if the table changes.

Worksheet object: The Worksheet object is the basis for the form.

Selecting the Revenue or Net Income optionbutton changes the data displayed in the chart. The ChartObject object linked to the data in the table displays either "Revenue" or "Net Income" in the title above the chart. Notice the number formatting applied to the data in the table: All numbers are formatted as currency, and negative numbers are enclosed in parentheses.

Flaws in the West Coast Airways Application

Because the West Coast Airways application is such a simple one, it would probably serve best as a prototype rather than as an actual information system. Taking a critical eye to the application shows that it suffers from several flaws that would limit its use in a real-world setting.

First, the application offers no mechanism for getting data into the application other than entering it manually. Instead, the application could be set up so that the manager for each state's operation could enter data in the separate state forms and then forward the forms to the company's Finance Department viae-mail; there, the forms could be combined with the rest of the data for the West Coast Airways system. Or the state forms could use database queries that would import data from a corporate database directly into the state forms.

The second flaw involves protection of data. Nothing has been done to protect the data in the forms or the individual objects that reside on the forms. In any of the tables on the various state forms or on the SummaryData form, any user can enter any data in any of the cells. A real-world application, on the other hand, would use different levels of protection. Some elements of the application would be fully protected, and other elements would allow for different levels of access so that only certain users could change or enter certain values.

The application's third flaw lies in some of the Excel interface artifacts that are displayed on the screen. For example, unless you've changed your menu and toolbar settings manually, the standard Excel menubar with all the standard menus is displayed at the top of the Excel screen, and some Excel toolbars are visible. A professional application would not allow these or any other Excel artifacts to be displayed, in order to give the impression that a true stand-alone application—not an Excel macro—is being used.

The fourth flaw in the application is that it does not provide any mechanism for printing or distributing data. The user could choose the Print command from the Excel File menu and print any screen; however, this possibility might not be obvious to a user who is not familiar with Excel. A professional application would provide a simple interface to allow the user to print data and might also allow the user to distribute the data over e-mail.

All of these flaws are easily eliminated by taking advantage of Excel's more advanced objects—objects that deal with database access, control of user input, interaction with e-mail systems, and the Excel environment. We will not fix these flaws here, but in upcoming chapters in this book you will learn about the more advanced Excel objects that allow you to build a fully functional information system.

Flying the Planes

Before you close the West Coast Airways application, you should be aware of one feature we have not yet explored. If you click any of the airplane bitmaps or the title box on the Control form, you can make the airplanes "fly." For a few seconds, the four airplanes move in succession across the screen and wrap around again, giving the impression of flight. You've actually launched a macro that uses a For-Next loop to give this animated effect. After you finish watching the airplanes fly across the screen, you can choose the Quit button to close the West Coast Airways application. Quit runs a macro that closes the file that contains the application but does not exit Excel.

Moving On

Shortly, we'll look at all of the macro code behind this application and even look at code that was used to build some of the application's interface elements. But first let's investigate some of the objects that this application includes.

Excel Objects Used in the West Coast Airways Application

In Chapter 1, we looked briefly at the purpose and function of a few Excel objects: Application, Workbook, Worksheet, and Range. The West Coast Airways application uses all of these objects plus a few others, most of which are graphical: Picture, ListBox, Button, Rectangle, TextBox, ChartObject, and OptionButton. All of these additional objects fall into a special class in Excel 5 known as "DrawingObject objects." In fact, a special collection called the "DrawingObjects collection" contains all of these objects, as well as some others. The DrawingObjects collection is a special collection in Excel 5 that contains objects of different types. It is itself contained in three different kinds of objects in Excel 5: Worksheet, DialogSheet, and Chart.

Note "Object A contains Object B" or "Collection A contains Object B" means that Object B is one level directly below A in the Excel object hierarchy, described in Chapter 1. Refer to Figure 1-2 on page 18, but note that the step in levels between a collection and a subobjectis illustrated quite differently from the step in levels between a singular object and a subobject. (Recall that a collection is itself a singular object and that you call a method on a collection with an index or a name argument to get to the subobjects it contains. You use a property, on the other hand, to get to a singular subobject.)

All floating graphical objects in Excel fall below the DrawingObjects collection in the Excel object hierarchy. It makes sense, then, that this collection is contained in the Worksheet, DialogSheet, and Chart objects because these three objects can serve as forms for designing user interfaces. You use objects from the DrawingObjects collection to add graphical elements and controls to such forms.

The DrawingObjects Collection

The DrawingObjects collection contains several objects, all of which are also contained in their own separate object-specific collections. Following is a list of all objects that fall beneath DrawingObjects in the Excel object hierarchy.

This list has been broken down into two different sections: "Graphical objects" and "Controls." A graphical object is used to design custom forms. A control, on the other hand, is an object that a user usually manipulates with a mouse to launch a macro.

Graphical objects

ChartObject: An on-sheet chart that is linked to a range of data.

GroupObject: A set of objects that have been grouped together to create a single object so that all the objects can be manipulated as a unit.

OLEObject: A linked or embedded OLE object.

Drawing: A polygon created with the Excel Freeform drawing tool on the Drawing toolbar.

Picture: An imported bitmap generated in a third-party drawing program.

TextBox: A box that contains text. (A textbox can be blank.)

Label: A static text label. Labels are often used with controls.

Arc: An arc.

Line: A line.

Oval: An oval.

Rectangle: A rectangle.

Controls

Button: A button control.

CheckBox: A checkbox control that turns on and off with alternating clicks of the mouse.

DropDown: A dropdown list.

GroupBox: A box used to group OptionButton objects so that only one option can be set at a time.

ListBox: A standard listbox control.

OptionButton: An optionbutton control for which only one button in a group can be selected at a time.

ScrollBar: A scrollbar control used to increment or decrement a value by using a slider.

Spinner: A spinner control used to increment or decrement a value by clicking the up or down arrow.

EditBox: An editbox control used to enter text (on dialogsheets only).

Note All of these objects are "objects in collections" and can be accessed either from their own collections or from the DrawingObjects collection. This is similar to the Sheets and Worksheets collections; each worksheet is contained both in the Worksheets collection and—along with other types of sheets—in the Sheets collection. Being able to use either the DrawingObjects collection or a specific collection allows you to perform the same action easily on all drawingobjects or on only certain kinds of drawingobjects.

Graphical objects

Although each of the objects in the "graphical objects" category on the preceding two pages has its own unique set of properties and methods, these objects also have a set of shared properties and methods. Below is a list of the properties that the graphical objects share. A list of the methods that the graphical objects share follows.

Border: Returns the border of the object (can be used to set the border's line style; does not apply to the Label object).

BottomRightCell: Applies only to objects on worksheets; returns the cell under the bottom right corner of the object.

Enabled: If True, the user can click the object to launch a macro if one has been assigned. If False, the user cannot launch a macro by clicking the object.

Height: The height of the object in points. (A point is 1/72 of an inch.)

Interior: Returns the interior of the object and is usually used to set the color (does not apply to the Line object).

Left: The distance in points (1/72 inch) that the object lies from the left border of the chart, worksheet, or dialogsheet on which the object resides.

Locked: If True, the user cannot manipulate the object in any way when the sheet is protected. If False, even if the sheet is protected, the object can be manipulated.

Name: The name of the object.

OnAction: The name of a macro that runs when the user clicks the object.

Placement: Can be one of three values: xlMoveAndSize (the object moves and resizes with the cells underneath it), xlMove (the object moves but does not resize with the cells underneath it), or xlFreeFloating (the object neither moves nor resizes with the cells underneath it). This property applies only to graphical objects on worksheets.

PrintObject: If True, the object is printed when a user prints the sheet. If False, the object does not appear on printouts.

RoundedCorners: If True, the object is displayed with rounded corners; if False, the object is displayed with square (90-degree-angle) corners (applies to the ChartObject, GroupObject, Rectangle, and TextBox objects only).

Shadow: If True, the object is displayed with a shadow behind it (does not apply to the Arc, Line, or Label objects).

Top: The distance in points (1/72 inch) that the object lies from the top border of the chart, worksheet, or dialogsheet on which the object resides.

TopLeftCell: Applies only to objects on worksheets; returns the cell under the top left corner of the object.

Visible: If True, the object is displayed. If False, the object is hidden from view.

Width: The width of the object in points (1/72 inch).

ZOrder: A placement order in which the object falls in the screen area in which the object resides. This order is used when objects are stacked on top of one another. A ZOrder of 1, for example, means that an object is hidden by any other object that overlaps it on the screen.

The following list shows the set of methods that graphical objects share:

BringToFront: Brings an object to the top of a three-dimensional stack of objects.

Copy: Copies the object to the clipboard.

CopyPicture: Copies the object to the clipboard as a picture.

Cut: Deletes the object and places it on the clipboard.

Delete: Deletes the object.

Duplicate: Duplicates the object (copies and pastes it in one action).

Select: Selects the object.

SendToBack: Places the object behind any overlapping objects on the screen (that is, sets the ZOrder property to 1).

Note Because all of these graphical objects share a common set of properties and methods, you have only one set of properties and methods to learn. Then the one set can be used for all of the graphical objects to which the properties and methods apply. Note that a number of the control objects in the DrawingObjects collection share some of the properties and methods listed above.

Building the West Coast Airways Application

Now that we've summarized the objects that are used in the West Coast Airways application, let's build it. A good place to start is with a conceptual understanding of the flow of the application. The diagram at the top of the next page shows the various paths the user can take when navigating the West Coast Airways system:

We should also consider the flow of data in the application. The data that governs the application resides in the state forms. The SummaryData form, however, contains a table in which formulas are linked to the data in the state forms, and the map form contains maps that are color coded based on the data in the state forms. Here's how data in the application flows:

Beginning the Process of Building the Application

We'll begin building the application by using a workbook in which some of the objects are already placed in their appropriate positions on various worksheets. Open the file CHAP03-2.XLS, which is included on the companion disk packaged with this book. After you open the file, you'll see a workbook that contains five sheets: Template, Module1, Control, SummaryData, and MapSheet. The worksheet named Template will be used as a template for making the individual state forms. Module1 will hold the VBA code for the application. Control, SummaryData, and MapSheet will be used to design the Control, SummaryData, and map forms.

Throughout the rest of this chapter, we will analyze several macros that you can use to build the application. All of these macros are contained in the text file named CHAP03.TXT. You can choose either to import the text file directly into Module1 of the file CHAP03-2.XLS and run the macros as you read or to type the macros manually as they appear in this chapter. To import the text file, click the Module1 tab to activate the module. Next choose the File command from the Insert menu, and then select CHAP03.TXT and choose OK. The code from the text file then appears in the body of the VBA module. To get the most out of this chapter, you might want to instead write the macros by yourself after reading about each macro. You can then use the code in CHAP03.TXT as a backup should you find it difficult to get your macros to run properly.

Option Statements

The code in this application uses arrays in a few different instances. To ensure that array indexing always starts at 1 (as opposed to 0), enter as the first line of code in Module1 an Option Base statement:

Option Base 1

You might also want to turn on forced variable declaration while writing your code. To do so, type the following statement at the top of the VBA module under the Option Base 1 statement:

Option Explicit

Creating the State Forms

So far, no worksheets in the workbook represent the different state forms. We will need 10 such state form worksheets. Each worksheet will be formatted in exactly the same manner—with a Control button, a map, a table of fictitious data, and a chart linked to that data. As a result, we can probably save time by using macros to set up the worksheets, as opposed to setting up each worksheet separately.

Using a worksheet template

To help begin the process of setting up the 10 worksheets, the Template worksheet is included in the CHAP03-2.XLS workbook. Click the Template tab to take a look at it. You will notice that a formatted table in the upper right area of the worksheet depicts revenue and profit for 1993 and 1994 as well as the percentage difference for such values between the two years.

If the formula bar is not currently displayed in Excel, choose the Formula Bar command from the View menu. The formula bar is a thin bar that resides just above the worksheet (see Figure 2-1 on page 38); it serves two purposes. The right portion of the formula bar can be used to enter data and formulas in cells; the left portion of the formula bar contains the Name drop-down list box, which you can use to manually set the Name property of any range or DrawingObject object on the worksheet. (You can also use the Name box to go to a cell on the worksheet; if you select a name from the list, Excel selects the cell that matches the name.) If you look at the contents of the cells in the ranges F4:G6 and F9:G10 on the Template worksheet, you see formulas that contain the RAND() worksheet function for generating random numbers. The RAND() function has been used here merely to generate fictitious data. If you select F4:G6, the name Rand1 is displayed in the Name box; likewise, if you select F9:G10, the name Rand2 is displayed. As you will see later in this chapter, these range names will be employed in one of the macros used to set up the application. Also note that the name of cell G7 is RevenueGrowth and that the name of cell G11 is NetIncomeGrowth. (Again, cell names are displayed in the Name box.)

Automating the process of creating forms

If you now select the MapSheet worksheet, you can see all of the states for which we need to create forms. And if you select an individual state, you can see the name of the state in the Name box. (The names of the state bitmaps, like the names of the ranges discussed in the previous section, have already been set up for you in the CHAP03-2.XLS workbook.) We can use the Name properties that are already set for the bitmaps on the MapSheet worksheet to create separate forms for each state. We would, however, like the separate state forms to appear in alphabetic order; as a result, we must sort the names of the bitmaps on the MapSheet worksheet before we use them to create the state forms. The Range object has a Sort method; if we can somehow transfer the names of the bitmaps to a worksheet range, we can sort them and then use them to create the state forms. The BuildStateList macro on the next page transfers all of the state bitmap names on the MapSheet worksheet to a range on the SummaryData worksheet and then sorts the names.

F Y I

Automated Macro Design vs. Manual Design

This chapter includes macros such as BuildStateList, below, which is used to set up your application, and macros such as GotoControl, on page 146, which is used in running your application. Often, you set up your application's environment manually, but the setup macros here serve to familiarize you with manipulating Excel objects through VBA—in addition to simply helping you get your sample application running.

To distinguish between the setup macros and the macros that run your application, each setup macro in this chapter is headed "Application Setup Macro." After you run the setup macros, you no longer need to include them in Module1 in order for the application to run.

APPLICATION SETUP MACRO

Sub BuildStateList()
    Dim TopOfList As Range
    Dim DrawVar As Drawing
    Dim Counter As Integer
    Worksheets("SummaryData").Activate
    Worksheets("SummaryData").Range("B11").Name = "TopOfList"
    Set TopOfList = Worksheets("SummaryData").Range("TopOfList")
    Counter = 11
    For Each DrawVar In Worksheets("MapSheet").Drawings
        Worksheets("SummaryData").Range("B" & Counter).Value = _
            DrawVar.Name
        Counter = Counter + 1
    Next
    TopOfList.CurrentRegion.Sort TopOfList
    TopOfList.CurrentRegion.Name = "StateList"
End Sub

In the fifth line of the BuildStateList macro, the SummaryData worksheet is made active by calling the Activate method. Then the Name property of Range("B11") on the SummaryData worksheet is set to "TopOfList", and the Set statement in the seventh line sets the TopOfList Range object to Range("TopOfList"). The For-Each-Next loop is used in the Drawings collection on the MapSheet worksheet; the Drawings collection contains all of the drawings (that is, all of the state bitmaps) on the worksheet. The statements in the For-Each-Next loop set the Value properties of cells on the SummaryData worksheet equal to the names of the drawings on the MapSheet worksheet. The list of names starts at TopOfList and then grows down one cell at a time. The Sort method is then called on the range returned by the CurrentRegion property of TopOfList. CurrentRegion is a Range property that holds a Range reference for all contiguous cells that contain data. Last, when we use the CurrentRegion property, the range that contains the sorted list is given the name StateList. Run the BuildStateList macro now to generate the sorted list.

Now we'll use the sorted list on the SummaryData worksheet to make worksheets that represent a state form for each state in the list. To add the 10 worksheets that represent the forms, we'll call the Copy method on the Worksheet object to copy the Template worksheet 10 times. We'll also set the Name property of each new worksheet to the appropriate state name and then place a ChartObject object on each worksheet. The MakeSheets macro below accomplishes these tasks:

APPLICATION SETUP MACRO

Sub MakeSheets()
    Dim StateList As Range
    Dim StateName As Range
    Set StateList = Worksheets("SummaryData").Range("StateList")
    For Each StateName In StateList
        ActiveWorkbook.Worksheets("Template").Copy ActiveSheet
        With ActiveSheet
            .Name = StateName.Value
            .Calculate
            .Range("Rand1").Copy
            .Range("Rand1").PasteSpecial xlValues
            .Range("Rand2").Copy
            .Range("Rand2").PasteSpecial xlValues
            .ChartObjects.Add(190.5, 155.25, 233.25, 118.5).Select
        End With
        ActiveChart.ChartWizard Range("E3:F3,H3," & _
                                      "E7:F7,H7," & _
                                      "E11:F11,H11")
        Range("A1").Select
    Next
End Sub

The MakeSheets macro uses a For-Each-Next loop to go through each of the cells in the StateList range, creating a new copy of the Template worksheet for each cell in the range and setting the Name property of each new worksheet to the value of each cell encountered. Notice that other things are going on in the body of the For-Each-Next loop as well. Recall that the Template worksheet contains formulas that use the RAND( ) worksheet function. By calling the Calculate method each time a new worksheet is copied, you force new random numbers to be generated, which makes it easy to create different fictitious data sets for each worksheet. After the worksheet is copied, however, you will want to convert the random formulas to actual values. You do so by calling the Range object's Copy method and then calling the PasteSpecial method, passing the constant xlValues as the first argument. This replaces all formulas in the range with the values such formulas represent (after the last recalculation). The MakeSheets macro converts the Rand1 and Rand2 ranges in this way.

Notice the call to the Add method of the ChartObjects collection. Recall that collections are actually objects that have properties and methods. In this instance, calling the Add method on the ChartObjects collection adds a new ChartObject object to the collection. Four arguments are passed to the Add method; these are values that are used to set the Left, Top, Width, and Height properties of the added ChartObject object.

In the same statement in which the Add method is called, the Select method is called as well, which ensures that the ChartObject object is selected after it has been added.

After you exit the With control structure, the ChartWizard method is called on the ActiveChart object. ActiveChart is used to reference the ChartObject object that was just added; ChartWizard is used, among other things, to link the ChartObject object to data in the worksheet. The first argument for ChartWizard takes a range address that represents the source of the linked data; in the call to ChartWizard, a series of noncontiguous ranges is specified to chart the values for Revenue and Net Income for 1993 and 1994. The last statement in the For-Each-Next loop selects the first range on the worksheet so that the ChartObject object does not remain selected.

F Y I

Using the Object Returned by the Add Method

How can you call the Add and Select methods in a single VBA statement? The Add method actually returns an object—specifically, the new object that the method created. If you want to be able to refer to the new object again easily, you can use this fact to set a variable to the new object, as in the following:

Dim NewChart As ChartObject
Set NewChart = ActiveSheet.ChartObjects.Add(50, 20, 80, 20)

You can also use the returned object immediately, as in the following example, which sets a property and calls a method on two new objects:

ActiveSheet.ChartObjects.Add(50, 20, 80, 20).Name = "MyNewChart1"
ActiveSheet.ChartObjects.Add(80, 30, 80, 20).SendToBack

In the MakeSheets macro (see page 143) we use this feature to select the new chart and then call the ChartWizard method on the ActiveChart, but we could have also called ChartWizard directly, at the cost of making the code more cluttered and less readable.

Note that when calling the Add method, if you do not use the result in an expression (by assigning it, setting a property on it, or calling a method on it), you must either explicitly use the Call keyword or omit the parentheses from the argument list, as in the following examples:

Call ActiveSheet.ChartObjects.Add(50, 20, 80, 20)
ActiveSheet.ChartObjects.Add 50, 20, 80, 20

Tip

If you have not already done so, run the MakeSheets macro now. As each new worksheet is added and each new ChartObject object is created, you see a lot of flashing on the screen whenever something on the screen changes. You can prevent intermediate screen updates—and improve performance—by inserting the following statement at the top of the macro:

Application.ScreenUpdating = False

This statement has been omitted from the macros in this chapter so that you can see the results of property settings and method calls as they occur.

Adding Control buttons to the state forms

Now that you have 10 worksheets to represent the 10 state forms, you must add some of the other objects to the forms. Start by adding a Control button to each form:

APPLICATION SETUP MACRO

Sub AddButtons()
    Dim WorksheetVar As Worksheet
    For Each WorksheetVar In ActiveWorkbook.Worksheets
        If WorksheetVar.Name <> "Control" Then
            WorksheetVar.Activate
            WorksheetVar.Buttons.Add(50, 20, 80, 20).Select
            With Selection
                .Caption = "Control"
                .OnAction = "GotoControl"
            End With
            Range("A1").Select
        End If
    Next
End Sub

The AddButtons macro above uses a For-Each-Next loop to go through each worksheet in ActiveWorkbook, adding a Button object to each worksheet except the Control worksheet. (The If statement prevents the Control worksheet from being modified.) The macro adds the Button objects by calling the Add method on the worksheet's Buttons collection. Like the ChartObjects collection, the Buttons collection has an Add method that takes four arguments; these are values that are used to set the Left, Top, Width, and Height properties of the new Button object. In the body of the For-Each-Next loop after the Button object is added, the Caption property is set to Control and the OnAction property is set to GotoControl. An object's OnAction property holds the name of a macro that is executed whenever the object is clicked. In this case, if the user chooses any of the Control buttons, the GotoControl macro is executed. Here is the macro:

Sub GotoControl()
    Worksheets("Control").Activate
    Worksheets("Control").Range("A1").Select
End Sub

This macro merely calls the Activate method on the Control Worksheet object. If you have not already done so, run the AddButtons macro now. After the macro completes, Control buttons are displayed on the 10 state forms and on the map and SummaryData forms.

Adding maps to the state forms

Next you need to add the map bitmaps to each of the state forms. You can do this easily by copying the bitmaps one by one from the MapSheet worksheet to the appropriate state forms. The CopyMaps macro automates the process:

APPLICATION SETUP MACRO

Sub CopyMaps()
    Dim DrawVar As Drawing
    For Each DrawVar In Worksheets("MapSheet").Drawings
        DrawVar.Copy
        With Worksheets(DrawVar.Name)
            .Activate
            .Range("B7").Select
            .Paste
        End With
        With Selection
            If .Width <= 80 Or .Height <= 110 Then
                Do Until .Width >= 80 Or .Height >= 110
                    .Width = .Width * 1.1
                    .Height = .Height * 1.1
                Loop
            Else
                Do Until .Width < 80 Or .Height < 110
                    .Width = .Width * 0.9
                    .Height = .Height * 0.9
                Loop
            End If
            .Top = 70
            .Left = 50
            .Interior.ColorIndex = 5
            .Shadow = True
        End With
        Range("A1").Select
    Next
End Sub

Copying the state map drawings from the MapSheet worksheet to each of the state forms presents one problem: Each state map is a different size, yet on each map form you probably want the state map to appear about the same size as the other state maps. So when copying each state map, it's important to adjust the relative size of the map as it is pasted to the state form.

The first few lines in the For-Each-Next loop of the CopyMaps macro copy a state map from the MapSheet worksheet to the appropriate state form. An If-Then-Else statement then determines whether the map is too small or too large in relative terms, with the target size of each drawing set at a width of 80 points and a height of 110 points. If the state map drawing is not the correct size, one of two Do-Loops enlarges or shrinks the map until it reaches the appropriate size. The Top and Left properties of the drawing are then set to adjust the position of the state map on the form, and the ColorIndex of the Interior object is set to 5 to make each map drawing blue. The Shadow property is then set to True to give each map a shadow. Last, Range("A1") is selected so that the maps do not remain selected.

Run the CopyMaps macro. A blue drawing is displayed on each state form to depict a map of the state.

Adding a rectangle behind each state form map

Use the following macro to add a dark gray rectangle behind each state bitmap to make it stand out:

APPLICATION SETUP MACRO

Sub AddRectangles()
    Dim RangeVar As Range
    Dim StateList As Range
    Set StateList = Worksheets("SummaryData").Range("StateList")
    For Each RangeVar In StateList
        Worksheets(RangeVar.Value).Activate
        ActiveSheet.Rectangles.Add(25, 50, 140, 200).Select
        With Selection
            .Interior.ColorIndex = 16
            .Shadow = True
            .SendToBack
        End With
        Range("A1").Select
    Next
End Sub

In the AddRectangles macro above, a For-Each-Next loop is used on the range that the StateList object represents. The macro uses the state name in each cell in the range to activate each state form in turn. For each state form, the Add method is called on the Rectangles collection, and arguments for Left, Top, Width, and Height are passed. The ColorIndex property of the Interior object is then set to 16 to color the rectangle dark gray. Next, setting the Shadow property to True places a shadow around the rectangle. And last, the SendToBack method is called to set the ZOrder property of the rectangle to 1 so that it appears behind the graphical image of the state map.

Adding a textbox to each state form

The last object that must be added to each state form is a TextBox object, which displays the name of the state. Use the AddTextBoxes macro below to add the textboxes:

APPLICATION SETUP MACRO

Sub AddTextBoxes()
    Dim RangeVar As Range
    Dim StateList As Range
    Set StateList = Worksheets("SummaryData").Range("StateList")
    For Each RangeVar In StateList
        Worksheets(RangeVar.Value).Activate
        ActiveSheet.TextBoxes.Add(35, 205, 115, 35).Select
        With Selection
            With .Font
                .Name = "Times New Roman"
                .Size = 18
                .Bold = True
            End With
            .Text = RangeVar.Value
            .Shadow = True
            .HorizontalAlignment = xlCenter
            .VerticalAlignment = xlCenter
            .Border.Weight = xlMedium
            .Interior.ColorIndex = 19
        End With
        Range("A1").Select
    Next
End Sub

Like the AddRectangles macro, the AddTextBoxes macro uses a For-Each-Next loop to call an Add method (this time on the TextBoxes collection) for each state form. After a textbox is added to each form, several properties of the textbox and of its font are set. The font properties that are set are Name, Size, and Bold. The following TextBox object properties are set:

Text | Value of the cell in StateList
Shadow | True
HorizontalAlignment | Set to xlCenter to center the text horizontally in the box
VerticalAlignment | Set to xlCenter
Border.Weight | Set to xlMedium to give the border a medium-weight line
Interior.ColorIndex | Set to 19 to give the textbox a light yellow color

F Y I

Automated Macro Design vs. Manual Design

The macros covered so far in this chapter have for the most part been used to create and design forms. The actions that these macros perform could have easily been accomplished manually in Excel rather than by using macros. For example, instead of using the MakeSheets macro (see page 143), you could have just as easily made 10 copies of the Template worksheet, used Excel's ChartWizard (on the Standard toolbar) to make charts on each worksheet, and then added the button, rectangle, and textbox to each worksheet by using the tools on the Drawing toolbar. Although we could perform these design tasks manually, we will continue to use macros to design the rest of the forms in this application so that you can further familiarize yourself with the objects, properties, and methods involved.

Working with the Control Form

Now that all of the state forms have been designed, let's start designing the Control form by changing the background color, adding a listbox, and drawing a rectangle around the listbox. To be sure you have a feel for the pros and cons of automated vs. manual design, we list the manual steps involved in setting up this form; running the AddListBox macro on the next page, however, accomplishes the same result. In this case, only a single form is being set up, so in a real-life situation you would probably perform these steps manually, rather than spending the time to write a macro such as AddListBox.

First the background color of the Control form should be set to blue to make it appear as more of a form than a spreadsheet grid. You can do this manually by selecting the range A1:Z70, clicking the right mouse button, and then selecting Format Cells from the shortcut menu. In the Format Cells dialog box, click the Patterns tab, and then select the blue color under Cell Shading. Finish by choosing OK.

Adding a listbox to the Control form

Now you need to add a listbox to the form. If the Forms toolbar is not visible, choose the Toolbars command from the View menu, check the Forms check box, and choose OK. Click the ListBox tool on the Forms toolbar and draw the listbox on the lower left portion of the screen.

To put a dark gray border around the listbox, add a rectangle behind it by first clicking the Filled Rectangle tool on the Drawing toolbar and then drawing a rectangle on top of the listbox. As with the Forms toolbar, you might need to first make the Drawing toolbar visible.

Next point to the rectangle, click the right mouse button, and select Format Object from the shortcut menu. Click the Patterns tab, and select a medium weight line from the Weight drop-down list box, check the Shadow check box, and select gray for the Fill color.

Now to place the rectangle behind the listbox, point to the rectangle, click the right mouse button, and select SendToBack from the shortcut menu.

You can also accomplish these same tasks—coloring the background cells blue and adding the listbox and the rectangle behind the background—by running the following macro:

APPLICATION S'ETUP MACRO

Sub AddListBox()
    With Worksheets("Control")
        .Select
        .Range("A1:Z70").Interior.ColorIndex = 5
        .ListBoxes.Add 100, 150, 100, 100
        .Rectangles.Add 90, 140, 120, 120
    End With
    With ActiveSheet.Rectangles(1)
        .Interior.ColorIndex = 16
        .Border.Weight = xlMedium
        .Shadow = True
        .SendToBack
    End With
End Sub

The AddListBox macro above first sets the ColorIndex property of the range's Interior object to blue, adds the listbox, adds the rectangle, and then formats the rectangle and calls the SendToBack method on the rectangle. After you add the listbox, you'll notice that no values are displayed in the list. You can choose from two ways to add a list of data so that it will be displayed in a listbox: You can link the listbox to a range on a worksheet, or you can add values to the listbox directly by using a macro. The second is the preferred way—adding values directly—because it results in better performance than does linking the listbox to a worksheet range.

The following macro assigns the appropriate values to the listbox by storing the values directly in the listbox. To do so, the macro assigns an array to the List property; the macro also assigns another macro to the OnAction property. The OnAction macro—GotoSheet—is executed whenever an item is selected from the listbox.

APPLICATION SETUP MACRO

Sub InitializeListBox()
    Dim StateList As Range
    Dim ListBox1 As ListBox
    Dim ListArray() As String
    Dim ArraySize As Integer
    Dim Counter As Integer
    Dim RangeVar As Range
    Set StateList = Worksheets("SummaryData").Range("StateList")
    Set ListBox1 = Worksheets("Control").ListBoxes(1)
    Counter = 1
    ArraySize = StateList.Rows.Count
    ReDim ListArray(ArraySize)
    Worksheets("Control").Activate
    For Each RangeVar In StateList
        ListArray(Counter) = RangeVar.Value
        Counter = Counter + 1
    Next
    With ListBox1
        .RemoveAllItems
        .List = ListArray
        .OnAction = "GotoSheet"
    End With
End Sub

The InitializeListBox macro first builds a dynamic array that contains all the values in the StateList Range object. The size of the array is determined by calling the Rows method on StateList to return the rows encompassed by StateList and then calling the Count method to get the exact number of rows. A For-Each-Next loop then goes through all the values in StateList to assign values to ListArray. Next the RemoveAllItems method is called on ListBox1 to remove any items currently in the list, and ListArray is assigned to ListBox1's List property. Last, the GotoSheet macro name is assigned to the OnAction property.

GotoSheet and ColorMap, which is called by GotoSheet, appear below:

Sub GotoSheet()
    Dim ListBox1 As ListBox
    Dim SheetName As String
    Set ListBox1 = Worksheets("Control").ListBoxes(1)
    SheetName = ListBox1.List(ListBox1.Value)
    With Worksheets(SheetName)
        ColorMap .Drawings(SheetName), "RevenueGrowth"
        .Activate
    End With
    Range("A1").Select
End Sub

Sub ColorMap(ByRef Map As Drawing, ByVal ValueName As String)
        Select Case Worksheets(Map.Name).Range(ValueName).Value
            Case Is < -0.2
                Map.Interior.ColorIndex = 3
            Case -0.2 To 0.2
                Map.Interior.ColorIndex = 4
            Case Is > 0.2
                Map.Interior.ColorIndex = 5
        End Select
End Sub

When the user selects a state from the listbox, the GotoSheet macro runs. GotoSheet retrieves the text of the item selected from the listbox in an interesting way: by indexing the list stored in the listbox. No single property of the ListBox object returns a text string that corresponds to the item selected. A ListBox object has a Value property that returns the index of the item selected and a List property that contains all of the items in the list. By using the Value property as an index on the List property, therefore, you can retrieve the text string that corresponds to the item selected. Doing so retrieves the name of the appropriate state form, which is used to call the Activate method on the worksheet that corresponds to the form.

Before the Activate method is called, a call is made to the ColorMap macro. ColorMap takes two arguments: a Drawing object passed by reference and a string passed by value. The Drawing object corresponds to the Drawing object that depicts the state map on the selected state form, and the string is "RevenueGrowth". You might recall that the cell in the state form table that contains the percentage change between 1993 and 1994 has the name RevenueGrowth. The ColorMap macro uses a Select Case statement to change the color of the map on the state form depending on the value in the cell named RevenueGrowth. If the value is less than –0.2, the map is colored red; if the value is between –0.2 and 0.2, the map is colored green; and if the value is greater than 0.2, the map is colored blue. This visual effect gives the user an immediate view of revenue growth for each state. A red map on a state form tells the user that revenue for 1994 was less than 80 percent of what it was for 1993. Likewise, a green map indicates a moderate revenue increase or decrease, and a blue map represents a high level of growth. After you run the InitializeListBox macro (see page 153), click several of the states in the listbox to see this effect.

Working with the Map Form

The next major component that you need to design is the map form. To create the map form, first select the MapSheet worksheet. This worksheet includes a Control button and 10 state maps. When completed, the form will have a dark gray background, two optionbuttons for changing the map color display to either revenue or net income growth, and a textbox that displays a legend for the map colors. You can make all of these changes by running the AddMapOptionButtons and AddMapLegend macros. However, you can also design the map form manually. The process of changing the background color of the map form manually is the same as it was for the Control form: You select the cells and then select a dark gray color in the Patterns tab of the Format Cells dialog box. To add optionbuttons to the form manually, use the Option Button tool on the Forms toolbar. Last, to manually add the textbox that displays the legend, use the Text Box tool on the Drawing toolbar.

Take a look now at the AddMapOptionButtons macro, which changes the background color and adds the optionbuttons for you:

APPLICATION SETUP MACRO

Sub AddMapOptionButtons()
    Dim CaptionArray As Variant
    Dim NameArray As Variant
    Dim ButtonCounter As Integer
    Dim TopValue As Integer
    CaptionArray = Array("Revenue", "Net Income")
    NameArray = Array("RevenueOpt", "NetIncomeOpt")
    With Worksheets("MapSheet")
        .Activate
        .Range("A1:Z70").Interior.ColorIndex = 16
        TopValue = 100
        For ButtonCounter = 1 To 2
            .OptionButtons.Add 20, TopValue, 80, 20
            With .OptionButtons(ButtonCounter)
                .Caption = CaptionArray(ButtonCounter)
                .Name = NameArray(ButtonCounter)
                .Border.Weight = xlMedium
                .Interior.ColorIndex = 15
                .OnAction = "ChangeMap"
            End With
            TopValue = TopValue + 20
        Next
    End With
End Sub

AddMapOptionButtons uses two arrays, CaptionArray and NameArray, to store the captions and names that will be assigned to the optionbuttons after they are added. After activating MapSheet, the macro sets the color of the background cells to dark gray. The macro then uses a For-Next loop to call the Add method on the OptionButtons collection twice to add two optionbuttons. Next the macro uses an index to CaptionArray and NameArray to assign values to the Caption and Name properties of the optionbuttons. Note that the Caption property refers to the text string that is displayed on the control, whereas the Name property is the name of the control as it appears in the formula bar's Name box when selected. Last the macro formats the weight of the border and the color of the interior and then assigns the ChangeMap macro name to the OnAction property. The ChangeMap macro follows:

Sub ChangeMap()
    Dim DrawVar As Drawing
    Dim DisplayValue As String
    Select Case Application.Caller
        Case "RevenueOpt"
            DisplayValue = "RevenueGrowth"
        Case "NetIncomeOpt"
            DisplayValue = "NetIncomeGrowth"
    End Select
    For Each DrawVar In Worksheets("MapSheet").Drawings
        ColorMap DrawVar, DisplayValue
    Next
End Sub

ChangeMap uses a Select Case statement with the Caller property of the Application object as the test expression. The Caller property contains the name of the object or control responsible for launching a macro. For example, the optionbuttons to which ChangeMap is assigned are named RevenueOpt and NetIncomeOpt; therefore, when ChangeMap is run, Application.Caller evaluates to either "RevenueOpt" or "NetIncomeOpt". Depending on the evaluation of the test expression, the DisplayValue string is assigned either "RevenueGrowth" or "NetIncomeGrowth". Then a For-Each-Next loop calls the ColorMap macro (described earlier, in the section titled "Working with the Control Form," beginning on page 151) to color each of the map drawings on the map form. The color assigned to each drawing depends on the level of growth of the company's revenue or net income—as shown in the respective state forms.

F Y I

Assigning OnAction Macros Manually

After you run the AddMapOptionButtons macro, beginning on page 155, try choosing the two optionbuttons on the map form to see the colors of the maps change. Note that up to this point we have always used the OnAction property of an object to assign a macro to the object. You can also assign a macro to an object manually by pointing to the object, clicking the right mouse button, and selecting Assign Macro from the shortcut menu. After you do this, you can select a macro from the Assign Macro dialog box.

Adding a legend to the map form

The next step is to add a legend to the map form. You can add it manually or by using the macro shown below:

APPLICATION SETUP MACRO

Sub AddMapLegend()
    Dim LegendString As String
    LegendString = "Red: > 20% Decrease" & Chr(10) & _
                   "Green: -20% to 20% Growth" & Chr(10) & _
                   "Blue: > 20% Growth"
    With Worksheets("MapSheet")
        .Select
        .TextBoxes.Add 10, 180, 175, 50
        With .TextBoxes(1)
            .Text = LegendString
            .Interior.ColorIndex = 19
            .Border.Weight = xlMedium
            .Shadow = True
            With .Font
                .Size = 12
                .Bold = True
            End With
        End With
    End With
End Sub

Note that in the AddMapLegend macro above, two line continuation characters (a space followed by an underscore [_]) are used in the portion that assigns a text string to the LegendString variable. Also notice that the Chr function inserts a carriage return character in the string. (Macintosh users should use Chr(13) to insert a linefeed in a TextBox object.)

All of the objects have now been added to the map form.

Assigning macros to the map drawings

Now you need to assign a macro to each of the state map drawings in the map form so that a user can click a state map to activate the appropriate state form. The AssignMapMacros macro below assigns the GotoStateForm macro to each state map on the map form:

APPLICATION SETUP MACRO

Sub AssignMapMacros()
    Dim DrawVar As Drawing
    With Worksheets("MapSheet")
        .Select
        For Each DrawVar In .Drawings
            DrawVar.OnAction = "GotoStateForm"
        Next
    End With
End Sub

The GotoStateForm macro is shown at the top of the facing page. Notice how Application.Caller in GotoStateForm is used to determine the appropriate worksheet to activate after a state map is clicked. Also notice that the ColorMap macro (described earlier, in the section titled "Working with the Control Form," beginning on page 151) is called to update the color of the map on the state form so that the map displays the appropriate color for depicting revenue growth. In this application, we always call the ColorMap macro when going to a state form in case the data on which the color of the map is based ever changes.

Sub GotoStateForm()
    Dim Map As String
    Map = Application.Caller
    With Worksheets(Map)
        ColorMap .Drawings(Map), "RevenueGrowth"
        .Activate
    End With
    Range("A1").Select
End Sub

Activating the map form from a state form

Although it is already possible to activate a state form from the map form, it should also be possible to go from a state form back to the map form. The AssignStateMapMacros macro below assigns the GotoMap macro name to the map drawings on the state forms:

APPLICATION SETUP MACRO

Sub AssignStateMapMacros()
    Dim StateList As Range
    Dim RangeVar As Range
    Set StateList = Worksheets("SummaryData").Range("StateList")
    For Each RangeVar In StateList
        Worksheets(RangeVar.Value).Drawings(1).OnAction = "GotoMap"
    Next
End Sub

The GotoMap macro below updates all of the drawings on the map form in case any of the underlying data on the state forms has changed. To update the colors, however, it is necessary to check to see which optionbutton on the map form is currently selected; an If statement does so by checking the value of the RevenueOpt optionbutton. If the value is equal to the constant xlOn, the map colors are updated to depict revenue growth. If the value is not equal to this constant, the map colors are updated to depict net income growth.

Sub GotoMap()
    Dim DrawVar As Drawing
    Dim DisplayVal As String
    Dim RevenueOpt As OptionButton
    Set RevenueOpt = _
            Worksheets("MapSheet").OptionButtons("RevenueOpt")
    If RevenueOpt.Value = xlOn Then
        DisplayVal = "RevenueGrowth"
    Else
        DisplayVal = "NetIncomeGrowth"
    End If
    For Each DrawVar In Worksheets("MapSheet").Drawings
        ColorMap DrawVar, DisplayVal
    Next
    Worksheets("MapSheet").Select
    Range("A1").Select
End Sub

Adding Buttons to the Control Form

As the application looks now, a user can go from the Control form to any state form and back again and from a state form to the map form and back again. We now need to link the forms so that the user can access either the map form or the SummaryData form by choosing a button on the Control form. The Control form should also include a button for quitting the application. So we need three more buttons on the Control form.

You can add these buttons manually by using the Button tool on the Forms toolbar or by running the AddControlButtons macro:

APPLICATION SETUP MACRO

Sub AddControlButtons()
    Dim CaptionArray As Variant
    Dim MacroArray As Variant
    Dim ButtonCounter As Integer
    Dim TopValue As Integer
    CaptionArray = Array("Map Sheet", "Summary Data", "Quit")
    MacroArray = Array("GotoMap", "GotoSummary", "QuitApp")
    With Worksheets("Control")
        .Activate
        TopValue = 140
        For ButtonCounter = 1 To 3
            .Buttons.Add 260, TopValue, 80, 30
            With .Buttons(ButtonCounter)
                .Caption = CaptionArray(ButtonCounter)
                .OnAction = MacroArray(ButtonCounter)
            End With
        TopValue = TopValue + 40
        Next
    End With
End Sub

The AddControlButtons macro uses two arrays—one to hold the caption for each button and one to hold the names of the macros to assign to each button. A For-Next loop is then used to add the buttons to the form and to assign the appropriate captions and macros. The macros that are launched by the SummaryData and Quit buttons are shown below:

Sub GotoSummary()
    Worksheets("SummaryData").Select
    Range("A1").Select
End Sub

Sub QuitApp()
    ActiveWorkbook.Close
End Sub

Designing the SummaryData Form

So far, you've done little to the SummaryData form, which currently holds only a list of state names. The completed SummaryData form, however, should contain a table that lists revenue and profit figures for each state, a chart that's linked to the table, and two optionbuttons that let the user toggle between revenue and net income data in the chart. The BuildTable macro shown below builds and formats the table. (You can also build and format this table manually.)

APPLICATION SETUP MACRO

Sub BuildTable()
    Dim TopOfList As Range
    Dim StateList As Range
    Dim StateName As Range
    Dim StCnt As Integer
    Set TopOfList = Worksheets("SummaryData").Range("TopOfList")
    Set StateList = Worksheets("SummaryData").Range("StateList")
    With Worksheets("SummaryData")
        .Activate
        .Range("A1:Z70").Interior.ColorIndex = 16
    End With

    'Add a formula in the cells--for example, =Arizona!Revenue
    StCnt = 0
    For Each StateName In StateList
        StateName.Offset(0, 1).Formula = _
                "=" & StateName.Value & "!Revenue"
        StateName.Offset(0, 2).Formula = _
                "=" & StateName.Value & "!Net_Income"
        StCnt = StCnt + 1
    Next

    'Add headings, totals formulas, and cell formatting
    With TopOfList
        'Column headings:
        .Offset(-1, 0).Value = "'1994"
        .Offset(-1, 1).Value = "Revenue"
        .Offset(-1, 2).Value = "Net Income"

        'Row heading and totals formulas on bottom row:
        .Offset(StCnt, 0).Value = "Total"
        .Offset(StCnt, 1).FormulaR1C1 = _
                "=SUM(R[-" & StCnt & "]C:R[-1]C)"
        .Offset(StCnt, 2).FormulaR1C1 = _
                "=SUM(R[-" & StCnt & "]C:R[-1]C)"

        'Cell formatting:
        .CurrentRegion.NumberFormat = "$#,##0_);($#,##0)"
        .CurrentRegion.AutoFormat Format:=xlColor2
        .CurrentRegion.BorderAround , xlMedium
    End With
    Worksheets("SummaryData").Columns(1).ColumnWidth = 2
End Sub

This macro takes advantage of several features of the Range object that have not yet been discussed; we'll look at those here. The first With statement activates the SummaryData worksheet and colors the background cells dark gray.

Next a For-Each-Next loop goes through StateList row by row, using the Range object's Offset method to refer to neighboring cells and assigning values to the Formula properties of those cells. Offset takes two arguments: a row number and a column number. The first call to Offset returns the cell that is one column to the right in the same row as the current cell in StateList. The Formula property is then set for this cell to a formula that evaluates to "=StateName!Revenue". This formula links the cell to the cell named Revenue on the appropriate state form. For example, in the California row of the table, this formula would be "=California!Revenue". Note that all Excel worksheet formulas that involve links to cells on other worksheets adhere to this syntax: a worksheet name followed by an exclamation point, and then either a cell address or a cell name. The next statement in the For-Each-Next loop performs a similar action: setting the Formula property of the cell in the next column equal to "=StateName!NetIncome". This formula links the cell to the NetIncome cell on the appropriate state form.

The block of code inside the With statement after the For-Each-Next loop adds headings and formats and fills in the bottom row with totals for the Revenue and Net Income columns. Labels are added using the Offset method and Value property of a Range object. The totals are created by setting the Formula properties of the respective cells to a SUM formula that calculates the sum of all numbers in the rows of that particular table column. The SUM formula takes a Range argument, specified here by a starting cell address and an ending cell address, with the two separated by a colon. The SUM formulas used in the BuildTable macro use relative addresses, in which row and column number offsets are specified. The exact syntax of the SUM formula is "=SUM(R[-" & StCnt & "]C:R[-1]C)", where StCnt represents the number of rows that contain data. The formula can be read as "sum the values starting at StCnt rows up in the same column and ending one row up in the same column." Note that because no column offset is specified, it is assumed to be zero.

After the macro enters the SUM formulas in the bottom row of the table, it formats the entire table. The NumberFormat property of the range that encompasses the table is set to a currency format, and the AutoFormat method is called on the range to apply a built-in format named xlColor2. Last the macro places a solid border of medium weight around the table and sets the ColumnWidth property of the worksheet's first column to 2 to reduce the width of the form's left margin, as shown here:

Adding a chart to the SummaryData form

Next you need to add a chart to the SummaryData form. You would typically create a single on-sheet chart manually by using the ChartWizard tool on the Standard toolbar. The CreateChart macro shown below adds a chart for you automatically:

APPLICATION SETUP MACRO

Sub CreateChart()
    Dim TableRange As Range
    Dim RevenueRange As Range
    Dim NetIncomeRange As Range
    Dim R1 As Range
    Dim R2 As Range
    Dim FirstRow As Integer
    Dim FirstColumn As Integer
    Dim LastRow As Integer
    Dim LastColumn As Integer

    Worksheets("SummaryData").Activate

    'TableRange is the entire table
    Set TableRange = Worksheets("SummaryData").Range("TopOfList") _
                     .CurrentRegion

    'Make it easy to refer to the boundaries of the table
    FirstRow = TableRange.Row
    FirstColumn = TableRange.Column
    LastRow = TableRange.Rows.Count + FirstRow - 1
    LastColumn = TableRange.Columns.Count + FirstColumn - 1

    'Point to and name the revenue portion of the table
    '(including row headings but not including totals)
    Set RevenueRange = Worksheets("SummaryData").Range( _
                            Cells(FirstRow, FirstColumn), _
                            Cells(LastRow - 1, LastColumn - 1))
    RevenueRange.Name = "RevenueRange"

    'R1 is the range that holds row headings (but not "Total"),
    'R2 is the range that holds NetIncome values (but not total)
    Set R1 = Range(Cells(FirstRow, FirstColumn), _
                   Cells(LastRow - 1, LastColumn - 2))
    Set R2 = Range(Cells(FirstRow, FirstColumn + 2), _
                   Cells(LastRow - 1, LastColumn))

    'Point to and name the net income portion of the table
    '(including row headings but not including totals)
    Set NetIncomeRange = Union(R1, R2)
    NetIncomeRange.Name = "NetIncomeRange"

    'Add a chart that's linked to RevenueRange
    RevenueRange.Select
    ActiveSheet.ChartObjects.Add(198.75, 12, 240, 243).Select
    ActiveChart.ChartWizard source:=RevenueRange, _
                            gallery:=xl3DPie, _
                            format:=1, _
                            plotBy:=xlColumns, _
                            categoryLabels:=1, _
                            seriesLabels:=1

    'Format the new chart
    Worksheets("SummaryData").ChartObjects(1).Activate
    With ActiveChart
        .Elevation = 55
        .Legend.Shadow = True
        .Legend.Interior.ColorIndex = 15
        .ChartTitle.Font.Size = 18
        .ChartTitle.Font.Bold = True
        .ChartTitle.Border.LineStyle = xlMedium
        .ChartTitle.Shadow = True
        .ChartTitle.Interior.ColorIndex = 15
    End With

    'Deactivate the chart by hiding the ActiveWindow
    ActiveWindow.Visible = False
    With Worksheets("SummaryData").ChartObjects(1)
        .Border.LineStyle = xlNone
        .Interior.ColorIndex = 16
    End With
    Worksheets("SummaryData").Range("A1").Select
End Sub

The CreateChart macro above selects the appropriate data range in the table that is on the SummaryData form, calls the Add method of the ChartObjects collection to add an on-sheet chart, and then calls the ChartWizard method to link the chart to the appropriate range in the table. The CreateChart macro then activates the chart and formats various properties of the chart itself.

The first portion of the CreateChart macro is rather complicated because the first two columns of the table (excluding the last row, which contains totals) must be selected before the macro can call the Add method of the ChartObjects collection. We know that the cell at the top of the list of states is named TopOfList. The eighth line of the macro sets the TableRange variable equal to the range that corresponds to the CurrentRegion property of the TopOfList range; this is actually the entire table. (The line continuation character [_] is used in the statement to carry it over to the next line.) The next four statements set integer variables that reference the table's first and last rows and first and last columns.

The RevenueRange object variable is then set equal to the range in the table that corresponds to the table's first two columns, excluding the last row. The statement uses the Range object and the Cells method. Cells takes two arguments—a row number and a column number—and returns a single cell that represents the intersection of the row and column numbers on the worksheet. The Cells method can be called on the Application, Worksheet, or Range object. In this case, the call is made on the Application object. (Application is the default when no object is specified.) Because Cells is called on the Application object here, the appropriate worksheet must be active at the time, which is why the Activate method is called on the SummaryData Worksheet object at the beginning of the macro.

Note that when called from a worksheet, Range acts as a method that returns a Range object and can take as arguments either a single range address or two individual cell addresses. When Range takes two cell addresses as arguments, the range that is returned is the entire range that falls between those two cells. By using the Range and Cells methods in conjunction, you can set the RevenueRange object to the table's first two columns, excluding the last row. A name is then assigned to the range so that this complicated process need not be repeated the next time you want to select this range.

The next set of statements are more complicated yet. They involve selecting a range of data to be used to chart net income values. Such a chart requires selecting the first and last columns of the table, excluding the last row. The chart created in the CreateChart macro displays revenue values. However, a range for charting net income will also be set in this macro to be used by the ChangeChart macro (described in the next section). The ChangeChart macro is called by the optionbuttons that you still must add to the SummaryData form. ChangeChart allows the user to change which set of data is linked to the chart. To set NetIncomeRange, two range variables, R1 and R2, are used. Again, by using the Range and Cells methods, R1 is set to the table's first column, excluding the last row, and R2 is set to the table's last column, excluding the last row. Then the Union function combines R1 with R2 and assigns the union to the NetIncomeRange variable. The range is then given a name so that it can be accessed easily in the future.

After all this complicated manipulation of ranges, RevenueRange is selected, and the Add method is called on the ChartObjects collection to add a chart to the form. Next the macro calls the ChartWizard method on the new chart to link it to RevenueRange. Notice that several other arguments are passed to the ChartWizard method to specify values for various properties of the chart. After the chart is linked to the worksheet, the chart is activated so that additional properties of the chart can be set, including the elevation of the chart and various properties of the Legend and ChartTitle objects. The chart is then deactivated when the macro sets the Visible property of the ActiveWindow object to False. Last the line style of the border and the color of the interior of the chart are set. The line style is set to xlNone so that no border appears, and the color is set to dark gray to make the chart blend in with the background.

Adding optionbuttons to the SummaryData form

You now need to add the two optionbuttons that allow the user to choose between displaying revenue information and displaying net income information on the chart. The AddChartOptionButtons macro below adds the two optionbuttons to the SummaryData form and sets the OnAction property of each optionbutton to the ChangeChart macro:

APPLICATION SETUP MACRO

Sub AddChartOptionButtons()
    Dim CaptionArray As Variant
    Dim NameArray As Variant
    Dim ButtonCounter As Integer
    Dim TopValue As Integer
    CaptionArray = Array("Revenue", "Net Income")
    NameArray = Array("RevenueChart", "NetIncomeChart")
    With Worksheets("SummaryData")
        .Select
        TopValue = 60
        For ButtonCounter = 1 To 2
            .OptionButtons.Add 20, TopValue, 80, 20
            With .OptionButtons(ButtonCounter)
                .Caption = CaptionArray(ButtonCounter)
                .Name = NameArray(ButtonCounter)
                .Border.Weight = xlMedium
                .Interior.ColorIndex = 15
                .OnAction = "ChangeChart"
            End With
            TopValue = TopValue + 20
        Next
    End With
End Sub

The AddChartOptionButtons macro is nearly identical to the AddMapOptionButtons macro discussed earlier, in the section titled "Working with the Map Form," beginning on page 155. We will not, therefore, look at AddChartOptionButtons in detail. However, the ChangeChart macro, which allows the user to change data that has been charted, appears below. It is assigned to the optionbuttons on the SummaryData form.

Sub ChangeChart()
    Dim RevenueRange As Range
    Dim NetIncomeRange As Range
    Set RevenueRange = Worksheets("SummaryData").Range("RevenueRange")
    Set NetIncomeRange = Worksheets("SummaryData").Range("NetIncomeRange")
    Worksheets("SummaryData").ChartObjects(1).Select
    Select Case Application.Caller
        Case "RevenueChart"
            ActiveChart.ChartWizard source:=RevenueRange
        Case "NetIncomeChart"
            ActiveChart.ChartWizard source:=NetIncomeRange
    End Select
    Worksheets("SummaryData").Range("A1").Select
End Sub

The ChangeChart macro above employs a Select Case statement that uses Application.Caller as the test expression. If the RevenueChart optionbutton is selected, RevenueRange is passed as the source argument to the ChartWizard method, and revenue data is displayed on the chart. If the NetIncomeChart optionbutton is selected, however, NetIncomeRange is passed as the source argument to ChartWizard, and net income data is displayed on the chart.

Completing the Control Form

The application is now nearly complete. Still missing are two elements on the Control form: the title textbox and the airplane graphics.

Adding the title textbox to the Control form

You can use the AddAppTitleBox macro below to add the title textbox:

APPLICATION SETUP MACRO

Sub AddAppTitleBox()
    Dim TitleString As String
    TitleString = "West Coast Airways"
    Worksheets("Control").Select
    ActiveSheet.TextBoxes.Add 90, 30, 250, 30
    With ActiveSheet.TextBoxes(1)
        .Text = TitleString
        .Interior.ColorIndex = 15
        .Border.Weight = xlMedium
        .Shadow = True
        .Font.Size = 22
        .Font.Bold = True
        .HorizontalAlignment = xlCenter
        .VerticalAlignment = xlCenter
    End With
    Range("A1").Select
End Sub

AddAppTitleBox merely calls the Add method on the TextBoxes collection and sets various properties of the added textbox.

Inserting the airplane graphics in the Control form

Now you're ready to insert the Picture objects that represent the bitmaps of the airplanes flying across the screen. A file named PLANE.BMP on the companion disk packaged with this book contains a bitmap of an airplane. To insert the bitmap file in the Control form manually, choose the Picture command from the Insert menu, and then select the PLANE.BMP file.

Note

Excel's Picture command (found on the Insert menu in Windows) is not available on the Macintosh. The CHAP03-2.XLS file on the Macintosh disk (available from Microsoft Press through a fulfillment order) contains a bitmap picture of an airplane already. Macintosh users should use this bitmap rather than the PLANE.BMP file. The InsertPlanes macro on the Macintosh disk omits the code for inserting the PLANE.BMP file and uses the following line of code in place of the With Selection statement:

With ActiveSheet.Pictures(1)

See the section titled "Using the Companion Disk," beginning on page xxvii, for instructions on ordering the Macintosh fulfillment disk.

Make three additional copies of the Picture object, and space them evenly across the form immediately below the application title box. The InsertPlanes macro below automates the process of inserting the bitmap, making the copies, and spacing the objects evenly. (This macro assumes that the PLANE.BMP file is saved in the same directory as is the workbook in which the macro is being run: ThisWorkbook.)

APPLICATION SETUP MACRO

Sub InsertPlanes()
    Dim PlaneCounter As Integer
    Dim LeftValue As Integer
    Dim PathString As String
    Dim DirectoryVar As String
    DirectoryVar = Application.PathSeparator
    PathString = ThisWorkbook.Path & DirectoryVar & "PLANE.BMP"
    Worksheets("Control").Activate
    ActiveSheet.Pictures.Insert(PathString).Select
    With Selection
        .Border.LineStyle = xlNone
        .Copy
    End With
    For PlaneCounter = 1 To 3
        ActiveSheet.Paste
    Next
    LeftValue = 50
    For PlaneCounter = 1 To 4
        With Worksheets("Control").Pictures(PlaneCounter)
            .Left = LeftValue
            .Top = 80
            .OnAction = "FlyPlanes"
            LeftValue = LeftValue + 110
        End With
    Next
    Worksheets("Control").TextBoxes(1).OnAction = "FlyPlanes"
    Range("A1").Select
End Sub

In the InsertPlanes macro, the string DirectoryVar is set to Application.PathSeparator, which returns the correct operating system path separator regardless of whether the macro is run on a Macintosh or in Windows (either ":" or "\"). You then build the path for the PLANE.BMP file by appending the directory separator and the PLANE.BMP filename to the end of the string returned by ThisWorkbook.Path. This happens to be the path to which the current workbook file is saved. You then insert the PLANE.BMP bitmap by calling the Insert method on the Pictures collection, and continue by setting the LineStyle property of the Border object to xlNone to take away the border around the picture. The picture is then copied to the clipboard. Next a For-Next loop pastes the picture three times so that you now have four pictures on the Control form. A For-Each-Next loop then spaces the four pictures evenly in a horizontal line across the form below the application title box. It does so by setting the Left and Top properties of each picture appropriately. The OnAction property of each picture is set to the FlyPlanes macro, and at the end of the macro, the OnAction property of the application's title TextBox object is also set to FlyPlanes. The FlyPlanes macro appears below:

Sub FlyPlanes()
    Dim DrawVar As Picture
    Dim FlightCounter As Integer
    Dim Counter As Integer
    For Counter = 1 To 4
        Worksheets("Control").Pictures.Group
        With Worksheets("Control").GroupObjects(1)
            For FlightCounter = 1 To 6
                .Left = .Left + 10
            Next
            .Ungroup
        End With
        For Each DrawVar In Worksheets("Control").Pictures
            If DrawVar.Left > 355 Then
                DrawVar.Left = 0
            End If
        Next
        Worksheets("Control").Pictures.Group
        With Worksheets("Control").GroupObjects(1)
            For FlightCounter = 1 To 5
                .Left = .Left + 10
            Next
            .Ungroup
        End With
    Next
    Range("A1").Select
End Sub

FlyPlanes first calls the Group method on the Control form's Pictures collection. Doing so groups all the airplane bitmap pictures together so that they can be treated as a single object—that is, as a GroupObject object. This single object is then referenced as GroupObjects(1), and a For-Next loop moves the group 60 points horizontally across the screen in an animated fashion by incrementing the Left property of the group. The Ungroup method is then called on the group to again break it into four separate Picture objects. The macro then moves the Picture object that is on the far right back to the far left by setting the Left property to 0. The objects are grouped again and then moved 50 more points across the screen to the right. Last the Ungroup method is called on the group so that FlyPlanes will work the next time it is called.

The Control form is now complete.

Setting Environment Properties

Although you are nearly finished creating the West Coast Airways application, one last task remains. You have probably noticed that many of the Excel artifacts that remind users that they are using a spreadsheet software program still appear in the application. Such artifacts include row and column headings, gridlines on many of the forms, scrollbars, worksheet tabs, and the formula bar at the top and the status bar at the bottom of the work area. Properties of the Window object control some of these artifacts. Properties of the Application object control others. For example, settings for gridlines, row and column headings, tabs, and scrollbars are made through Window properties; settings for the formula bar and status bar display are made through Application properties. You can save Window property settings with a workbook file, but you cannot do so with Application property settings. In addition, some of these Window properties are specific to the Worksheet object, and others are specific to the Workbook object. For example, settings for gridlines and row and column headings are Worksheet specific; settings for scrollbars and tabs are Workbook specific. So to turn off the display of gridlines and row and column headings on all of the forms in the application, you must activate each worksheet and set the appropriate display property for gridlines and row and column headings. You can do this manually by going to each worksheet, choosing the Options command from the Tools menu, and making the appropriate selections from the View tab. The necessary Workbook-specific and Application-specific property settings can be made in the same Options dialog box, but they need be made only one time. However, the SetUpEnvironment macro below will perform all these tasks for you:

APPLICATION SETUP MACRO

Sub SetUpEnvironment()
    Dim WorksheetVar As Worksheet
    For Each WorksheetVar In ActiveWorkbook.Worksheets
        WorksheetVar.Select
        With ActiveWindow
            .DisplayGridlines = False
            .DisplayHeadings = False
        End With
    Next
    With ActiveWindow
        .DisplayHorizontalScrollBar = False
        .DisplayVerticalScrollBar = False
        .DisplayWorkbookTabs = False
    End With
    Application.DisplayFormulaBar = False
    Application.DisplayStatusBar = False
    Worksheets("Control").Activate
End Sub

SetUpEnvironment uses a For-Each-Next loop to set all of the Worksheet-specific Window properties and then uses a With statement on the ActiveWindow to set all of the Workbook-specific Window properties. Last the macro sets the necessary Application-specific properties.

Run the SetUpEnvironment macro. If you save the file, all but the Application-specific property settings are saved with the file and are then restored when the file is opened again. To restore the Application property settings, write an Auto_Open macro that sets the property settings whenever the workbook file is opened.

The Auto_Open macro below sets the Application-specific properties of DisplayStatusBar and DisplayFormulaBar:

Sub Auto_Open()
    Application.DisplayStatusBar = False
    Application.DisplayFormulaBar = False
End Sub

Auto_Open is called automatically when the file is opened. Note that VBA also provides an Auto_Close macro that runs every time a workbook file is closed. After you add the Auto_Open macro, return to the Control form and save the file.

Finding Module1 in the Completed Application

If you would like to review the code in Module1, you can redisplay the worksheet tabs through the Options dialog box, or you can press the Ctrl-PgUp or Ctrl-PgDown keys until Module1 becomes the active sheet. Such key combinations let you move from one sheet to another without using tabs.

Looking Ahead

Congratulations! You have successfully built the West Coast Airways application. As mentioned, this application suffers from a few flaws that would limit its implementation as a full-fledged information system. If you have mastered the concepts covered in this chapter, however, you are well on your way to building powerful information systems in Excel.

The rest of the chapters in this book cover more advanced topics associated with more complicated Excel objects, including database access, data flow, control of user input, and e-mail integration. Mastering these advanced topics and the more complicated objects in Excel will allow you to transform applications such as West Coast Airways into full-fledged information systems. The discussion of such advanced topics begins with the next chapter, "Building Information Systems with Pivottables and Charts."

S U M M A R Y

This chapter introduced most of Excel's graphical objects and showed you how to manipulate them through VBA to create a simple application. The following list summarizes this chapter's key points:

  • Graphical objects share many methods and properties, with which you can manipulate collections of objects using a single For-Each-Next loop.
  • You can set up the environment for your application manually or by using macros. How efficient either method is depends on how many times you repeat the same series of setup steps.
  • You can call the ChartWizard method in a macro to create or change a chart, or you can use Excel's ChartWizard tool to create or change a chart manually. A chart can be set up so that it changes automatically whenever the data to which it is linked changes.
  • You tell an object on a sheet to respond to mouse clicks by setting the object's OnAction property to a macro name. A macro can use the Application.Caller property to determine which object was clicked.
  • The Range object's Offset method can be used to manipulate cells; the Cells and Union methods can be used to create ranges.
  • Some aspects of the Excel environment can be saved with a workbook. Others must be reset each time a workbook is opened; to reset these aspects, you use the Auto_Open macro.


Intended Audience

This document is for programmers who are interested in learning Visual Basic for Applications (VBA). It assumes the reader is not a Visual Basic expert, but has some programming knowledge and some experience with graphical programming concepts such as events, controls, and dialogs. To help the reader become an effective VBA programmer as quickly as possible it includes interesting techniques and lots of code examples. Reading it should help the new VBA programmer save much time, and help in exploring more of the language. If this document seems too advanced, first read some of the books suggested at the end in the "Further Reading" section. A copy of Excel version 5.0 or later is required to follow the examples in this document.

Example 1. Changing Excel's title bar

VBA represents a major advance in macro language technology. It makes macro programming easier to learn because it is based on the Basic language standard. Because it is becoming common across all Microsoft applications, there is no need to be an expert in several different languages to use the features of more than one Microsoft application in a macro project. Finally, VBA represents a fundamental change in the way Microsoft designs its products. VBA makes just about every feature in Excel programmable, and open to customization. Try the following in Excel. Right click on a worksheet tab, then choose the Insert... option. In the next dialog, select "Module" from the list. A new VBA module sheet will appear in the workbook.

Next, type in the code shown in Example 1 below. Now run it by placing the cursor on the Sub NewTitle() line and clicking the Run button (the one with the green arrow on the VBA toolbar.) If the VBA toolbar isn't visible, right click on any toolbar or select the View/Toolbars menu and choose "Visual Basic". After the code runs Excel's title bar changes from "Microsoft Excel" to whatever text was assigned to the Application.Caption property. This brief exercise illustrates that Excel's internal properties are now exposed as objects for the programmer to control.


Sample Application Description

This document describes how to create an Excel wizard. VBA is powerful enough to create custom wizards, and it's a fairly simple matter to write one. The histogram wizard discussed here shows how close VBA can come to matching the Chart Wizard that's built in to Excel. The histogram wizard is a demonstration of what is possible with VBA rather than an attempt at the perfect histogram utility. It includes a number of bullet-proofing features such as validation of the selected data and user-specified dialog items—it's a good jumping-off point for other projects.


Structure

The histogram wizard has five main dialogs. They are called from a main subroutine which is essentially a series of nested Select Case statements. One block has the following structure.

This is the basic structure. Each step in the wizard has a few quirks, such as validation routines and setting status flags. Each dialog has one or more routines that handle the setup and display of the dialog, respond to user events, and manage a worksheet and chart the wizard creates for each histogram. The final dialog has a chart preview feature. Although Excel does not include a chart preview as part of VBA, A serviceable preview is possible by pasting a chart object onto the dialog sheet. While the dialog is displayed, the chart object updates in real time in response to changes made to controls on the dialog. It's a rather nifty feature.


Object Fundamentals

When looking at a VBA macro that is all debugged and polished, the code seems so easy to write! However, those who haven't done object-oriented programming before may discover that typing in a bunch of object names in a way that makes sense to the developer isn't a guarantee that the code will execute properly. There is a set of rules for object syntax and relationships between objects that the VBA programmer needs to learn. The rest of this section covers some important principles and good tools to simplify learning and make it easy to work with objects. It's the principles and tools that are important, not the objects themselves. Since there are so many objects, it's not worth spending time trying to memorize them.


Objects, Methods, And Properties

Breaking up Excel into multiple objects gives the benefit of code reusability. It's possible to include a Chart object in a presentation, or a PivotTable object in an interactive document. The developer provides the code that sets up the object or helps the user make changes. The rest of the code is already debugged and documented. There are over six million lines of code in the Microsoft Office applications…that's a lot of code you don't have to write! To take advantage of these objects requires knowing some concepts that may be new to the reader.

Objects

Think of an object as something visible in the real world. For instance, a picture hanging on a wall is an object. In Excel, some objects are the Worksheet, Chart, and Range objects. In the real world, a person would change things about the picture by picking it up and doing whatever they want, within the limits of good taste. A developer changes things about Excel's objects through the VBA language.

Methods

Think of a method as an action done to an object. For instance: hanging the picture, cleaning the glass, or showing the picture if it had a velvet cloth covering it. In Excel, the Show method shows a dialog box; the Activate method makes a worksheet visible and ready for editing.

Properties

Think of a property as something that describes an object. A picture has a frame style, dimensions, and the photo itself. An Excel chart has similar properties; for instance the Border, Height, and Width properties of the ChartArea object. Code can both examine and change the values of a property if it can be written to, but some properties are read-only.

Collections

Collections are another useful concept. There could be a collection of all the pictures in a museum. In Excel, a collection is a group of similar objects. The Worksheets collection is all the Worksheet objects in a Workbook object. With collections, code can do things like list the names of all the worksheets in a workbook to build a table of contents. VBA has a For Each… statement that lets code step through all the objects in a collection, one at a time.


Finding Your Way Around The Object Hierarchy

To begin learning about objects, a beginning VBA programmer might want to count the number of cells in a range the user selected, then display a message if the user selected only one cell. Try typing in the statement:

If Application.Range.Selection.Count = 1 Then MsgBox("Only one cell")...

then, run it and there will be an error message "Range method of Application class failed." Isn't VBA supposed to be easy? Well, it will seem easier in a moment. Let's take some time to study how objects work. Start by drawing a diagram of what this line tries to do. One way to do this is to look the key words up in the VBA reference manual or Excel Help and note the definitions.

Count Property: Returns the number of items in a collection. Read-only.

Range Method:

Returns a cell or range of cells

If Application.Range.Selection.Count = 1 Then ...

Selection Property: Returns the current selection in the active Window of the Application object. Read-only.

Example 2. Invalid object reference

Selection Property: Returns the object that is currently selected in the active window of the Application object. Read-only.

If Application.Selection.Cells.Count = 1 Then...

Cells Method: Returns a collection of cells as a Range.

Example 3. Valid object reference

From Example 2 above, it's easy to see why the first attempt failed. To understand an object reference, always read it from right to left—this seems backwards—but remember that VBA parses it from left to right. The code in Example 2 is trying to "count the number of items in the selection in the range in the application". So, why did the Range method fail? Let's bring up the Object Browser [image] and see how the Range method works.

As Figure 1 below shows, it's easy to bring up Help on the Range method by finding it under the Application object (remember, the error message told us this is how it parsed the code). Then click on the question-mark button. Help for the Range method says it returns a cell or a range of cells (a Range Object). Now, let's check Help for the Selection property. The first thing the help information shows is that the Selection property applies to the Application and Window objects. It does not apply to a Range. This is important! We have learned two things. First, it's OK to say Application.Range("A1"), but it's completely invalid to use anything besides a cell reference with the Range method. Second, it's not possible to ask for a selection from a range, code must ask for a selection from a window or the application.

Now, on to fixing the problem. Since VBA is parsing from left to right, it looked in the application for a range, then tried to find a selection in that range, which it can't do. To get to the cells in the user's selection, the reference should look like Application.Selection.Something. Referring to Help again, the Selection property returns the object currently selected in the active window, which is a Range object. This means the code has to work with the Range object, not the Range method.

Use the Object Browser again to look at the properties and methods for the Range object. Now it becomes clear that "Cells" is the Something. It is a method that returns a collection of cells as a Range object. Since a collection of cells is returned, the Count property will work to tell how many cells were selected. Now, where do the cells come from? That's the easy part, the user just selected them. So, to take the user's selection, return it as a range, and count the cells in that range, use the code in Example 3, Application.Selection.Cells.Count.

Figure 1. Using the Object Browser to check a reference

But it's not over yet, it's time for the advanced lesson. If the user selected a range, isn't the Cells method just returning a range as another range? Yes, it is! Help for the Cells method says that applying the syntax object.Cells to a Range returns the same Range object (in other words, it does nothing). Hmmm. So try the code

If Selection.Count = 1 Then MsgBox("Only one cell")

Try this by selecting a single cell and running the macro. It works! This brings to mind two great truisms of VBA:

Truism 1: There are many ways to accomplish the same result in VBA.

Truism 2: It's easier to write complex code than it is to write simple code.

One final tip on the Object Browser. Most new users will try to search for a keyword in the left-hand pane of the browser (titled "Objects/Modules" in Figure 1 above.) If the keyword is a method or property it will not appear in this pane. For this reason, the browser works best when the programmer knows the correct object in advance. If this isn't the case, searching Help first for the keyword will return its parent object. Also remember that the most frequently-used methods and properties are children of the Application object. For these, just select "Application" on the left and then look in the right-hand pane of the browser to find the keyword of interest.


If You Get Lost, Use A Map

Another useful tool for navigating in the object universe is a tree diagram of VBA objects. The Microsoft Office Developer Kit (ODK) has a useful diagram that shows the relationships between objects in Excel, Project, and Access in a graphical format. It can be indispensable. There's an on-line version of this diagram on the ODK CD. The Office Developer Kit ships with Visual Basic Professional Edition.


Summary

This short list has been a great help in learning VBA. When trying to debug an object reference error, do the following:

1. Look in the Object Browser for exactly the object, method, or property that is reported to fail in the error dialog.

2. Think about what the object reference is trying to do, and how VBA is parsing it.

3. Check the help on that topic, especially the "Applies To" section. Jump to the "Properties" and "Methods" sections to be sure the reference is valid for the object—and stare at the code for a while (those with more experience will spend less time here.)

4. If unsure of the mistake after checking Help, try writing a very simple example in a blank worksheet to explore what may be wrong. This can be a great tool for getting things clear quickly.

5. After doing these four things, only then is it a good idea to change the code to work with a different object, method, or property. Doing this too soon may create more confusion!

Remember: Look, Think, Check Help, Simple Example...Then, change the code!


Working With The Range Object: Understanding Ranges And Names

The Range Object is one of the keys to being a productive Excel VBA programmer. Though powerful, it's also challenging to learn. Here are some helpful tips. First, named ranges. Naming a range is helpful in order to assign a friendly name to a group of cells and refer to the cells by that name later on. For instance, to select a range containing the user's data, it's a lot easier to write Range("UserData").Select than to keep track of the cell addresses, especially if code will be inserting or removing cells from the range. To create a named range first select the cells, then click in the range name drop-down (see Figure 3) and type in the name. Be sure to press return after typing or the name won't be assigned. To see how to do this in VBA, keep reading.

The first dialog in the Histogram Wizard needs to create a named range of all the contiguous cells around the currently-active cell. Tools like Excel's automatic subtotals and the Chart Wizard use this feature. Here's how to do it. First, place the active cell within the range. Then type something like the following:

Selection.CurrentRegion.Select

Selection.Name = "Bins1" 'or some other friendly name!

Range(Selection.Address).Name = "Bins1" 'This does the same thing

' in a different way.

The trick is to use the command Selection.CurrentRegion.Select , which selects all the contiguous non-blank cells around the active cell. In the second line, the selection property returns an object containing the current selection, in this case a Range object. The Range object has a Name property. In plain English, the second line of code above means "Assign the name Bins1 to a Range which is the current selection." There still may be times when a macro needs to get at the actual cell addresses. The third line of code illustrates the Address property of the Range object, which returns the address (for instance "$E$1:$E$4") of the selected cells.

There are times when Excel can be picky about range address formats. In the case of the FREQUENCY function, Excel insists on an R1C1-style reference. Fortunately, there's a special argument for the Address property that gives the desired result:

Selection.FormulaArray = "=FREQUENCY(" + Range("Data1").Address(True, _ True, xlR1C1) + "," + Range("Bins1").Address(True, True, xlR1C1) + ")"

What's odd is that typing in an A1-style reference manually for FREQUENCY works just fine, but VBA complains. So, be sure to try changing the reference style if unexplained errors happen and the range looks perfectly valid.

The Cells Method

Use the Cells method to work with the cells in a range as if they were an array. The Cells method accepts a row and column address, but the address is local to the cells in the range itself. For instance, to assign the text "Data" to the cell in row 1, column 1 of the HCriteria range, use the code

Range("HCriteria").Cells(1, 1) = "Data"


Learning The Development Environment

VBA has a development environment designed for working with code. Gone is the Excel 4-style macro sheet format where code is entered into cells. VBA code is written in module sheets, with access to a text editor, debugger, and syntax highlighting. There's plenty of good material that discusses the details of editing code (see the "Further Reading" section), but a few handy tips are covered below.


Navigating to Procedures in Code

Use the window split bars to be in two places in the code at the same time. It's often convenient to have the top pane set to the declarations section and the bottom pane at the location where code is being entered. That way, it's easy to add new declarations right away before they're forgotten.

To jump to a procedure from somewhere else in the code, do the following. First, split the window into two panes. This is optional, but helpful to return to the current place. Then, right mouse click anywhere on the line of code containing the procedure call. A pop-up menu will appear with an option to go to the procedure definition. Select that, and Excel jumps to the procedure and places the insertion point there. With the windows split, just click back in the other pane showing the calling code and there's no wasted time scrolling back to the original spot.

Figure 2. Navigating to procedures in your code


Getting Help

Help on Visual Basic for Applications is available in a separate help file. In Excel 5, get to it by pressing F1 or choosing the Help/Contents menu item, and then choosing Programming With Visual Basic. In Excel 7, choose Help/Microsoft Excel Help Topics, then use the Contents, Index, or Find tabs to search for the topic. To get help on a VBA keyword while editing a module sheet just select the keyword in the code, then press F1. VBA help will automatically search for the keyword and display help on it.


The VBA Toolbar

Here is the toolbar used for editing and debugging code along with a brief description of what each button does.

Inserts a blank module sheet

Starts the Menu Editor

Starts Debug Window with execution paused as first line of the sub

Adds or examines watch variables

Sets or clears a breakpoint in the code

Starts the Object Browser

Steps through code, does not enter calls

Runs the sub where editing cursor is located, starting at the beginning

Pauses or resumes macro execution

Halts macro execution

Records a new macro

Steps through code and into calls


Syntax Highlighting

While typing VBA code, it is automatically checked for correct syntax (another advance over Excel 4). It is also color-coded—Making it easy to see those lines commented out a week ago are still comments and need to be changed back. To control the colors VBA assigns to code open the Tools/Options/Module Format dialog. This dialog can also change the font and size of the text.


Declarations and Variables

For a macro language, VBA has sophisticated data types and the means to hide or share data in the code. For instance, use the Public statement to declare a variable that is available to all modules in all applications that support VBA. There is also a Private statement to declare variables that are available only to procedures within the same module. The Static statement defines variables inside procedures that retain their value as long as a macro is running. These procedures can remember their state the last time they were called.

As far as performance is concerned, always try to use the smallest, most specific data type to get the best speed of execution. The Variant data type is very flexible because it can have the attributes of both a number and a string, but code that accesses Variant data frequently runs slower than code that uses a simpler data type such as String or Integer.

Visual Basic for Applications also has an Object data type. It can refer to any VBA object, such as a worksheet, cell, chart, or even objects in other applications. One example would be Word's WordBasic object. Object variables can also reduce the work needed to refer to a lengthy identifier in code. For instance, both ways of referring to the Wiz1 dialog sheet are valid in the code below, but which is better?

Const GWizBookName = "PERSONAL.XLS"

Dim GWiz1 As Object

Sub Main()

' Initializations...

' Here's one way of referring to an edit control in the Wiz1 dialog:

Set GWiz1 = ThisWorkbook.DialogSheets("Wiz1")

GWiz1.[RangeEdit].Caption = GDataRange.Address

' Here's another way:

Workbooks(GWizBookName).DialogSheets("Wiz1").[RangeEdit].Caption _

= GDataRange.Address

Example 4. Two kinds of variable reference styles

Actually, there are many more ways than just two!. The first method, using the ThisWorkbook property, is the best way to reference contained sheets in a workbook. ThisWorkbook returns the workbook containing the running code regardless of whether the workbook is an add-in or an ordinary workbook users can edit.

Besides making the code more readable, using ThisWorkbook makes code independent of:

· Whether it is in the active workbook

· Whether the workbook is an add-in

· The name of the workbook (If code references Workbooks("PERSONAL.XLS") as was done above, when the user renames the workbook the code will break).

This will become important if code is installed in PERSONAL.XLS, the personal macro workbook. When this code runs the user's data will be in a different workbook from the one where the dialog sheets and macros are. Using ThisWorkbook is also more maintainable because there is only one hard-coded reference to the Wiz1 dialog. Renaming the dialog affects only one line of code. An explicit object reference (the second method above) should be used only when code needs to refer to something in a different workbook and the names of both workbooks won't change.

Another consideration in working with variables is performance. With VBA objects, shorter references are better. The reason for this is that each property or method in a variable reference counts as an IDispatch transaction. IDispatch is one of the interfaces in Object Linking and Embedding (OLE). In the reference

ActiveSheet.Worksheets(1).Range("A1").Value,

1 2 3 4

there are four IDispatch transactions. The more object accessors or "dot" operators there are in code, the slower it will be. An object variable improves performance whenever a variable reference is used multiple times, as in the example below.

Dim GWiz3 As Object

Sub Main()

'Use an object variable since we will be accessing this a lot.

Set GWiz3 = ThisWorkbook.DialogSheets("Wiz3")

...

End Sub

Sub OptionBinCount_Click()

GWiz3.[BinWidthHelp].Visible = False

GWiz3.[BinCountHelp].Visible = True

GWiz3.Focus = GWiz3.[EditBinValue].Name

End Sub

If the same reference is needed for just a few lines of code rather than in many places, the With statement is a useful way of "factoring" an object reference. Once inside the With...End With block an object reference is re-used for each statement. So, instead of writing

ActiveDialog.Buttons.[ButtonWiz3Cancel].DismissButton = True

ActiveDialog.Buttons.[ButtonWiz3Back].DismissButton = True

ActiveDialog.Buttons.[ButtonWiz3Next].DismissButton = False

ActiveDialog.Buttons.[ButtonWiz3Finish].DismissButton = False

Save six IDispatch transactions (and a lot of typing!) by writing

With ActiveDialog.Buttons

.[ButtonWiz3Cancel].DismissButton = True

.[ButtonWiz3Back].DismissButton = True

.[ButtonWiz3Next].DismissButton = False

.[ButtonWiz3Finish].DismissButton = False

End With

Loops containing object references should always be factored. The fastest way to set properties for a large number of cells is to enclose the loop in a With...End With block:

With ActiveWorkbook.Sheets(2)

For c = 1 to 1000

.Cells(c, 1) = c

Next c

End With


Working With User Dialogs

Excel 7 has a new dialog editor that's a dream compared to the one in Excel 4. There's graphical support for laying out all dialog box controls, and the right mouse button works to set the control properties. In addition to the standard controls (buttons, check boxes, etc.) it's now possible to place drawing objects in a dialog box, so it's easy to make some imaginative user dialogs. Code can even set properties of the drawing objects at runtime. Read on to see some of the possibilities.


Tab Order

Set the tab order of controls in a dialog by right clicking on the dialog worksheet background, and selecting the tab order menu option.


Accelerator Keys

These are the keys that people without mice love. When developing a dialog, it is good practice to include them. To add accelerator keys open a control's format object dialog. Right-click on the control, select Format Object, and add the key in the Control tab of the dialog. Trick: To set the accelerator key for an edit box, create some fixed text in the dialog called a label control. Put the label next to the edit box and set an accelerator key for the label. Then, place the edit box immediately after the label in the tab order. When the user tabs through the controls while the dialog is running, Excel automatically passes the focus to the next control in the tab order that can accept the focus. This will be the edit box (labels can't accept focus, but they can have accelerator keys!)


Setting Control Focus

One way to make dialogs friendly is to write a small piece of code that intelligently moves the focus when a control is selected. This "AutoFocus" code is helpful in the case where the user clicks an option button and there is an associated edit box as in the example below:

After selecting the Bin Width option button, the next logical thing is to enter the width value. Here's how to set up an event procedure that automatically sets the focus on the edit box for the bin width. In the dialog editor, select the control the user will click on (in this case the option button.) Next, click on the View Code button on the forms toolbar [image]. Excel starts the code editor and positions the cursor in the event procedure for the control. The code in Example 5 below does two things. The first two lines of the procedure make some help text visible to explain what the option button does. The third line sets the focus on the edit box.

There's a lot of talk about repetitive-motion injuries among computer users these days. Small touches like this can make working with an application not just easier, but safer too.

'

' OptionBinWidth_Click Macro

'

'

Sub OptionBinWidth_Click()

DialogSheets("Wiz3").[BinCountHelp].Visible = False

DialogSheets("Wiz3").[BinWidthHelp].Visible = True

DialogSheets("Wiz3").Focus = _ DialogSheets("Wiz3").[EditBinValue].Name

End Sub

Example 5. AutoFocus code example


Friendly Names for Dialog Box Controls

Naming an edit box "ChartDataRange" makes code is much more readable compared to Excel's default control names, which look something like "EditBox12". Assign custom names to controls by selecting the control in the dialog editor, then clicking in the range name drop-down. Type in any friendly name, as long as it adheres to VBA syntax rules. After typing the name, be sure to press return to get Excel to assign it to the control.

A caution is in order here. After changing the name of a dialog box control, be sure to use quotes around the name when referring to it through a collection object. Excel will accept a name without the quotes–but Excel uses an un-quoted name as a reference to a variable! If the variable is unassigned, Excel will think it is item zero of the collection. In this situation some very frustrating errors can happen, such as "EditBoxes method of DialogSheet class failed."

Range Name Drop-Down, also used for entering control names.

Figure 3. Using the Range Name Drop-Down to define maintainable control names

Here's an example. To display a range address in an edit box called RangeEdit:

Do this:

DialogSheets("Wiz1").EditBoxes("RangeEdit").Caption = DataRange.Address

' or...

Dim REdit As String

REdit = "RangeEdit"

DialogSheets("Wiz1").EditBoxes(REdit).Caption = DataRange.Address

But don't do this:

'Assuming RangeEdit is not a declared variable, this won't work!

DialogSheets("Wiz1").EditBoxes(RangeEdit).Caption = DataRange.Address

Expressions also accept control names placed inside square brackets:

DialogSheets("Wiz1").[RangeEdit].Caption = DataRange.Address

Spaces are permitted in control names to make them more readable.


Creating Event Procedures

Unlike Visual Basic, VBA does not have a pre-defined list of event procedures handy in a control's property sheet. Generally one event is supported per control. For instance, when first showing a VBA dialog, Excel supports an event to initialize the dialog's controls, set focus, and do other things. There are two ways to create the event code. The first one is to create an init procedure for the dialog by writing one in a Module sheet, for instance:

Sub Wiz1_init()

'Set the focus to the edit box for the data range:

DialogSheets("Wiz1").Focus =DialogSheets("Wiz1").[RangeEdit].Name

End Sub

Now, switch back to the dialog editor and select the dialog. Do this by clicking on its edge, or anywhere in its title bar. The entire dialog will be outlined if it was selected properly. Next, right-click the edge or title bar and select Assign Macro. In the next dialog box, pick out the name of the init procedure just created. Now when Excel displays the dialog the init procedure will run before the user sees the dialog box. The advantage of this method is that the writer can control the exact procedure name and where the procedure appears in the module sheet.

The other way to create the procedure is to select the control or dialog and then click the Edit Code button [image] on the Forms toolbar. Excel will create the stub of a procedure, complete with a small commented header. Then add the rest of the code.


Linking Dialog Buttons To Code

It's easy to run a macro when a user clicks buttons in a dialog. Create the macro, then right click on the button and select Assign Macro. In the case of the wizard the same Cancel, Back, Next, and Finish buttons appear in each dialog. There are four common routines to set a global variable (GWizReturn) to a different value for each button. The main routine then uses GWizReturn to control processing in the Select Case statements. Here's a partial listing of the code:

GProgress = 0

Wiz1Entry:

Call WizStep1 'WizStep1 will set GWizReturn depending on what button

' the user clicks.

'Set the tracking variable to indicate first dialog is complete.

GProgress = 1

Select Case GWizReturn

Case GO_BACK, CANCEL

Call UndoWiz1

GoTo TheVeryEnd

Case GO_NEXT

'now set up for the second step of the wizard.

Wiz2Entry:

Call WizStep2(UserInput:=True)

GProgress = 2

Select Case GWizReturn

Case GO_BACK

Call UndoWiz2

GoTo Wiz1Entry

Case CANCEL

Call UndoWiz2

Call UndoWiz1

GoTo TheVeryEnd

Case GO_NEXT

Wiz3Entry:

Call WizStep3(UserInput:=True)

' . . .

' Code for steps 3 through 5 deleted for clarity

' . . .

End Select

Case FINISH

Call FinishIt

End Select

Case FINISH

Call FinishIt

End Select

Example 6. Main routine processing


Setting Up Button Properties And Validating Input

To assign properties to a command button in a dialog, right-click the button and select Format Object. It's helpful to do things like assign a default property to one of the buttons so it will be automatically activated when the user presses the return key.

Figure 4. How to assign button properties

The Dismiss property will cause the dialog box to close when the user clicks the button. If there's no need to validate the dialog entries, go ahead and check the Dismiss box. If validation is required it's best to keep the dialog open just in case the user needs to change something. In that case, leave the Dismiss box blank and assign a validation macro to the button. Do the validation steps in the macro and let the macro control whether or not the dialog should be closed (dismissed). Here's a code sample that accomplishes this.

Sub ValidateGraph()

Dim Btn As Object

'Set the DismissButton property to be True so the dialog will close

' if all the validation tests pass.

Select Case GWizReturn

'Since the user could have clicked two possible buttons, make sure

' we choose the right one.

Case GO_NEXT

Set Btn = Wiz3.[ButtonWiz3Next]

Case FINISH

Set Btn = Wiz3.[ButtonWiz3Finish]

End Select

Btn.DismissButton = True

'Check to see if:

'1. Start value is less than end value

'2. There are data to graph

'3. Bin Width/number of bins is valid (nonzero)

If Wiz3.[EditStartValue].Caption = "" Then

MsgBox ("Start Value must be filled in")

'Keep the dialog box displayed until it passes validation.

Btn.DismissButton = False

Wiz3.Focus = Wiz3.[EditStartValue].Name

Exit Sub

End If

If Wiz3.[EditEndValue].Caption = "" Then

MsgBox ("End Value must be filled in")

Btn.DismissButton = False

Wiz3.Focus = Wiz3.[EditEndValue].Name

Exit Sub

End If

If Wiz3.[EditBinValue].Caption = "" Then

MsgBox ("Bin Width or Number of Bins must be filled in")

Btn.DismissButton = False

Wiz3.Focus = Wiz3.[EditEndValue].Name

Exit Sub

End If

If Wiz3.[EditStartValue].Caption >= Wiz3.[EditEndValue].Caption Then

MsgBox ("Start Value must be less than End Value")

Btn.DismissButton = False

Wiz3.Focus = Wiz3.[EditStartValue].Name

Exit Sub

End If

If Wiz3.[EditBinValue].Caption <= 0 Then

MsgBox ("Bin Width or Number of Bins must be greater than zero")

Btn.DismissButton = False

Wiz3.Focus = Wiz3.[EditBinValue].Name

Exit Sub

End If

If Int(Wiz3.[EditBinValue].Caption) <> _

Val(Wiz3.[EditBinValue].Caption) And _

Wiz3.[OptionBinCount].Value = xlOn Then

MsgBox ("Number of Bins must not be fractional")

Btn.DismissButton = False

Wiz3.Focus = Wiz3.[EditBinValue].Name

Exit Sub

End If

End Sub

Example 7. Sample validation code

The code in this example is a simplified version of the ValidateGraph routine in the Wizard. Take a look at the real routine to see the extra work needed to fully bullet-proof a dialog. You will gain a new appreciation for the work that Microsoft development teams go through.

Excel also supports built-in validation for edit controls. Set this option in the control's Format Object dialog, shown in Figure 5 below. A new feature in Excel 7 is the ability to set password validation (the code can capture typed characters, but only asterisks are displayed). The Reference validation option checks to be sure the user types a valid cell reference. It also tracks the mouse! All a user needs to do is select cells in the worksheet while the dialog is open and Excel will automatically insert the reference into the edit box, updating it as the mouse moves.

Figure 5. Validation options for edit boxes


Dialog Design

Dialogs support a surprising number of object types. For instance, the drawing toolbar can be used to place any drawing object on the dialog. Add a thin embossed line above the wizard buttons by creating two lines—one gray, one white. Then move them very close together but not quite on top of each other. This is done by turning off the forms toolbar's grid button [image] or holding down the ALT key while positioning the drawing object. Here's the result:

Use the drawing toolbar to add circles, freehand shapes, and even text in a special color, size or font. Code can change properties like color and shading at runtime, or make drawing objects visible or hidden.

The fifth wizard dialog has some "custom controls" to change the chart fill colors. Excel VBA doesn't support custom controls yet, but being creative with drawing objects goes a long way. The color selector controls are grouped drawing objects, each consisting of a filled rectangle with gray borders and two white lines on the right and bottom sides to give a sunken 3D appearance. Position the rectangles over buttons in the dialog. Clicking on the rectangle activates the button beneath it. There's no way to make the vertical size of the buttons any smaller than the example, but they do work very nicely. This wasn't tested on Excel for the Macintosh, so there's no guarantee it will work there. See Figure 6 below for a picture of how the controls are set up.

A rectangle drawing object is positioned over a control button

Figure 6. Using drawing objects to create color selector controls


Working With Toolbars


Creating Custom ToolTips

To make Toolbar buttons with custom ToolTips, the easiest way is to add the button to a custom toolbar. This defines the toolbar name and order of the buttons in advance. The Name property of the custom toolbar button is the ToolTip. Here is a code example:

Application.Toolbars("Custom Charts").ToolbarButtons(1).Name = _ "Histogram"

After setting the name, Excel will remember it permanently—until the toolbar is deleted.

To copy a button and insert a gap before the copied button, first insert a gap on the destination

toolbar using the ToolbarButtons.Add method, then copy the button to the position after the new

gap. Toolbars can be saved inside a workbook, making them more transportable. Code can also create new toolbars and assign custom bitmaps to the toolbar buttons. For more information on these topics, see the Add-Ins section.


Debugging, Debugging, Debugging

Ah, debugging! Nothing else combines fun and frustration so well. Here's some tips that will hopefully save many hours.


Viewing The Code And Worksheet At The Same Time

Seeing the code while watching how it changes a worksheet is a powerful way to diagnose bugs. It's easy to do this by setting a breakpoint just before the place that there's trouble (Step 1 below).

Step 1. Inserting a breakpoint in code

Next, run the macro. When Excel reaches the breakpoint the debug window will appear. Step through the code using the step into and step over buttons (Step 2 below). The arrangement for windows and toolbars in Step 2 is especially handy for debugging. It makes the worksheet, debug window, and VBA toolbar visible while leaving ample space for editing the code.

Step 2. Stepping through code using the Debug Window


Tracking Down Errors

Gaining more experience with VBA makes it easier to find those pesky errors. Some error messages can be challenging, like the one in Figure 7 below:

Figure 7. Syntax error in module out of the current context.

When this error appeared, there was no way to enter the debugger at the line that failed. It was necessary to step through the code a line at a time to find that the error happens while trying to display a dialog box called "Wiz1". But the syntax of this line is correct! Where is the syntax error?

There are macros in another module sheet assigned to controls in the Wiz1 dialog. When the Show statement activates the dialog, VBA parses the macros and finds an error. The debug window context is in Sub Main in a different module sheet, so VBA can't show the error—it just displays a general message. An easy way to find the error is to stop the macro and select the dialog sheet for the Wiz1 dialog. Then run the dialog using the Run Dialog button [image] in the Forms toolbar, or the Tools/Run Dialog menu selection. This will force syntax checking of the event procedures linked to the controls in the dialog. The debug window will open and point at the mistake. Alternatively, set a breakpoint in the module containing the init macro for the dialog and step through the code from there. There's even a third way, which is to use the Step Into button in the VBA toolbar to step into the dialog's macro code.

With a bit of practice the developer can get pretty good at deciphering the error messages to understand their deeper, hidden meanings. In Figure 8 below, a dot is missing from the front of the reference to an edit box for the chart title. The VBA parser says "Where's my object?" while the human says "Huh?"

Here's another example where learning to think like the VBA parser helps to get past a confusing error message. In Figure 9 below, the brackets around a button name are missing. Instead of typing DialogSheets("GWiz3") to refer to the dialog box, an object variable called GWiz3 was defined. VBA looks at GWiz3 and understands it is a dialog box object, so it next looks at ButtonWiz3Next and expects to find a property or method by that name. Since it doesn't, Excel displays an error dialog. Perhaps a better error message would be "Object doesn't support ButtonWiz3Next property or method". The figure shows the lines that were typed in the debugger's immediate window to figure out the problem.

Figure 8. True meaning: "Shouldn't there be a dot in front of this line?

Figure 9. Learning to think like the VBA parser.


Using the Immediate Window

The debugger's Immediate Window is a powerful tool, ranking right up there with those electric bug zappers sold at a good hardware store. Since the Immediate Window is interactive it can do things the Object Browser and Help can't, like viewing variables and giving instant feedback on syntax. To troubleshoot an error set a breakpoint in the code just before the problem and then try printing key variables. If an object reference is confusing just type it in on the fly and see what happens. Chances are that typing a few combinations of references into the immediate window will hit on the correct one or at least produce valuable clues about what's wrong. To print a variable or expression, just place a question-mark character in front of it. There's no need to type in similar keystrokes several times; just use the scrollbar to bring the lines into view. Modify the line or cut and paste the line to duplicate it. Think of the Immediate window as a fast, interactive way to try out object references to see if they're right.

Type in the object reference here, then watch the result.

Figure 10. Using the Immediate Window to resolve a tricky object reference.

Here's another tip. Code can activate objects in the Immediate Window. The activation shows up on the screen right away. When debugging there are times when it's important to see another part of the workbook, but the debugger prevents you from clicking on the worksheet tabs. Instead, just type in the command to activate the worksheet in the Immediate Window, as in Figure 11 below. To scroll a window, use the LargeScroll method. The following statement

ActiveWindow.LargeScroll down:=1

will scroll the active window down a page. To scroll in any direction use the up, down, toRight, and toLeft parameters. In Excel 7 there's less of a need to do this manually as most window operations can be performed with the mouse while the debug window is open.

Figure 11. Activating a worksheet from the Immediate Window.


Set Property Values Accurately

Excel VBA does not always perform error checking when changing a property's value. To make sure things work right, code should only use what the documentation says are allowed values. For instance, will the following line set an option button so it is "on"?

Application.DialogSheets("Wiz2").[Option Button 5].Value = True

Nope. The code will run without reporting an error. A subsequent check of the button's value will fail because an option button's value property can only be xlOn or xlOff. A quick trip to the documentation will show this. So, the correct way to set the button's value property is:

Application.DialogSheets("Wiz2").[Option Button 5].Value = xlOn


Beware Of Naming Conflicts

Be careful when using special characters to name objects. For instance, don't try to create a temporary worksheet named Histo$Tmp. It's possible, since Excel allows a worksheet name with a $ character. But using VBA to create a named range on that worksheet fails—the line defining the name will give the message "Error in formula". This is because the $ character is a special character for absolute cell references. It's good practice to stick to the simplest possible styles for naming objects…especially if the code is behaving in strange ways.


Helpful Tips And Tricks


Tips For Editing Code

If a macro selects an object but does not deselect it, it may not be possible to enter new text in a module sheet. It looks like the system has locked up but all that's needed is to find the selected object on another worksheet and deselect it by typing ESC. This commonly happens when there's an error or Excel reaches a breakpoint while debugging.


Use The Macro Recorder

Really. USE IT! It's not just a tool for dummies, the macro recorder can save valuable time. For instance, what's the fastest way to find the name of the property to make a text box scale automatically when a chart is re-sized? First try right-clicking the text box and selecting Format Object, then click the Properties tab. This dialog appears:

Searching Help for Object Positioning, Text Boxes, positioning, Size, and Chart turns up a big goose egg. Ah, what a productive morning! But, wait a minute. Because it's interactive, the macro recorder can write code faster than trying to look it up in Help. Turn it on, and in five seconds, the answer: set the Placement property to xlMoveAndSize.

Here's an example of code the macro recorder produces and how to adapt it to an existing macro. To follow along, select a chart and then start the macro recorder to change the font size on the axis. The recorded code:

ActiveChart.Axes(xlValue).Select

With Selection.TickLabels.Font

.Size = 8

End With

becomes...

With DialogSheets("Wiz4").DrawingObjects(GWiz4ChartName)

.Chart.Axes(xlValue).TickLabels.Font.Size = 8

End With

In this case, it's not a good idea to have the chart active while working with it because the user would see the changes the macro was making. So, replace the selection code and references to the selection with a With...End With block that has an explicit reference to the chart. Writing the code this way also makes it independent of what is currently selected.

The macro recorder can record using absolute or relative references. Absolute references are useful when code needs to work with the exact same cells every time it runs. Relative references are useful to write code that could work with cells anywhere on a worksheet. For example, code that creates a list of the worksheet names in a workbook would place a sheet name in a cell, then move the selection down a row and insert the next name. The row number is not important, just the fact that the selection must move down one row.

To record this example using relative references, mark the position in code where the move operation should happen with the menu option Tools/Record Macro/Mark Position for Recording, then select the option Tools/Record Macro/Use Relative References. Now switch back to the worksheet, place the cursor in the list, and select Tools/Record Macro/Record at Mark. Use the arrow key to move the selection down a row, then click the Stop Recording button on the floating toolbar. The recorder will generate a relative reference in the code, as shown below:

Sub Main()

Dim ws As Object

For Each ws In ActiveWorkbook.Sheets

ActiveCell.Value = ws.Name

'The following line was recorded with relative references:

ActiveCell.Offset(1, 0).Range("A1").Select

Next ws

End Sub


The Order Of Property Changes Makes A Difference

If code is working inconsistently try checking the order of the property settings. This can happen because changing a property can have side effects on other properties. For instance, the code

With DialogSheets("Wiz4").DrawingObjects(GWiz4ChartName).Chart

.HasLegend = True

.Legend.Top = 93

.Legend.Position = xlRight

End With

will not work correctly because setting the Position property to xlRight also changes the Top property. To set the position of the legend to the right side of the chart and adjust the location of the top, set the Top property first, then change the Position.


Changing Data Invisibly

There are times when the user shouldn't see lots of screen activity while a macro is running. After all, macros are supposed to work magically! Screen updating can be distracting, plus it slows down the macro. Here's a couple of ways to solve the problem. First, there's no need to activate a sheet to work with its objects if the code provides an explicit reference to them. For example, the first line in the following code selects objects in GTempSheet without activating it so the user does not see the changes while the code is running.

Worksheets(GTempSheet).Range("A1").Select '<--Explicit reference so

' GTempSheet doesn't have to be activated.

LastRow = Selection.CurrentRegion.Cells.Count

If Gheader = xlNo Then

Selection.Range(Cells(2, 1), Cells(LastRow, 1)).Name = "Data1"

Else

Selection.Range(Cells(1, 1), Cells(LastRow, 1)).Name = "Data1"

End If

The above code example also illustrates using the Count property to count the cells in a range and then adjust the range to include or exclude the first cell.

The second way to control screen updating is to turn it off with the Application.ScreenUpdating property. Here's code that does this:

Application.ScreenUpdating = False

'Sort the data allowing for a label in first cell if needed.

Selection.Sort key1:="Data1", order1:=xlAscending, header:=xlYes, Orientation:=xlTopToBottom

Set this property to False to turn screen updating off, then set it back to True when it should happen again. The macro will run faster, but it will be important to test the effects of turning screen updating off before going crazy with it. If a dialog box is visible, the user may want to move the dialog to see a cell behind it. With updating turned off, all they will get is a blank hole staring at them. Usually the best philosophy is to turn updating off only when absolutely needed, and the rest of the time try to use explicit references to objects the user doesn't need to see.


Clipboard Behavior

Those who've done Excel macro programming before probably know this: Assigning a value to a range clears the clipboard. For instance, with data copied to the clipboard, the following code works just fine:

ActiveSheet.Paste (Range("A2"))

Range("A1").Value = "Data1"

Reversing the two lines causes the error "Paste method of worksheet class failed." Turning off the AutoFilter feature also clears the clipboard. To copy a filtered range to another spot in the worksheet use the Advanced Filter method instead, which supports copying filtered data to another range.


Add-Ins

If the Histogram Wizard is installed in a user's personal macro workbook (PERSONAL.XLS) it will work properly but with one little annoyance. The macro makes changes to its internal dialogs so Excel will ask about saving changes to the personal macro workbook upon exiting the application. A macro can set a special Saved property to prevent the "Save Changes" dialog from coming up—but then the user might not be notified if they happen to have other macros stored in the workbook and decide to edit them during the same session.

A better way to solve this problem is to make the wizard into an Add-in. With add-ins, the macro code behaves as if it's built into Excel. The code is compiled into a form that executes more quickly and is protected against editing. Because of this protection there's no way to debug the add-in code except by displaying messages or writing data to another worksheet, so be sure the code is well tested. To begin the process start with a .XLS workbook file and create an add-in from it using the Tools/Make Add-in command. Never delete the .XLS source workbook since it's impossible to edit the .XLA file the Make Add-In command creates.


Exposing An Add-In's Routines

The add-in code needs to be accessed from the outside world. One method is to create a custom toolbar with buttons that activate the add-in's macros. There's a way to install the toolbar without any programming at all. Just open the add-in's VBA module and select Attach Toolbars from the Tools menu. Then copy the custom toolbar to the add-in workbook. When a user loads the add-in the toolbar will automatically appear.

Another approach is to declare a public function that starts the add-in's main routine. After loading the add-in the public function appears in the list of "All" and "User Defined" functions shown in the function wizard. Next write a small macro in the personal macro workbook that calls the function. Again it's possible to assign this macro to a toolbar button. Example 8 below illustrates this method. If the add-in is a function library rather than an interactive utility like a wizard, this method works well.

'THIS CODE APPEARS IN PERSONAL.XLS:

Sub StartHistogramWizard()

Dim Ret As Integer

Ret = HistogramWizard(Selection)

End Sub

'THIS CODE APPEARS IN THE ADD-IN:

Public Function HistogramWizard(s As Object) As Integer

'This function starts the histogram wizard.

Call HistoMain(s)

HistogramWizard = 1

End Function

Sub HistoMain(s As Object)

'This is the Main sub in the add-in.

' Initializations...

Example 8. Simple method for exposing add-in routines.

If code in PERSONAL.XLS can't locate the add-in function, use the Tools/References command from the module sheet in PERSONAL.XLS to create a reference to the add-in file.


Auto_Add and Auto_Remove Subs

The add-in manager calls the Auto_Add and Auto_Remove routines when installing or removing the add-in, allowing code to perform setup or cleanup tasks. As an example that further illustrates working with toolbars, the code in Example 9 below sets up a toolbar manually. Set the Name property of the custom toolbar when creating it with the syntax Application.Toolbars.Add Name:="Your Toolbar Name". Trying to set the toolbar's Name property using a separate line of code generates an error that a toolbar does not have a writeable name property. This can be confusing because Help says the Name property is writeable for custom toolbars.

Each new button added to the toolbar requires an ID in order for the Add method to work. Any ID will do since the code will modify the button properties after creating it. To insert a blank Custom button, use ID 231. A helpful trick is to store the custom button bitmaps on one of the dialog sheets in the add-in workbook. Just place them off to the side of the dialog and they will be invisible, but the code will be able to copy them to the toolbar button's face. This trick eliminates the need to store button images in separate files.

'Toolbar constants

Const TBNAME = "Custom Charts"

Const CUSTOMBTNID = 231

Sub Auto_Add()

'This routine is called from the add-in manager when the add-in

' is loaded.

Dim Tbar As Object

Dim TbarExists As Boolean

TbarExists = False

'Scan installed toolbars to see if the one for the Histogram Wizard

' is installed.

For Each Tbar In Application.Toolbars

If Tbar.Name = TBNAME Then

TbarExists = True

End If

Next Tbar

'Install the toolbar if necessary.

If Not TbarExists Then

Application.Toolbars.Add Name:=TBNAME

Application.Toolbars(TBNAME).Visible = True

'Copy the button face picture (stored in the Wiz1 dialog).

' Must copy as xlBitmap format for paste operation to work!

ThisWorkbook.DialogSheets("Wiz1").[HWButtonFace].CopyPicture _ format:=xlBitmap

'When accessing buttons by item number, remember that a gap

' counts as an item!

'Add a button to the toolbar and define properties...

Application.Toolbars(TBNAME).ToolbarButtons.Add (CUSTOMBTNID)

With Application.Toolbars(TBNAME).ToolbarButtons(1)

.PasteFace

.Name = "Histogram"

.OnAction = "HistoMain"

End With

End If

End Sub

Sub Auto_Remove()

'This routine is called from the add-in manager when the add-in

' is removed.

On Error Resume Next

Application.Toolbars(TBNAME).Delete

On Error GoTo 0

End Sub

Example 9. Auto_Add and Auto_Remove routines


Helpful Hints for Add-Ins

Give the add-in a name and description by filling in the file properties (file summary information) for the source workbook. The title field appears in the add-in manager's available add-ins list, and the comments field becomes the description. This is shown in Figure 12 below.

Figure 12. Setting up the add-in title and description

If add-in code accesses objects within its own workbook such as dialog sheets or internal worksheets, be sure to declare object references using the syntax

ThisWorkbook.DialogSheets("Wiz1")

rather than

Application.DialogSheets("Wiz1") or ActiveWorkbook.DialogSheets("Wiz1").

Using the reference style ActiveWorkbook.DialogSheets works as long as the active workbook actually contains the dialog, as is probably the case while writing the application. However it won't work after making the workbook into an add-in since by definition an add-in can't be the active workbook.

Code should convert to an add-in quite smoothly by following the guidelines above. If there are any problems try adding Debug.Print or MsgBox statements to the code, or write data to a visible worksheet as a way of tracing errors.

During the process of debugging an add-in there's the need to create and install new versions. If the add-in doesn't seem to behave properly when updating to a new version be sure to clear the check box for the add-in using the Tools/Add-Ins dialog, then delete or rename the old add-in file, make a new version, close and exit Excel, then restart it and load your new version. If this becomes a frequent process, create a small utility routine in the add-in to unload it from memory:

Sub RemoveMyAddIn

ThisWorkbook.Close

End Sub

Assign this routine to a menu item or toolbar button. Closing a file through the add-in manager takes some time, but the add-in can close itself and this process is very fast. When ready to update the add-in the above routine can quickly remove it from memory and install a new version without leaving Excel. Use this method only for convenience while debugging; don't include it in the finished version.

Comments in code are saved in the add-in file. If there's any concern about security or reducing the file size, remove all comments from code before making the final version. A good way to do this is to prefix all comments with two single quotes, as in the example below.

''These comments will be deleted

''when the final version of the add-in is created

Sub Main()

Just before making the final version enable pattern matching in the Edit/Replace command and use it to replace all occurrences of ''* with null text.


Conclusion

The examples in this document are a great way to get started learning about Visual Basic for Applications, the common macro language for Microsoft Office. This knowledge gained can be applied right away to Microsoft Project and Access 95, and much of it will also carry over to development with Word. Please take time to explore the sample code and have fun with your own VBA projects!


Further Reading

The items below are available through local resellers , book stores, or by calling Microsoft Consumer Sales, 800-426-9400 in the USA. Books with an ISBN number may be ordered by calling 800-MSPRESS. Note that the list includes books on both Excel 5 and Excel 7 for Windows 95.

Microsoft Excel Visual Basic for Windows 95 Step By Step | Beginner's Instructions on programming in the Excel VBA language. | ISBN 1-55615-830-0 SRP $29.95
Developing Microsoft Excel 95 Solutions with Visual Basic for Applications | Advanced guide on programming in the Excel VBA language | ISBN 1-55615-893-9 SRP $39.95
Excel 5 Worksheet Function Reference | Reference information for all functions for Excel 5 for Windows and Macintosh | ISBN 1-55615-637-5 SRP $12.95
Excel Visual Basic for Applications Reference | Reference manual for the VBA language in Excel. Paper version of the on-line VBA help. | ISBN 1-55615-624-3 SRP $24.95
Excel Visual Basic for Applications Step By Step | Beginner's Instructions on programming in the Excel VBA language. | ISBN 1-55615-589-1 SRP $29.95
Excel Development Kit | Information on C-API, Excel file format, Apple Events/Apple Script, EXCEL5.INI, and file conversion. | ISBN 1-55615-632-4 SRP $49.95
Microsoft Office Developer Kit | Effective May 1994, the Electronic Forms Designer and Workgroup Templates will be bundled with VB Professional Edition 3.0 along with other Office sample applications to form the Office Developer Kit. | 203-851V300 SRP $495.00 (This is the VB 3.0 Professional Edition product). Licensed VB 3.0 users should order 203-052-005, SRP $49.95

Acknowledgments

Special thanks to Eric Wells for providing valuable advice and sample code. Without his help, this document could not have been written. Thanks also to Russell Williams for providing much of the information on performance and add-ins.

About The Author

Chris Carvalho is an Office Architectural Specialist in Microsoft's Portland office. He joined Microsoft in 1992. Before that, he worked at Intel Corporation for 11 years in their manufacturing, information systems, and marketing groups. He has experience in semiconductor wafer fabrication, engineering and manufacturing data systems design, and real-time operating systems.


Data Access Reference

Microsoft Office 95

Information in this document is subject to change without notice. Companies, names, and data used in examples herein are fictitious unless otherwise noted. No part of this document may be reproduced or transmitted in any form or by any means, electronic or mechanical, for any purpose, without the express written permission of Microsoft Corporation.

© 1995 Microsoft Corporation. All rights reserved.

Microsoft, Microsoft Press, MS, MS-DOS, FoxPro, Visual Basic, Visual C++, Windows, and Windows NT are either registered trademarks or trademarks of Microsoft Corporation in the United States and/or other countries.

Btrieve is a registered trademark of Btrieve Technologies, Inc.

dBASE, dBASE III, and dBASE IV are registered trademarks of Borland International, Inc.

Paradox is a registered trademark of Ansa Software, a Borland Company.

Unicode is a trademark of Unicode, Incorporated.

ZIP Code is a registered trademark of the United States Postal Service.

Document No. DB65279-1095

Printed in the United States of America.


Introduction

Welcome to the Microsoft® Office 95 Data Access Reference, your reference for using data access objects and SQL to create data access applications in Microsoft Access and Microsoft Excel. This book contains information on the data access objects, methods, and properties and the SQL statements and functions available to you when you program in Visual Basic® in Microsoft Access or Microsoft Excel.

Microsoft Access and Microsoft Excel both include the Microsoft Jet database engine. The Jet database engine creates and stores the structure of your database and maintains all the data within it. From Visual Basic, there are two ways to work with the Jet database engine to control the structure and content of your database. You can use either data access objects or Microsoft Jet database engine SQL to create, alter, and delete objects and data in your database.


How to Use This Book

This book is divided into two sections. The first section contains reference information on data access objects and their methods and properties. The second section contains reference information on SQL statements and functions.

Because you may use data access objects or SQL differently in Microsoft Excel than you would in Microsoft Access, many topics contain general information followed by specific information for either or both applications. You will also see general examples demonstrating the use of a particular language element followed by examples showing how you might use it in Microsoft Access and Microsoft Excel.


Other Resources

All the reference topics in this book are available in online Help in Microsoft Access and Microsoft Excel. If you view examples online, you can copy them into your application and run them. You can also search for information in the online index, or ask the Answer Wizard a question if you're not sure what topic you're looking for. Online Help may also include updated or late-breaking information that wasn't available before this book was published.

For more information about Visual Basic programming in Microsoft Access and Microsoft Excel, see the following resources:

  • Building Applications with Microsoft Access for Windows 95, a guide to designing and creating database applications in Microsoft Access, is available with Microsoft Access.
  • Microsoft Access Language Reference is available in the Microsoft Access Developer's Toolkit.
  • Microsoft Excel/Visual Basic for Windows 95 Programmer's Guide, a guide to programming in Visual Basic and creating applications in Microsoft Excel, is published by Microsoft Press®.
  • Microsoft Excel/Visual Basic Language Reference, Second Edition, is published by Microsoft Press.


Using Data Access Objects

Data access objects provide a way to control your database from Visual Basic. If you are working in Microsoft Access, you can do many of the same things in Visual Basic code that you do from the Microsoft Access interface. Many data access objects have graphical representations in Microsoft Access. For instance, a TableDef object corresponds to a Microsoft Access table.

Programming with data access objects gives you a finer degree of control over your application than you have from the Microsoft Access interface, and enables you to adapt your application to changing environments. You don't have to create an entire database from Visual Basic. To speed development, you can create objects in Microsoft Access and write Visual Basic code later to enhance and complete your application.

If you are working in Microsoft Excel, you must use data access objects to manipulate your database, because Microsoft Excel does not have graphical representations of these objects. If you need to control a database from Microsoft Excel, you can create that database graphically in Microsoft Access and write code later to manipulate it from Microsoft Excel. Because both Microsoft Access and Microsoft Excel include the Jet database engine, both applications can use the same database files. Database files are saved with the .MDB filename extension.

Data access objects represent the different components of a database. The objects have a hierarchical relationship to one another; one type of object or collection contains or is contained by another type of object or collection. For a graphical representation of the data access object hierarchy, see "Data Access Object Hierarchy" in the Appendix or in online Help.

DBEngine Object

At the top of the hierarchy is the DBEngine object. This object represents the Jet database engine. The DBEngine object exists whenever you launch Microsoft Access or reference the Microsoft DAO 3.0 Object Library in Microsoft Excel. You don't have to create it explicitly.

Workspace Object

The Jet database engine supports multiple sessions, each of which begins when a particular user logs on and ends when that user logs off. Each session is represented by a Workspace object. Unless you're programming security into your application, you're usually using the default Workspace object implicitly.

Database Object

Within a session, you can open one or more databases, each of which is represented by a Database object. A Database object corresponds to a saved .MDB file. A Database object contains all the other objects and the data in your database. If you're working in Microsoft Access, the database that is currently open can be represented by a Database object.

TableDef, QueryDef Objects

Within a Database object are the tables that contain data, represented by TableDef objects. QueryDef objects represent saved queries of any type and contain combined data from one or more tables. These objects are stored in the database file, so you don't have to recreate them each time you use them. The data in a table or query is organized into fields, represented by Field objects.

Index Object

An Index object corresponds to an index on a table. An index is a cross-reference on one or more fields in a table and enables faster access to data. An index is also useful for defining some rules about data, such as whether the combination of data entered in certain fields must be unique.

Parameter Object

A Parameter object represents any parameters defined for a query. You can use Parameter objects to change the values of query parameters from code before you run the query.

Recordset Object

A Recordset object represents a set of data, or recordset. A recordset is created using data in a table or query. Unlike tables and queries, however, recordsets are not stored to disk and must be re-created each time you use them. Data in Recordset objects is organized into Field objects representing fields in the underlying table or query.

You can think of a TableDef or QueryDef object as an object that defines the structure of a table or query, and a Recordset object as the object that represents the data stored in the table or query. To add, delete, or change data in your database, you must create a Recordset. You can manipulate data by applying the methods of the Recordset and setting and returning its properties.

There are three types of Recordset objects: table-type, dynaset-type, and snapshot-type. Not all Recordset types are updatable in all situations. To determine when you should use each one, see the topics discussing these objects.

Relation Object

A Relation object represents a relationship between fields in two tables in a database. Relationships are a key structural component of your database, in that they link like fields in your tables. They also determine how data in one table is affected when corresponding data in another table is changed or deleted.

Container Object

A Container object represents a type of object in your database. Both Microsoft Access and Microsoft Excel provide the Databases, Tables, and Relations Container objects. Microsoft Access also provides Forms, Modules, Reports, and Scripts Container objects.

Document Object

A Document object represents an object of the type defined by its corresponding Container object. For instance, each database has at least one Table Document object within the Tables Container object. You use Container and Document objects together with User and Group objects to program security into your application.

User, Group Objects

A User object represents a user account with certain access permissions. A Group object represents a group of user accounts with common access permissions. You use User and Group objects together with Container and Document objects to program security into your application.

Error Object

An Error object stores information about data access errors that have occurred. Several data access errors can occur at the same time; information about each is stored in an Error object in the Errors collection. The Errors collection is cleared each time a new error occurs.

Property Object

Every data access object has a set of properties, which are represented by Property objects and stored in the Properties collection associated with that object.


Using SQL

You can use Microsoft Jet database engine SQL to create and change both the structure of your database and the data within it. Unless you're an experienced SQL programmer, it's easiest to create your database either in Microsoft Access or with data access objects in Microsoft Excel. However, you may need to be familiar with basic SQL when you're working with data access objects. Some objects, such as the QueryDef object, include an SQL statement as part of their definition.

If you are working with Microsoft Access, you can create a query in the query design grid and change to SQL view to see the corresponding SQL statement, which Microsoft Access generates for you. This is the easiest way to generate an SQL statement, and is useful if you're not familiar with SQL. You can also write SQL code in SQL view in the Query window, or you can include SQL statements in Visual Basic code.

If you are working with Microsoft Excel, you can only use SQL statements in Visual Basic code. You may want to use Microsoft Access to create a query in the query design grid and save it. You can then open the database from Microsoft Excel and use the corresponding QueryDef object. Your code will run faster if you execute a saved query rather than one that you create on the fly.

There are two parts to SQL: the Data Definition Language (DDL) and the Data Manipulation Language (DML). Using DDL, you can create a database or alter the structure of an existing database. Using DML, you can add, change, or delete data in an existing database. Most of the time you will use DML to create SQL statements.

The following DDL statements are available in Jet database engine SQL:

CREATE TABLE statement

CREATE INDEX statement

ALTER TABLE statement

CONSTRAINT clause

DROP statement

SELECT... INTO statement

The following DML statements are available in Jet database engine SQL:

SELECT statement

INSERT INTO statement

UPDATE statement

DELETE statement

TRANSFORM statement

UNION operation

The following SQL clauses and operations are used to extend the basic SELECT statement in Jet database engine SQL:

FROM clause

IN clause

WHERE clause

GROUP BY clause

HAVING clause

ORDER BY clause

ALL, DISTINCT, DISTINCTROW, TOP predicates

PROCEDURE clause

INNER JOIN operation

LEFT JOIN, RIGHT JOIN operations

PARAMETERS declaration

WITH OWNERACCESS OPTION declaration

Jet database engine SQL also includes the SQL aggregate functions, which you can use to perform statistical operations on your data. The aggregate functions include the Avg, Count, Min, Max, StDev, StDevP, Sum, Var, and VarP functions.


AbsolutePosition Property

Applies To

Dynaset-Type Recordset Object, Recordset Object, Snapshot-Type Recordset Object.

Description

Sets or returns the relative record number of a Recordset object's current record.

Settings and Return Values

The setting or return value is an integer from 0 to one less than the number of records in the Recordset object. It corresponds to the ordinal position of the current record in the Recordset object specified by the object. The data type is Long.

Remarks

The AbsolutePosition property enables you to position the current record pointer to a specific record based on its ordinal position in a dynaset- or snapshot-type Recordset object. You can also determine the current record number by checking the AbsolutePosition property setting.

Because the AbsolutePosition property value is zero-based (that is, a setting of 0 refers to the first record in the Recordset object), it cannot be set to a value greater than or equal to the number of populated records; doing so causes a trappable error. You can determine the number of populated records in the Recordset object by checking the RecordCount property setting. The maximum allowable setting for the AbsolutePosition property is the value of the RecordCount property minus 1.

If there is no current record, as when there are no records in the Recordset object, –1 is returned. If the current record is deleted, the AbsolutePosition property value isn't defined, and a trappable error occurs if it's referenced. New records are added to the end of the sequence.

This property isn't intended to be used as a surrogate record number. Bookmarks are still the recommended way of retaining and returning to a given position and are the only way to position the current record across all types of Recordset objects. In particular, the position of a given record changes when one or more records preceding it are deleted. There is also no assurance that a given record will have the same absolute position if the Recordset object is re-created again because the order of individual records within a Recordset object isn't guaranteed unless it's created with an SQL statement using an ORDER BY clause.

Note

The AbsolutePosition property isn't available on a forward-only scrolling snapshot type Recordset object, or on a Recordset object opened from a pass-through query against a remote database.

See Also

PercentPosition Property, RecordCount Property.

Example

This example positions the current record to the nth record in a dynaset-type Recordset object.

Function MoveToRecord (intPosition As Long, rstTest As recordset) _
    As Integer
    rstTest.MoveLast
    If rstTest.RecordCount > intPosition Then
        rstTest.AbsolutePosition = intPosition
        MoveToRecord = True
    Else
        MoveToRecord = False
    End If
End Function
Example (Microsoft Access)

The following example uses the AbsolutePosition property to set the ordinal position of the first record in a dynaset-type Recordset object to 1.

Sub FirstRecord()
    Dim dbs As Database, rst As Recordset

    ' Return Database variable that points to current database.
    Set dbs = CurrentDb
    Set rst = dbs.OpenRecordset("SELECT * FROM Orders WHERE " & _
        "[ShippedDate] >= #1-1-95#;")
    rst.MoveFirst
    rst.AbsolutePosition = 1
End Sub
Example (Microsoft Excel)

This example prompts the user for a record number. The example uses this number to move to a record in the Customer recordset in the NWINDEX.MDB database, and then it copies the values for three specified fields onto Sheet1.

To create the NWINDEX.MDB database, run the Microsoft Excel example for the CreateDatabase method.

Dim db As Database, rs As Recordset
Sheets("Sheet1").Activate
recordNumber = Application.InputBox(Prompt:="Record number to copy " _
    & "to Sheet1", Title:="Record to copy", Type:=1)
If recordNumber = False Then    ' user cancelled InputBox
    Exit Sub
End If
Set db = Workspaces(0).OpenDatabase(Application.Path & "\NWINDEX.MDB")
Set rs = db.OpenRecordset("Customer", dbOpenSnapshot)
rs.MoveLast
If rs.RecordCount > recordNumber Then
    rs.AbsolutePosition = recordNumber
    ActiveCell.Value = rs.Fields("CONTACT").Value
    ActiveCell.Offset(, 1).Value = rs.Fields("ADDRESS").Value
    ActiveCell.Offset(, 2).Value = rs.Fields("CITY").Value

Else
    MsgBox "The record #" & recordNumber & " doesn't exist."
End If
rs.Close
db.Close


AddNew Method

Applies To

Dynaset-Type Recordset Object, Recordset Object, Table-Type Recordset Object.

Description

Creates a new record for a table-type or dynaset-type Recordset object.

Syntax

object.AddNew

The object placeholder represents the name of an open table-type or dynaset-type Recordset object to which you want to add a new record.

Remarks

The AddNew method creates a new record you can edit and add to the Recordset object named by object. This method sets the fields to Null (the default values specified for a table-type Recordset) or default values, if any.

After you modify the new record, use the Update method to save the changes and add the record to the recordset. No changes are made to the database until you use the Update method.

Caution

If you issue an AddNew and then perform any operation that moves to another record without using Update, your changes are lost without warning. In addition, if you close the object or end the procedure that declares the object or its Database object, the new record and the changes made to it are discarded without warning.

When you use AddNew and the Microsoft Jet database engine has to create a new 2-kilobyte page to hold the current record, page locking is pessimistic. If the new record fits in an existing page, page locking is optimistic.

If you haven't moved to the last record of your dynaset, records added to base tables may be included if they would be positioned beyond the current record. If you add a record to a dynaset-type Recordset using the AddNew method, however, the record is visible in the Recordset and included in the underlying table where it becomes visible to any new Recordset objects.

The position of the new record depends on the type of Recordset:

    In a dynaset-type Recordset object, records are inserted at the end of the recordset, regardless of any sorting or ordering rules that may have been in effect when the recordset was opened.In a table-type Recordset object whose Index property has been set, records are returned in their proper place in the sort order. If the Index property hasn't been set, new records are returned at the end of the recordset.

The record that was current before you used AddNew remains current. If you want to make the new record current, you can set the Bookmark property to the bookmark identified by the LastModified property setting.

See Also

Bookmark Property; Delete Method; Index Object; LastModified Property; Move Method; MoveFirst, MoveLast, MoveNext, MovePrevious Methods; Seek Method.

Specifics (Microsoft Access)

When you use a bookmark in a Microsoft Access module, you must include an Option Compare Binary statement in the Declarations section of the module. A bookmark is a Variant array of Byte data, so the string comparison method for the module must be binary. If a bookmark is evaluated with a text-based string comparison method, such as the Option Compare Text statement or the default setting for the Option Compare Database statement, the current record may be set to an incorrect record.

Example

This example creates a new record in a table named Customers, enters values, saves the changes, and then moves to and deletes the new record.

Dim dbsNorthwind As Database, rstCustomers As Recordset
Set dbsNorthwind = DBEngine.Workspaces(0).OpenDatabase("Northwind.mdb")
' Open table.
Set rstCustomers = dbsNorthwind.OpenRecordset("Customers")
With rstCustomers
    .AddNew    ' Create new record.
    !CustomerID = "FINNF"    ' Set record key.
    !CompanyName = "Finnegan's Foods"    ' Set company name.
    .Update    ' Save changes.
    .Bookmark = rstCustomers.LastModified    ' Go to new record
    .Delete    ' Delete new record.
    .Close    ' Close Table.
End With
dbsNorthwind.Close    ' Close Database.
Example (Microsoft Access)

The following example creates a new record in an Employees table and saves the changes.

Sub NewRecord()
    Dim dbs As Database, rst As Recordset

    ' Return Database variable pointing to current database.
    Set dbs = CurrentDb
    Set rst = dbs.OpenRecordset("Employees")
    With rst
        ' Add new record to end of Recordset object.
        .AddNew
        .[LastName] = "Russell"    ' Add data.
        .[FirstName] = "Peter"
        .Update            ' Save changes.
    End With
    dbs.Close
End Sub


AllowZeroLength Property

Applies To

Field Object.

Description

Sets or returns a value that indicates whether a zero-length string ("") is a valid setting for the Value property of a Field object with a Text or Memo data type. For an object not yet appended to the Fields collection, this property is read/write.

Settings and Return Values

The setting or return value is a Boolean expression that indicates if a value is valid. The data type is Boolean. It returns True (-1) if a zero-length string is a valid value.

Remarks

For a Field object, use of the AllowZeroLength property depends on the object that contains the Fields collection that the Field object is appended to, as the following table shows.

Object appended to | Usage
Index | Not supported
QueryDef | Read-only
Recordset | Read-only
Relation | Not supported
TableDef | Read/write

You can set this property to False (0) to make sure you can't use a zero-length string to set the Value property of a Field object.

You can use this property along with the Required, ValidateOnSet, or ValidationRule property to determine the validity of a value in a field.

See Also

QueryDef Object, Required Property, TableDef Object, ValidateOnSet Property, ValidationRule Property, ValidationText Property, Value Property.

Example (Microsoft Access)

The following example creates a new Field object and sets its AllowZeroLength property to True.

Sub ZeroLengthField()
    Dim dbs As Database, tdf As TableDef, fld As Field

    ' Return Database variable that points to current database.
    Set dbs = CurrentDb
    Set tdf = dbs.TableDefs!Employees
    ' Create new field in Employees table.
    Set fld = tdf.CreateField("SpouseName", dbText, 15)
    ' Allow zero-length strings in field.
    fld.AllowZeroLength = True
    ' Append Field object.
    tdf.fields.Append fld
End Sub


AllPermissions Property

Applies To

Container Object, Document Object.

Description

Returns all the permissions that apply to the current UserName property of the Container or Document object, including permissions that are specific to the user as well as the permissions a user inherits from memberships in groups.

Returned Values

For any Container or Document object, the returned values may include the following.

Constant | Description
dbSecReadDef | Can read the table definition including column and index information.
dbSecWriteDef | Can modify or delete the table definition including column and index information.
dbSecRetrieveData | Can retrieve data from the Document object.
dbSecInsertData | Can add records.
dbSecReplaceData | Can modify records.
dbSecDeleteData | Can delete records.

In addition, the Databases Container object or any Document object in a Documents collection may include the following.

Constant | Description
dbSecDeleteData | Can delete records.
dbSecDBAdmin | Gives user permission to make a database replicable and change the database password.
dbSecDBCreate | Can create new databases (valid only on the databases Container object in the system database [System.mdw]).
dbSecDBExclusive | Exclusive access.
dbSecDBOpen | Can open the database.

Remarks

These constants are listed in the Data Access (DAO) object library in the Object Browser.

This property contrasts with the Permissions property, which returns only the permissions that are specific to the user and doesn't include any permissions that the user may also have as a member of groups. If UserName is a group, then AllPermissions property returns the same values as Permissions.

Specifics (Microsoft Access)

Microsoft Access defines four types of Container objects in addition to those defined by the Microsoft Jet database engine. These include the Forms, Reports, Scripts, or Modules Container objects. Individual Form, Report, Script and Module Document objects belong to the Documents collections of these Container objects. For these Container and Document objects, you can also set the AllPermissions property to the following constants.

Constant | User or group can
acSecFrmRptReadDef | Open the form or report in Design view but not make any changes.
acSecFrmRptWriteDef | Modify or delete the form or report in Design view.
acSecFrmRptExecute | Open the form in Form view or Datasheet view; print or open the report in Sample Preview or Print Preview.
acSecMacReadDef | Open the Macro window and view a macro without making changes.
acSecMacWriteDef | Modify or delete the macro in the Macro window.
acSecModReadDef | Open the module but not make any changes.
acSecModWriteDef | Modify or delete the contents of a module.
acSecMacExecute | Run the macro.

Example (Microsoft Access)

The following example checks the AllPermissions property for the Forms Container object and determines whether the user specified by the UserName property has full access to forms.

Sub CheckAllPermissions()
    Dim dbs As Database, ctr As Container

    ' Return Database variable that points to current database.
    Set dbs = CurrentDb
    ' Return Container object that points to Forms container.
    Set ctr = dbs.Containers!Forms
    ' Print current value of UserName for container.
    Debug.Print ctr.UserName
    ' Check if AllPermissions property includes full access.
    If (ctr.AllPermissions And dbSecFullAccess) Then
        MsgBox "User " & ctr.UserName & " has full access to all forms."
    End If
End Sub


Append Method

Applies To

Documents Collection; Fields Collection; Groups Collection; Indexes Collection; Properties Collection; QueryDefs Collection; Relations Collection; TableDefs Collection; Users Collection; Workspaces Collection.

Description

Adds a new data access object to a collection.

Syntax

collection.Append object

The Append method syntax has these parts.

Part | Description
collection | Any collection that can accept new objects (for limitations, see the following table).
object | A variable of an object data type identifying the object being appended, which must be of the same type as the elements of collection.

Remarks

Uses of the Append method include adding a new table to a database, adding a field to a table, and adding a field to an index.

The appended object becomes a persistent object, stored on disk, until you delete it using the Delete method. If the collection is a Workspaces collection (which is stored only in memory), the object is active until you remove it using the Close method.

The addition of a new object occurs immediately, but you should use the Refresh method on any other collections that may be affected by changes to the database structure.

If the object being appended isn't complete (such as when you haven't appended any Field objects to a Fields collection of an Index object before it's appended to an Indexes collection) or if the properties set in one or more subordinate objects are incorrect, the Append method triggers a trappable error. For example, if you haven't specified a field type and then try to append the Field object to the Fields collection in a TableDef object, the Append method triggers a trappable error.

The following table shows some limitations on the use of the Append method. The object in the first column is an object containing the collection in the second column. The third column indicates when, if ever, you can append an object to that collection (for example, you can never append a Container object to the Containers collection of a Database object).

Object | Collection | When you can use Append
Workspace | Databases | Never; use the OpenDatabase method instead
Database | Containers | Never
Database | Recordsets | Never; use the OpenRecordset method instead
Container | Documents | Never
Index | Fields | When the Index object is a new, unappended object
QueryDef | Fields | Never
QueryDef | Parameters | Never
Recordset | Fields | Never
Relation | Fields | Never
TableDef | Fields | When the Updatable property of the TableDef is set to True
TableDef | Indexes | When the Updatable property of the TableDef is set to True
Database, Field, Index, QueryDef, TableDef | Properties | When the Database, Field, Index, QueryDef, or TableDef is persistent

See Also

Delete Method, GetChunk Method, Refresh Method, Type Property.

Example

The following example defines a new field and appends it to a Fields collection.

Dim dbsBiblio As Database, fldPhone As Field, tdfAuthors As TableDef
            ' Open a database.
Set dbsBiblio = DBEngine.Workspaces(0).OpenDatabase("Biblio.mdb")
Set tdfAuthors = dbsBiblio.TableDefs("Authors")
Set fldPhone = dbsBiblio.CreateField()
fldPhone.Name = "Phone"    ' Set field properties.
fldPhone.Type = dbText
fldPhone.Size = 15
' Append field to collection.
dbsBiblio.tdfAuthors.Fields.Append fldPhone
dbsBiblio.tdfAuthors.Fields.Delete "Phone"
dbsBiblio.Close
Example (Microsoft Access)

The following example defines a new Field object and appends it to the Fields collection of a TableDef object.

Sub NewField()
    Dim dbs As Database, tdf As TableDef, fld As Field

    ' Return Database variable that points to current database.
    Set dbs = CurrentDb
    Set tdf = dbs.TableDefs!Employees
    ' Create new field in Employees table.
    Set fld = tdf.CreateField("SocialSecurity#", dbText, 15)
    ' Append field to collection.
    dbs.TableDefs!Employees.Fields.Append fld
End Sub
Example (Microsoft Excel)

This example creates a new database (NWINDEX.MDB). The example attaches two tables from the C:\Program Files\Common Files\Microsoft Shared\MSquery folder to the database. (On Windows NT™, the two tables are in the \WINDOWS\MSAPPS\MSQUERY folder.)

Const sourceDir = "C:\Program Files\Common Files\Microsoft Shared\"

Sub createNWindEx()
    Dim nWindEx As Database, customerTable As TableDef, _
        supplierTable As TableDef
    Dim dataSource As String
    dataSource = "dbase IV;DATABASE=" & sourceDir & "MSquery"    appPath = Application.Path
    Set nWindEx = Workspaces(0).CreateDatabase(Application.Path _
        & "\NWINDEX.MDB", dbLangGeneral)
    Set customerTable = nWindEx.CreateTableDef("Customer")
    customerTable.Connect = dataSource
    customerTable.SourceTableName = "Customer"
    nWindEx.TableDefs.Append customerTable
    Set supplierTable = nWindEx.CreateTableDef("Supplier")

    supplierTable.Connect = dataSource
    supplierTable.SourceTableName = "Supplier"
    nWindEx.TableDefs.Append supplierTable
    MsgBox "The database " & nWindEx.Name & " has been created."
    nWindEx.Close
End Sub


AppendChunk Method

Applies To

Field Object.

Description

Appends data from a string expression to a Memo or OLE Object Field object in the Fields collection of a Recordset object.

Syntax

recordset ! field.AppendChunk source

The AppendChunk method syntax has these parts.

Part | Description
recordset | A variable of an object data type that refers to the Recordset object containing the Fields collection.
field | The name of a Field object whose Type property is set to dbMemo (Memo), dbLongBinary (OLE Object), or the equivalent.
source | A string expression or variable containing the data you want to append to the Field object specified by field.

Remarks

You can use the AppendChunk and GetChunk methods to access subsets of data in a Memo and OLE Object field.

You can also use these methods to conserve string space when you work with Memo and OLE Object fields. Certain operations (copying, for example) involve temporary strings. If string space is limited, you may need to work with chunks of a field instead of the entire field.

If there is no current record when you use AppendChunk, an error occurs.

Note

The initial AppendChunk (after the first Edit method), even if the record already contains data, will simply place the data in the field as the only data. Subsequent AppendChunk calls within a single Edit session will then add to the data.

See Also

FieldSize Method, GetChunk Method, Type Property.

Example

This example uses the GetChunk method to return consecutive 16K chunks of the Notes field in the Employees table of the database Northwind.mdb. It uses FieldSize to determine how many chunks it needs to copy and then copies the chunks to the string array NoteArray() where they can be changed. It then uses AppendChunk to copy NoteArray() back to Notes.

' This line should be in Declarations section.
Option Base 1

Sub GetNotes
    Const ChunkSize = 16384    ' Set size of chunk.
    Dim intChunks As Integer, lngTotalSize As Long, intX As Integer
    Dim dbsNorthwind As Database, rstEmployees As Recordset
    Set dbsNorthwind = _
        DBEngine.Workspaces(0).OpenDatabase("Northwind.mdb")
            ' Open table.
    Set rstEmployees = dbsNorthwind.OpenRecordset("Employees")
    ' Get field size.
    lngTotalSize = rstEmployees![Notes].FieldSize()
    ' How many chunks?
    intChunks = lngTotalSize\ChunkSize - (lngTotalSize Mod ChunkSize _
        <> 0)
    ReDim NoteArray(intChunks) As String * ChunkSize
    ' Get current Notes field.
    For intX = 1 To intChunks
        NoteArray(intX) = rstEmployees![Notes].GetChunk((intX - 1) * _
            ChunkSize, ChunkSize)
    Next intX
    ...        ' Make changes.
    rstEmployees.Edit    ' Enable editing.
    rstEmployees!Notes = ""    ' Initialize Notes field.
    For intX = 1 To intChunks
        ' Replace with edited Notes.
        rstEmployees![Notes].AppendChunk NoteArray(intX)
    Next intX
    rstEmployees.Update    ' Save changes.
    rstEmployees.Close
dbsNorthwind.Close     ' Close database.
End Sub
Example (Microsoft Access)

The following example appends data to a Notes field in an Employees table. The Notes field is Memo data type. The procedure then returns the contents of the field using the GetChunk method, adds to the data, and appends the altered data back to the Notes field using the AppendChunk method.

Sub AddToMemo()
    Dim dbs As Database, rst As Recordset
    Dim fldNotes As Field, fldFirstName As Field
    Dim lngSize As Long, strChunk As String

    ' Return Database variable pointing to current database.
    Set dbs = CurrentDb
    ' Create table-type Recordset object.
    Set rst = dbs.OpenRecordset("Employees")
    Set fldNotes = rst.Fields!Notes
    Set fldFirstName = rst.Fields!FirstName
    rst.MoveLast                ' Populate Recordset object.
    rst.MoveFirst            ' Move to first record.
    Do Until rst.EOF
        ' Determine size of field in current record.
        lngSize = fldNotes.FieldSize
        If lngSize = 0 Then
            MsgBox "No text in " & fldNotes.Name & " field!"
            Exit Do
        Else
            ' Return contents of Notes field.
            strChunk = fldNotes.GetChunk(0, lngSize)
            ' Alter data.
            strChunk = strChunk & "  " & fldFirstName.Value & _
                " is a terrific employee!"
            With rst
                .Edit                ' Enable editing.
                .[Notes] = ""            ' Initialize field.
                .[Notes].AppendChunk strChunk    ' Append altered data.
                .Update            ' Save changes.
                .MoveNext            ' Move to next record.
            End With
        End If
    Loop
End Sub


Attributes Property

Applies To

Field Object, Relation Object, TableDef Object.

Description

Sets or returns a value that indicates one or more characteristics of a Field object, a Relation object, or a TableDef object. For an object not yet appended to a collection, this property is read/write. For an appended TableDef object, the property is read/write, although not all of the constants may be set if the object is appended, as noted below.

Settings and Return Values

The data type of the setting or return value is Long.

For a Field object, the value specifies characteristics of the field represented by the Field object and can be a sum of these constants.

Constant | Description
dbFixedField | The field size is fixed (default for Numeric fields).
dbVariableField | The field size is variable (Text fields only).
dbAutoIncrField | The field value for new records is automatically incremented to a unique Long integer that can't be changed (supported only for Microsoft Jet database tables).
dbUpdatableField | The field value can be changed.
dbDescending | The field is sorted in descending (Z to A or 100 to 0) order (applies only to a Field object in a Fields collection of an Index object). If you omit this constant, the field is sorted in ascending (A to Z or 0 to 100) order (default).
dbSystemField | The field is a replication field (on a TableDef object) used on replicable databases and cannot be deleted.

For a Relation object, value specifies characteristics of the relationship represented by the Relation object and can be a sum of these constants.

Constant | Description
dbRelationUnique | Relationship is one-to-one.
dbRelationDontEnforce | Relationship isn't enforced (no referential integrity).
dbRelationInherited | Relationship exists in a noncurrent database that contains the two attached tables.
dbRelationUpdateCascade | Updates will cascade.
dbRelationDeleteCascade | Deletions will cascade.

Note

If you set the Relation object's Attributes property to activate cascade operations, the Microsoft Jet database engine automatically updates or deletes records in one or more other tables when changes are made to related primary key tables.

For example, suppose you establish a cascade delete relationship between a Customers table and an Orders table. When you delete records from the Customers table, records in the Orders table related to that customer are also deleted. In addition, if you establish cascade delete relationships between the Orders table and other tables, records from those tables are automatically deleted when you delete records from the Customers table.

For a TableDef object, value specifies characteristics of the table represented by the TableDef object and can be a sum of these Long constants.

Constant | Description
dbAttachExclusive | For databases that use the Jet database engine, indicates the table is an attached table opened for exclusive use. This constant can be set on an appended TableDef object for a local table, but not for a remote table.
dbAttachSavePWD | For databases that use the Jet database engine, indicates that the user ID and password for the remotely attached table are saved with the connection information. This constant can be set on an appended TableDef object for a remote table, but not for a local table.
dbSystemObject | Indicates the table is a system table provided by the Jet database engine. This constant can be set on an appended TableDef object.
dbHiddenObject | Indicates the table is a hidden table provided by the Jet database engine. This constant can be set on an appended TableDef object.
dbAttachedTable | Indicates the table is an attached table from a non-ODBC database, such as a Microsoft Jet or Paradox® database (read-only).
dbAttachedODBC | Indicates the table is an attached table from an ODBC database, such as Microsoft SQL Server (read-only).

Remarks

These constants are listed in the Data Access (DAO) object library in the Object Browser.

For a Field object, use of the Attributes property depends on the object that contains the Fields collection that the Field object is appended to, as shown in the following table.

Object appended to | Usage
Index | Read/write until the TableDef object that the Index object is appended to is appended to a Database object; then the property is read-only
QueryDef | Read-only
Recordset | Read-only
Relation | Not supported
TableDef | Read/write

For a Relation object, the Attributes property setting is read-only for an object appended to a collection.

When setting multiple attributes, you can combine them by summing the appropriate constants. Any nonmeaningful values are ignored without producing an error. For example, to use the Attributes property to make the Text field represented by a new Field object variable-sized and changeable, you can use this code:

fldLastName.Attributes = dbVariableField + dbUpdatableField
Example (Microsoft Access)

The following example checks the Attributes property for each table in the current database, and prints the names of system and hidden tables provided by the Microsoft Jet database engine.

Note that the And operator performs a bitwise comparison to determine whether an attribute is currently set.

Sub CheckAttributes()
    Dim dbs As Database, tdf As TableDef

    ' Return Database variable that points to current database.
    Set dbs = CurrentDb
    For Each tdf In dbs.TableDefs
        ' Compare property setting and constant in question.
        If (tdf.Attributes And dbSystemObject) Or _
            (tdf.Attributes And dbHiddenObject) Then
            Debug.Print tdf.Name
        End If
    Next tdf
End Sub


BeginTrans, CommitTrans, Rollback Methods

Applies To

Workspace Object.

Description

The transaction methods manage transaction processing during a session defined by a Workspace object as follows:

    BeginTrans begins a new transaction.CommitTrans ends the current transaction and saves the changes.Rollback ends the current transaction and restores the databases in the Workspace object to the state they were in when the current transaction began.

Syntax

workspace.BeginTrans | CommitTrans | Rollback

The transaction methods have this part.

Part | Description
workspace | A variable of an object data type identifying the Workspace.

Remarks

You use these methods with a Workspace object when you want to treat a series of changes made to the databases in a session as one unit.

Typically, you use transactions to maintain the integrity of your data when you must update records in two or more tables and make sure changes made are completed (committed) in all tables or none at all (rolled back). For example, if you transfer money from one account to another, you might subtract an amount from one and add the amount to another. If either update fails, the accounts no longer balance. Use the BeginTrans method before updating the first record, and then, if any subsequent update fails, you can use the Rollback method to undo all of the updates. Use the CommitTrans method after you successfully update the last record.

Caution

Within one Workspace object, transactions are always global to the Workspace and aren't limited to only one database or recordset. If you perform operations on more than one database or recordset within a Workspace transaction, the Rollback method restores all operations on those databases and recordsets.

After you use CommitTrans, you can't undo changes made during that transaction unless the transaction is nested within another transaction that is itself rolled back. You can have up to five levels of transactions open at once in a single Workspace object by using multiple, nested combinations of BeginTrans and CommitTrans or Rollback. If you nest transactions, you must save or roll back the current transaction before you can save or roll back a transaction at a higher level of nesting. If you want to have simultaneous transactions with overlapping, non-nested scopes, you can create additional Workspace objects to contain the concurrent transactions.

If you close a Workspace object without saving or rolling back any pending transactions, the transactions are automatically rolled back.

If you use the CommitTrans or Rollback methods without first using the BeginTrans method, an error occurs.

Some databases may not support transactions, in which case the Transactions property of the Database object or Recordset object is False. To make sure that the database supports transactions, check the value of the Transactions property of the Database object before using the BeginTrans method. If you are using a Recordset object based on more than one database, check the Transactions property of the Recordset object. If a recordset is based entirely on Microsoft Jet database engine tables, you can always use transactions. Dynaset-type Recordset objects based on tables created by other database products, however, may not support transactions. For example, you can't use transactions in a Recordset based on a Paradox table. In this case, the Transactions property is False. If the Database or Recordset doesn't support transactions, the methods are ignored and no error occurs.

When using external ODBC SQL databases, you can't nest transactions.

Tip

In addition to performing transactions to maintain data integrity, you can often improve the performance of your application by breaking operations that require disk access on your database into transaction blocks. This ensures buffering of your operations and may greatly reduce the number of times a disk is accessed.

Note

When you begin a transaction, the Jet database engine records its operations in a file kept in the directory specified by the TEMP environment variable on the workstation. If the transaction log file exhausts the available storage on your TEMP drive, the Jet database engine triggers a trappable error (2004). At this point, if you use CommitTrans, an indeterminate number of operations are committed but the remaining uncompleted operations are lost, and the operation has to be restarted. Using a Rollback method releases the transaction log and rolls back all operations in the transaction.

See Also

Close Method, CreateWorkspace Method, Refresh Method, Transactions Property.

Example

This example changes the job title of all sales representatives in the Employees table of the database. After the BeginTrans method starts a transaction that isolates all the changes made to the Employees table, the CommitTrans method saves the changes. Notice that you can use the Rollback method to undo changes that you saved using the Update method.

One or more table pages remain locked while the user decides whether or not to accept the changes. For this reason, this technique isn't recommended but shown only as an example.

Sub ChangeTitle
    Dim strName As String, strMessage As String, strPrompt As String
    Dim wspDefault As Workspace, dbsNorthwind As Database
    Dim rstEmployees As Recordset

    strPrompt = "Change title to Account Executive?"
    Set wspDefault = DBEngine.Workspaces(0)   ' Get default Workspace.
    ' Get current database.
    Set dbsNorthwind = wspDefault.OpenDatabase("Northwind.mdb")
    ' Open table.
    Set rstEmployees = dbsNorthwind.OpenRecordset("Employees", _
        dbOpenTable)
    wspDefault.BeginTrans        ' Start of transaction.
    rstEmployees.MoveFirst
    Do Until rstEmployees.EOF
        If rstEmployees![Title] = "Sales Representative" Then
            strName = rstEmployees![LastName] & ", " & _
                rstEmployees![FirstName]
            strMessage = "Employee: " & strName & vbCrLf & vbCrLf
            If MsgBox(strMessage & Prompt, vbQuestion + vbYesNo, _
                    "Change Job Title") = YES Then
                rstEmployees.Edit    ' Enable editing.
                rstEmployees![Title] = "Account Executive"
                rstEmployees.Update    ' Save changes.
            End If
        End If
        rstEmployees.MoveNext        ' Move to next record.
    Loop
    If MsgBox("Save all changes?", vbQuestion + vbYesNo, _
        " Save Changes") = YES Then
        wspDefault.CommitTrans    ' Commit changes.
    Else
        wspDefault.Rollback        ' Undo changes.
    End If
    rstEmployees.Close    ' Close table.
    dbsNorthwind.Close
End Sub
Example (Microsoft Access)

The following example changes the job title of all sales representatives in an Employees table. After the BeginTrans method starts a transaction that isolates all the changes made to the Employees table, the CommitTrans method saves the changes. Notice that you can use the Rollback method to undo changes that you saved using the Update method.

One or more table pages remain locked while the user decides whether or not to accept the changes. Consequently, this technique isn't recommended but only shown as an example.

Sub ChangeTitle()
    Dim wsp As Workspace, dbs As Database, rst As Recordset
    Dim strName As String, strMessage As String, strPrompt As String

    strPrompt = "Change title to Account Executive?"
    ' Get default Workspace.
    Set wsp = DBEngine.Workspaces(0)

    ' Get current database.
    Set dbs = CurrentDb
    ' Create table-type Recordset object.
    Set rst = dbs.OpenRecordset("Employees", dbOpenTable)
    ' Start of transaction.
    wsp.BeginTrans
    rst.MoveFirst
    Do Until rst.EOF
        If rst![Title] = "Sales Representative" Then
            strName = rst![LastName] & ", " & rst![FirstName]
            strMessage = "Employee: " & strName & vbCrLf & vbCrLf
            If MsgBox(strMessage & strPrompt, vbQuestion + vbYesNo, _
                "Change Job Title") = vbYes Then
                ' Enable editing.
                rst.Edit
                rst![Title] = "Account Executive"
                ' Save changes.
                rst.Update
            End If
        End If
        ' Move to next record.
        rst.MoveNext
    Loop
    If MsgBox("Save all changes?", vbQuestion + vbYesNo, _
        "Save Changes") = vbYes Then
        wsp.CommitTrans            ' Commit changes.
    Else
        wsp.Rollback                ' Undo changes.
    End If
End Sub


BOF, EOF Properties

Applies To

Dynaset-Type Recordset Object, Recordset Object, Snapshot-Type Recordset Object, Table-Type Recordset Object.

    BOF — returns a value that indicates whether the current record position is before the first record in a Recordset object.EOF — returns a value that indicates whether the current record position is after the last record in a Recordset object.

Return Values

The BOF property returns True (-1) if the current record position is before the first record, and False if the current record position is on or after the first record.

The EOF property returns True if the current record position is after the last record, and False (0) if the current record position is on or before the last record.

Remarks

The BOF and EOF properties return values are determined by the location of the current record pointer.

You can use the BOF and EOF properties to determine whether a Recordset object contains records or whether you've gone beyond the limits of a Recordset object as you move from record to record.

If either the BOF or EOF property is True, there is no current record.

If you open a Recordset object containing no records, the BOF and EOF properties are set to True, and the recordset's RecordCount property setting is 0. When you open a Recordset object that contains at least one record, the first record is the current record and the BOF and EOF properties are False; they remain False until you move beyond the beginning or end of the Recordset object using the MovePrevious or MoveNext method, respectively. When you move beyond the beginning or end of the recordset, there is no current record or no record exists.

If you delete the last remaining record in the Recordset object, the BOF and EOF properties may remain False until you attempt to reposition the current record.

If you use the MoveLast method on a Recordset object containing records, the last record becomes the current record; if you then use the MoveNext method, the current record becomes invalid and the EOF property is set to True. Conversely, if you use the MoveFirst method on a Recordset object containing records, the first record becomes the current record; if you then use the MovePrevious method, there is no current record and the BOF property is set to True.

Typically, when you work with all the records in a Recordset object, your code will loop through the records using the MoveNext method until the EOF property is set to True.

If you use the MoveNext method while the EOF property is set to True or the MovePrevious method while the BOF property is set to True, an error occurs.

This table shows which Move methods are allowed with different combinations of the BOF and EOF properties.

 | MoveFirst, MoveLast | MovePrevious, Move < 0 | Move 0 | MoveNext, Move > 0
BOF=True, EOF=False | Allowed | Error | Error | Allowed

 | MoveFirst, MoveLast | MovePrevious, Move < 0 | Move 0 | MoveNext, Move > 0
BOF=False, EOF=True | Allowed | Allowed | Error | Error
Both True | Error | Error | Error | Error
Both False | Allowed | Allowed | Allowed | Allowed

Allowing a Move method doesn't mean that the method will successfully locate a record. It merely indicates that an attempt to perform the specified Move method is allowed and won't generate an error. The state of the BOF and EOF flags may change as a result of the attempted Move.

Effects of specific methods on the BOF and EOF property settings are as follow:

    An OpenRecordset method internally invokes a MoveFirst method. Therefore, an OpenRecordset method on an empty set of records results in the BOF and EOF properties being set to True. (See the following table for the behavior of a failed MoveFirst method.)All Move methods that successfully locate a record clear (set to False) both the BOF and EOF properties.An AddNew method followed by an Update method that successfully inserts a new record will clear the BOF property, but only if the EOF property is already set to True. The state of the EOF property will always remain unchanged. As defined by the Microsoft Jet database engine, the current record pointer of an empty recordset is at the end of a file, so any new record is inserted after the current record.Any Delete method, even if it removes the only remaining record from a recordset, won't change the setting of the BOF or EOF property.

The effect of Move methods that don't locate a record on the BOF and EOF property settings is shown in the following table.

 | BOF | EOF
MoveFirst, MoveLast | True | True
Move 0 | No change | No change
MovePrevious, Move < 0 | True | No change
MoveNext, Move > 0 | No change | True

See Also

MoveFirst, MoveLast, MoveNext, MovePrevious Methods.

Example

This example uses the BOF and EOF properties to find the beginning and end of an Orders table. The example moves through the records from the beginning of the file to the end and then from the end to the beginning. Notice that there is no current record immediately following the first loop.

Set dbsNorthwind = DBEngine.Workspaces(0).OpenDatabase("Northwind.mdb")
Set rstOrders = dbsNorthwind.OpenRecordset("Orders")    ' Open Recordset.
Do Until rstOrders.EOF                ' Do until end of file.
    rstOrders.MoveNext                ' Move to next record.
    ...
Loop
rstOrders.MoveLast                ' Establish a current record.
Do Until rstOrders.BOF                ' Do until beginning of file.
    rstOrders.MovePrevious                ' Move to previous record.
    ...
Loop
rstOrders.Close
dbsNorthwind.Close
Example (Microsoft Access)

The following example uses the EOF property of a Recordset object to move the current record pointer past the last record in the Recordset object, then uses the BOF property to move the current record pointer to before the first record in the Recordset object.

Sub EndsOfFile()
    Dim dbs As Database, rst As Recordset

    ' Return Database variable that points to current database.
    Set dbs = CurrentDb
    Set rst = dbs.OpenRecordset("Orders")
    ' Do until end of file.
    Do Until rst.EOF
        ' Move to next record.
        rst.MoveNext
        .
        .
        .
    Loop
    ' Move to last record to set a current record.
    rst.MoveLast
    ' Do until beginning of file.
    Do Until rst.BOF
        rst.MovePrevious

        .
        .
        .
    Loop
    rst.Close
    dbs.Close
End Sub


Bookmark Property

Applies To

Dynaset-Type Recordset Object, Recordset Object, Snapshot-Type Recordset Object, Table-Type Recordset Object.

Description

Sets or returns a bookmark that uniquely identifies the current record in a Recordset object or sets the current record in a Recordset object to a valid bookmark.

Settings and Return Values

The setting or returned value is a string expression or variant expression that evaluates to a valid bookmark. (Data type is Variant array of Byte data.)

Remarks

You can use the Bookmark property with Recordset objects. For a Recordset object based entirely on Microsoft Jet database engine tables, the value of the Bookmarkable property is True and bookmarks can be used. Other database products may not support bookmarks, however. For example, you can't use bookmarks in any Recordset object based on an attached Paradox table that has no primary key.

When a Recordset object is created or opened, each of its records already has a unique bookmark. You can save the bookmark for the current record by assigning the value of the Bookmark property to a variable. To quickly return to that record at any time after moving to a different record, set the Recordset object's Bookmark property to the value of that variable.

There is no limit to the number of bookmarks you can establish. To create a bookmark for a record other than the current record, move to the desired record and assign the value of the Bookmark property to a String variable that identifies the record.

To make sure the Recordset object supports bookmarks, inspect the value of its Bookmarkable property before you use the Bookmark property. If the Bookmarkable property is False, the Recordset object doesn't support bookmarks, and using the Bookmark property results in a trappable error.

If you create a copy of a Recordset object using the Clone method, the Bookmark property settings for the original and the duplicate Recordset objects are identical and can be used interchangeably. However, you can't use bookmarks from different Recordset objects interchangeably, even if they were created using the same object or the same SQL statement.

If you set the Bookmark property to a value that represents a deleted record, a trappable error occurs.

To refresh the contents of a record, set the Bookmark property to itself. (This technique, however, also cancels any pending operations invoked by the Edit or AddNew methods.) For example:

rstCustomers.Bookmark = rstCustomers.Bookmark
The value of the Bookmark property isn't the same as a record number.

Note

The Bookmark property doesn't apply to forward-only scrolling snapshots.

See Also

Bookmarkable Property, RecordCount Property.

Specifics (Microsoft Access)

When you write Visual Basic® code that uses the Bookmark property, you must include an Option Compare Binary statement in the Declarations section of the module. The Bookmark property sets and returns a bookmark, which is a Variant array of Byte data. The string comparison method for the module must therefore be binary. If a bookmark is evaluated with a text-based string comparison method, such as the Option Compare Text statement or the default setting for the Option Compare Database statement, the current record may be set to an incorrect record.

Note

Don't confuse this property with the Microsoft Access Bookmark property, which applies to a Form object and stores a bookmark for a particular record in the table or query underlying the form. These two properties do not interfere with each other; you can have separate bookmarks on a form and on a Recordset object at the same time.

Example

This example shows how you can save your place in a Recordset by saving a bookmark. Once saved, this bookmark can be applied to the Bookmark property to reposition the current record pointer to any location in the Recordset. The FindYear function works with the Biblio.mdb database. It looks up all titles in a given Recordset published in a given year, and fills a string array with the bookmarks of any records that match.

Function FindYear (intYear As Integer, rstBooks As Recordset, _
    avarRecord() As Variant) As Integer
    Dim intCount As Integer
    rstBooks.FindFirst "[Year Published] = " & intYear

    If (rstBooks.NoMatch = True) Or (rstBooks.Bookmarkable = False) _
        Then
        FindYear = 0
        Exit Function
    Else
        Do Until rstBooks.NoMatch = True
            avarRecord(intCount) = rstBooks.Bookmark
            rstBooks.FindNext "[Year Published] = " & intYear
            intCount = intCount + 1
        Loop
    End If
    FindYear = intCount
End Function
Example (Microsoft Access)

The following example moves through the records of the Employees table from the beginning of the file to the end and stores the value of the Bookmark property for each record in an array.

' Include this statement in the Declarations section of the module.
Option Compare Binary

Sub RecordPositions()
    Dim dbs As Database, rst As Recordset, fld As Field
    Dim intI As Integer
    ' Declare array to hold bookmarks.
    Dim varRecord() As Variant

    ' Return Database variable that points to current database.
    Set dbs = CurrentDb
    ' Open a table-type Recordset object.
    Set rst = dbs.OpenRecordset("Employees")
    Set fld = rst.Fields!LastName
    ' Populate the Recordset object.
    rst.MoveLast
    rst.MoveFirst
    ' Redimension array with value of RecordCount as upper bound.
    ReDim varRecord(0 To rst.RecordCount - 1)
    intI = 0
    ' Check Bookmarkable property of Recordset object.
    If rst.Bookmarkable Then
        Do Until rst.EOF
            ' Populate array with bookmarks.
            varRecord(intI) = rst.Bookmark
            ' Increment counter.
            intI = intI + 1
            rst.MoveNext
        Loop
    End If
End Sub

Example (Microsoft Excel)

This example prompts the user for a two-letter abbreviation for a state. The example uses this value to find up to 101 matching records in the Customer recordset in the NWINDEX.MDB database. It then marks each record with a bookmark and copies the values of the first and third fields onto Sheet1.

To create the NWINDEX.MDB database, run the Microsoft Excel example for the CreateDatabase method.

Dim Found(100)
i = 0
Set db = Workspaces(0).OpenDatabase(Application.Path & "\NWINDEX.MDB")
Set rs = db.OpenRecordset("Customer")
Sheets("Sheet1").Activate
region = Application.InputBox("What state do you want data from?", _
    "Specify two letters (e.g. 'WA')", Type:=2)
If region = False Then    ' user cancelled InputBox
    Exit Sub
End If
criteria = "[REGION] = '" & region & "'"
rs.FindFirst criteria
If rs.NoMatch Or rs.Bookmarkable = False Then
    MsgBox "No records for this state"
    Exit Sub
Else
    Do Until rs.NoMatch = True
        i = i + 1
        Found(i) = rs.Bookmark
        rs.FindNext criteria
    Loop
End If
For n = 1 To i
    rs.Bookmark = Found(n)
    Cells(n + 1, 1).Value = rs.fields(0).Value
    Cells(n + 1, 2).Value = rs.fields(2).Value
Next
MsgBox "There are " & i & " records from this region"
rs.Close
db.Close


Bookmarkable Property

Applies To

Dynaset-Type Recordset Object, Recordset Object, Snapshot-Type Recordset Object, Table-Type Recordset Object.

Description

Returns True (-1) if the Recordset object supports bookmarks, which you can set using the Bookmark property.

Remarks

You can use the Bookmarkable property with Recordset objects.

Check the Bookmarkable property setting before you attempt to set or check the Bookmark property to make sure that the Recordset object supports bookmarks.

For a Recordset object based entirely on Microsoft Jet database engine tables, the value of the Bookmarkable property is True, and bookmarks can be used. Other database products may not support bookmarks, however. For example, you can't use bookmarks in any Recordset object based on an attached Paradox table that has no primary key.

Note

The Bookmarkable property doesn't apply to forward-only scrolling snapshots.

See Also

Bookmark Property, RecordCount Property.

Example

See the Bookmark property example.

Example (Microsoft Excel)

See the Bookmark property example (Microsoft Excel).


CacheSize, CacheStart Properties

Applies To

Dynaset-Type Recordset Object, Recordset Object.

  • CacheSize — sets or returns a value that specifies the number of records in a dynaset-type Recordset object containing data to be locally cached from an ODBC data source.
  • CacheStart — sets or returns a value that specifies the bookmark of the first record in the Recordset object to be cached.
 Settings and Returned Values

The setting or return value is a number or string expression. The setting for CacheSize specifies the number of records and must be between 5 and 1200, but not greater than available memory. A typical value is 100. A setting of 0 turns off caching. (Data type is Long.) The setting for CacheStart specifies a bookmark. (Data type is String.)

Remarks

Data caching improves the performance of an application that retrieves data from a remote server through dynaset-type Recordset objects. A cache is a space in local memory that holds the data most recently retrieved from the server in the event that the data will be requested again while the application is running. When data is requested, the Microsoft Jet database engine checks the cache for the requested data first rather than retrieving it from the server, which takes more time. Data that doesn't come from an ODBC data source isn't saved in the cache.

Any ODBC data source, such as an attached table, can have a local cache. To create the cache, open a Recordset object from the remote data source, set the CacheSize and CacheStart properties, and then use the FillCache method or step through the records using the Move methods.

The CacheSize property setting can be based on the number of records your application can work with at one time. For example, if you're using a Recordset object as the source of the data to be displayed on screen, you could set its CacheSize property to 20 to display 20 records at one time.

The CacheStart property setting is the bookmark of the first record in the Recordset object to be cached. You can use the bookmark of any record to set the CacheStart property. Make the record you want to start the cache with the current record, establish a bookmark for that record, and set the CacheStart property to the bookmark.

The Jet database engine requests records within the cache range from the cache, and it requests records outside the cache range from the server.

Notes

  • Records retrieved from the cache don't reflect changes made concurrently to the source data by other users.
  • To force an update of all the cached data, set the CacheSize property of the Recordset object to 0, set it to the size of the cache you originally requested, and then use the FillCache method.
 See Also

Bookmark Property, Bookmarkable Property, FillCache Method.

Specifics (Microsoft Access)

When you use the CacheStart property in a Microsoft Access module, you must include an Option Compare Binary statement in the Declarations section of the module. The bookmark set or returned by the CacheStart property is a Variant array of Byte data, so the string comparison method for the module must be binary. If a bookmark is evaluated with a text-based string comparison method, such as the Option Compare Text statement or the default setting for the Option Compare Database statement, the current record may be set to an incorrect record.

Example (Client/Server)

This example moves through all records in a Recordset twice; once with no cache and once with a 50 record cache. The example then displays the performance statistics for the uncached and cached runs through the Recordset.

Dim wspDefault As Workspace, dbsPubs As Database
Dim tdfPerformanceTest As TableDef, rstRemote As Recordset
Dim strNoCache As String, strCache As String

Set wspDefault = DBEngine.Workspaces(0)
Set dbsPubs = wspDefault.OpenDatabase("PUBLISH.mdb")
Set tdfPerformanceTest = dbsPubs.CreateTableDef("TestData")

tdfPerformanceTest.Connect = _     "ODBC;DATABASE=pubs;UID=sa;PWD=;DSN=Publishers"
tdfPerformanceTest.SourceTableName = "dbo.roysched"
dbsPubs.TableDefs.Append tdfPerformanceTest
ConnectSource = True
Set rstRemote = dbsPubs.OpenRecordset("TestData")

MsgBox "This example moves through all records in the Recordset " & _
    "twice; once with no cache and once with a 50 record cache."
' Start uncached run
tmStart = Timer
For i% = 1 To 2
    rstRemote.MoveFirst
    While Not rstRemote.EOF
        v = rstRemote(0)
        rstRemote.MoveNext
    Wend
Next i%
tmEnd = Timer
strNoCache = "Time without caching: " & Format$(tmEnd - tmStart) & _
    Chr$(13) & Chr$(10)
' Start cached run
rstRemote.MoveFirst
rstRemote.CacheStart = rstRemote.Bookmark
rstRemote.CacheSize = 50
tmStart = Timer
For i% = 1 To 2
    rstRemote.MoveFirst
    While Not rstRemote.EOF
        v = rstRemote(0)
        rstRemote.MoveNext
    Wend
Next i%
tmEnd = Timer
strCache = "Time with 50 record cache: " & Format$(tmEnd - tmStart) & _
    Chr$(13) & Chr$(10)
' Display performance results
MsgBox "Caching Performance Results:" & Chr$(13) & Chr$(10) & _
    strNoCache & strCache
rstRemote.Close
dbsPubs.Close
Example (Microsoft Access)

The following example opens a Recordset object from an attached Orders table that is stored on an ODBC server. The procedure next sets the CacheSize and CacheStart properties, and then uses the FillCache method to cache data from the server to the database.

Sub CacheData()
    Dim rst As Recordset, dbs As Database

    ' Return Database variable pointing to current database.
    Set dbs = CurrentDb
    ' Open local dynaset-type Recordset object.
    Set rst = dbs.OpenRecordset("Orders", DbOpenDynaset)
    ' Locate record with OrderID of 11000.
    rst.FindFirst "OrderID = 11000"
    ' Start caching records beginning with OrderID 11000.
    rst.CacheStart = rst.Bookmark
    rst.CacheSize = 12            ' Set cache size to 12 records.
    rst.FillCache            ' Fill cache.
    ' Display rows.
    .
    .
    .
End Sub


CancelUpdate Method

Applies To

Dynaset-Type Recordset Object, Recordset Object, Table-Type Recordset Object.

Description

Cancels any pending updates for the Recordset object represented by the object placeholder.

Syntax

object.CancelUpdate

The object placeholder represents an object expression that evaluates to an object in the Applies To list.

Remarks

The CancelUpdate method cancels any pending updates due to an Edit or AddNew operation. For example, if a user invokes the Edit or AddNew method and hasn't yet invoked the Update method, CancelUpdate cancels any changes made after Edit or AddNew was invoked.

Note

Using the CancelUpdate method has the same effect as moving to another record without using the Update method except that the current record doesn't change, and various properties, such as BOF and EOF, aren't updated.

Use the EditMode property to determine if there is a pending operation that can be canceled.

See Also

AddNew Method; BOF, EOF Properties; EditMode Property.

Example (Microsoft Access)

The following example creates a new record in an Employees table, enters values, and prompts the user to save the changes. If the user chooses not to save the changes, the Update method is canceled.

Sub NewRecord()
    Dim dbs As Database, rst As Recordset

    ' Return Database variable pointing to current database.
    Set dbs = CurrentDb
    Set rst = dbs.OpenRecordset("Employees")
    With rst
        ' Add new record to end of Recordset object.
        .AddNew
        .[LastName] = "Christopher"        ' Add data.
        .[FirstName] = "Kevin"
    End With
    ' Prompt user to save changes.
    If MsgBox("Save these changes?", vbYesNo) = vbNo Then
        ' If user chooses No, cancel changes.
        rst.CancelUpdate
    Else
        ' If user chooses Yes, save changes.
        rst.Update
    End If
    dbs.Close
End Sub


Clone Method

Applies To

Dynaset-Type Recordset Object, Recordset Object, Snapshot-Type Recordset Object, Table-Type Recordset Object.

Description

Creates a duplicate Recordset object that refers to the original object.

Syntax

Set duplicate = original.Clone( )

The Clone method syntax has these parts.

Part | Description
duplicate | A variable of an object data type identifying the duplicate Recordset object you're creating.
original | A variable of an object data type identifying the Recordset object you want to duplicate.

Remarks

Use the Clone method to create multiple, duplicate Recordset objects. Each recordset can have its own current record. Using Clone by itself doesn't change the data in the objects or in their underlying structures. Using the Clone method, you can share bookmarks between two or more recordsets because their bookmarks are interchangeable.

Note

When used on a table-type Recordset object, the Index property setting is not cloned on the new copy of the Recordset. You must copy the Index property setting manually.

You can use Clone when you want to perform an operation on a recordset that requires multiple current records. This is faster and more efficient than creating a second recordset.

A recordset you create with Clone initially lacks a current record. To make a record current before you use the recordset object specified by duplicate, you must set the Bookmark property or use one of the Move methods, one of the Find methods (for dynaset- and snapshot-type Recordset objects only), or the Seek method (for table-type Recordset objects only).

Cloning a recordset that resulted from running a QueryDef object doesn't run the query again.

Using the Close method on either the original or duplicate object doesn't affect the other object. For example, using Close on the original Recordset does not close the clone.

Note

You can't use the Clone method with forward-only-scrolling snapshots.

See Also

Bookmark Property.

Specifics (Microsoft Access)

If you use the Bookmark property of a Recordset object in a Microsoft Access module, you must include an Option Compare Binary statement in the Declarations section of the module. A bookmark is a Variant array of Byte data, so the string comparison method for the module must be binary. If a bookmark is evaluated with a text-based string comparison method, such as the Option Compare Text statement or the default setting for the Option Compare Database statement, the current record may be set to an incorrect record.

Example

This example creates a Recordset object based on the Orders table in the Northwind database and uses the Clone method to create a second Recordset object. Each Recordset object has its own current record that can be moved independently of the other. A bookmark is used to initially make the same record current in both Recordset objects.

Dim dbsNorthwind As DatabaseDim rstOriginal As Recordset, rstDuplicate _     As RecordsetDim strPosition As String

Set dbsNorthwind = DBEngine.Workspaces(0).Databases("Northwind.mdb")
' Create first Recordset.
Set rstOriginal = dbsNorthwind![Orders].OpenRecordset(dbOpenDynaset)
strPosition = rstOriginal.Bookmark    ' Save current record position.
rstDuplicate = rstOriginal.Clone ()    ' Create duplicate. Recordset.rstDuplicate.Bookmark = strPosition    ' Go to same record.
Example (Microsoft Access)

The following example creates a Recordset object using an SQL statement on an Employees table and then uses the Clone method to create a clone of the Recordset object so that bookmarks can be shared between the two objects. This technique is especially useful when you have to compare the results of a query from more than one point at the same time.

The following function creates a dynaset-type Recordset object on an Employees table, then creates a clone of that Recordset object. The function reads and stores in a string variable the value of the Bookmark property for the current record, in this case the second record in the original Recordset object. The Bookmark property of the duplicate Recordset object is set to this string, making the second record the current record in this Recordset object as well. The current values of the LastName field for both recordsets are identical, as you can see once they are printed in the Debug window.

Sub CreateClone()
    Dim dbs As Database
    Dim rstEmployees As Recordset, rstDuplicate As Recordset
    Dim fldName As Field, strBook As String

    ' Return Database variable that points to current database.
    Set dbs = CurrentDb
    ' Open dynaset-type Recordset object.
    Set rstEmployees = dbs.OpenRecordset("SELECT * FROM Employees " & _
        " ORDER by [LastName]")
    ' Clone Recordset object.
    Set rstDuplicate = rstEmployees.Clone
    Set fldName = rstEmployees.Fields!LastName
    ' Set current record.
    rstEmployees.MoveFirst
    ' Move to second record.
    rstEmployees.MoveNext
    ' Get Bookmark value and print current field value.
    If rstEmployees.Bookmarkable Then
        strBook = rstEmployees.Bookmark
        Debug.Print fldName.value
    Else
    ' If Recordset object doesn't support bookmarks, exit procedure.
        Exit Sub
    End If
    ' Set Bookmark property of clone to obtained value.

    rstDuplicate.Bookmark = strBook
    Debug.Print fldName.value
End Sub
Example (Microsoft Excel)

This example displays a custom dialog box containing the lists of data from the CONTACTS and CUSTMR_ID fields in the Customer recordset of the NWINDEX.MDB database.

To create the NWINDEX.MDB database, run the Microsoft Excel example for the CreateDatabase method.

Dim db As Database
Dim rs1 As Recordset, rs2 As Recordset
Set db = Workspaces(0).OpenDatabase(Application.Path & "\NWINDEX.MDB")
Set rs1 = db.OpenRecordset("SELECT * FROM Customer" _
    & " WHERE [REGION] = 'WA' ORDER BY [CUSTMR_ID];")
Set theDialog = DialogSheets.Add
Set list1 = theDialog.ListBoxes.Add(78, 42, 84, 80)
Set list2 = theDialog.ListBoxes.Add(183, 42, 84, 80)
Set rs2 = rs1.Clone()
rs2.MoveFirst
Do Until rs1.EOF
    list1.AddItem (rs1.Fields("CONTACT").Value)
    rs1.MoveNext
Loop
Do Until rs2.EOF
    list2.AddItem (rs2.Fields("CUSTMR_ID").Value)
    rs2.MoveNext
Loop
rs1.Close
rs2.Close
db.Close


Close Method

Applies To

Database Object, Dynaset-Type Recordset Object, Recordset Object, Snapshot-Type Recordset Object, Table-Type Recordset Object, Workspace Object.

Description

Closes an open data access object.

Syntax

object.Close

The object placeholder represents the name of an open Database, Recordset, or Workspace object.

Remarks

Closing an open object removes it from the collection to which it's appended. Any attempt to close the default workspace is ignored.

To remove objects from collections other than the Databases, Recordsets, and Workspaces collections, use the Delete method on those collections.

Caution

Use the Update method (if there are pending edits) and the Close method on all open recordset objects before you close a database. If you exit a procedure that declares recordset or Database objects, the database is closed, any unsaved changes are lost, all pending transactions are rolled back, and any pending edits to your data are lost.

If you try to close a Database object while any recordset objects are open, or if you try to close a Workspace object while any Database objects belonging to that specific Workspace are open, those Recordset objects will be closed and any pending updates or edits will be rolled back.

If you try to close a Workspace object while any Database objects belonging to it are open, the operation closes all Database objects belonging to that specific Workspace object which may result in Recordset objects being closed and pending edits lost.

If the Database object is defined outside the scope of the procedure, and you exit the procedure without closing it, the Database object will remain open until explicitly closed or the module in which it is defined is out of scope.

If the Database, Recordset, or Workspace object named by object is already closed when you use Close, a trappable error occurs.

Using the Close method on either the original or duplicate object doesn't affect the other object. For example, using Close on the original Recordset does not close the clone.

See Also

Clone Method, Delete Method, OpenDatabase Method, OpenRecordset Method.

Specifics (Microsoft Access)

If a Visual Basic procedure contains an object variable that represents the database currently open in Microsoft Access, using the Close method on that object will cause the variable to go out of scope. The Close method will not affect the database that is open in the Microsoft Access Database window.

Example

This example opens and then closes a database and a table-type Recordset object for the Customers table in the database.

Dim dbsNorthwind As Database, rstCustomers As Recordset
' Open database.
Set dbsNorthwind = DBEngine.Workspaces(0).OpenDatabase("Northwind.mdb")
' Open table.
Set rstCustomers = dbsNorthwind.OpenRecordset("Customers")

...
rstCustomers.Close    ' Close recordset.
dbsNorthwind.Close    ' Close database.
Example (Microsoft Access)

The following example creates a Database object that points to the current database and opens a table-type Recordset object based on a Customers table in the database. It then uses the Close method on these object variables, which causes them to go out of scope and frees the memory resources they have been using.

Sub UseClose()
    Dim dbs As Database, rst As Recordset

    ' Return Database object that represents current database.
    Set dbs = CurrentDb
    ' Create table-type Recordset.
    Set rst = dbs.OpenRecordset("Customers")
    .
    .
    .
    rst.Close                    ' Close recordset.
    dbs.Close                    ' Close database.
End Sub
Example (Microsoft Excel)

This example opens the Customer recordset of the NWINDEX.MDB database, counts how many records are available, and enters the result on Sheet1.

To create the NWINDEX.MDB database, run the Microsoft Excel example for the CreateDatabase method.

Dim db As Database, rs As Recordset
Set db = Workspaces(0).OpenDatabase(Application.Path & "\NWINDEX.MDB")
Set rs = db.OpenRecordset("Customer")
Set resultsSheet = Sheets("Sheet1")
resultsSheet.Activate
With resultsSheet.Cells(1, 1)
    .Value = "Records in " & rs.Name & " table:"
    .Font.Bold = True
    .EntireColumn.AutoFit
End With
rs.MoveLast
resultsSheet.Cells(1, 2).Value = rs.RecordCount
rs.Close
db.Close


Clustered Property

Applies To

Index Object.

Description

Sets or returns a value that indicates whether an Index object represents a clustering index for a table. This property setting is read/write for a new Index object not yet appended to a collection and read-only for an existing Index object in an Indexes collection.

Settings and Return Values

The setting or return value is True if the Index object represents a clustering index. The data type is Boolean.

Remarks

A clustering index consists of one or more nonkey fields that, taken together, arrange all records in a table in a predefined order. A clustering index provides efficient access to records in a table in which the index values may not be unique.

Notes

  • The Clustered property is ignored for databases that use the Microsoft Jet database engine because the Jet database engine doesn't support clustering indexes.
  • For ODBC databases, the Clustered property always returns False (0); it does not detect whether the ODBC database has a clustering index or not.
  • You don't have to create indexes for tables, but in large, unindexed tables, accessing a specific record can take a long time. The Attributes property of each Field object in the Index object determines the order of records and consequently determines the access techniques to use for that index.
 See Also

Attributes Property, Primary Property, Unique Property.


CollatingOrder Property

Applies To

Database Object, Field Object.

Description

Returns a value that specifies the sequence of the sort order in text for string comparison or sorting. This property setting is read-only.

Return Values

The possible return values are:

Values | Description
dbSortGeneral | Use the General (English, French, German, Portuguese, Italian, and Modern Spanish) sort order.
dbSortArabic | Use the Arabic sort order.
dbSortCyrillic | Use the Russian sort order.
dbSortCzech | Use the Czech sort order.
dbSortDutch | Use the Dutch sort order.
dbSortGreek | Use the Greek sort order.
dbSortHebrew | Use the Hebrew sort order.
dbSortHungarian | Use the Hungarian sort order.
dbSortIcelandic | Use the Icelandic sort order.
dbSortJapanese | Use the Japanese sort order.
dbSortNeutral | Use the neutral sort order.
dbSortNorwdan | Use the Norwegian or Danish sort order.
dbSortPDXIntl | Use the Paradox International sort order.
dbSortPDXNor | Use the Paradox Norwegian or Danish sort order.
dbSortPDXSwe | Use the Paradox Swedish or Finnish sort order.
dbSortPolish | Use the Polish sort order.
dbSortSpanish | Use the Spanish sort order.
dbSortSwedFin | Use the Swedish or Finnish sort order.
dbSortTurkish | Use the Turkish sort order.
dbSortUndefined | The sort order is undefined or unknown.

Remarks

These constants are listed in the Data Access (DAO) object library in the Object Browser.

For a Field object, the CollatingOrder property depends on the object that contains the Fields collection, as shown in the following table.

Object appended to | Usage
Index | Not supported
QueryDef | Read-only
Recordset | Read-only
Relation | Not supported
TableDef | Read only

The CollatingOrder property setting corresponds to the locale argument of the CreateDatabase method when the database was created or the CompactDatabase method when the database was most recently compacted.

Check the CollatingOrder property setting of a Database or Field object to find out the string comparison method for the database or field. You can set the CollatingOrder property of a new Field object if you want the setting of the Field object to differ from that of the Database object that contains it.

The CollatingOrder and Attributes property settings of a Field object in a Fields collection of an Index object together determine the sequence and direction of the sort order in an index. However, you can't set a collating order for an individual index — only for an entire table.

See Also

Attributes Property.

Example (Microsoft Access)

The following example checks the CollatingOrder property for the current database.

Sub SetSortOrder()
    Dim dbs As Database

    ' Return Database variable that points to current database.
    Set dbs = CurrentDb
    ' Check CollatingOrder property for database.
    Debug.Print dbs.CollatingOrder
End Sub


CommitTrans Method

See BeginTrans, CommitTrans, Rollback Methods.


CompactDatabase Method

Applies To

DBEngine Object.

Description

Copies, compacts, and gives you the option of changing the version, collating order, and encryption of a closed database.

Syntax

DBEngine.CompactDatabase olddb, newdb [, locale [, options [, ú;pwd=password]]]

The CompactDatabase method syntax has these parts.

Part | Description
olddb | A string expression that identifies an existing, closed database. It can be a full path and filename, such as "C:\MYDB.mdb". If the filename has an extension, you must specify it. If your network supports it, you can also specify a network path, such as "\\MYSERVER\MYSHARE\MYDIR\MYDB.mdb".
newdb | A string expression that is the full path of the compacted database that you're creating. You can also specify a network path as with olddb. You can't use the newdb argument to specify the same database file as olddb.
locale | A string expression used to specify collating order for creating newdb, as specified in Settings. If you omit this argument, the locale of newdb is the same as olddb.
options | An integer that indicates one or more options, as specified in Settings. You can combine options by summing the corresponding constants.
password | An optional string argument containing a password, if the database is password protected. The string ";pwd=" must precede the actual password.

Settings

You can use one of the following constants for the locale argument to specify the CollatingOrder property for string comparisons of text.

Constant | Collating order
dbLangGeneral | English, German, French, Portuguese, Italian, and Modern Spanish
dbLangArabic | Arabic
dbLangCyrillic | Russian
dbLangCzech | Czech
dbLangDutch | Dutch
dbLangGreek | Greek
dbLangHebrew | Hebrew
dbLangHungarian | Hungarian
dbLangIcelandic | Icelandic
dbLangNordic | Nordic languages (Microsoft Jet database engine version 1.0 only)
dbLangNorwdan | Norwegian and Danish

Constant | Collating order
dbLangPolish | Polish
dbLangSpanish | Traditional Spanish
dbLangSwedfin | Swedish and Finnish
dbLangTurkish | Turkish

You can use one of the following constants in the options argument to specify whether to encrypt or to decrypt the database as it's compacted.

Constant | Description
dbEncrypt | Encrypt the database while compacting.
dbDecrypt | Decrypt the database while compacting.

If you omit an encryption constant or if you include both dbDecrypt and dbEncrypt, newdb will have the same encryption as olddb.

You can use one of the following constants in the options argument to specify the version of the data format for the compacted database. This constant affects only the version of the data format of newdb and doesn't affect the version of any Microsoft Access-defined objects, such as forms and reports.

Constant | Description
dbVersion10 | Creates a database that uses the Microsoft Jet database engine version 1.0 while compacting.
dbVersion11 | Creates a database that uses the Jet database engine version 1.1 while compacting.
dbVersion20 | Creates a database that uses the Jet database engine version 2.0 while compacting.
dbVersion30 | Creates a database that uses the Jet database engine version 3.0 while compacting.

You can specify only one version constant. If you omit a version constant, newdb will have the same version as olddb. You can compact newdb only to a version that is the same or later than that of olddb.

Remarks

As you change data in a database, the database file can become fragmented and use more disk space than necessary. Periodically, you can compact your database to defragment the database file. The compacted database is usually smaller and often runs faster. You can also choose to change the collating order, the encryption, or the version of the data format while you copy and compact the database.

The CompactDatabase method copies all the data and the security permissions settings from the database specified by olddb to the database specified by newdb. In the process, the data in the compacted database is organized contiguously to recover disk space.

You must close olddb before you compact it. In a multiuser environment, other users can't have olddb open while you're compacting it. If olddb isn't closed or isn't available for exclusive use, an error occurs.

Because CompactDatabase creates a copy of the database, you must have enough disk space for both the original and the duplicate databases. The compact operation fails if there isn't enough disk space available. The newdb duplicate database doesn't have to be on the same disk as olddb. After successfully compacting a database, you can delete the olddb file and rename the compacted newdb file to the original filename.

See Also

CollatingOrder Property, CreateDatabase Method, Database Object.

Specifics (Microsoft Access)

The CompactDatabase method won't completely convert a Microsoft Access database from one version to another. Only the data format is converted. Microsoft Access-defined objects, such as forms and reports, aren't converted.

Use the Convert Database command on the File menu to convert Microsoft Access databases from an earlier version to the current version.

Example

This example uses CompactDatabase to compact a database and keeps a backup copy of the original database. The new database has the same locale as the source database, but is encrypted.

DBEngine.CompactDatabase "C:\Biblio.mdb","C:\BibNew.mdb","",dbEncrypt
...
Kill "C:\Biblio.BAK"
Name "C:\Biblio.mdb" As "C:\BIBLIO.BAK"
Name "C:\BibNew.mdb" As "C:\Biblio.mdb"
This example copies a database named Northwind.mdb and keeps a new, compacted copy named COPY.NEW. The new database is encrypted.

DBEngine.CompactDatabase "C:\Northwind.mdb", "C:\Copy.NEW","",dbEncrypt


ConflictTable Property

Applies To

TableDef Object.

Description

Returns the name of a side table containing the database records that conflicted during the synchronization of two replicas. The property is read-only and returns a zero-length string if there is no side table or the database is non-replicable.

Remarks

If two users at two separate replicas each make a change to the same record in the database, the changes made by one user will fail to be applied to the other replica. Consequently, the user with the failed change must address the problem in a process called "conflict resolution."

Conflict occurs at the record level, not between fields. For example, if one user changes the Address field and another updates the Phone field in the same record, then one change is rejected. Because conflict occurs at the record level, the rejection occurs even though the successful change and the rejected change are unlikely to result in a true conflict of information.

The exchange mechanism handles the record conflicts by creating conflict tables, which contain the information that would have been placed in the table, if the change had been successful. As a DAO programmer, you examine these conflict tables and work through them row by row, fixing whatever is appropriate.

All side tables are named table_conflict, where table is the original name of the table, truncated to the maximum table name length.

Note

The ConflictTable property can be used only if your application has Microsoft Access with Briefcase Replication installed.

Example

This example finds the name of the conflict table containing the records that were not updated during the replica synchronization, calls a custom routine for resolving the conflicts, deletes the record in the conflict table, and deletes the table after all records have been processed.

Sub Resolve (dbsResolve As Database)
    Dim tdfTest As TableDef, rstConflict As Recordset
    For Each tdfTest In dbsResolve.TableDefs
        If (tdfTest.ConflictTable <> " ") Then
            Set rstConflict = dbsResolve.OpenRecordset _
                (tdfTest.ConflictTable)
            rstConflict.MoveFirst        ' Process each record
            While Not rstConflict.EOF
                .
                .        ' Do conflict resolution
                .
                rstConflict.Delete        ' Remove conflicting
                rstConflict.MoveNext
            Wend
            rstConflict.Close
        End If
    Next tdfTest
End Sub


Connect Property

Applies To

Database Object, QueryDef Object, TableDef Object.

Description

Sets or returns a value that provides information about the source of an open database, a database used in a pass-through query, or an attached table. For QueryDef objects, Database objects, attached tables, and TableDef objects not yet appended to a collection, this property setting is read/write. For a base table, this property is read-only.

Syntax

object.Connect = [databasetype;[parameters;]]

The Connect property syntax has these parts.

Part | Description
object | An object expression that evaluates to an object in the Applies To list.
databasetype | A string expression that specifies a database type. For Microsoft Jet databases, exclude this argument; if you specify parameters, use a semicolon (;) as a placeholder. The data type is String.
parameters | A string expression that specifies additional parameters to pass to ODBC or installable ISAM drivers. Use semicolons to separate parameters. The data type is String.

Settings

The Connect property setting is a String composed of a database type specifier and zero or more parameters separated by semicolons. The Connect property is used to pass additional information to ODBC and certain ISAM drivers as needed. It isn't used for Jet databases, except for those containing attached tables, to allow SQL pass-through queries.

To perform an SQL pass-through query on a table attached to your .mdb file, you must first set the Connect property of the attached table's database to a valid ODBC connect string.

For a TableDef object that represents an attached table, the Connect property setting consists of one or two parts (a database type specifier and a path to the database), each of which ends with a semicolon.

The path as shown in the following table is the full path for the directory containing the database files and must be preceded by the identifier "DATABASE=". In some cases (as with Jet, Btrieve®, and Microsoft Excel databases) a specific filename is included in the database path argument.

The following table shows possible database types and their corresponding database specifiers and paths for the Connect property setting.

Database type | Specifier | Path
Database using the Jet database engine | "[database];" | "drive:\path\filename.mdb"
dBASE III® | "dBASE III;" | "drive:\path"
dBASE IV® | "dBASE IV;" | "drive:\path"
dBASE 5 | "dBASE 5;" | "drive:\path"
Paradox 3.x | "Paradox 3.x;" | "drive:\path"
Paradox 4.x | "Paradox 4.x;" | "drive:\path"
Paradox 5.x | "Paradox 5.x;" | "drive:\path"
Btrieve | "Btrieve;" | "drive:\path\filename.ddf"
FoxPro® 2.0 | "FoxPro 2.0;" | "drive:\path"
FoxPro 2.5 | "FoxPro 2.5;" | "drive:\path"
FoxPro 2.6 | "FoxPro 2.6;" | "drive:\path"
Excel 3.0 | "Excel 3.0;" | "drive:\path\filename.xls"
Excel 4.0 | "Excel 4.0;" | "drive:\path\filename.xls"
Excel 5.0 | "Excel 5.0;" | "drive:\path\filename.xls"
Excel 7.0 | "Excel 7.0;" | "drive:\path\filename.xls"
Text | "Text;" | "drive:\path"
ODBC | "ODBC; DATABASE=defaultdatabase; UID=user; PWD=password; DSN=datasourcename LOGINTIMEOUT=seconds" (This may not be a complete connection string for all servers; it's just an example.) | None

Remarks

If the specifier is only "ODBC;", a dialog box listing all registered ODBC data source names is displayed by the ODBC driver so the user can select a database.

If a password is required but not provided in the Connect property setting, a login dialog box is displayed the first time a table is accessed by the ODBC driver and again if the connection is closed and reopened.

For Jet database base tables, the Connect property setting is a zero-length string ("").

You can set the Connect property for a Database object by providing a source argument to the OpenDatabase method. You can check the setting to determine the type, path, user ID, Password, or ODBC data source of the database.

For a QueryDef object, you use the Connect property with the ReturnsRecords property to create an ODBC SQL pass-through query. The databasetype of the connection string is "ODBC;", and the remainder of the string contains information specific to the ODBC driver used to access the remote data. For more information, see the documentation for the specific driver.

Note

The Connect property must be set before the ReturnsRecords property is set.

See Also

OpenDatabase Method, ReturnsRecords Property.

Example

This example creates a TableDef object in the specified database; sets its Connect, Name, and SourceTableName properties; and then appends it to the TableDefs collection.

Function ConnectSource () As Integer
    Dim dbsLocal As Database, tdfPDXAuthor As TableDef
    Set dbsLocal = DBEngine.Workspaces(0).OpenDatabase("Northwind.mdb")
    Set tdfPDXAuthor = dbsLocal.CreateTableDef("PDXAuthor")
    ' Attach Paradox table Author in database C:\PDX\PUBLISH.
    tdfPDXAuthor.Connect = "Paradox 4.x;DATABASE=C:\PDX\PUBLISH"
    tdfPDXAuthor.SourceTableName = "Author"
    dbsLocal.TableDefs.Append tdfPDXAuthor    ' Attach table.
    ConnectSource = True
End Function
Example (Microsoft Access)

The following example creates a TableDef object in the specified database. The procedure then sets its Connect, Name, and SourceTableName properties and appends the object to the TableDefs collection.

Sub ConnectSource()
    Dim dbs As Database, tdf As TableDef

    ' Return Database variable that points to current database.
    Set dbs = CurrentDb
    Set tdf = dbs.CreateTableDef("PDXAuthor")
    ' Attach Paradox table Author in database C:\PDX\Publish.
    tdf.Connect = "Paradox 4.x;DATABASE=C:\PDX\Publish"
    tdf.SourceTableName = "Author"
    dbs.TableDefs.Append tdf
End Sub

Example (Microsoft Excel)

This example attaches the table PRODUCT.DBF (a dBASE IV table located in the \Program Files\Common Files\Microsoft Shared\MSquery folder) to the NWINDEX.MDB database. (On Windows NT, PRODUCT.DBF is located in the \WINDOWS\MSAPPS\MSQUERY folder.)

To create the NWINDEX.MDB database, run the Microsoft Excel example for the CreateDatabase method.

Const sourceDir = "C:\Program Files\Common Files\Microsoft Shared\"
Dim nWindEx As Database, tDef As TableDef
Dim dataSource As String
dataSource = "dbase IV;DATABASE=" & sourceDir & "MSquery"
Set nWindEx = Workspaces(0).OpenDatabase(Application.Path _
    & "\NWINDEX.MDB")
Set tDef = nWindEx.CreateTableDef("Product")
tDef.Connect = dataSource
tDef.SourceTableName = "Product"
nWindEx.TableDefs.Append tDef
nWindEx.Close


Container Object

Description

A Container object groups similar types of Document objects together — for example, one container might have Tables documents. Applications can define their own document types and corresponding containers.

Remarks

Each Database object has a Containers collection consisting of built-in Container objects. Some of these Container objects are defined by the Microsoft Jet database engine while others may be defined by other applications. The following table lists the name of each Container object defined by the Jet database engine and what type of information it contains.

Container name | Contains information about
Databases | Containing database
Tables | Saved tables and queries
Relations | Saved relationships

Note

Don't confuse the particular types of Container objects listed in the preceding table with the collection types of the same name. The Databases type of Container object refers to all saved objects of the specified type, but the Databases collection refers only to open objects of the specified type.

Each Container object has a Documents collection that contains a Document object for each instance of the type of object it describes. You typically use a Container object with one of the Document objects in the Documents collection, so you can consider a Container object to be an intermediate link to the information that the Document object contains.

Because Container objects are built-in, you can't create new Container objects or delete existing ones. Using the properties of an existing Container object, you can:

  • Determine the predefined names an object has by checking its Name property setting.
  • Determine or specify the owner of the Container object by checking or setting its Owner property. To set the Owner property, you must have write permission for the Container object, and you must set the property to the name of an existing User or Group object.
  • Set access permissions for the Container object using the Permissions and UserName properties; any Document object created in the Documents collection of a Container object inherits these access permission settings.
 You can refer to a Container object in a collection by its ordinal number or by its Name property setting, using either of the following syntax forms:

Containers(0)

Containers("name")

Properties

AllPermissions Property, Inherit Property, Name Property, Owner Property, Permissions Property, UserName Property.

See Also

User Object; Appendix, "Data Access Object Hierarchy."

Specifics (Microsoft Access)

In addition to the Container objects defined by the Microsoft Jet database engine, the following four Container objects are defined by Microsoft Access.

Container name | Contains information about
Forms | Saved forms
Modules | Saved modules
Reports | Saved reports
Scripts | Saved macros

The Container objects defined by Microsoft Access are Microsoft Access database objects, not data access objects. These Container objects provide the Jet database engine with information about Microsoft Access objects. The Jet database engine uses this information to implement security on Microsoft Access database objects in the same way it does for data access objects.

The Container objects defined by Microsoft Access and the Container objects defined by the Jet database engine are all included in the Containers collection in Microsoft Access.

The Documents collection of a Container object contains Document objects representing the individual objects of the type described by the Container object. For example, the Forms Container object has a Documents collection that might include a Document object corresponding to a form named Orders.

You can use Container objects to establish and enforce permissions for Microsoft Access database objects. To set permissions for a Container object, set the UserName property of the Container object to the name of an existing User or Group object. Then set the Permissions property for the Container object.

Note

Don't confuse the particular types of Container objects with the collection types of the same name. The Forms and Reports Container objects each contain Documents collections, which include individual Document objects representing each saved form or report. The Forms and Reports collections refer only to open forms or reports.

Example

This example enumerates the properties of all the Container and Document objects in the current database.

Function EnumerateDocuments () As Integer
    Dim dbsCurrent As Database
    Dim conTest As Container, docTest As Document
    Dim intC As Integer, intD As Integer
    Set dbsCurrent = _
        DBEngine.Workspaces(0).OpenDatabase("Northwind.mdb")
    For intC = 0 To dbsCurrent.Containers.Count - 1
        Set conTest = dbsCurrent.Containers(intC)
        Debug.Print ">> Container: "; conTest.Name;
        Debug.Print "  Owner: "; conTest.Owner
        Debug.Print "  UserName: "; conTest.UserName;
        Debug.Print "  Permissions: "; conTest.Permissions
        Debug.Print
        For intD = 0 To conTest.Documents.Count - 1
            Set docTest = conTest.Documents(intD)
            Debug.Print " > Document: "; docTest.Name;
            Debug.Print "  Owner: "; docTest.Owner;
            Debug.Print "  Container: "; docTest.Container
            Debug.Print "  UserName: "; docTest.UserName;
            Debug.Print "  Permissions: "; docTest.Permissions
            Debug.Print "  DateCreated: "; docTest.DateCreated;
            Debug.Print "  LastUpdated: "; docTest.LastUpdated
            Debug.Print
        Next intD

    Next intC
    EnumerateDocuments = True
End Function
Example (Microsoft Access)

The following example grants programmers full access to all modules in a database, and grants all other users read-only permissions on modules.

Sub SetModulePermissions()
    Dim dbs As Database, wrk As Workspace, ctr As Container
    Dim grp As Group

    Set wrk = DBEngine.Workspaces(0)
    ' Return Database object pointing to current database.
    Set dbs = CurrentDb
    Set ctr = dbs.Containers!Modules
    wrk.Groups.Refresh
    For Each grp In wrk.Groups
        ctr.UserName = grp.Name
        If ctr.UserName = "Programmers" Then
            ctr.Permissions = ctr.Permissions Or dbSecFullAccess
        Else
            ctr.Permissions = ctr.Permissions Or acSecModReadDef
        End If
    Next grp
End Sub


Container Property

Applies To

Document Object.

Description

Returns the name of the Container object to which a Document object belongs.

Return Values

This property's return value is a String data type.

See Also

Container Object.

Example

This example determines the name of the Container object to which a Document object belongs.

Sub Doc_Analyzer(docUnknown As Document)
    Dim strContainerName As String
    strContainerName = docUnknown.Container
    Select Case strContainerName
        Case "Tables"
            ...
        Case "Databases"
            ...

        Case "Forms"
            ...
        Case Else
            ...
    End Select
End Sub
Example (Microsoft Access)

The following example determines the name of the Container object to which a Document object belongs, and sets permissions accordingly for the specified group account. Remember that you must denote a particular user or group account before you set permissions for an object. The following example assumes that you have defined a Marketers group.

Note that Microsoft Access defines additional Container objects beyond those defined by the Microsoft Jet database engine. These include the Form, Report, Script, and Module Container objects.

Sub DocAnalyzer(docUnknown As Document)
    Dim strContainerName As String
    ' Set UserName property to valid existing group account.
    docUnknown.UserName = "Marketers"
    ' Get value of Container property.
    strContainerName = docUnknown.Container
    Select Case strContainerName
        Case "Forms"
            ' Set permissions for Form Document object.
            docUnknown.Permissions = docUnknown.Permissions Or _
                acSecFrmRptWriteDef
        Case "Reports"
            ' Set permissions for Report Document.
            docUnknown.Permissions = docUnknown.Permissions Or _
                acSecFrmRptExecute
        Case "Scripts"
            ' Set permissions for Script Document.
            docUnknown.Permissions = docUnknown.Permissions Or _
                acSecMacWriteDef
        Case "Modules"
            ' Set permissions for Module Document object.
            docUnknown.Permissions = docUnknown.Permissions Or _
                acSecModReadDef
        Case Else
            Exit Sub
    End Select
End Sub


Containers Collection

Description

A Containers collection contains all of the Container objects that are defined in a database.

Remarks

Each Database object has a Containers collection consisting of built-in Container objects. Some of these Container objects are defined by the Microsoft Jet database engine while others may be defined by other applications.

Properties

Count Property.

Methods

Refresh Method.

See Also

Appendix, "Data Access Object Hierarchy."

Specifics (Microsoft Access)

See the Container object example (Microsoft Access).

Example

See the Container object example.

Example (Microsoft Access)

See the Container object example (Microsoft Access).


CopyQueryDef Method

Applies To

Dynaset-Type Recordset Object, Recordset Object, Snapshot-Type Recordset Object.

Description

Returns a QueryDef object which is a copy of the QueryDef used to create the Recordset object represented by the object placeholder.

Syntax

Set <querydefobject> = <object>.CopyQueryDef

The <querydefobject> is an object variable declared as a QueryDef.

Remarks

You must first open a Recordset with the OpenRecordset method before using the CopyQueryDef method. CopyQueryDef creates a new QueryDef that is a duplicate of the QueryDef used to create the Recordset. If a QueryDef wasn't used to create this Recordset, you'll see a message that the feature is not available.

See Also

QueryDef Object.

Example (Microsoft Access)

The following example uses the CopyQueryDef method to return a copy of a QueryDef object representing an Invoices query, and prints the SQL property of that QueryDef object.

Sub GetQueryDefCopy()
    Dim dbs As Database, rst As Recordset
    Dim qdfOriginal As QueryDef, qdfCopy As QueryDef

    ' Return Database variable pointing to current database.
    Set dbs = CurrentDb
    ' Return QueryDef variable pointing to Invoices query.
    Set qdfOriginal = dbs.QueryDefs!Invoices
    ' Open dynaset-type Recordset object.
    Set rst = qdfOriginal.OpenRecordset
    ' Get copy of original QueryDef object.
    Set qdfCopy = rst.CopyQueryDef
    ' Print value of SQL property for copy.
    Debug.Print qdfCopy.SQL
End Sub


Count Property

Applies To

Containers Collection, Databases Collection, Documents Collection, Errors Collection, Fields Collection, Groups Collection, Indexes Collection, Parameters Collection, Properties Collection, QueryDefs Collection, Recordsets Collection, Relations Collection, TableDefs Collection, Users Collection, Workspaces Collection.

Description

Returns the number of objects in a collection.

Return Value

This property's return value is a Long integer data type.

Remarks

Because members of a collection are numbered starting with 0, loops are always coded starting with the 0 member; for example:

    For I = 0 to Databases.Count - 1
The Count property setting is never Null. If its value is 0, there are no objects in the collection.

See Also

Append Method, Delete Method, Refresh Method.

Example

This example lists the names and total number of TableDef and QueryDef objects in the current database.

Dim dbsLocal As Database, intCount As Integer
Set dbsLocal = DBEngine.Workspaces(0).OpenDatabase("Northwind.mdb")

For intCount = 0 To dbsLocal.TableDefs.Count - 1
    Debug.Print dbsLocal.TableDefs(intCount).Name
Next intCount
Debug.Print dbsLocal.TableDefs.Count
For intCount = 0 To dbsLocal.QueryDefs.Count - 1
    Debug.Print dbsLocal.QueryDefs(intCount).Name
Next intCount
Debug.Print dbsLocal.QueryDefs.Count
Example (Microsoft Access)

The following example prints the names and total number fields in an Orders table.

Sub CountFields()
    Dim dbs As Database, tdf as TableDef
    Dim intI As Integer

    ' Return Database variable that points to current database.
    Set dbs = CurrentDb
    Set tdf = dbs.TableDefs!Orders
    ' Count fields in Fields collection of TableDef object.
    Debug.Print tdf.Fields.Count
    ' List names of all fields.
    For Each fld In tdf.Fields
        Debug.Print fld.Name
    Next fld
End Sub
Example (Microsoft Excel)

This example displays the number of recordsets in the NWINDEX.MDB database and then enters the names on Sheet1.

To create the NWINDEX.MDB database, run the Microsoft Excel example for the CreateDatabase method.

Dim db As Database, i As Integer
Sheets("Sheet1").Activate
Set db = Workspaces(0).OpenDatabase(Application.Path & "\NWINDEX.MDB")
Cells(1, 1).Value = "TableDef list for " & db.Name
Cells(1, 1).EntireColumn.AutoFit
For i = 0 To db.TableDefs.Count - 1
    Cells(i + 2, 1).Value = db.TableDefs(i).Name
Next i
MsgBox "There are " & db.TableDefs.Count & " TableDefs"
db.Close


CreateDatabase Method

Applies To

Workspace Object.

Description

Creates a new Database object, saves the database on disk and returns an opened Database object.

Syntax

Set database = workspace.CreateDatabase (databasename, locale [, options])

The CreateDatabase method syntax has these parts.

Part | Description
database | A variable of an object data type that references the Database object you're creating.
workspace | A variable of an object data type that represents the existing Workspace object that will contain the database. If you omit the workspace part, the default Workspace is used.
databasename | A string expression that is the name of the database file that you're creating. It can be the full path and filename, such as "C:\MYDB.mdb". If you don't supply a filename extension, .mdb is appended. If your network supports it, you can also specify a network path, such as "\\MYSERVER\MYSHARE\MYDIR\MYDB". Only .mdb database files can be created using this method.
locale | A string expression used to specify collating order for creating the database. You must supply this argument or an error will occur. See the table that lists locale constants later in this topic.
options | An integer that indicates one or more options, as specified in Settings. You can combine options by summing the corresponding constants.

Settings

You can use one of the following constants for the locale argument to specify the CollatingOrder property of text for string comparisons.

Constant | Collating order
dbLangGeneral | English, German, French, Portuguese, Italian, and Modern Spanish
dbLangArabic | Arabic
dbLangCyrillic | Russian
dbLangCzech | Czech

Constant | Collating order
dbLangDutch | Dutch
dbLangGreek | Greek
dbLangHebrew | Hebrew
dbLangHungarian | Hungarian
dbLangIcelandic | Icelandic
dbLangNordic | Nordic languages (Microsoft Jet database engine version 1.0 only)
dbLangNorwdan | Norwegian and Danish
dbLangPolish | Polish
dbLangSpanish | Traditional Spanish
dbLangSwedfin | Swedish and Finnish
dbLangTurkish | Turkish

You can use one or more of the following constants in the options argument to specify which version the data format should have and whether or not to encrypt the database.

Constant | Description
dbEncrypt | Creates an encrypted database.
dbVersion10 | Creates a database that uses the Jet database engine version 1.0.
dbVersion11 | Creates a database that uses the Jet database engine version 1.1.
dbVersion20 | Creates a database that uses the Jet database engine version 2.0.
dbVersion30 | Creates a database that uses the Jet database engine version 3.0.

If you omit the encryption constant, an unencrypted database is created. You can specify only one version constant. If you omit a version constant, a database that uses the Jet database engine version 3.0 is created.

Remarks

The CreateDatabase method creates and opens a new, empty database and returns the Database object. You must complete its structure and content using additional data access objects. If you want to make a partial or complete copy of an existing database, you can use the CompactDatabase method to make a copy that you can customize.

See Also

CollatingOrder Property, CompactDatabase Method, Database Object, DBEngine Object, OpenDatabase Method.

Specifics (Microsoft Access)

You can use the CreateDatabase method to create a new database from Visual Basic. The new database is immediately opened, appended to the Databases collection, and saved to disk. However, only the current database is open in the Microsoft Access Database window. To open a database that you have created with CreateDatabase in the Database window, you must click Open Database on the File menu.

Example

This example uses CreateDatabase to create a new, encrypted Database object. The example customizes some properties of the new database, completes its structure, and then closes it.

Dim wspDefault As Workspace, dbsDefault As Database, dbsNew As Database
Set wspDefault = DBEngine.Workspaces(0)
Set dbsDefault = wspDefault.OpenDatabase("Northwind.mdb")
If Dir$("NewDB.mdb") <> "" Then
    Kill "NewDB.mdb"
Set dbsNew = wspDefault.CreateDatabase("NewDB.mdb", dbLangGeneral, _
    dbEncrypt)
dbsNew.QueryTimeout = dbsDefault.QueryTimeout
...
' Complete structure of dbsNew, possibly using structure of dbsDefault.
...
dbsNew.Close
dbsDefault.Close
Example (Microsoft Access)

The following example uses CreateDatabase to create a new, encrypted database named Newdb.mdb.

Sub NewDatabase()
    Dim wspDefault As Workspace, dbsNew As Database

    Set wspDefault = DBEngine.Workspaces(0)
    ' Create new, encrypted database.
    Set dbsNew = wspDefault.CreateDatabase ("Newdb.mdb", _
        dbLangGeneral, dbEncrypt)
    ' Create and append tables to new database.
    .
    .
    .
    dbsNew.Close
End Sub

Example (Microsoft Excel)

This example creates a new database (NWINDEX.MDB). The example attaches two tables from the C:\Program Files\Common Files\Microsoft Shared\MSquery folder to the database. (On Windows NT, the two tables are in the \WINDOWS\MSAPPS\MSQUERY folder.)

Const sourceDir = "C:\Program Files\Common Files\Microsoft Shared\"

Sub createNWindEx()
    Dim nWindEx As Database, customerTable As TableDef, _
        supplierTable As TableDef
    Dim dataSource As String
    dataSource = "dbase IV;DATABASE=" & sourceDir & "MSquery"    appPath = Application.Path
    Set nWindEx = Workspaces(0).CreateDatabase(Application.Path _
        & "\NWINDEX.MDB", dbLangGeneral)
    Set customerTable = nWindEx.CreateTableDef("Customer")
    customerTable.Connect = dataSource
    customerTable.SourceTableName = "Customer"
    nWindEx.TableDefs.Append customerTable
    Set supplierTable = nWindEx.CreateTableDef("Supplier")
    supplierTable.Connect = dataSource
    supplierTable.SourceTableName = "Supplier"
    nWindEx.TableDefs.Append supplierTable
    MsgBox "The database " & nWindEx.Name & " has been created."
    nWindEx.Close
End Sub


CreateField Method

Applies To

Index Object, Relation Object, TableDef Object.

Description

Creates a new Field object.

Syntax

Set variable = object.CreateField([name[, type [, size]]])

The CreateField method syntax has these parts.

Part | Description
variable | A variable declared as an object data type Field.
object | The variable name of the Index, Relation, or TableDef object you want to use to create the new Field object.
name | A String variable that uniquely names the new Field object. See the Name property for details on valid Field names.
type | An Integer constant that determines the data type of the new Field object. See the Type property for valid data types.

Part | Description
size | An integer that indicates the maximum size, in bytes, of a Field object that contains text. See the Size property for valid size values. This argument is ignored for numeric and fixed-width fields.

Remarks

If you omit one or more of the optional parts when you use CreateField, you can use an appropriate assignment statement to set or reset the corresponding property before you append the new object to a collection. After you append the new object, you can alter some but not all of its property settings. See the individual property topics for more details.

Note

The type and size arguments apply only to Field objects in a TableDef object. These arguments are ignored when a Field object is associated with Index and Relation objects.

If name refers to an object that is already a member of the collection, a trappable error occurs when you use the Append method.

To remove a Field object from a collection, use the Delete method on the collection. You can't delete a Field object from a TableDef object's Fields collection once an index has been created that references the field.

See Also

Append Method, Delete Method, Field Object, Name Property, Size Property, Type Property.

Example

This example creates a new Field object.

Dim dbsNorthwind As Database
Dim tdfEmployees As TableDef
Dim fldPhone As Field
Set dbsNorthwind = DBEngine.Workspaces(0).OpenDatabase("Northwind.mdb")
Set tdfEmployees = dbsNorthwind.TableDefs("Employees")
' Create new Field object.
Set fldPhone = tdfEmployees.CreateField("Phone", dbText)
' Set another property of fldPhone.
fldPhone.Size = 25    ' Greater than longest phone number.
' Save fldPhone definition by appending it to Fields collection.
tdfEmployees.Fields.Append fldPhone
dbsNorthwind.Close
Example (Microsoft Access)

The following example creates a new Field object and appends it to an Employees table.

Sub NewField()
    Dim dbs As Database, tdf As TableDef
    Dim fld As Field

    ' Return Database variable pointing to current database.

    Set dbs = CurrentDb
    Set tdf = dbs.TableDefs!Employees
    ' Create new Field object.
    Set fld = tdf.CreateField("Phone", dbText)
    ' Set another property of field.
    fld.Size = 25
    ' Append new field to Fields collection.
    tdf.Fields.Append fld
End Sub


CreateGroup Method

Applies To

User Object, Workspace Object.

Description

Creates a new Group object.

Syntax

Set variable = object.CreateGroup([name[, pid]])

The CreateGroup method syntax has these parts.

Part | Description
variable | A variable declared as object data type Group.
object | The variable name of the User or Workspace object you want to use to create the new Group object.
name | A String variable that uniquely names the new Group object. See the Name property for details on valid Group names.
pid | A String variable containing the PID of a group account. The identifier must contain from 4 to 20 alphanumeric characters. See the PID property for more information on valid personal identifiers.

Remarks

If you omit one or both of the optional parts when you use CreateGroup, you can use an appropriate assignment statement to set or reset the corresponding property before you append the new object to a collection. After you append the object, you can alter some but not all of its property settings. See the individual property topics for more details.

If name refers to an object that is already a member of the collection, a trappable error occurs when you use the Append method.

To remove a Group object from a collection, use the Delete method on the collection.

See Also

Append Method, Delete Method, Group Object, Name Property, PID Property.

Specifics (Microsoft Access)

Once you have created a new Group object and appended it to the Groups collection of a Workspace or User object, you can verify that the new group exists by examining the Name drop-down list box on the Groups tab of the User And Group Accounts dialog box. This dialog box is available by pointing to Security on the Tools menu and then clicking User And Group Accounts.

Example

This example creates a new Group object.

Dim grpManagers As Group, strManagersPID As String
strManagersPID = "2222abc"
' Create new Group object.
Set grpManagers = DBEngine.Workspaces(0).CreateGroup("Managers", _
    strManagersPID)
' Create new group in workgroup by appending it to Groups collection.
Workspaces(0).Groups.Append grpManagers


CreateIndex Method

Applies To

TableDef Object.

Description

Creates a new Index object.

Syntax

Set variable = tabledef.CreateIndex([name])

The CreateIndex method syntax has these parts.

Part | Description
variable | A variable declared as object data type Index.
tabledef | The variable name of the TableDef object you want to use to create the new Index object.
name | A String variable that uniquely names the new Index object. See the Name property for details on valid Index names.

Remarks

If you omit the optional name part when you use CreateIndex, you can use an appropriate assignment statement to set or reset the Name property before you append the new object to a collection. After you append the object, you may or may not be able to set its Name property, depending on the type of object the Indexes collection resides in. See the Name property topic for more details.

If name refers to an object that is already a member of the collection, a trappable error occurs when you use the Append method.

To remove an Index object from a collection, use the Delete method on the collection.

See Also

Append Method, Delete Method, Index Object, Name Property.

Example

This example creates a new Index object.

Dim idxAnother As Index, fldLastName As Field
Dim tdfEmployees As TableDef, dbsNorthwind As Database
Set dbsNorthwind = DBEngine.Workspaces(0).OpenDatabase("Northwind.mdb")
Set tdfEmployees = dbsNorthwind.TableDefs("Employees")
' Create new Index object.
Set idxAnother = tdfEmployees.CreateIndex("Another")
Set fldLastName = idxAnother.CreateField("LastName")
idxAnother.Primary = False
idxAnother.Required = True
idxAnother.Fields.Append fldLastName
' Save Index definition by appending it to Indexes collection.
tdfEmployees.Indexes.Append idxAnother
tdfEmployees.Indexes.Delete "Another"
dbsNorthwind.Close
Example (Microsoft Access)

The following example creates a new Index object on an Employees table. The new index consists of two fields, LastName and FirstName.

Sub NewIndex()
    Dim dbs As Database, tdf As TableDef
    Dim idx As Index, rst As Recordset
    Dim fldLastName As Field, fldFirstName As Field

    ' Return Database variable pointing to current database.
    Set dbs = CurrentDb
    Set tdf = dbs.TableDefs!Employees
    ' Return Index object that points to new index.
    Set idx = tdf.CreateIndex("FullName")
    ' Create and append index fields.
    Set fldLastName = idx.CreateField("LastName", dbText)
    Set fldFirstName = idx.CreateField("FirstName", dbText)
    idx.Fields.Append fldLastName
    idx.Fields.Append fldFirstName
    ' Append Index object.
    tdf.Indexes.Append idx
End Sub


CreateProperty Method

Applies To

Database Object, Field Object, Index Object, QueryDef Object, TableDef Object.

Description

Creates a new user-defined Property object.

Syntax

Set variable = object.CreateProperty([name[, type[, value[, fDDL]]]])

The CreateProperty method syntax has these parts.

Part | Description
variable | A variable declared as an object data type Property.
object | The variable name of the Database, Field, Index, QueryDef, or TableDef object you want to use to create the new Property object.
name | A String variable that uniquely names the new Property object. See the Name property for details on valid Property names.
type | An Integer constant that defines the data type of the new Property object. See the Type property for valid data types.
value | A Variant variable containing the initial property value. See the Value property for details.
fDDL | A Boolean variable indicating whether or not the Property is a DDL object. The default is False. If the fDDL is True, this Property object can't be changed or deleted unless the user has dbSecWriteDef permission.

Remarks

You can create a user-defined Property object only in the Properties collection of an object that is persistent (that is, already stored on disk).

If you omit one or more of the optional parts when you use CreateProperty, you can use an appropriate assignment statement to set or reset the corresponding property before you append the new object to a collection. After you append the object, you can alter some but not all of its property settings. See the individual property topics for more details.

If name refers to an object that is already a member of the collection, a trappable error occurs when you use the Append method.

To remove a user-defined Property object from the collection, use the Delete method on the Properties collection. You can't delete built-in properties.

Note

If you omit the fDDL part, it defaults to False (non-DDL). Because no corresponding DDL property is exposed, you must delete and re-create a Property object you want to change from DDL to non-DDL.

See Also

Append Method, Delete Method, Name Property, Type Property, Value Property.

Specifics (Microsoft Access)

Microsoft Access defines a number of properties on data access objects. These properties are not automatically recognized by the Microsoft Jet database engine. In order to set or return values for a Microsoft Access-defined property in Visual Basic, you must specifically add the property to the Properties collection of the object to which it applies. You can do this by using the CreateProperty method to create the property and then appending it to the Properties collection.

A Microsoft Access-defined property is automatically added to the Properties collection when it is first set from the Microsoft Access window. If the property has already been set in this way, then you don't need to add it to the Properties collection.

When you write code to set a Microsoft Access-defined property, you should include an error-handling routine that creates a Property object representing that property and appends it to the Properties collection if it does not already exist in the collection.

When you refer to a Microsoft Access-defined property in Visual Basic, you must explicitly refer to the Properties collection. For example, you would refer to the AppTitle property in the following manner, once it exists within the Properties collection of a Database object representing the current database.

Dim dbs As Database
Set dbs = CurrentDb
dbs.Properties!AppTitle = "Northwind Traders"

Note

You need to create and append only the Microsoft Access properties that apply to data access objects. You can set other Microsoft Access properties in Visual Basic using the standard object.property syntax.

Example

This example creates a new Property object.

Dim prpPrivilege As Property
Dim dbsNorthwind As Database
Set dbsNorthwind = DBEngine.Workspaces(0).OpenDatabase("Northwind.mdb")
' Create new Property object.
Set prpPrivilege = dbsNorthwind.CreateProperty("Privilege")
' Set other properties of prpPrivilege.
prpPrivilege.Type = dbBoolean
prpPrivilege.Value = True
' Save Property definition by appending it to Properties collection.
dbsNorthwind.Properties.Append prpPrivilege

Example (Microsoft Access)

The following example sets the Subject property. The Subject property is a database property that can also be set on the Summary tab of the Database Properties dialog box, available by clicking Database Properties on the File menu.

The Subject property applies to a data access object — the SummaryInfo Document object. However, it is defined by Microsoft Access, so the Microsoft Jet database engine does not automatically recognize it. Therefore, you must specifically add this property to the Properties collection of the Document object before you can set it. If the property does not exist in the Properties collection, Microsoft Access will generate an error when you attempt to set it.

In the following example, if Microsoft Access generates an error upon trying to set the Subject property, the error-handling routine creates the property and appends it to the Properties collection.

Sub SetAccessProperty()
    Dim dbs As Database, ctr As Container, doc As Document
    Dim prp As Property

    ' Enable error handling.
    On Error GoTo ErrorHandler
    ' Return Database variable pointing to current database.
    Set dbs = CurrentDb
    ' Return Container variable pointing to Databases container.
    Set ctr = dbs.Containers!Databases
    ' Return Document variable pointing to SummaryInfo document.
    Set doc = ctr.Documents!SummaryInfo
    ' Attempt to set Subject property.
    doc.Properties!Subject = "Business Contacts"
    Exit Sub

ErrorHandler:
    ' Check number of error that has occurred.
    If Err.Number = 3270 Then
        ' Create Subject property and set its value.
        Set prp = doc.CreateProperty("Subject", dbText, _
            "Business Contacts")
        ' Append property.
        doc.Properties.Append prp
        ' Resume main procedure.
        Resume Next
    Else
        ' If different error has occurred, display message.
        MsgBox "Unknown error!", vbCritical
    End If
End Sub


CreateQueryDef Method

Applies To

Database Object.

Description

Creates a new QueryDef object in a specified database.

Syntax

Set querydef = database.CreateQueryDef([name][, sqltext])

The CreateQueryDef method syntax has these parts.

Part | Description
querydef | A variable of an object data type that references the QueryDef object you want to create.
database | A variable of an object data type that references the open Database object that contains the new QueryDef.
name | A string expression identifying the new QueryDef.
sqltext | A string expression (a valid SQL statement) that defines the QueryDef. If you omit this argument, you can define the QueryDef by setting its SQL property before or after you append it to a collection.

Remarks

If you include name but omit sqltext or include both name and sqltext, the QueryDef is automatically saved when you create or change it.

If the object specified by name is already a member of the QueryDefs collection, a trappable error occurs.

You can create a temporary QueryDef by setting the Name property of a newly created QueryDef to a zero-length string ("") or by using a zero-length string for the name argument when you execute the CreateQueryDef method. You can't append a temporary QueryDef to any collection because a zero-length string isn't a valid name for a permanent QueryDef. You can set the Name and SQL properties of the newly created QueryDef and subsequently append the QueryDef to the QueryDefs collection where it's stored in the database. If you provide anything other than a zero-length string for the name when you create a QueryDef, the resulting QueryDef object is automatically appended to the QueryDefs collection.

To remove a QueryDef object from a QueryDefs collection, use the Delete method on the collection.

To run the SQL statement in a QueryDef object, use the Execute method.

Using a QueryDef object is the preferred way to perform SQL pass-through queries with ODBC databases. See the QueryDef object for more information.

See Also

Append Method, Connect Property, CreateProperty Method, Delete Method, LogMessages Property, Name Property, OpenRecordset Method, QueryDef Object, ReturnsRecords Property, SQL Property, Type Property, Value Property.

Example

This example creates a QueryDef named All Pubs with an SQL statement, and then creates a dynaset-type Recordset based on the query.

Dim dbsBiblio As Database, qdfAllPubs As QueryDef
Dim rstAllPubs As Recordset
' Open a database.
Set dbsBiblio = DBEngine.Workspaces(0).OpenDatabase("Biblio.mdb")
' Create a QueryDef.
Set qdfAllPubs = dbsBiblio.CreateQueryDef("All Pubs", _
    "SELECT * FROM Publishers;")
' Create Recordset from query.
Set rstAllPubs = qdfAllPubs.OpenRecordset
...
Example (Microsoft Access)

The following example creates a new QueryDef object, then opens the query in Datasheet view.

Sub NewQuery()
    Dim dbs As Database, qdf As QueryDef, strSQL As String

    ' Return Database variable pointing to current database.
    Set dbs = CurrentDb
    strSQL = "SELECT * FROM Employees WHERE [HireDate] >= #1-1-95#"
    Set qdf = dbs.CreateQueryDef("RecentHires", strSQL)
    DoCmd.OpenQuery qdf.Name
End Sub
Example (Microsoft Excel)

This example creates a new query based on the Customer recordset in the NWINDEX.MDB database. The query selects a snapshot of all customers in the state of Washington and then copies it onto Sheet1.

To create the NWINDEX.MDB database, run the Microsoft Excel example for the CreateDatabase method.

Dim db As Database, qDef As QueryDef, rs As Recordset
Set db = Workspaces(0).OpenDatabase(Application.Path & "\NWINDEX.MDB")
Set qDef = db.CreateQueryDef("WA Region")
qDef.SQL = "SELECT * FROM Customer WHERE [Region] = 'WA';"
Set rs = db.OpenRecordset("WA Region")
numberOfRows = Sheets("Sheet1").Cells(1, 1).CopyFromRecordset(rs)
Sheets("Sheet1").Activate
MsgBox numberOfRows & " records have been copied."
rs.Close
db.Close


CreateRelation Method

Applies To

Database Object.

Description

Creates a new Relation object.

Syntax

Set variable = database.CreateRelation([name[, table[, foreigntable[,
ú attributes]]]])

The CreateRelation method syntax uses these parts.

Part | Description
variable | A variable declared as an object data type Relation.
database | The variable name of the Database object you want to use to create the new Relation object.
name | A String variable that uniquely names the new Relation object. See the Name property for details on valid Relation names.
table | A String variable that names the primary table in the relation. If the table doesn't exist before you append the Relation object, a trappable error occurs.
foreigntable | A String variable that names the foreign table in the relation. If the table doesn't exist before you append the Relation object, a trappable error occurs.
attributes | A Long variable that contains information about the relationship type. See the Attributes property for details.

Remarks

The Relation object relays information to the Microsoft Jet database engine about the relationship between fields in two TableDef or QueryDef objects. The Jet database engine can provide referential integrity through the Attributes property.

If you omit one or more of the optional parts when you use CreateRelation, you can use an appropriate assignment statement to set or reset the corresponding property before you append the new object to a collection. After you append the object, none of its property settings can be altered. See the individual property topics for more details.

Before you can use the Append method on a Relation object, you must append the appropriate Field objects to define the primary and foreign key relationship tables.

If name refers to an object that is already a member of the collection or if the Field object names provided in the subordinate Fields collection are invalid, a trappable error occurs when you use the Append method.

To remove a Relation object from a collection, use the Delete method on the collection.

See Also

Append Method, Attributes Property, Delete Method, Name Property, TableDef Object.

Example

This example creates a new Relation object. In this case, the Customers table is related to a ValidStates table. Once established, the relationship requires that an entry exist in the ValidStates table corresponding to the Customers.CustState field before it can be added to the Customers table. Any changes to the State field that violate this relationship trigger a trappable error.

By setting the dbRelationUpdateCascade attribute, the Microsoft Jet database engine changes the Primary table Customers.CustState if a corresponding value changes in the ValidStates table. For example, if the ValidState entry TR was changed to TX, all Customers records having TR as a CustState code would be changed to TX.

Dim relTableOne As Relation
Dim dbsNorthwind As Database
Dim fldCustState As Field
Set dbsNorthwind = DBEngine.Workspaces(0).OpenDatabase("Northwind.mdb")
' Create new Relation object.
Set relTableOne = dbsNorthwind.CreateRelation("TableRelationOne")
relTableOne.Table = "Customers"    'Name the Primary Table.
relTableOne.ForeignTable = "ValidStates"    'Name the Foreign Table.
relTableOne.Attributes = dbRelationUpdateCascade
Set fldCustState = relTableOne.CreateField("CustState")
fldCustState.ForeignName = "StateCode"
relTableOne.Fields.Append fldCustState
' Save Relation definition by appending it to Relations collection.
dbsNorthwind.Relations.Append relTableOne
Example (Microsoft Access)

The following example creates a new Relation object that defines a relationship between a Categories table and a Products table. The Categories table is the primary table in the relationship, and the Products table is the foreign table. The CategoryID field is the primary key in the Categories table, and a foreign key in the Products table.

To test this example in the Northwind database, click Relationships on the Tools menu, and delete the relationship between the Categories table and the Products table. Close the Relationships window, saving the current configuration at the prompt. Run the following procedure. Then view the Relationships window again to see the new relationship.

Sub NewRelation()
    Dim dbs As Database, rel As Relation, fld As Field

    ' Return Database variable pointing to current database.
    Set dbs = CurrentDb

    ' Create new Relation object and specify foreign table.
    Set rel = dbs.CreateRelation("CategoryID", "Categories", "Products")
    ' Set attributes to enforce referential integrity.
    rel.Attributes = dbRelationUpdateCascade + dbRelationDeleteCascade
    ' Create field in relation.
    Set fld = rel.CreateField("CategoryID")
    ' Specify field name in foreign table.
    fld.ForeignName = "CategoryID"
    ' Append Field object to Fields collection of Relation object.
    rel.Fields.Append fld
    ' Append Relation object to Relations collection.
    dbs.Relations.Append rel
End Sub


CreateTableDef Method

Applies To

Database Object.

Description

Creates a new TableDef object.

Syntax

Set variable = database.CreateTableDef([name[, attributes[, source[, ú connect]]]])

The CreateTableDef method syntax has these parts.

Part | Description
variable | A variable declared as an object data type TableDef.
database | The variable name of the Database object you want to use to create the new TableDef object.
name | A String variable that uniquely names the new TableDef object. See the Name property for details on valid TableDef names.
attributes | A Long variable that indicates one or more characteristics of the new TableDef object. See the Attributes property for more information.
source | A String variable containing the name of a table in an external database that is the original source of the data. The source string becomes the SourceTableName property setting of the new TableDef object.
connect | A String variable containing information about the source of an open database, a database used in a pass-through query, or an attached table. See the Connect property for more information on valid connection strings.

Remarks

If you omit one or more of the optional parts when you use CreateTableDef, you can use an appropriate assignment statement to set or reset the corresponding property before you append the new object to a collection. After you append the object, you can alter some but not all of its properties. See the individual property topics for more details.

If name refers to an object that is already a member of the collection or you specify an invalid property in the TableDef or Field object you're appending, a trappable error occurs when you use the Append method.

To remove a TableDef object from a collection, use the Delete method on the collection.

See Also

Append Method, Attributes Property, Connect Property, Delete Method, Name Property, TableDef Object.

Example

This example creates a new TableDef object in the Biblio.mdb database.

Dim tdfTitleDetail As TableDef, fldComments As Field
Dim dbsBiblio As Database
Set dbsBiblio = DBEngine.Workspaces(0).OpenDatabase("Biblio.mdb")
' Create new TableDef.
Set tdfTitleDetail = dbsBiblio.CreateTableDef("Title Detail")
' Add field to tdfTitleDetail.
Set fldComments = tdfTitleDetail.CreateField("Comments",dbMemo)
tdfTitleDetail.Fields.Append fldComments
' Save TableDef definition by appending it to TableDefs collection.
dbsBiblio.TableDefs.Append tdfTitleDetail
Example (Microsoft Access)

The following example creates a new TableDef object and appends it to the TableDefs collection of the current database.

Sub NewTable()
    Dim dbs As Database, tdf As TableDef, fld As Field

    ' Return Database variable pointing to current database.
    Set dbs = CurrentDb
    ' Return TableDef object variable that points to new table.
    Set tdf = dbs.CreateTableDef("Contacts")
    ' Define new field in table.
    Set fld = tdf.CreateField("ContactName", dbText, 40)
    ' Append Field object to Fields collection of TableDef object.
    tdf.Fields.Append fld
    ' Append TableDef object to TableDefs collection of database.
    dbs.TableDefs.Append tdf
End Sub
Example (Microsoft Excel)

See the CreateDatabase method example (Microsoft Excel).


CreateUser Method

Applies To

Group Object, Workspace Object.

Description

Creates a new User object.

Syntax

Set variable = object.CreateUser([name[, pid [, password]]])

The CreateUser method syntax has these parts.

Part | Description
variable | A variable declared as an object data type User.
object | The variable name of the Group or Workspace object you want to use to create the new User object.
name | A String variable that uniquely names the new User object. See the Name property for details on valid User names.
pid | A String variable containing the PID of a user account. The identifier must contain from 4 to 20 alphanumeric characters. See the PID property for more information on valid personal identifiers.
password | A String variable containing the password for the new User object. The password can be up to 14 characters long and can include any characters except the ASCII character 0 (null). See the Password property for more information on valid passwords.

Remarks

If you omit one or more of the optional parts when you use CreateUser, you can use an appropriate assignment statement to set or reset the corresponding property before you append the new object to a collection. After you append the object, you can alter some but not all of its property settings. See the individual property topics for more details.

If name refers to an object that is already a member of the collection, a trappable error occurs when you use the Append method.

To remove a User object from a collection, use the Delete method on the collection.

See Also

Append Method, Delete Method, Name Property, Password Property, PID Property, User Object.

Specifics (Microsoft Access)

Once you have created a new User object and appended it to the Users collection of a Workspace or Group object, you can verify that the new user exists by examining the Name drop-down list box on the Users tab of the User And Group Accounts dialog box. This dialog box is available by pointing to Security on the Tools menu and then clicking User And Group Accounts.

Example

This example creates a new User object.

Dim usrPartner As User
Dim strManagersPID As String

strManagersPID = "1122aabb"
' Create new user account.
Set usrPartner = DBEngine.Workspaces(0).CreateUser("Partner", _
    strManagersPID)
' Set other properties of usrPartner.
usrPartner.Password = "NewPassword"
' Save user account definition by appending it to Users collection.
DBEngine.Workspaces(0).Users.Append usrPartner
' Re-create usrPartner and append to Groups collection
Set usrPartner = DBEngine.Workspaces(0).CreateUser("Partner")
DBEngine.Workspaces(0).Groups(0).Users.Append usrPartner


CreateWorkspace Method

Applies To

DBEngine Object.

Description

Creates a new Workspace object.

Syntax

Set variable = CreateWorkspace(name, user, password)

The CreateWorkspace method syntax has these parts.

Part | Description
variable | A variable declared as object data type Workspace.
name | A String variable that uniquely names the new Workspace object. See the Name property for details on valid Workspace names.
user | A String variable that identifies the owner of the new Workspace object. See the UserName property for more information.
password | A String variable containing the password for the new Workspace object. The password can be up to 14 characters long and can include any characters except ASCII character 0 (null). See the Password property for more information on valid passwords.

Remarks

Unlike the other methods you use to create data access objects, CreateWorkspace requires that you provide all of its parts. In addition, Workspace objects aren't permanent and can't be saved. Once you create a Workspace object, you can't alter any of its property settings.

You don't have to append the new Workspace object to a collection before you can use it. You append a newly created Workspace object only if you need to be able to refer to it through the Workspaces collection.

If name refers to an object that is already a member of the Workspaces collection, a trappable error occurs.

Once you use CreateWorkspace to create a new Workspace object, a Workspace session is started, and you can refer to the Workspace object in your application.

To remove a Workspace object from the Workspaces collection, close all open databases and then use the Close method on the Workspace object.

See Also

Close Method, Name Property, Password Property, UserName Property, Workspace Object.

Example

This example creates a new Workspace object named Special, and sets its UserName property to "guest."

Dim wspSpecial As Workspace
' Create new workspace.
Set wspSpecial = DBEngine.CreateWorkspace("Special","guest", "")


Data Access Constants

Description

You can use the Object Browser to view a list of built-in constants. From the View menu, choose Object Browser, select the appropriate library, and then select the Constants object. Scroll the list in the Methods/Properties box to see the complete list of constants.

The data access objects provide built-in constants that you can use with methods or properties. These constants all begin with the letters db and are documented with the method or property to which they apply.

Attributes Property Constants

Field.Attributes Property

Constant | Description
dbFixedField | Read/write. Field size fixed (default for Numeric fields).
dbVariableField | Read/write. Field size variable (Text fields only).
dbAutoIncrField | Read/write. New record field value incremented to unique Long integer (Counter type).
dbUpdatableField | Read-only. Field is updatable.
dbDescending | Read/write. Field sorted in descending order.
dbSystemField | Read-only. The field is a replication field (on a TableDef object).

Relation.Attributes Property

Constant | Description
dbRelationUnique | Read/write. One-to-one relationship.
dbRelationDontEnforce | Read/writeRelationship not enforced (no referential integrity).
dbRelationInherited | Read-only. Relationship exists in the database containing the two attached tables.
dbRelationUpdateCascade | Read/write. Updates cascade.
dbRelationDeleteCascade | Read/write. Deletions cascade.

TableDef.Attributes Property

Constant | Description
dbAttachExclusive | Read/write. Attached Microsoft Jet database engine table opened for exclusive use.
dbAttachSavePWD | Read/write. Save user ID and password for attached remote table.
dbSystemObject | Read-only. System table.
dbHiddenObject | Read/write. Hidden table (for temporary use).
dbAttachedTable | Read-only. Attached non-ODBC database table.
dbAttachedODBC | Read-only. Attached ODBC database table.

CollatingOrder Property Constants

All of the following constants are read/write.

Constant | Description
dbSortArabic | Arabic collating order.
dbSortCyrillic | Russian collating order.
dbSortCzech | Czech collating order.
dbSortDutch | Dutch collating order.
dbSortGeneral | English, German, French, and Portuguese collating order.
dbSortGreek | Greek collating order.
dbSortHebrew | Hebrew collating order.
dbSortHungarian | Hungarian collating order.

Constant | Description
dbSortIcelandic | Icelandic collating order.
dbSortJapanese | Japanese collating order.
dbSortNeutral | Neutral collating order.
dbSortNorw | Norwegian and Danish collating order.
dbSortPDXIntl | Paradox international collating order.
dbSortPDXNor | Paradox Norwegian and Danish collating order.
dbSortPDXSwe | Paradox Swedish and Finnish collating order.
dbSortPolish | Polish collating order.
dbSortSpanish | Spanish collating order.
dbSortSwedFin | Swedish and Finnish collating order.
dbSortTurkish | Turkish collating order.
dbSortUndefined | Collating order undefined or unknown.

EditMode Property Constants

All of the following constants are read-only.

Constant | Description
dbEditNone | No editing operation in effect.
dbEditInProgress | Edit method invoked.
dbEditAdd | AddNew method invoked.

Permissions Property Constants

Container.Permissions Property

All of the following constants are read/write.

Constant | Description
dbSecNoAccess | No access to the object.
dbSecFullAccess | Has full access to the object.
dbSecDelete | Can delete the object.
dbSecReadSec | Can read the object's security-related information.
dbSecWriteSec | Can alter access permissions.
dbSecWriteOwner | Can change the Owner property setting.

Databases Container.Permissions Property

All of the following constants are read/write.

Constant | Description
dbSecDBAdmin | Gives user permission to make a database replicable and change the database password.
dbSecDBCreate | Can create new databases (valid only on the databases Container object in the system database).
dbSecDBOpen | Can open the database.
dbSecDBExclusive | Has exclusive access.

Tables Container.Permissions Property

All of the following constants are read/write.

Constant | Description
dbSecCreate | Create new tables (valid only with a Container object that represents a table or with the databases Container object in the system database).
dbSecReadDef | Read the table definition, including column and index information.
dbSecWriteDef | Modify or delete table definition, including column and index information.
dbSecRetrieveData | Retrieve data from the document.
dbSecInsertData | Add records.
dbSecReplaceData | Modify records.
dbSecDeleteData | Delete records.

Document.Permissions Property

All of the following constants are read/write.

Constant | Description
dbSecCreate | Create new tables (valid only with a Container object that represents a table).
dbSecDBCreate | Can create new databases (valid only on the databases Container object in the system database).
dbSecDelete | Can delete the object.

Constant | Description
dbSecDBOpen | Can open the database.
dbSecDBExclusive | Has exclusive access.
dbSecDelete | Can delete the object.
dbSecDeleteData | Delete records.
dbSecFullAccess | Has full access to the object.
dbSecInsertData | No access to the object.
dbSecReadDef | Read the table definition, including column and index information.
dbSecReadSec | Can read the object's security-related information.
dbSecReplaceData | Modify records.
dbSecRetrieveData | Retrieve data from the document.
dbSecWriteDef | Modify or delete table definition, including column and index information.
dbSecWriteSec | Can alter access permissions.
dbSecWriteOwner | Can change the Owner property setting.

Type Property Constants

Field.Type Property, Parameter.Type Property, Property.Type Property

All of the following constants are read/write.

Constant | Description
dbBoolean | Boolean (True/False) data.
dbByte | Byte (8-bit) data.
dbInteger | Integer data.
dbLong | Long Integer data.
dbCurrency | Currency data.
dbSingle | Single-precision floating-point data.
dbDouble | Double-precision floating-point data.
dbDate | Date value data.
dbText | Text data (variable width).
dbLongBinary | Binary data (bitmap).
dbMemo | Memo data (extended text).
dbGUID | GUID data.

QueryDef.Type Property

All of the following constants are read-only.

Constant | Description
dbQSelect | SELECT query.
dbQAction | Action query.
dbQCrosstab | Crosstab query.
dbQDelete | DELETE query.
dbQUpdate | UPDATE query.
dbQAppend | APPEND query.
dbQMakeTable | Make-table query.
dbQDDL | Data definition language (DDL) query.
dbQSQLPassThrough | SQL pass-through query.
dbQSetOperation | Set operation query.
dbQSPTBulk | Bulk operation query.

Recordset.Type Property

All of the following constants are read-only.

Constant | Description
dbOpenTable | Open table-type Recordset.
dbOpenDynaset | Open dynaset-type Recordset.
dbOpenSnapshot | Open snapshot-type Recordset.

CompactDatabase, CreateDatabase Methods

The following constants are for the locale argument. All are read/write.

Constant | Description
dbLangArabic | Arabic collating order.
dbLangCyrillic | Russian collating order.
dbLangCzech | Czech collating order.
dbLangDutch | Dutch collating order.
dbLangGeneral | English, German, French, Portuguese, Italian, and Modern Spanish collating order.
dbLangGreek | Greek collating order.
dbLangHebrew | Hebrew collating order.
dbLangHungarian | Hungarian collating order.
dbLangIcelandic | Icelandic collating order.
dbLangJapanese | Japanese collating order.

Constant | Description
dbLangNeutral | Neutral collating order.
dbLangNordic | Nordic collating order.
dbLangNorwdan | Norwegian and Danish collating order.
dbLangPolish | Polish collating order.
dbLangSpanish | Spanish collating order.
dbLangSwedfin | Swedish and Finnish collating order.
dbLangTurkish | Turkish collating order.

CompactDatabase Method

The following constants are for the options argument. All are read/write.

Constant | Description
dbDecrypt | Decrypt database while compacting.
dbEncrypt | Encrypt database.
dbVersion10 | Microsoft Jet database engine version 1.0.
dbVersion11 | Microsoft Jet database engine version 1.1.
dbVersion20 | Microsoft Jet database engine version 2.0.
dbVersion30 | Microsoft Jet database engine version 3.0.

CreateDatabase Method

The following constants are for the options argument. All are read/write.

Constant | Description
dbEncrypt | Encrypt database.
dbVersion10 | Microsoft Jet database engine version 1.0.
dbVersion11 | Microsoft Jet database engine version 1.1.
dbVersion20 | Microsoft Jet database engine version 2.0.
dbVersion30 | Microsoft Jet database engine version 3.0.

Execute Method

The following constants are for the options argument. All are read/write.

Constant | Description
dbDenyWrite | Deny write permission to other users.
dbInconsistent | Inconsistent updates.
dbConsistent | Consistent updates.
dbSQLPassThrough | SQL pass-through. Causes the SQL statement to be passed to an ODBC database for processing.
dbFailOnError | Rolls back updates if an error occurs.
dbSeeChanges | Generates a run-time error if another user is changing data you are editing.

Idle Method

The following constant is for the optional argument.

Constant | Description
dbFreeLocks | Read/write. Delay processing until all read locks are released.

OpenRecordset Method

The following constants are for the type argument. All are read/write.

Constants | Description
dbOpenTable | Open table-type Recordset.
dbOpenDynaset | Open dynaset-type Recordset.
dbOpenSnapshot | Open snapshot-type Recordset.

The following constants are for the options argument. All are read/write.

Constant | Description
dbDenyWrite | Other users can't change Recordset records.
dbDenyRead | Other users can't read Recordset records.
dbReadOnly | Open the Recordset as read-only.
dbAppendOnly | You can add new records to the dynaset, but you can't read existing records.
dbInconsistent | Updates apply to all dynaset fields, even if other records are affected.
dbConsistent | Updates apply only to those fields that will not affect other records in the dynaset.
dbSQLPassThrough | Sends an SQL statement to an ODBC database.
dbForwardOnly | Create a forward-only scrolling snapshot-type Recordset.

MakeReplica Method

The following constant is for the optional argument.

Constant | Description
dbRepMakeReadOnly | Read/Write. Replicable elements of new database are read-only.

Synchronize Method

The following constants are for the exchange argument.

Constant | Description
dbRepExportChanges | Read/Write. Send changes from current database to target database.
dbRepImportChanges | Read/Write. Receive changes from target database.


Database Object

Description

A Database object represents an open database.

Remarks

You manipulate an open database using a Database object and its methods and properties. You can examine the collections in a Database object to learn about its tables, queries, and relationships. You can also use its collections to modify or create tables, queries, recordsets, and relationships. For example, you can:

  • Use the Execute method to run an action QueryDef object or pass an SQL string to an ODBC database.
  • Use the OpenRecordset method to create a new Recordset object directly from the Database object.
  • Use the Close method to close an open database.
 You use the CreateDatabase method to create a new, persistent Database object and append it to the Databases collection, thereby saving it to disk. After you create a new database, you must create new tables to hold your data. You can also create new indexes and table relationships, attach existing external tables, or establish a protection scheme using permissions, groups, and users.

To open an existing Database object, use the OpenDatabase method, which appends the object to the Databases collection. The OpenDatabase method applies to the Workspace object. You can use the OpenDatabase method on the default Workspace(0) object, or on a different opened Workspace object.

When you use one of the transaction methods (BeginTrans, CommitTrans, or Rollback) on the Workspace object, these transactions apply to all databases opened on the Workspace from which the Database object was opened. If you want to use independent transactions, you must first open an additional Workspace object, and then open another Database object in that Workspace object. For example, the following creates two independent Database objects:

Dim dbsThisOne As Database, dbsThatOne As Database
Dim wspFirst As Workspace, wspSecond As Workspace
Dim strUserName As String
Set wspFirst = Workspaces(0)    ' Use the default Workspace.
Set dbsThisOne = wspFirst.OpenDatabase("Biblio.mdb")

' Get UserName of default Workspace.
strUserName = wspFirst.UserName
' Create new Workspace.
Set wspSecond = DBEngine.CreateWorkspace("Special", strUserName, _
    "SpecialPW")
Set dbsThatOne = wspSecond.OpenDatabase("Biblio.mdb")
You don't need to specify the DBEngine object when using the OpenDatabase method. If you need to open a Database object in a separate transaction context, then you must reference a specific Workspace object. For example, the following statements are equivalent:

Set dbsBiblio = DBEngine.Workspaces(0).OpenDatabase("Biblio.mdb")
Set dbsBiblio = Workspaces(0).OpenDatabase("Biblio.mdb")
Set dbsBiblio = OpenDatabase("Biblio.mdb")
Opening a database with attached tables doesn't automatically establish links to the specified external files or external ODBC databases; either the table's TableDef or Field objects must be referenced, or a Recordset object opened on it. If links to these tables can't be established, a trappable error occurs. You may also need permission to access the database, or the database may already be open for exclusive use by another user. In these cases, trappable errors occur.

You can also open an external database (such as FoxPro, dBASE, and Paradox) directly instead of opening a Microsoft Jet database that has links to its tables. See the OpenDatabase method for more information.

For example, to open a FoxPro database, you could use the following code.

Dim dbsFoxFiles As Database
Set dbsFoxFiles = Workspaces(0).OpenDatabase("C:\FoxFiles", _
    False,False,"FoxPro 2.5")
Note

Opening a Database object directly on an ODBC data source such as Microsoft SQLServer is not recommended because query performance is much slower than when using linked tables. Performance is not a problem with opening a Database object on an external ISAM database, such as FoxPro, Paradox, etc.

You use the Close method to remove a Database object from the Databases collection without deleting it from disk. Any open Recordset objects in the database are closed automatically when the Database object is closed.

When a procedure that declares a Database object completes execution, these local Database objects are closed along with any open Recordset objects. Any pending updates are lost and any pending transactions are rolled back, but no trappable error occurs. You should explicitly complete any pending transactions or edits and close Recordset objects and Database objects before exiting procedures that declare these object variables locally.

The first database opened is Databases(0). The Name property setting of a database is a string that specifies the path of the database file. The Connect property specifies the database type and any other parameters used to connect to external databases. You can refer to any Database object by its Name property setting using this syntax:

Databases("name")

You can also refer to the object by its ordinal number using this syntax (which refers to the first member of the Databases collection):

Databases(0)

Properties

CollatingOrder Property, Connect Property, Name Property, QueryTimeout Property, RecordsAffected Property, Replicable Property, ReplicaID Property, Transactions Property, Updatable Property, Version Property.

Methods

Close Method, CreateProperty Method, CreateQueryDef Method, CreateRelation Method, CreateTableDef Method, Execute Method, MakeReplica Method, NewPassword Method, OpenRecordset Method, Synchronize Method.

See Also

OpenDatabase Method; Appendix, "Data Access Object Hierarchy."

Specifics (Microsoft Access)

When working with data access objects from Microsoft Access, you will often need a Database object variable that represents the current database. Use the CurrentDb function to return a Database object for the database that is currently open. This Database object is automatically appended to the Databases collection.

For example, suppose you are currently working with the Northwind sample database in Microsoft Access. You can create a Database object that refers to that database by first declaring a Database object variable, then pointing it to the Database object returned by the CurrentDb function.

Dim dbs As Database
Set dbs = CurrentDb
You don't need to know the name of the database or its position in the Databases collection in order to use the current database. If you do want to know the name of the current database, check the Name property of the Database object, which contains the path and filename of the database. To find its position in the Databases collection, enumerate through the collection.

You can open only one database at a time in the Microsoft Access window. From Visual Basic code, however, you can create multiple independent Database object variables to represent multiple open databases. In this way, you can manipulate more than one database at a time from code. You can also create multiple Database object variables and point them to the current database.

Note

In your Visual Basic code, use the CurrentDb function to return a Database object that refers to the current database, rather than the DBEngine(0)(0) syntax. The CurrentDb function creates another instance of the current database, while the DBEngine(0)(0) syntax refers to the open copy of the current database. Using the CurrentDb function enables you to create more than one variable of type Database that refers to the current database. Microsoft Access still supports the DBEngine(0)(0) syntax, but you should consider making this modification to your code in order to avoid possible conflicts in a multiuser environment.

Example

This example creates a new Database object and opens it (thereby appending it to the Databases collection) in the default Workspace object. Then it enumerates all the collections contained by each Database object and the properties of the new Database object and closes the new Database.

Function EnumerateDatabase () As Integer
    Dim wrkDefault As Workspace
    Dim dbsEnum As Database, dbsTemp As Database
    Dim intOBJ As Integer, intDB As Integer
    Set wrkDefault = Workspaces(0)
    Set dbsEnum = wrkDefault.CreateDatabase("Northwind.mdb", _
        dbLangGeneral)
' Enumerate all open databases.
    For intDB = 0 To wrkDefault.Databases.Count - 1
        Set dbsTemp = wrkDefault.Databases(intDB)
        Debug.Print
        Debug.Print "Enumeration of Databases: "; dbsTemp.Name
        Debug.Print
' Enumerate containers.
        Debug.Print "Container: Name, Owner"
        For intOBJ = 0 To dbsTemp.Containers.Count - 1
            Debug.Print "  "; dbsTemp.Containers(intOBJ).Name;
            Debug.Print ", "; dbsTemp.Containers(intOBJ).Owner
        Next intOBJ
        Debug.Print
' Enumerate query definitions.
        Debug.Print "QueryDef: Name"
        For intOBJ = 0 To dbsTemp.QueryDefs.Count - 1
            Debug.Print "  "; dbsTemp.QueryDefs(intOBJ).Name
        Next intOBJ
        Debug.Print
' Enumerate Recordsets.
' No output because no Recordset is open.
        Debug.Print "Recordset: Name"
        For intOBJ = 0 To dbsTemp.Recordsets.Count - 1
            Debug.Print "  "; dbsTemp.Recordsets(intOBJ).Name
        Next intOBJ
        Debug.Print

' Enumerate relationships.
        Debug.Print "Relation: Name, Table, ForeignTable"
        For intOBJ = 0 To dbsTemp.Relations.Count - 1
            Debug.Print "  "; dbsTemp.Relations(intOBJ).Name;
            Debug.Print ", "; dbsTemp.Relations(intOBJ).Table;
            Debug.Print ", "; dbsTemp.Relations(intOBJ).ForeignTable
        Next intOBJ
        Debug.Print
' Enumerate table definitions.
        Debug.Print "TableDef: Name, DateCreated"
        For intOBJ = 0 To dbsTemp.TableDefs.Count - 1
            Debug.Print "  "; dbsTemp.TableDefs(intOBJ).Name;
            Debug.Print ", "; dbsTemp.TableDefs(intOBJ).DateCreated
        Next intOBJ
        Debug.Print
    Next intDB
' Enumerate built-in properties of dbsEnum.
    Debug.Print " dbsEnum.Name: "; dbsEnum.Name
    Debug.Print " dbsEnum.CollatingOrder: "; dbsEnum.CollatingOrder
    Debug.Print " dbsEnum.Connect: "; dbsEnum.Connect
    Debug.Print " dbsEnum.QueryTimeout: "; dbsEnum.QueryTimeout
    Debug.Print " dbsEnum.Transactions: "; dbsEnum.Transactions
    Debug.Print " dbsEnum.Updatable: "; dbsEnum.Updatable
    Debug.Print
    dbsEnum.Close    ' File remains on disk.
    EnumerateDatabase = True
End Function
Example (Microsoft Access)

The following example show three ways to return a Database object in Microsoft Access. The procedure returns a Database object representing the current database, which is open in the Microsoft Access window. Next, the procedure creates another database called Newdb.mdb and saves it to disk. Then it opens an existing database called Another.mdb. Finally, it enumerates all Database objects in the Databases collection.

Sub ReferenceDatabases()
    Dim wsp As Workspace
    Dim dbsCurrent As Database, dbsNew As Database,
    Dim dbsAnother As Database, dbs As Database

    ' Return Database object pointing to current database.
    Set dbsCurrent = CurrentDb
    ' Return Workspace object pointing to current workspace.
    Set wsp = DBEngine.Workspaces(0)
    ' Create new Database object.
    Set dbsNew = wsp.CreateDatabase("Newdb.mdb", dbLangGeneral)
    ' Open database other than current database.
    set dbsAnother = wsp.OpenDatabase("Another.mdb", dbLangGeneral)
    ' Enumerate all open databases.

    For Each dbs in wsp.Databases
        Debug.Print dbs.Name
    Next dbs
End Sub


Databases Collection

Description

A Databases collection contains all open Database objects opened or created in a Workspace object of the Microsoft Jet database engine.

Remarks

When you open an existing Database object or create a new one from a Workspace, it is automatically appended to the Databases collection. When you close a Database object with the Close method, it is removed from the Databases collection but not deleted from disk. You should close all open Recordset objects before closing a Database object.

The first database that is opened is appended to the collection as Databases(0). The Name property setting of a database is a string that specifies the path of the database file. You can refer to any Database object in a collection by its Name property using this syntax:

Databases("name")

You can also refer to the object by its ordinal number using this syntax (which refers to the first member of the Databases collection):

Databases(0)

Properties

Count Property.

Methods

Refresh Method.

See Also

Appendix, "Data Access Object Hierarchy."

Specifics (Microsoft Access)

See the Database object specifics (Microsoft Access).

Example

See the Database object example.

Example (Microsoft Access)

See the Database object example (Microsoft Access).


DataUpdatable Property

Applies To

Field Object.

Description

Returns a value that indicates whether the data in the field represented by a Field object is updatable. Returns a True (-1) if the data in the field is updatable.

Remarks

Use this property to determine whether you can change the Value property setting of a Field object. The DataUpdatable property is always read-only. It is not supported on Field objects appended to the Fields collection of Index and Relation objects.

See Also

Updatable Property, Value Property.

Example (Microsoft Access)

The following example creates two Recordset objects, a dynaset-type Recordset object and a snapshot-type Recordset object, from the same table. The procedure then checks the DataUpdatable property for the LastName field in each Recordset object. The value of the DataUpdatable property is True (-1) for the dynaset-type Recordset object, and False (0) for the snapshot-type Recordset object.

Sub CheckUpdatable()
    Dim dbs As Database
    Dim rstDynaset As Recordset, rstSnapshot As Recordset
    Dim fldDynaset As Field, fldSnapshot As Field

    ' Return Database variable that points to current database.
    Set dbs = CurrentDb
    ' Open dynaset-type Recordset object.
    Set rstDynaset = dbs.OpenRecordset("Employees", dbOpenDynaset)
    ' Open snapshot-type Recordset object.
    Set rstSnapshot = dbs.OpenRecordset("Employees", dbOpenSnapshot)
    ' Get Field object variables pointing to field in each Recordset
    'object.
    Set fldDynaset = rstDynaset.Fields!LastName
    Set fldSnapshot = rstSnapshot.Fields!LastName
    ' Get current record.
    rstDynaset.MoveFirst
    rstSnapshot.MoveFirst
    ' Display value of DataUpdatable property for each Recordset object.
    Debug.Print "DataUpdatable (Dynaset-type Recordset): "; _
        fldDynaset.DataUpdatable
    Debug.Print "DataUpdatable (Snapshot-type Recordset): "; _
        fldSnapshot.DataUpdatable
End Sub


DateCreated, LastUpdated Properties

Applies To

Document Object, QueryDef Object, Recordset Object, Table-Type Recordset Object, TableDef Object.

  • DateCreated — returns the date and time that the object was created (or the base table if the object is a table-type Recordset object).
  • LastUpdated — returns the date and time of the most recent change made to the object (or the base table if the object is a table-type Recordset object).
 Return Values

This property returns a Date/Time data type.

Remarks

You can use the DateCreated and LastUpdated properties with Recordset, TableDef, QueryDef, and Document objects.

For table-type Recordset objects, the date and time settings are derived from the computer on which the base table was created or last updated. For other objects, this property returns the date and time that the object was created or last updated. In a multiuser environment, users should get these settings directly from the file server to avoid discrepancies in the DateCreated and LastUpdated property settings.

Example

This example determines the date and time when the Employees table was created and last updated.

Dim varCreation As Variant, varDesignChange As Variant
Dim rstEmployees As Recordset, dbsNorthwind As Database
Set dbsNorthwind = DBEngine.Workspaces(0).OpenDatabase("Northwind.mdb")
Set rstEmployees = dbsNorthwind.OpenRecordset("Employees", dbOpenTable)
varCreation = rstEmployees.DateCreated
varDesignChange = rstEmployees.LastUpdated
Example (Microsoft Access)

The following example enumerates through all QueryDef objects in the database and lists those which have been created or changed within the last week.

Sub TimeUpdated()
    Dim dbs As Database, tdf As TableDef, qdf As QueryDef
    Dim strList As String, intI As Integer
    Dim dteWeek As Date

    ' Return Database variable that points to current database.
    Set dbs = CurrentDb
    dteWeek = Now - 7
     intI = 0
    ' Enumerate through QueryDefs collection.
    For Each qdf In dbs.QueryDefs
        ' Evaluate LastUpdated and DateCreated properties.
        If (qdf.LastUpdated > dteWeek) Or (qdf.DateCreated > dteWeek) _             Then
            ' Create list.

            strList = strList & Chr(13) & Chr(10) & qdf.Name
        End If
        intI = intI + 1
    Next qdf
    MsgBox strList
End Sub
Example (Microsoft Excel)

This example displays the dates and times when the Customer recordset in the NWINDEX.MDB database was created and last updated.

To create the NWINDEX.MDB database, run the Microsoft Excel example for the CreateDatabase method.

Dim creation As Variant, changed As Variant
Dim db As Database, td As TableDef
Set db = Workspaces(0).OpenDatabase(Application.Path & "\NWINDEX.MDB")
Set td = db.TableDefs("Customer")
creation = td.DateCreated
changed = td.LastUpdated
MsgBox "The " & td.Name & " table was created on " & creation _
    & " and updated on " & changed
db.Close


DBEngine Object

Description

The DBEngine object represents the Microsoft Jet database engine. As the top-level object, it contains and controls all other objects in the hierarchy of data access objects.

Remarks

Use the DBEngine object to control the Jet database engine, manipulate its properties, and perform tasks on temporary objects that aren't elements of collections. For example, you can:

  • Use the Version property to obtain the version number of the Jet engine, the LoginTimeout property to obtain or set the ODBC login timeout, and the RegisterDatabase method to provide ODBC information to the Jet engine.
  • Use the Idle method to enable the Jet engine to complete any pending tasks and the CompactDatabase and RepairDatabase methods to maintain database files.
  • Use the CreateWorkspace method to create a new session.
  • Use the Errors collection to examine data access error details.
 The DBEngine object is a predefined object; you can't create additional DBEngine objects. To refer to a collection that belongs to the DBEngine object, or to refer to a method or property that applies to this object, use this syntax:

[DBEngine.][collection | method | property]

The DBEngine object isn't an element of any collection.

Properties

DefaultUser, DefaultPassword Properties; IniPath Property; LoginTimeout Property; Version Property.

Methods

CompactDatabase Method, CreateWorkspace Method, Idle Method, RegisterDatabase Method, RepairDatabase Method.

See Also

Appendix, "Data Access Object Hierarchy."

Specifics (Microsoft Access)

Microsoft Access provides a means of manipulating data access objects from other applications through OLE Automation. If you are controlling Microsoft Access from another application, such as Visual Basic or Microsoft Excel, you can use the DBEngine property of the Microsoft Access Application object to return a reference to the DBEngine object. All data access objects and collections are then accessible through the DBEngine object.

Example

This example enumerates the collections of the DBEngine object. See the methods and properties of DBEngine for additional examples.

Function EnumerateDBEngine () As Integer
    Dim wrkEnum As Workspace, intWSP As Integer
    Debug.Print "Enumeration of DBEngine"
    Debug.Print
    ' Enumerate all workspaces.
    Debug.Print "Workspaces: Name, UserName"
    For intWSP = 0 To Workspaces.Count - 1
        Set wrkEnum = Workspaces(intWSP)
        Debug.Print "  "; wrkEnum.Name;
        Debug.Print ", "; wrkEnum.UserName
    Next intWSP
    Debug.Print
    ' Enumerate built-in properties.
    Debug.Print "DBEngine.Version: "; DBEngine.Version
    Debug.Print "DBEngine.LoginTimeout: "; DBEngine.LoginTimeout
    EnumerateDBEngine = True
End Function
Example (Microsoft Access)

The following example prints all the properties of the DBEngine object.

Sub EngineProperties()
    Dim prp As Property

    For Each prp In DBEngine.Properties
        Debug.Print prp.Name
    Next prp
End Sub


DefaultUser, DefaultPassword Properties

Applies To

DBEngine Object.

  • DefaultUser — sets the user name used by the Microsoft Jet database engine when it is initialized.
  • DefaultPassword — sets the password used by the Microsoft Jet database engine when it is initialized.
 Settings

The setting for user name can be 1–20 characters long and can include alphabetic characters, accented characters, numbers, spaces, and symbols except for: " (quotation marks), / (forward slash), \ (backslash), [ ] (brackets), : (colon), | (pipe), < (less-than sign), > (greater-than sign), + (plus sign), = (equal sign), ; (semicolon), , ( comma), ? (question mark), * (asterisk), leading spaces, and control characters (ASCII 00 to ASCII 31).

The setting for password can be up to 14 characters long and can contain any character except ASCII 0. The data type is String.

Remarks

User names aren't usually case-sensitive; however, if you're re-creating a user account that was deleted or created in a different workgroup, the user name must be an exact case-sensitive match of the original name. Passwords are case-sensitive.

Typically, the CreateWorkspace method is used to create a Workspace object with a given user name and password. However, for backward compatibility with earlier versions and for convenience when secured databases aren't being used, the Jet engine automatically creates a default Workspace object when needed if one isn't already open. In this case, the DefaultUser and DefaultPassword property values define the user and password for the default Workspace object.

By default, the DefaultUser property is set to "admin" and the DefaultPassword property is set to a zero-length string ("").

For this property to take effect, it should be set before any data access functions are called.


DefaultValue Property

Applies To

Field Object.

Description

Sets or returns the default value of a Field object. For a Field object not yet appended to the Fields collection, this property is read/write.

Settings and Return Values

The setting or return value for this property is a string expression, which can contain a maximum of 255 characters. It can be either text or an expression. If the property setting is an expression, it can't contain user-defined functions; Microsoft Jet database engine SQL aggregate functions; or references to queries, forms, or other Field objects.

Note

You can also set the DefaultValue property of a Field object on a TableDef object to a special value called "GenUniqueId( )". This causes a random number to be assigned to this field whenever a new record is added or created. The field's Type property must be Long.

Remarks

Use of the DefaultValue property depends on the parent object of the Field objects, as shown in the following table.

Object appended to | Usage
Index | Not supported
QueryDef | Read-only
Recordset | Read-only
Relation | Not supported
TableDef | Read/write

When a new record is created, the DefaultValue property setting is automatically entered as the value for the field. You can change the field value by setting its Value property.

The DefaultValue property doesn't apply to Counter and OLE Object fields.

See Also

AllowZeroLength Property, QueryDef Object, Required Property, TableDef Object, ValidateOnSet Property, ValidationRule Property, ValidationText Property, Value Property.

Specifics (Microsoft Access)

If the DefaultValue property setting is an expression, it can't contain user-defined functions, Microsoft Access domain aggregate functions, SQL aggregate functions, the CurrentUser function, the Eval function, or references to queries, forms, or other Field objects.

Example (Microsoft Access)

The following example creates a new Field object and sets its DefaultValue property. The procedure then appends the new object to the Fields collection of the Employees table in the TableDefs collection of the database.

Sub NewField()
    Dim dbs As Database, tdf As TableDef
    Dim fld As Field

    ' Return Database object that points to current database.
    Set dbs = CurrentDb
    ' Return TableDef variable pointing to Employees table.
    Set tdf = dbs.TableDefs!Employees
    ' Create Field object.
    Set fld = tdf.CreateField("DaysOfVacation", dbText, 20)
    ' Set field properties.
    fld.DefaultValue = "10"
    ' Append fld to Fields collection.
    tdf.Fields.Append fld
End Sub


Delete Method

Applies To

Dynaset-Type Recordset Object, Fields Collection, Groups Collection, Indexes Collection, Properties Collection, QueryDefs Collection, Recordset Object, Relations Collection, Table-Type Recordset Object, TableDefs Collection, Users Collection, Workspaces Collection.

  • Recordset objects — deletes the current record in an open dynaset-type or table-type Recordset object.
  • Collections — deletes a stored object from a collection.
 Syntax

recordset.Delete

collection.Delete objectname

The Delete method syntax has these parts.

Part | Description
recordset | A variable of an object data type identifying an open dynaset-type or table-type Recordset object containing the record you want to delete.
collection | A variable of an object data type identifying a collection.
objectname | A String that is the Name property setting of an object in collection.

Remarks

You can use the Delete method to delete a current record from a recordset or a member from a collection, such as a stored table from a database, a stored field from a table, and a stored index from a table.

Recordsets

When you delete records from a recordset, the recordset must contain a current record before you use Delete; otherwise, a trappable error occurs.

In table- and dynaset-type Recordset objects, Delete removes the current record and makes it inaccessible. Although you can't edit or use the deleted record, it remains current. Once you move to another record, however, you can't make the deleted record current again. Subsequent references to a deleted record in a Recordset are invalid and produce an error.

You can undelete a record if you use transactions and the Rollback method.

If the base table is the primary table in a cascade delete relationship, deleting the current record may also delete one or more records in a foreign table.

Collections

You can use the Delete method to delete a persistent object. However, if the collection is a Databases, Recordsets, or Workspaces collection (each of which is stored only in memory), you can remove an open or active object only by closing that object using the Close method.

The deletion of a stored object occurs immediately, but you should use the Refresh method on any other collections that may be affected by changes to the database structure.

When you delete a TableDef object from the TableDefs collection, you delete the table definition and the data in the table.

The following table shows some limitations on the use of the Delete method. The object in the first column contains the collection in the second column. The third column indicates when, if ever, you can delete an object from that collection (for example, you can never delete a Container object from the Containers collection of a Database object).

Object | Collection | When you can use Delete method
DBEngine | Workspaces | Never; use the Close method instead
Workspace | Databases | Never; use the Close method instead
Database | Containers | Never
Database | Recordsets | Never; use the Close method instead
Container | Documents | Never

Object | Collection | When you can use Delete method
Index | Fields | On new objects that haven't been appended to the database
QueryDef | Fields | Never
QueryDef | Parameters | Never
Recordset | Fields | Never
Relation | Fields | On new objects that haven't been appended to the database
TableDef | Fields | On new objects that haven't been appended to the database or when the Updatable property of the TableDef is set to True
TableDef | Indexes | On new objects that haven't been appended to the database or when the Updatable property of the TableDef is set to True
Database, Field, Index, QueryDef, TableDef | Properties | When the property is user-defined

See Also

AddNew Method, Append Method, Close Method, Count Property, Name Property, Refresh Method.

Example

This example finds a record in a Recordset and deletes it.

' Find the record you want to delete.
rstPublications.FindFirst "PubNum = 9"
If Not rstPublications.NoMatch Then    ' Check if record found.
    rstPublications.Delete    ' Delete the record.
End If
This example adds and then deletes an Index from a TableDef.

Dim dbsBiblio As Database
Dim tdfAuthors As TableDef
Dim idxAuthorName As Index, fldAuthor As Field
' Open the database.
Set dbsBiblio = DBEngine.Workspaces(0).OpenDatabase("Biblio.mdb")
' Set the TableDef.
Set tdfAuthors = dbsBiblio.TableDefs("Authors")
Set idxAuthorName = tdfAuthors.CreateIndex("Author Name")
Set fldAuthor = idxAuthorName.CreateField("Author")
idxAuthorName.Fields.Append fldAuthor    ' Add Field to Index.
' Append Index to TableDef.
tdfAuthors.Indexes.Append idxAuthorName
tdfAuthors.Indexes.Delete "Author Name"    ' Delete the Index.
Example (Microsoft Access)

The following example creates a field in a table and then deletes the field.

Sub DeleteField()
    Dim dbs As Database, tdf As TableDef
    Dim fldInitial As Field, fld As Field

    ' Return Database variable pointing to current database.
    Set dbs = CurrentDb
    Set tdf = dbs.TableDefs!Orders
    ' Create new Field object, specifying name, type, and size.
    Set fldInitial = tdf.CreateField("MiddleInitial", dbText, 2)
    ' Append new Field object.
    tdf.Fields.Append fldInitial
    ' Enumerate through Fields collection to find new Field object.
    For Each fld In tdf.Fields
        If fld.Name = "MiddleInitial" Then
            ' Delete new Field object.
            tdf.Fields.Delete fld.Name
            MsgBox "Field deleted."
        End If
    Next fld
End Sub
Example (Microsoft Excel)

This example adds a new record to PRODUCT.DBF (a dBASE IV table located in the C:\Program Files\Common Files\Microsoft Shared\MSquery folder) and then deletes it. (On Windows NT, PRODUCT.DBF is located in the \WINDOWS\MSAPPS\MSQUERY folder.)

Const sourceDir = "C:\Program Files\Common Files\Microsoft Shared\MSQuery"
Dim db As Database, rs As Recordset
Sheets("Sheet1").Activate
Set theID = ActiveSheet.Cells(1, 2)
Set theCategory = ActiveSheet.Cells(2, 2)
theID.Value = 200
theCategory.Value = "BEVR"
Set db = OpenDatabase(sourceDir, False, False, "dBASE IV")
Set rs = db.OpenRecordset("PRODUCT.DBF", dbOpenTable)
rs.AddNew
rs("PRODUCT_ID") = theID.Value
rs("CATEGORY") = theCategory.Value
rs.Update
MsgBox "The new record has been created with " & theID.Value _
    & " and " & theCategory.Value
rs.Move 0, rs.LastModified
rs.Delete
MsgBox "The record you just created has been deleted"
rs.Close
db.Close


Description Property

Applies To

Error Object.

Description

Returns a descriptive string associated with an error.

Remarks

The Description property comprises a short description of the error. Display this property to alert the user to an error that you cannot or do not want to handle.

See Also

HelpContext, HelpFile Properties; Number Property; Source Property.

Specifics (Microsoft Access)

The data access Description property applies to the Error object and returns a string associated with an error. You can set it only from Visual Basic.

Note

Don't confuse this property with the Microsoft Access Description property, which describes a table or query and its fields. This property applies to a TableDef object, a QueryDef object, or a Field object in the Fields collection of a TableDef or QueryDef object.

Example

This example forces an error, traps it, and displays the Description, Number, and Source properties of the resulting Error object.

Sub ForceError()
    Dim dbsTest As Database
    On Error GoTo TestErrorHandler
    Set dbsTest = OpenDatabase("DoesNotExist")
    Exit Sub

TestErrorHandler:
    Dim strError As String
    Dim errObj As Error
    strError = " "
    For Each errObj in DBEngine.Errors
        strError = strError & Format$(errObj.Number)
        strError = strError & " : " & errObj.Description
        strError = strError & " (" & errObj.Source & ") . "
        strError = strError & Chr$(13) & Chr$(10)
    Next
    MsgBox strError
    Resume Next
End Sub


DesignMasterID Property

Applies To

Database Object.

Description

Sets or returns a 16-byte, OLE 2 GUID, created by the Microsoft Jet database engine, that uniquely identifies the Design Master in a replica set.

Remarks

The DesignMasterID property setting is stored in the MSysReplicas system table. Setting the DesignMasterID property gives a specific replica in the replica set design-master status. The DesignMasterID property can be set only if you are at the current Design Master. Under extreme circumstances, for example, the loss of the original Design Master, you can set the value at another replica. However, setting this value at a replica, when there is already another Design Master, might partition your replica set into two irreconcilable sets and prevent any further synchronization of data.

Warning

This property should be set only at the current Design Master. Setting this property at a replica, when there is already another Design Master, can partition your replica set into two irreconcilable sets and prevent any further synchronization of data. You can set the property at another replica only if the original Design Master is lost or erased. This will designate the current replica as the new Design Master.

See Also

ReplicaID Property.

Example

This example sets the DesignMasterID property to the ReplicaID property setting of another database giving that database design-master status in the replica set.

' Open current Design Master in exclusive mode.
Set dbs = DBEngine(0).OpenDatabase(strOldDM, True)
' Open new Design Master.
set newdmdb = DBEngine(0).OpenDatabase(strNewDB)

dbs.DesignMasterID = newdmdb.ReplicaID
dbs.Synchronize strNewDB,dbRepImpExpChanges

dbs.Close
newdmdb.Close


DistinctCount Property

Applies To

Index Object.

Description

Returns a value that indicates the number of unique values for the Index object that are included in the associated table.

Return Values

This property returns a Long data type.

Remarks

Check the DistinctCount property to determine the number of unique values, or keys, in an index. Any key is counted only once, even though there may be multiple occurrences of that value if the index permits duplicate values. This information is useful in applications that attempt to optimize data access by evaluating index information. The number of unique values is also known as the cardinality of an Index object.

The DistinctCount property won't always reflect the actual number of keys at a particular time. For example, a change caused by a transaction rollback won't be reflected immediately in the DistinctCount property. The number will be accurate immediately after using the CreateIndex method.

Example

This example checks the DistinctCount property of an Index of a TableDef object opened on a table in the database.

Dim dbsNorthwind As Database, tdfCustomers As TableDef
Dim idxCurrent As Index
Set dbsNorthwind =  DBEngine.Workspaces(0).OpenDatabase("Northwind.mdb")
Set tdfCustomers = dbsNorthwind!Customers
Set idxCurrent = tdfCustomers.Indexes(0)
Debug.Print idxCurrent.DistinctCount
Example (Microsoft Access)

The following example prints the number of unique values in the indexes on the OrderID and OrderDate fields of an Orders table. Note that the DistinctCount property is guaranteed to return the number of unique values in an index only immediately after an index has been created with the CreateIndex method, or after a database has been compacted or converted using the CompactDatabase method.

Sub CountKeys()
    Dim dbs As Database, tdf As TableDef
    Dim idx As Index, fldOrderID As Field, fldOrderDate As Field

    ' Return Database variable that points to current database.
    Set dbs = CurrentDb
    ' Return TableDef object pointing to Orders table.
    Set tdf = dbs.TableDefs!Orders
    ' Create new index.
    Set idx = tdf.CreateIndex("OrderIDDate")
    ' Create and append index fields.
    Set fldOrderID = idx.CreateField("OrderId", dbLong)

    Set fldOrderDate = idx.CreateField("OrderDate", dbDate)
    idx.Fields.Append fldOrderID
    idx.Fields.Append fldOrderDate
    ' Append new index.
    tdf.Indexes.Append idx
    ' Refresh Indexes collection.
    tdf.Indexes.Refresh
    ' Print value of DistinctCount property for new index.
    Debug.Print idx.DistinctCount
End Sub


Document Object

Description

A Document object includes information about one instance of a type of object. The object can be a database, saved table, query, or relationship.

Remarks

Each Container object has a Documents collection containing Document objects that describe instances of built-in Container types. The following table lists the type of object each Document describes, the name of its Container object, and what type of information Document contains.

Document | Container | Contains information about
Database | Databases | Containing database
Table or query | Tables | Saved table or query
Relationship | Relations | Saved relationship
Note

Don't confuse the particular types of Container objects with the collection types of the same name. For example, the Databases Container object refers to all saved objects of the specified type, but the Databases collection refers only to open objects of the specified type.

Because a Document object corresponds to an existing object, you can't create new Document objects or delete existing ones. Using the properties of an existing Document object, you can:

  • Determine the name that a user or the Microsoft Jet database engine gave to the object when it was created by checking the Name property setting.
  • Determine or specify the owner of the object by checking or setting the Owner property. To set the Owner property, you must have write permission for the Document object, and you must set the property to the name of an existing User or Group object.
  • Determine the name of the Container object that contains the Document object by checking the Container property setting.
  • Determine or specify the access permissions of a user or group for the object by checking or setting the UserName or Permissions property. To set these properties, you must have write permission for the Document object, and you must set the UserName property to the name of an existing User or Group object.
  • Determine the date and time when the Document object was created and last modified by checking the DateCreated and LastUpdated property settings.
 You can refer to a Document object by its Name property setting using this syntax:

cntApplication.Documents("name")

Properties

AllPermissions Property; Container Property; DateCreated, LastUpdated Properties; Name Property; Owner Property; Permissions Property; UserName Property.

See Also

User Object; Appendix, "Data Access Object Hierarchy."

Specifics (Microsoft Access)

In addition to the Document objects defined by the Microsoft Jet database engine, the following Document objects are defined by Microsoft Access.

Document | Container | Contains information about
Form | Forms | Saved form
Macro | Scripts | Saved macro
Module | Modules | Saved module
Report | Reports | Saved report
SummaryInfo | Databases | Database document summary
UserDefined | Databases | User-defined properties

The Document objects defined by Microsoft Access are Microsoft Access database objects, not data access objects. These Document objects provide the Jet database engine with information about Microsoft Access objects. The Jet database engine uses this information to implement security on Microsoft Access database objects in the same way it does for data access objects.

The Documents collection of a Container object contains Document objects representing the individual objects of the type described by the Container object. For example, the Forms Container object has a Documents collection that might include a Document object corresponding to a form named Orders.

Microsoft Access defines two Document objects in the Databases Container object — SummaryInfo and UserDefined.

The SummaryInfo Document object provides programmatic access to document summary properties — including Title, Subject, Author, Keywords, Comments, Manager, Company, and Category. You can also set these properties on the Summary tab of the Database Properties dialog box, available by clicking Database Properties on the File menu.

To set these properties in Visual Basic, you must create them and append them to the Properties collection of the SummaryInfo Document object if they have not already been set in the Database Properties dialog box. Once a property has been created, you must explicitly refer to the Properties collection to set it. In the following example, doc is an object variable pointing to the SummaryInfo Document object.

doc.Properties!Title = "Northwind Traders"
For more information on creating and setting Microsoft Access-defined properties, see the topics for the Property object and CreateProperty method.

The UserDefined Document object provides programmatic access to user-defined properties defined on the Custom tab of the Database Properties dialog box. You can also create these properties in Visual Basic and append them to the Properties collection of the UserDefined Document object.

Note

Don't confuse properties defined in the Properties collection of a Database document with properties defined in the Properties collection of a Database object. You can create user-defined properties in either Properties collection, but only those defined on the SummaryInfo or UserDefined Document objects can be set from the Database Properties dialog box.

You can use Document objects to establish and enforce permissions for individual Microsoft Access database objects. To set permissions for a Document object, set the UserName property of the Document object to the name of an existing User or Group object. Then set the Permissions property for the Document object.

Note

Don't confuse the particular types of Container objects with the collection types of the same name. The Forms and Reports Container objects each contain Documents collections, which include individual Document objects representing each saved form or report. The Forms and Reports collections refer only to open forms or reports.

Example

See the Container object example.

Example (Microsoft Access)

The following example prints the name of each Form Document object in the current database and the date it was last modified.

Sub DocumentModified()
    Dim dbs As database, ctr As container, doc As Document

    ' Return Database variable pointing to current database.
    Set dbs = CurrentDb
    ' Return Container variable pointing to Forms container.
    Set ctr = dbs.Containers!Forms
    ' Enumerate through Documents collection of Forms container.
    For Each doc In ctr.Documents
        ' Print Document object name and value of LastUpdated property.
        Debug.Print doc.Name; "    "; doc.LastUpdated
    Next doc
End Sub


Documents Collection

Description

A Documents collection contains all of the Document objects for a specific type of object.

Remarks

Each Container object has a Documents collection containing Document objects that describe instances of built-in Container types property settings.

You can refer to a Document object in a collection by its Name property setting using this syntax:

cntApplication.Documents("name")

Properties

Count Property.

Methods

Refresh Method.

See Also

Appendix, "Data Access Object Hierarchy."

Specifics (Microsoft Access)

See the Document object specifics (Microsoft Access).

Example

See the Container object example.

Example (Microsoft Access)

See the Document object example (Microsoft Access).


Dynaset-Type Recordset Object

Description

A dynaset-type Recordset object is a type of Recordset object you can use to manipulate data in an underlying database table or tables. A dynaset-type Recordset object is a dynamic set of records that can contain fields from one or more tables or queries in a database and may be updatable.

Remarks

To create a dynaset-type Recordset object, use the OpenRecordset method on an open database, against another dynaset- or snapshot-type Recordset object, or on a QueryDef object.

A dynaset-type Recordset object is different from a snapshot-type Recordset object because only a unique key for each record is brought into memory, instead of actual data. As a result, a dynaset is normally updated with changes made to the source data, while the snapshot is not. Like the table-type Recordset object, a dynaset's current record is fetched only when its fields are referenced.

If you request a dynaset-type Recordset object and the Microsoft Jet database engine is unable to gain read-write access to the records, the Jet database engine may create a read-only, dynaset-type Recordset object. If the Recordset object created isn't updatable, its Updatable property setting is False (0).

As base table data changes due to updates made by your application or by other users, current data is available to your application when you reposition the current record. In a multiuser database, more than one user can open a dynaset-type Recordset object referring to the same records. Because a dynaset-type Recordset object is dynamic, when one user changes a record, other users have immediate access to the changed data. However, if one user adds a record, other users aren't notified until they use the Requery method on the Recordset object. If a user deletes a record, other users are notified when they try to access it.

Records added to the database don't become a part of your dynaset-type Recordset object unless you add them using the AddNew method. For example, if you use an action query containing an INSERT INTO SQL statement to add records, the new records aren't included in your dynaset-type Recordset object until you either use the Requery method or you rebuild your Recordset object using the OpenRecordset method.

To maintain data integrity, dynaset- and table-type Recordset objects are locked during Edit (pessimistic locking) and Update methods operations (optimistic locking) so that only one user can update a particular record at a time. When the Jet database engine locks a record, it locks the entire 2K page containing the record.

Optimistic and pessimistic locking are also used with non-ODBC tables. When you access external tables using ODBC you should always use optimistic locking. The locking conditions in effect during editing are determined by the LockEdits property.

Not all fields can be updated in all dynaset-type Recordset objects. To determine whether you can update a particular field, check the Updatable property setting of the Field object.

A dynaset-type Recordset object may not be updatable if:

  • There isn't a unique index on the ODBC or Paradox table or tables.
  • The data page is locked by another user.
  • The record has changed since you last read it.
  • The user doesn't have permission.
  • One or more of the tables or fields are set to read-only.
  • The database is opened as read-only.
  • The Recordset object was either created from multiple tables without a JOIN statement or the query was too complex.
 The order of dynaset-type Recordset object or Recordset data doesn't necessarily follow any specific sequence. If you need to order your data, use an SQL statement with an ORDER BY clause to create the Recordset object. You can also use this technique to filter the records so that only certain records are added to the Recordset object. For example, the following code selects only titles that were published between 1993 and 1994 and sorts the resulting records by title.

Dim dbsBiblio As Database, rstTitles As Recordset
Dim strSelect As String
Set dbsBiblio = Workspaces(0).OpenDatabase("Biblio.mdb")
strSelect = "SELECT * FROM Titles  " _
    & " WHERE [Year Published] BETWEEN 1993 AND 1994 " _
        & " ORDER BY ISBN;"
Set rstTitles = dbsBiblio.OpenRecordset(strSelect, dbOpenDynaset)
Using this technique instead of using the Filter or Sort properties or testing each record individually generally results in faster access to your data.

Properties

AbsolutePosition Property; BOF, EOF Properties; Bookmark Property; Bookmarkable Property; CacheSize, CacheStart Properties; EditMode Property; Filter Property; LastModified Property; LockEdits Property; Name Property; NoMatch Property; PercentPosition Property; RecordCount Property; Restartable Property; Sort Property; Transactions Property; Type Property; ValidationRule Property; ValidationText Property.

Methods

CancelUpdate Method; Clone Method; Close Method; CopyQueryDef Method; Edit Method; FillCache Method; FindFirst, FindLast, FindNext, FindPrevious Methods; GetRows Method; Move Method; MoveFirst, MoveLast, MoveNext, MovePrevious Methods; OpenRecordset Method; Requery Method; Update Method.

See Also

OpenRecordset Method; Recordset Object; Updatable Property; Appendix, "Data Access Object Hierarchy."

Example

This example creates a new dynaset-type Recordset object and opens it, appending it to the Recordsets collection in the default database. It then edits the record(s).

Function ChangeSQL () As Integer
    Dim dbsBiblio As Database, rstTitles As Recordset
    Dim strSelect As String
    Set dbsBiblio = DBEngine.Workspaces(0).OpenDatabase("Biblio.mdb")
    strSelect = "Select * From Titles Where Title = 'Using SQL' "
    Set rstTitles = dbsBiblio.OpenRecordset(strSelect, dbOpenDynaset)
    If rstTitles.RecordCount > 0 and rstTitles.Updatable Then
        Do Until rstTitles.EOF
            With rstTitles
                .Edit
                ![Year Published] = 1994    ' Change year published.
                .Update
                .MoveNext
            End With
        Loop
    Else
        Debug.Print "No such title or table not updatable"
    End If
    dbsBiblio.Close
    ChangeSQL = True
End Function
Example (Microsoft Access)

The following example creates a dynaset-type Recordset object, then checks the Updatable property of the Recordset object.

Sub RecentHires()
    Dim dbs As Database, rst As Recordset
    Dim strSQL As String

    ' Return Database object pointing to current database.
    Set dbs = CurrentDb
    strSQL = "SELECT * FROM Employees WHERE HireDate >= #1-1-95#;"
    Set rst = dbs.OpenRecordset(strSQL, dbOpenDynaset)
    Debug.Print rst.Updatable
End Sub


Edit Method

Applies To

Dynaset-Type Recordset Object, Recordset Object, Table-Type Recordset Object.

Description

Copies the current record from a dynaset-type or table-type Recordset object to the copy buffer for subsequent editing.

Syntax

recordset.Edit

The recordset placeholder represents the name of an open, updatable Recordset object that contains the record you want to edit.

Remarks

Once you use the Edit method, changes made to the current record's fields are copied to the copy buffer. After you make the desired changes to the record, use the Update method to save your changes.

Caution

If you edit a record and then perform any operation that moves to another record without first using Update, your changes are lost without warning. In addition, if you close recordset or end the procedure which declares the recordset or the parent Database object, your edited record is discarded without warning.

When the Recordset object's LockEdits property setting is True (pessimistically locked) in a multiuser environment, the record remains locked from the time Edit is used until the updating is complete. If the LockEdits property setting is False (optimistically locked), the record is locked and compared with the pre-edited record just before it's updated in the database. If the record has changed since you used the Edit method, the Update operation fails with a trappable error (3197).

Note

Optimistic locking is always used on external database formats, such as ODBC and installable ISAM.

The current record remains current after you use Edit.

To use Edit, there must be a current record. If there is no current record or if recordset doesn't refer to an open table-type or dynaset-type Recordset object, an error occurs.

Using Edit produces an error under the following conditions:

  • There is no current record.
  • The database or recordset is read-only.
  • No fields in the record are updatable.
  • The database or recordset was opened for exclusive use by another user.
  • Another user has locked the page containing your record.
 See Also

AddNew Method, Delete Method, LockEdits Property.

Example

This example finds the first record in a Recordset object that matches the search criteria and opens it for editing. Then it changes the value in the Title field and saves the change using the Update method.

Dim strCriteria As String, strNewTitle As String
strCriteria = "Title = 'My Right Hand'"    ' Create the criteria.
strNewTitle = "My Right Foot"    ' Create a new title.
rstTitles.FindFirst strCriteria    ' Make record current.
Do While Not rstTitles.NoMatch
    rstTitles.Edit    ' Open record.
    rstTitles.Fields("Title") = strNewTitle    ' Enter new title.
    rstTitles.Update    ' Save changes.
    rstTitles.FindNext strCriteria
Loop
The following example achieves the same effect without using the Edit method.

' Create the criteria string.
strSQLQuery = "UPDATE Titles SET Title = 'My Right Foot'" & _
    " WHERE Title = 'My Right Hand';"
dbsPublishers.Execute strSQLQuery    ' Execute the query.
This example opens a Recordset object and locates each record whose Title field satisfies the search criteria and copies it to the copy buffer. The example then prepares the record for subsequent editing, changes the job title, and saves the change using the Update method.

Dim dbsNorthwind As Database, rstEmployees As Recordset
Dim strCriteria As String, strNewTitle As String
' Set search criteria.
strCriteria = "Title = 'Sales Representative'"
strNewTitle = "Account Executive"    ' Set new job title.
Set dbsNorthwind = DBEngine.Workspaces(0).OpenDatabase("Northwind.mdb")
' Create dynaset.
Set rstEmployees = dbsNorthwind.OpenRecordset("Employees", _
    dbOpenDynaset)
rstEmployees.FindFirst strCriteria    ' Find first occurrence.
' Loop until no matching records.
Do Until rstEmployees.NoMatch
    With rstEmployees
       .Edit    ' Enable editing.
       !Title = strNewTitle    ' Change title.
       .Update    ' Save changes.
       .FindNext strCriteria    ' Find next occurrence.
    End With
Loop    ' End of loop.
Tip

Using an update query to change job titles might be more efficient. For example, you could use the following code to achieve the same results:

strSQL = "Update Employees Set Title = 'Account Executive' " & _
    "WHERE Title = 'Sales Representative' "
dbsNorthwind.Execute strSQL
Example (Microsoft Access)

The following example opens a Recordset object and locates each record satisfying the search criteria for the Title field. The procedure then uses the Edit method to prepare the record for subsequent editing, changes the job title, and saves the change.

Sub ChangeTitle()
    Dim dbs As Database, rst As Recordset
    Dim strCriteria As String, strNewTitle As String

    ' Return Database variable pointing to current database.
    Set dbs = CurrentDb
    ' Set search criteria.
    strCriteria = "Title = 'Sales Representative'"
    strNewTitle = "Account Executive"
    ' Create dynaset-type Recordset object.
    Set rst = dbs.OpenRecordset("Employees", dbOpenDynaset)
    ' Find first occurrence.
    rst.FindFirst strCriteria
    ' Loop until no matching records.
    Do Until rst.NoMatch
        With rst
            .Edit            'Enable editing.
            !Title = strNewTitle    'Change title.
            .Update             'Save changes.
            .FindNext strCriteria    'Find next occurrence.
        End With
    Loop
End Sub
Tip

Using an update query to alter data is more efficient. For example, you can use the following code to achieve the same results.

strSQL = "Update Employees Set Title = 'Account Executive' " & _
    "WHERE Title = 'Sales Representative' "
dbs.Execute strSQL


EditMode Property

Applies To

Dynaset-Type Recordset Object, Recordset Object, Snapshot-Type Recordset Object, Table-Type Recordset Object.

Description

Returns a value that indicates the state of editing for the current record.

Return Values

The return value is an integer that indicates the state of editing. The data type is Integer.

The possible return values are:

Value | Description
dbEditNone | No editing operation is in progress.
dbEditInProgress | Edit method has been invoked, and the current record is in the copy buffer.
dbEditAdd | AddNew method has been invoked, and the current record in the copy buffer is a new record that hasn't been saved in the database.

These constants are listed in the Data Access (DAO) object library in the Object Browser.

Remarks

The EditMode property is most useful when you want to depart from the default functionality of a Data control. You can check the value of the EditMode property and the value of the action parameter in the Validate event procedure to determine whether to invoke the UpdateRecord method.

You can also check to see if the LockEdits property setting is True (-1) and the EditMode property setting is dbEditInProgress to determine whether the current data page is locked.

See Also

CancelUpdate Method, LockEdits Property.

Example

This example checks the EditMode property of a Recordset object and completes the update if the AddNew method has been invoked or the object is being edited.

Function PostChange(rstTarget as Recordset) As Integer
    If (rstTarget.EditMode = dbEditAdd) or  _
            (rstTarget.EditMode = dbEditInProgress) Then
        rstTarget.Update
        PostChange = True
    Else
        PostChange = False
    End If
End Function

Example (Microsoft Excel)

This example checks to see whether the Customer recordset in the NWINDEX.MDB database can be edited. If so, the example updates the value of the first field of the first record with the value in cell C3 on Sheet1.

To create the NWINDEX.MDB database, run the Microsoft Excel example for the CreateDatabase method.

Dim db As Database, rs As Recordset
Set db = Workspaces(0).OpenDatabase(Application.Path & "\NWINDEX.MDB")
Set rs = db.OpenRecordset("Customer")
If Not ((rs.EditMode = dbEditAdd) Or _
        (rs.EditMode = dbEditInProgress)) Then
    rs.Edit
    rs.Fields(0).Value = Worksheets(1).Cells(3, 3).Value
    rs.Update
Else
    MsgBox ("Cannot update database with cell value")
End If
rs.Close
db.Close


EOF Property

See BOF, EOF Properties.


Error Object

Description

The Error object contains details about data access errors, each of which pertains to a single operation involving data access objects (DAO).

Remarks

Any operation involving data access objects can generate one or more errors. As each error occurs, one or more Error objects are placed in the Errors collection of the DBEngine object.

When another DAO operation generates an error, the Errors collection is cleared, and the new Error object is placed in the Errors collection. DAO operations that don't generate an error have no effect on the Errors collection.

Elements of the Errors collection aren't appended as they typically are with other collections. The set of Error objects in the Errors collection describes one error. The first Error object is the lowest level error, the second the next higher level, and so forth. For example, if an ODBC error occurs while trying to open a Recordset object, the last Error object contains the DAO error indicating that the object couldn't be opened. The first error object contains the lowest level ODBC error; subsequent errors contain the ODBC errors returned by the various layers of ODBC. In this case, the driver manager, and possibly the driver itself, return separate Error objects.

Note

If you use the New keyword to create an object that subsequently causes an error before that object has been appended to a collection, the DBEngine Errors collection will not contain an entry for that object's error (because it might still contain information from a previous error).

To determine if the error information in the Errors collection is valid, compare the Number property of the first element of the Errors collection (DBEngine.Errors(0)) with the value of the Visual Basic Err object.

Error handling code should examine the Errors collection whenever you anticipate a data access error. If you are writing a centralized error handler, test the Visual Basic Err object. If it matches the Errors(0) object, you can then use a series of Select Case statements to identify the particular data access error or errors that occurred.

Properties

Description Property; HelpContext, HelpFile Properties; Number Property; Source Property.

See Also

Appendix, "Data Access Object Hierarchy."

Example

See the Description property example.

Example (Microsoft Access)

The following example generates an error by attempting to open a Recordset object on a non-existent Students table. Information about the error is stored in both the data access Error object and the Visual Basic Err object. The procedure prints the value of the Description, Source, and Number properties of the Error object. Then it prints the values of the corresponding properties of the Err object.

Note that the first Error object in the Errors collection, Errors(0), should always refer to the same error as the Err object. If it doesn't, information in the Errors collection may be outdated. Use the Refresh method to ensure that the Errors collection includes the most recent error information.

Sub CheckError()
    Dim dbs As Database, tdf As TableDef, rst As Recordset
    Dim prp As Property
    ' Declare Error variable for enumeration of Errors collection.
    Dim errX As Error

    ' Ignore errors.
    On Error Resume Next
    ' Clear error in Err object.
    Err.Clear
    ' Refresh Errors collection.
    Errors.Refresh
    ' Return Database variable pointing to current database.
    Set dbs = CurrentDb
    ' Attempt to open Recordset object on nonexistent table.
    Set rst = dbs.OpenRecordset("Students")
    Debug.Print "DAO Error Object:"
    ' Print number of errors in Errors collection.
    Debug.Print ">>>Number of errors: "; Errors.Count
    ' Enumerate Errors collection and key properties.
    For Each errX In DBEngine.Errors
        Debug.Print errX.Description
        Debug.Print errX.Source
        Debug.Print errX.Number
    Next errX
    Debug.Print
    Debug.Print "VBA Err Object:"
    ' Display corresponding properties of Err object.
    Debug.Print Err.Description
    Debug.Print Err.Source
    Debug.Print Err.Number
End Sub


Errors Collection

Description

The Errors collection contains all stored Error objects, each of which pertains to a single operation involving data access objects (DAO).

Remarks

Any operation involving data access objects can generate one or more errors. As each error occurs, one or more Error objects are placed in the Errors collection of the DBEngine object. When another DAO operation generates an error, the Errors collection is cleared, and the new Error object is placed in the Errors collection. DAO operations that don't generate an error have no effect on the Errors collection.

Elements of the Errors collection aren't appended as they typically are with other collections.

The set of Error objects in the Errors collection describes one error. The first Error object is the lowest level error, the second the next higher level, and so forth. For example, if an ODBC error occurs while trying to open a Recordset object, the last Error object contains the DAO error indicating that the object couldn't be opened. The first error object contains the lowest level ODBC error; subsequent errors contain the ODBC errors returned by the various layers of ODBC. In this case, the driver manager, and possibly the driver itself, return separate Error objects.

Note

If you use the New keyword to create an object that causes an error either before or while being placed into the Errors collection, the collection doesn't contain error information about that object (because it might contain information from a previous error).

The error information is available in the Visual Basic Err object.

Properties

Count Property.

Methods

Refresh Method.

See Also

Appendix, "Data Access Object Hierarchy."

Example (Microsoft Access)

See the Error object example (Microsoft Access).


Execute Method

Applies To

Database Object, QueryDef Object.

Description

Runs an action query or executes an SQL statement on a specified Database object.

Syntax

database.Execute source[, options]

querydef.Execute [options]

For a Database object, the Execute method syntax has these parts.

Part | Description
database | The name of the Database object on which the query will run.
source | The SQL statement or QueryDef object.
options | An integer constant that determines the data integrity characteristics of the query, as specified in Settings.
For a QueryDef object, the Execute method syntax has these parts.

Part | Description
querydef | The name of the QueryDef object whose SQL property setting specifies the SQL statement to execute.
options | An integer constant that determines the data integrity characteristics of the query, as specified in Settings.
Settings

You can use the following constants for the options part.

Constant | Description
dbDenyWrite | Deny write permission to other users.
dbInconsistent | (Default) Inconsistent updates.
dbConsistent | Consistent updates.
dbSQLPassThrough | SQL pass-through. Causes the SQL statement to be passed to an ODBC database for processing.
dbFailOnError | Rolls back updates if an error occurs.
dbSeeChanges | Generates a run-time error if another user is changing data you are editing.
Remarks

The Execute method is valid only for action queries. If you use Execute with another type of query, an error occurs. Because an action query doesn't return any records, Execute doesn't return a recordset.

Tips

  • Given a syntactically correct SQL statement and proper permissions, the Execute method won't fail — even if not a single row can be modified or deleted. Therefore, always use the dbFailOnError option when using the Execute method to run an update or delete query. This option generates a trappable error and rolls back all successful changes if any of the records affected are locked and can't be updated or deleted.
  • For best performance, especially in a multiuser environment, nest the Execute method inside a transaction: Use the BeginTrans method on the current Workspace object, then use the Execute method, and complete the transaction by using the CommitTrans method on the Workspace. This saves changes on disk and frees any locks placed while the query was running.
 Use the RecordsAffected property of the Database or QueryDef object to determine the number of records affected by the most recent Execute method. For example, RecordsAffected contains the number of records deleted, updated, or inserted when executing an action query. When you use the Execute method to run a Querydef, the RecordsAffected property of the QueryDef object is set to the number of records affected.

If both dbInconsistent and dbConsistent are included or if neither is included, the result is the default.

Using Execute on a query that selects records produces an error.

Execute doesn't return a recordset.

See Also

RecordsAffected Property.

Example

This example uses a Data control to execute an action query that updates all titles that have no value in the ISBN column in the Titles table. If there is an error, all changes are rolled back.

Dim strSQL as String
strSQL = "DELETE FROM Titles WHERE ISBN IS NULL"
dbsBiblio.Execute strSQL, dbFailOnError
Example (Microsoft Access)

The following example executes an action query and prints the number of records affected.

Sub RecordsUpdated()
    Dim dbs As Database, qdf As QueryDef
    Dim strSQL As String

    ' Return Database variable pointing to current database.
    Set dbs = CurrentDb
    strSQL = "UPDATE Employees SET Title = " & _
        "'Senior Sales Representative' " & _
            "WHERE Title = 'Sales Representative';"
    ' Create new QueryDef.
    Set qdf = dbs.CreateQueryDef("UpdateTitles", strSQL)
    ' Execute QueryDef.
    qdf.Execute
    Debug.Print qdf.RecordsAffected
End Sub


Field Object

Description

A Field object represents a column of data with a common data type and a common set of properties.

Remarks

The Fields collections of Index, QueryDef, Relation, and TableDef objects contain the specifications for the fields those objects represent. The Fields collection of a Recordset object represents the Field objects in a row of data, or in a record. You use the Field objects in a Recordset object to read and set values for the fields in the current record of the Recordset object.

You manipulate a field using a Field object and its methods and properties. For example, you can:

  • Get or set the presentation order of the Field object in a Fields collection using the OrdinalPosition property.
  • Read the SourceField and SourceTable property settings to determine the original source of the data.
  • Read or set the ForeignName property setting for a field in a Relation object.
  • Read or set the AllowZeroLength, DefaultValue, Required, ValidateOnSet, ValidationRule, or ValidationText property setting to find or specify validation conditions.
  • Read or set the Value property of a Recordset object.
  • Use the AppendChunk, FieldSize, and GetChunk methods to get or set a value in an OLE Object or Memo field of a Recordset object.
You can refer to the Value property of a Field object that you create and append to a Fields collection by its Name property setting using following syntax:

Fields("name")

Note

Fields that have names with embedded spaces must be delimited with brackets ([ ]), for example [Part Number], or enclosed in single quotation marks (' ') or double quotation marks (" "), as in 'Part Number' or "Part Number".

You can also refer to the Value property of a Field object that you create and append to a Fields collection by its position in the Fields collection using this syntax:

Fields(0)

To create a new Field object in an Index, TableDef, or Relation object, use the CreateField method.

When the Field object is accessed as part of a Recordset object, data from the current record is visible in the Field object's Value property. To manipulate data in the Recordset object, you don't usually reference the Fields collection directly; instead you indirectly reference the Value property of the Field object in the Fields collection of the Recordset object, as in the following example.

Dim dbsCatalog As Database, rstParts As Recordset
Dim strSelect As String

Set dbsCatalog = Workspaces(0).OpenDatabase("Catalog.mdb")
strSelect = "SELECT [Part Name], Size,  " _
    & "[Part Type], [Part Age] AS Age FROM Parts"
Set rstParts = dbsCatalog.OpenRecordset(strSelect)

'Return Part Name field in Recordset object.
Debug.Print rstParts.Fields(0).Value
' Otherwise, use indirect coding.
Debug.Print rstParts(0)    ' Return value of Part Name field.
Debug.Print rstParts![Part Name]    ' Also return Part Name field value.
Debug.Print rstParts![Part Type]    ' Return Part Type field.
Debug.Print rstParts!Age    ' Return Part Age field aliased as Age.
Properties

AllowZeroLength Property; Attributes Property; CollatingOrder Property; DataUpdatable Property; DefaultValue Property; ForeignName Property; Name Property; OrdinalPosition Property; Required Property; Size Property; SourceField, SourceTable Properties; Type Property; V1xNullBehavior Property; ValidateOnSet Property; ValidationRule Property; ValidationText Property; Value Property.

Methods

AppendChunk Method, CreateProperty Method, FieldSize Method, GetChunk Method.

See Also

CreateField Method; Appendix, "Data Access Object Hierarchy."

Specifics (Microsoft Access)

In addition to the properties defined by the Microsoft Jet database engine, a Field object in the Fields collection of a QueryDef object or a TableDef object may also contain the following Microsoft Access application-defined properties.

Example

This example creates a TableDef object and a Field object, appends the Field to the Fields collection in the new TableDef, and appends the TableDef to the TableDefs collection in the current database. The example enumerates all the fields in the new TableDef object and all the properties of the new Field. See the methods and properties listed in the Field summary topic for additional examples.

Function EnumerateField () As Integer
    Dim dbsNorthwind As Database
    Dim tdfTest As TableDef
    Dim fldTest As Field
    Dim I As Integer
    Set dbsNorthwind =_
        DBEngine.Workspaces(0).OpenDatabase("Northwind.mdb")
    Set tdfTest = dbsNorthwind.CreateTableDef("MyTable")
    Set fldTest = tdfTest.CreateField("MyField", dbDate)
    tdfTest.Fields.Append fldTest
    dbsNorthwind.TableDefs.Append tdfTest
' Get database name.
    Debug.Print
    Debug.Print "Database Name: "; dbsNorthwind.Name
    Debug.Print
' Enumerate all fields in tdfTest.
    Debug.Print "TableDefs: Name; Fields: Name"
    For I = 0 To tdfTest.Fields.Count - 1
        Debug.Print "  "; tdfTest.Name;

        Debug.Print "; "; tdfTest.Fields(I).Name
    Next I
    Debug.Print
' Enumerate built-in properties of fldTest.
    Debug.Print "fldTest.Name: "; fldTest.Name
    Debug.Print "AllowZeroLength: "; fldTest.AllowZeroLength
    Debug.Print "Attributes: "; fldTest.Attributes
    Debug.Print "CollatingOrder: "; fldTest.CollatingOrder
    Debug.Print "DefaultValue: "; fldTest.DefaultValue
    Debug.Print "OrdinalPosition: "; fldTest.OrdinalPosition
    Debug.Print "Required: "; fldTest.Required
    Debug.Print "Size: "; fldTest.Size
    Debug.Print "SourceField: "; fldTest.SourceField
    Debug.Print "SourceTable: "; fldTest.SourceTable
    Debug.Print "Type: "; fldTest.Type
    Debug.Print "ValidationRule: "; fldTest.ValidationRule
    Debug.Print "ValidationText: "; fldTest.ValidationText
    EnumerateField = True
End Function
Example (Microsoft Access)

The following example creates a new Field object, sets some of its properties, and appends it to the Fields collection of a TableDef object. The procedure then enumerates all fields in the Fields collection of the TableDef object.

Sub NewField()
    Dim dbs As Database, tdf As TableDef
    Dim fld As Field

    ' Return Database variable that points to current database.
    Set dbs = CurrentDb
    Set tdf = dbs.TableDefs!Employees
    ' Create new Field object.
    Set fld = tdf.CreateField("SSN#")
    ' Set Type and Size properties of Field object.
    fld.Type = dbText
    fld.Size = 11
    ' Append field.
    tdf.Fields.Append fld
    ' Enumerate all fields in Fields collection of TableDef object.
    For Each fld in tdf.Fields
        Debug.Print fld.Name
    Next fld
End Sub


Fields Collection

Description

A Fields collection contains all stored Field objects of an Index, QueryDef, Recordset, Relation, or TableDef object.

Remarks

The Fields collections of the Index, QueryDef, Relation, and TableDef objects contain the specifications for the fields those objects represent. The Fields collection of a Recordset object represents the Field objects in a row of data, or in a record. You use the Field objects in a Recordset object to read and to set values for the fields in the current record of the Recordset object.

You can refer to the Value property of a Field object that you create and append to a Fields collection by its Name property setting using the following syntax:

Fields("name")

Fields that have names with embedded spaces must be delimited with brackets ([ ]) or enclosed in double quotation marks (" "), using either of the following syntax forms:

Fields("long name")

You can refer to the Value property of a Field object that you create and append to a Fields collection by its position in the Fields collection using this syntax:

Fields(0)

Properties

Count Property.

Methods

Append Method, Delete Method, Refresh Method.

See Also

Appendix, "Data Access Object Hierarchy."

Specifics (Microsoft Access)

See the Field object specifics (Microsoft Access).

Example

See the Field object example.

Example (Microsoft Access)

See the Field object example (Microsoft Access).


FieldSize Method

Applies To

Field Object.

Description

Returns the number of bytes used in the database (rather than in memory) of a Memo or an OLE Object Field object in the Fields collection of a Recordset object.

Syntax

varname = recordset ! field.FieldSize( )

The FieldSize method syntax has these parts.

Part | Description
varname | The name of a Long or Variant variable.
recordset | A variable of an object data type that specifies the Recordset object containing the Fields collection.
field | The name of a Field object whose Type property is set to dbMemo (Memo), dbLongBinary (OLE Object), or the equivalent.

Remarks

Because the size of an OLE Object field or Memo field can exceed 64K, you should assign the value returned by FieldSize to a variable large enough to store a Long variable.

You can use FieldSize with the AppendChunk and GetChunk methods to manipulate large fields.

Note

To determine the size of a Field object (except Memo and Long Binary types), use the Size property.

See Also

AppendChunk Method, GetChunk Method, Size Property, Type Property.

Specifics (Microsoft Access)

The data access FieldSize method is different from the Microsoft Access FieldSize property, which is set in table Design view. The data access FieldSize method returns the number of bytes in a Field object of type Memo data type or OLE Object data type.

You set the Microsoft Access FieldSize property in order to limit the size of a field in a table. The FieldSize property is only available in table Design view. From Visual Basic, use the Size property to set the size of a field in a table.

Example

See the AppendChunk method example.

Example (Microsoft Access)

The following example uses the FieldSize method to return the size in bytes of two fields in an Employees table. The Notes field is Memo data type and the Photo field is Binary data type.

Sub GetFieldSize()
    Dim dbs As Database, rst As Recordset
    Dim fldNotes As Field, fldPhoto As Field
    Dim strSQL As String

    ' Return Database variable pointing to current database.
    Set dbs = CurrentDb
    ' Construct SQL statement to return Notes and Photo fields.
    strSQL = "SELECT Notes, Photo FROM Employees;"
    ' Create dynaset-type Recordset object.
    Set rst = dbs.OpenRecordset(strSQL)
    Set fldNotes = rst.Fields!Notes
    Set fldPhoto = rst.Fields!Photo
    ' Move to first record.
    rst.MoveFirst
    Debug.Print "Size of Notes:"; "    "; "Size of Photo:"
    ' Print sizes of fields for each record in Recordset object.
    Do Until rst.EOF
        Debug.Print fldNotes.FieldSize; "        "; fldPhoto.FieldSize
        rst.MoveNext
    Loop
End Sub


FillCache Method

Applies To

Dynaset-Type Recordset Object, Recordset Object.

Description

Fills all or a part of a local cache for a Recordset object that contains data from an ODBC data source.

Syntax

recordset.FillCache [rows[, start]]

The FillCache method syntax has these parts.

Part | Description
recordset | A Recordset object created from an ODBC data source, such as a TableDef representing an attached table or a QueryDef object derived from such a TableDef.
rows | An Integer specifying the number of rows to fill in the cache. If you omit this argument, the value is determined by the CacheSize property setting.
start | A string specifying a bookmark. The cache is filled starting from the record indicated by this bookmark. If you omit this argument, the cache is filled starting from the record indicated by the CacheStart property.
Remarks

Caching improves the performance of an application that retrieves, or fetches, data from a remote server. A cache is space in local memory that holds the data most recently fetched from the server on the assumption that the data will probably be requested again while the application is running. When data is requested, the Microsoft Jet database engine checks the cache for the data first rather than fetching it from the server, which takes more time. Data that doesn't come from an ODBC data source isn't saved in the cache.

Rather than waiting for the cache to be filled with records as they are fetched, you can explicitly fill the cache at any time using the FillCache method. This is a faster way to fill the cache because FillCache fetches several records at once instead of one at a time. For example, while each screenful of records is being displayed, you can have your application use FillCache to fetch the next screenful of records.

Any ODBC database accessed with Recordset objects can have a local cache. To create the cache, open a Recordset object from the remote data source, and then set the CacheSize and CacheStart properties of the Recordset.

If rows and start create a range of records that is partly or wholly outside the range of records specified by the CacheSize and CacheStart properties, the portion of the recordset outside this range is ignored and isn't loaded into the cache.

If FillCache requests more records than remain in the remote data source, only the remaining records are fetched, and no error occurs.

Notes

  • Records fetched from the cache don't reflect changes made concurrently to the source data by other users.
  • FillCache fetches only records not already cached. To force an update of all the cached data, set the CacheSize property of the Recordset to 0, set it to the size of the cache you originally requested, and then use FillCache.
See Also

Bookmark Property; Bookmarkable Property; CacheSize, CacheStart Properties.

Specifics (Microsoft Access)

When you use a bookmark in a Microsoft Access module, you must include an Option Compare Binary statement in the Declarations section of the module. A bookmark is a Variant array of Byte data, so the string comparison method for the module must be binary. If a bookmark is evaluated with a text-based string comparison method, the current record may be set to an incorrect record. The Option Compare Text statement denotes a text-based comparison method, as does the default setting for the Option Compare Database statement.

Example (Client/Server)

See the CacheSize, CacheStart properties example.

Example (Microsoft Access)

See the CacheSize, CacheStart properties example (Microsoft Access).


Filter Property

Applies To

Dynaset-Type Recordset Object, Recordset Object, Snapshot-Type Recordset Object.

Description

Sets or returns a value that determines the records included in a subsequently opened Recordset object.

Settings and Return Values

A string expression that contains the WHERE clause of an SQL statement without the reserved word WHERE. The data type is String.

Remarks

Use the Filter property to apply a filter to a dynaset- or Snapshot-Type Recordset object.

You can use the Filter property to restrict the records returned from an existing object when a new Recordset object is opened based on an existing Recordset object.

The following example shows how the Filter property can be used to return only the records for customers who live in a particular region:

rstCustomers.Filter = "Region = 'NY'"
Set rstNYCustomers = rstCustomers.OpenRecordset()
Notes

  • In many cases, it's faster to open a new Recordset object using an SQL statement that includes a WHERE clause.
  • Use the U.S. date format (month-day-year) when you filter fields containing dates, even if you're not using the U.S. version of the Microsoft Jet database engine; otherwise, the data may not be filtered as you expect. You can use the Visual Basic Format function to make this easier. For example:
    rstEmployees.Filter = "HireDate > #" & Format(mydate, "m/d/yy") & "#"
 See Also

OpenRecordset Method, Sort Property.

Specifics (Microsoft Access)

The data access Filter property applies a filter to a Recordset object. You can set it only from Visual Basic.

Note

The Microsoft Access Filter property applies a filter to a form. You can set it in a form's property sheet in form Design view, in a macro, or from Visual Basic.

Example

This example creates a dynaset-type Recordset that contains only records for orders shipped to the United Kingdom.

Dim dbsNorthwind As Database
Dim rstOrders As Recordset, rstFiltered As Recordset
Set dbsNorthwind =  DBEngine.Workspaces(0).OpenDatabase("Northwind.mdb")
' Create dynaset-type Recordset.
Set rstOrders = dbsNorthwind.OpenRecordset("Orders", dbOpenDynaset)
rstOrders.Filter = "ShipCountry = 'UK'"        ' Set filter condition.
' Create filtered dynaset.
Set rstFiltered = rstOrders.OpenRecordset()
Note

To change the contents of rstOrders, you must set its Filter property, and then open a second Recordset object based on rstOrders.

Tip

In some situations, it may be more efficient to create the second Recordset object with the conditions you want in one step. As a general rule, when you know the data you want to select, it's usually more efficient to create a Recordset with an SQL statement. This example shows how you can create just one Recordset and obtain the same results as in the preceding example:

Dim dbsNorthwind As Database, rstOrders As Recordset
Set dbsNorthwind =  DBEngine.Workspaces(0).OpenDatabase("Northwind.mdb")
Set rstOrders = dbsNorthwind.OpenRecordset("SELECT * FROM Orders " & _
    "WHERE ShipCountry = 'UK';")
Example (Microsoft Access)

The following example prompts the user to enter the name of a country on which to filter, and then sets the Filter property of a dynaset-type Recordset object. For example, if the user enters "Italy," the filtered recordset will contain only those records in which the ShipCountry field contains the value "Italy."

Note that you first create a dynaset-type Recordset object and set its Filter property, then open a second dynaset-type Recordset object based on the first. Setting the Filter property of the first Recordset object doesn't actually affect the records that it contains, so you need to create a second Recordset object in order to see the effects of the filter.

Sub SetRecordsetFilter()
    Dim dbs As Database, strInput As String
    Dim rstOrders As Recordset, rstFiltered As Recordset

    ' Return Database variable that points to current database.
    Set dbs = CurrentDb
    ' Prompt for value on which to filter.
    strInput = InputBox("Enter name of country on which to filter.")
    ' Create dynaset-type Recordset object.
    Set rstOrders = dbs.OpenRecordset("Orders", dbOpenDynaset)
    ' Set filter condition.
    rstOrders.Filter = "[ShipCountry] = '" & strInput & "'"
    ' Create filtered dynaset-type Recordset object.
    Set rstFiltered = rstOrders.OpenRecordset()
    ' Populate recordset.
    rstFiltered.MoveLast
    ' Second Recordset object is now subset of the first.
    Debug.Print rstFiltered.RecordCount
End Sub
Tip

In most situations, it is more efficient to create the second Recordset object with the desired conditions in one step. When you know what data you want to select, it's generally more efficient to create a recordset with an SQL statement. The following example shows how you can create just one recordset and obtain the same results as in the preceding example.

Dim dbs As Database, rstOrders As Recordset, strInput As String
Set dbs = CurrentDb
strInput = InputBox("Enter name of country on which to filter.")
Set rstOrders = dbs.OpenRecordset("SELECT * FROM Orders " & _
    "WHERE [ShipCountry] = '" & strInput & "';")
Example (Microsoft Excel)

This example creates a new recordset containing records of the Supplier recordset in the NWINDEX.MDB database, and then it copies the recordset contents onto Sheet1. These records contain only data on suppliers located in Canada. The example copies a new, sorted recordset into Microsoft Excel.

To create the NWINDEX.MDB database, run the Microsoft Excel example for the CreateDatabase method.

Dim db As Database, rs As Recordset, sortedSet As Recordset
Set db = Workspaces(0).OpenDatabase(Application.Path & "\NWINDEX.MDB")
Set rs = db.OpenRecordset("Supplier", dbOpenDynaset)
rs.Filter = "[COUNTRY] = 'Canada'"
Set sortedSet = rs.OpenRecordset()
Sheets("Sheet1").Activate
ActiveCell.CopyFromRecordset sortedSet
sortedSet.Close
rs.Close
db.Close


FindFirst, FindLast, FindNext, FindPrevious Methods

Applies To

Dynaset-Type Recordset Object, Recordset Object, Snapshot-Type Recordset Object.

Description

Locates the first, last, next, or previous record in a dynaset- or Snapshot-Type Recordset object that satisfies the specified criteria and makes that record the current record.

Syntax

recordset.{FindFirst | FindLast | FindNext | FindPrevious} criteria

The Find methods have these parts.

Part | Description
recordset | The name of an existing dynaset- or Snapshot-Type Recordset object.
criteria | A string expression (like the WHERE clause in an SQL statement without the word WHERE) used to locate the record.

Remarks

If you want to include all the records in your search — not just those that meet a specific condition — use the Move methods to move from record to record. To locate a record in a table-type Recordset, use the Seek method.

If a record matching the criteria isn't located, the current record pointer is undetermined, and the NoMatch property is set to True. If recordset contains more than one record that satisfies the criteria, FindFirst locates the first occurrence, FindNext locates the next occurrence, and so on.

Caution

If you edit the current record, be sure you save the changes using the Update method before you move to another record. If you move to another record without updating, your changes are lost without warning.

Each of the Find methods begins its search from the location and in the direction specified in the following table.

Find methods | Begin | Search direction
FindFirst | Beginning of recordset | End of recordset
FindLast | End of recordset | Beginning of recordset
FindNext | Current record | End of recordset
FindPrevious | Current record | Beginning of recordset

When you use the FindLast method, the Microsoft Jet database engine fully populates your recordset before beginning the search, if this hasn't already been done.

Using one of the Find methods isn't the same as using a Move method, however, which simply makes the first, last, next or previous record current without specifying a condition. You can follow a Find operation with a Move operation.

Always check the value of the NoMatch property to determine whether the Find operation has succeeded. If the search succeeds, NoMatch is set to False. If it fails, NoMatch is set to True and the current record isn't defined. In this case, you must position the current record pointer back to a valid record, as shown in the following example.

Dim Here as Variant
Here = rstCustomers.Bookmark
rstCustomers.Find "Name = 'Ms. Schmidt'"    'Search for a name in the
                    ' recordset.
If rstCustomers.NoMatch then     'Was it found?
    rstCustomers.Bookmark = Here    'If not, go back to
                    ' previously current record.
Else
.                     'Match found.
...
...
End If
Using the Find methods with ODBC-accessed recordsets can be inefficient. You may find that rephrasing your criteria to locate a specific record is faster, especially when working with large recordsets.

You should use the U.S. date format (month-day-year) when you search for fields containing dates, even if you're not using the U.S. version of the Jet database engine; otherwise, the data may not be found. Use the Visual Basic Format function to convert the date. For example:

rstEmployees.FindFirst "HireDate > #" & Format(mydate, 'm/d/yy' ) & "#"
When working with ODBC databases and large dynasets, you might discover that using the Find methods or using the Sort or Filter properties is slow. You can improve performance by using SQL queries with customized ORDER BY or WHERE clauses, parameter queries, or QueryDef objects that retrieve specific indexed records.

Note

You can't use the Find methods with forward-only-scrolling snapshots.

See Also

AbsolutePosition Property; Move Method; MoveFirst, MoveLast, MoveNext, MovePrevious Methods; NoMatch Property; Seek Method.

Specifics (Microsoft Access)

When specifying criteria for the Find methods, you must be careful to reference fields and controls properly, and to construct the criteria string correctly.

When you use a bookmark in a Microsoft Access module, you must include an Option Compare Binary statement in the Declarations section of the module. A bookmark is a Variant array of Byte data, so the string comparison method for the module must be binary. If a bookmark is evaluated with a text-based string comparison method, such as the Option Compare Text statement or the default setting for the Option Compare Database statement, the current record may be set to an incorrect record.

You should use the the month-day-year format when you search for fields containing dates, even if the Regional Settings of the Windows® Control Panel is set to a different format; otherwise, the data may not be found. You can use the Visual Basic Format function to make this easier. The following code requests a date from the user and constructs a string on which to search.

dim dteAny As Date
dteAny = InputBox ("Please enter a date in month-day-year format.")
rstOrders.FindFirst "[OrderDate] > #" & Format(dteAny, "m/d/yy") & "#"
Example

This example uses FindFirst to find the first record matching the specified criteria in a Recordset object and then uses FindNext to find the next matching record.

Dim strCriteria As String
strCriteria = "State = 'NY'"    ' Set the criteria.
rstAddress.FindFirst strCriteria    ' Find first matching record.
If rstAddress.NoMatch = False Then    ' Check if record is found.
    rstAddress.FindNext strCriteria    ' Find next matching record.
...
This example creates a dynaset-type Recordset object and then uses FindFirst to locate the first record satisfying the title condition.

Dim strCriteria As String
Dim dbsBiblio As Database, rstPublishers As Recordset
strCriteria = "State = 'NY'"     ' Define search criteria.
Set dbsBiblio = DBEngine.Workspaces(0).OpenDatabase("Biblio.mdb")
' Create a dynaset-type Recordset based on Publishers table.
Set rstPublishers = dbsBiblio.OpenRecordset("Publishers",dbOpenDynaset)
rstPublishers.FindFirst strCriteria    ' Find first matching record.
If rstPublishers.NoMatch = False Then    ' Check if record is found.
    rstPublishers.FindNext strCriteria    ' Find next matching record.
...
Example (Microsoft Access)

The following example creates a dynaset-type Recordset object and then uses the FindFirst method to locate the first record satisfying the specified criteria. The procedure then finds the remaining records that satisfy the criteria.

Sub FindRecord()
    Dim dbs As Database, rst As Recordset
    Dim strCriteria As String

    ' Return Database variable pointing to current database.
    Set dbs = CurrentDb
    ' Define search criteria.
    strCriteria = "[ShipCountry] = 'UK' And [OrderDate] >= #1-1-95#"
    ' Create a dynaset-type Recordset object based on Orders table.
    Set rst = dbs.OpenRecordset("Orders", dbOpenDynaset)
    ' Find first matching record.
    rst.FindFirst strCriteria
    ' Check if record is found.
    If rst.NoMatch Then
        MsgBox "No record found."
    Else
        ' Find other matching records.
        Do Until rst.NoMatch
            Debug.Print rst!ShipCountry; "   "; rst!OrderDate
            rst.FindNext strCriteria
        Loop
    End If
End Sub


Foreign Property

Applies To

Index Object.

Description

Returns a value that indicates whether an Index object represents a foreign key in a table. This property setting is read-only and returns True (-1) if the Index object represents a foreign key.

Remarks

A foreign key consists of one or more fields in a foreign table that uniquely identify all rows in a primary table.

The Microsoft Jet database engine creates an Index object for the foreign table and sets the Foreign property when you create a relationship that enforces referential integrity.

See Also

Primary Property, TableDef Object.

Example (Microsoft Access)

The following example prints the value of the Foreign property for each index in an Orders table.

Sub CheckForeign()
    Dim dbs As Database, tdf As TableDef, idx As Index

    ' Return Database variable that points to current database.
    Set dbs = CurrentDb
    Set tdf = dbs.TableDefs!Orders

    ' Enumerate through Indexes collection of Orders table.
    For Each idx In tdf.Indexes
        ' Print value of Foreign property.
        Debug.Print idx.Name; "      "; idx.Foreign
    Next idx
End Sub


ForeignName Property

Applies To

Field Object.

Description

Sets or returns a value that, in a relationship, specifies the name of the Field object in a foreign table that corresponds to a field in a primary table.

Settings and Return Values

The setting or return value is a string expression that evaluates to the name of a Field in the associated TableDef object's Fields collection.

Remarks

Only a Field object that belongs to a Fields collection contained by a Relation object can support the ForeignName property. If the Relation isn't appended to the Database, but the Field is appended to the Relation, you can still change the ForeignName property. Once the Relation object is appended to the database, the properties of the Field object are read-only.

The Name and ForeignName property value settings for a Field object specify the names of the corresponding fields in the primary and foreign tables of a relationship. The Table and ForeignTable property value argument settings of a Relation object determine the primary and foreign tables of a relationship.

For example, if you had a list of valid part codes (in a field named PartNo) stored in a ValidParts table, you could establish a relationship with an OrderItem table such that if a part code was entered into the OrderItem table it must exist in the ValidParts table. If the part code did not exist in the ValidParts table and you had not indicated no enforcement of referential integrity in the Attributes property, a trappable error would occur.

In this case, the ValidParts table would be an example of a Primary table, so the ForeignTable property of the Relation object would be set to OrderItem and the Table property of the Relation object would be set to ValidParts. The Name property and ForeignName property of the Field object would both be PartNo.

See Also

ForeignTable Property, Name Property, Table Property.

Example

This example shows how you can use the ForeignName, ForeignTable, and Table properties when you create a relationship between two existing tables — in this case, Table1 (the primary table) and Table2 (the foreign table) in the specified database. Field1 is the primary key in Table1, and Field2 is a foreign key in Table2. The relationship is one-to-many and referential integrity is enforced.

Function ForeignNameTable () As Integer
    Dim dbsDefault As Database
    Dim fldLocal As Field, relForeign As Relation
' Get database.
    Set dbsDefault = _
         DBEngine.Workspaces(0).OpenDatabase("Northwind.mdb")
' Create new relationship and set its properties.
    Set relForeign = dbsDefault.CreateRelation("MyRelation")
    relForeign.Table = "Table1"
    relForeign.ForeignTable = "Table2"
' Create field and set its properties.
    Set fldLocal = relForeign.CreateField("Field1")
    fldLocal.ForeignName = "Field2"
' Append field to relation and relation to database.
    relForeign.Fields.Append fldLocal
    dbsDefault.Relations.Append relForeign
    dbsDefault.Close
End Function
Example (Microsoft Access)

The following example shows how you can use the ForeignName, ForeignTable, and Table properties when you create a relationship between two existing tables — in this case, Employees (the primary table) and Orders (the foreign table) in the current database. EmployeeID is the primary key in the Employees table, and also a foreign key in the Orders table. The relationship is one-to-many and referential integrity is enforced.

To test the following example in Microsoft Access, open the Northwind database and click Relationships on the Tools menu. Delete the relationship between the Employees table and the Orders table. Close the Relationships window, saving the current configuration when prompted. Then run the following procedure from a standard module, and view the Relationships window again to see the new relationship.

Sub ForeignNameTable()
    Dim dbs As Database
    Dim fld As Field, rel As Relation

    ' Return Database variable that points to current database.
    Set dbs = CurrentDb
    ' Create new relationship and set its properties.
    Set rel = dbs.CreateRelation("EmployeesRelation")
    ' Denote primary table.
    rel.Table = "Employees"

    ' Denote foreign table.
    rel.ForeignTable = "Orders"
    rel.Attributes = dbRelationUpdateCascade + dbRelationDeleteCascade
    ' Create field in Fields collection of Relation.
    Set fld = rel.CreateField("EmployeeID")
    ' Provide name of foreign key field.
    fld.ForeignName = "EmployeeID"
    ' Append field to Relation and Relation to database.
    rel.Fields.Append fld
    dbs.Relations.Append rel
End Sub


ForeignTable Property

Applies To

Relation Object.

Description

Sets or returns the name of the foreign table in a relationship. This property setting is read/write for a new Relation object not yet appended to a collection and read-only for an existing Relation object in the Relations collection.

Settings and Return Values

The setting or return value is a string expression that evaluates to the name of a table in the Database object's TableDefs collection. The data type is String.

Remarks

The ForeignTable property setting of a Relation object is the Name property setting of the TableDef or QueryDef object that represents the foreign table or query; the Table property setting is the Name property setting of the TableDef or QueryDef object that represents the primary table or query.

For example, if you had a list of valid part codes (in a field named PartNo) and stored in a ValidParts table, you could establish a relationship with an OrderItem table such that if a part code was entered into the OrderItem table, it must exist in the ValidParts table. If the part code did not exist in the ValidParts table and you had not indicated no enforcement of referential integrity in the Attributes property, a trappable error would occur.

In this case, the ValidParts table would be an example of a foreign table, so the ForeignTable property of the Relation object would be set to ValidParts and the Table property of the Relation object would be set to OrderItem. The Name property and ForeignName property of the Field object would both be set to PartNo.

See Also

ForeignName Property, Name Property, QueryDef Object, Table Property, TableDef Object.

Example

See the ForeignName property example.

Example (Microsoft Access)

See the ForeignName property example (Microsoft Access).


GetChunk Method

Applies To

Field Object.

Description

Returns all or a portion of the contents of a Memo or an OLE Object Field object in the Fields collection of a Recordset object.

Syntax

stringvar = recordset ! field.GetChunk(offset, numbytes)

The GetChunk method syntax has these parts.

Part | Description
stringvar | The name of a String variable or Variant that receives the data from the Field object named by field.
recordset | A variable of an object data type that specifies the Recordset object containing the Fields collection.
field | The name of a Field object whose Type property is set to dbMemo (Memo) or dbLongBinary (OLE Object).
offset | A numeric expression that is the number of bytes to skip before copying begins.
numbytes | A numeric expression that is the number of bytes you want to return.

Remarks

Assign the bytes returned by GetChunk to stringvar. Use GetChunk to return a portion of the total data value at a time. You can use the AppendChunk method to reassemble the pieces.

If offset is 0, GetChunk begins copying from the first byte of the field.

If numbytes is greater than the number of bytes in the field, the actual number of bytes in the field is returned.

Note

Use a Memo-type field for human-readable textual data, and put binary data only in OLE-type fields. Doing otherwise will cause undesirable results.

See Also

AppendChunk Method, FieldSize Method, Type Property.

Specifics (Microsoft Access)

After assigning the results of the GetChunk method to a string variable, you can use the Visual Basic Len function to determine the number of characters in the string. Or you can use the LenB function to determine the number of bytes used to represent that string.

Example

See the AppendChunk method example.

Example (Microsoft Access)

See the AppendChunk method example (Microsoft Access).


GetRows Method

Applies To

Dynaset-Type Recordset Object, Recordset Object, Snapshot-Type Recordset Object, Table-Type Recordset Object.

Description

Retrieves multiple rows of a Recordset into an array.

Syntax

varArray = object.GetRows (numrows)

The GetRows Method syntax has the following parts.

Part | Description
varArray | The name of a Variant type variable to store the returned data.
object | An object expression that evaluates to an object in the Applies To list.
numrows | The number of rows to retrieve.

Remarks

Use the GetRows method to copy one or more entire records from a Recordset. GetRows returns a two-dimensional array. The first subscript identifies the field and the second identifies the row number, as follows:

avarRecords(intField, intRecord)
To get the first field value in the second row returned, use the following:

field1 = avarRecords(0,1)
To get the second field value in the first row, use the following:

field2 = avarRecords(1,0)
If more rows are requested than are available, then only the number available are returned. Use Ubound to determine how many rows were actually fetched, as the array is sized to fit how many rows were returned. For example, if you returned the results into a variant called varA, you could determine how many rows were actually returned by using:

numReturned = Ubound(varA,2) + 1

The "+ 1" is used because the first data returned is in the 0 element of the array. The number of rows that can be fetched is constrained by available memory and should be chosen to suit your application — don't expect to use GetRows to bring your whole table into an array if it is a large table.

Because all fields of the recordset are returned in the array, including long memo and binary fields, you might want to use a query that restricts the columns returned.

After a call to GetRows, the current record is positioned at the next unread row. That is, GetRows has an equivalent positioning effect to Move numrows.

If you are trying to fetch all the rows using multiple GetRows calls, use the EOF property to be sure that you're at the end of the Recordset. GetRows returns less than the number requested either at the end of the Recordset, or if it cannot fetch a row in the range requested. For example, if a fifth record cannot be retrieved in a group of ten records that you're trying to fetch, GetRows returns four records and leaves currency on the record that caused a problem. It will not generate a run-time error. This situation might occur if a record in a dynaset has been deleted by another user.

See Also

FillCache Method, Move Method, Value Property.

Example

The following example uses an SQL statement to retrieve three fields from an Employees table into a Recordset object. It then uses the GetRows method to retrieve the first three records of the Recordset, and stores the selected records in a two-dimensional array. Each record is then printed, one field at a time, using the two array indexes to select specific fields and records.

Note

To clearly illustrate how the array indexes are used, the example uses a separate statement to identify and print each field of each record. In practice, it would be more reliable to use two loops, one nested in the other, and provide integer variables for the indexes, to step through both dimensions of the array.

Sub GetRows_Test()

    Dim dbsCurrent As Database, rstEmployees As Recordset
    Dim varRecords As Variant

    Set dbsCurrent = CurrentDB()
    Set rstEmployees = dbsCurrent.OpenRecordset("SELECT FirstName, " & _
        "LastName, Title FROM Employees", dbOpenSnapshot)

    varRecords = rstEmployees.GetRows(3)

    Debug.Print "First Name", "Last Name", "Title"
    Debug.Print varRecords(0, 0),
    Debug.Print varRecords(1, 0),
    Debug.Print varRecords(2, 0)

    Debug.Print varRecords(0, 1),
    Debug.Print varRecords(1, 1),
    Debug.Print varRecords(2, 1)
    Debug.Print varRecords(0, 2),
    Debug.Print varRecords(1, 2),
    Debug.Print varRecords(2, 2)

End Sub
Example (Microsoft Access)

The following example uses the GetRows method to return a two-dimensional array containing the first ten rows of data in a Recordset object.

Sub RowsArray()
    Dim dbs As Database, rst As Recordset, strSQL As String
    Dim varRecords As Variant, intI As Integer, intJ As Integer

    ' Return Database variable pointing to current database.
    Set dbs = CurrentDb
    ' Build SQL statement that returns specified fields.
    strSQL = "SELECT [FirstName], [LastName], [HireDate] " & _
        "FROM [Employees]"
    ' Open dynaset-type Recordset object.
    Set rst = dbs.OpenRecordset(strSQL)
    ' Return first ten rows into array.
    varRecords = rst.GetRows(10)
    ' Find upper bound of second dimension.
    For intI = 0 To UBound(varRecords, 2)
        Debug.Print
        ' Find upper bound of first dimension.
        For intJ = 0 To UBound(varRecords, 1)
            ' Print data from each row in array.
            Debug.Print varRecords(intJ, intI)
        Next intJ
    Next intI
End Sub
Example (Microsoft Excel)

This example copies records from a selection of the Customer recordset in the NWINDEX.MDB database to Sheet1.

To create the NWINDEX.MDB database, run the Microsoft Excel example for the CreateDatabase method.

Dim db As Database, rs As Recordset
Dim data As Variant
Set db = Workspaces(0).OpenDatabase(Application.Path & "\NWINDEX.MDB")
Set rs = db.OpenRecordset("SELECT CUSTMR_ID, CONTACT FROM Customer;")
data = rs.GetRows(6)
Sheets("Sheet1").Activate
For r = 1 to UBound(data, 2) + 1

    For c = 1 to 2
        Cells(r, c).Value = data(c - 1, r - 1)
    Next
Next
rs.Close
db.Close


Group Object

Description

A Group object represents a group of user accounts that have common access permissions when a Workspace object operates as a secure workgroup.

Remarks

You create Group objects and then use their names to establish and enforce access permissions for your databases, tables, and queries using the Document objects that represent the database and database objects (tables and queries) you're working with.

You can append an existing Group object to the Groups collection in a User object to establish membership of a user account in that Group object. Alternatively, you can append a User object to the Users collection in a Group object to give a user account the global permissions of that group. If you use a Groups or Users collection other than the one to which you just appended an object, you may need to use the Refresh method to refresh the collection with current information from the database.

Using the properties of a Group object, you can:

  • Check the Name property setting of an existing Group object to determine its name. You can't check the PID property setting of an existing Group object.
  • Set the Name and PID properties of a newly created, unappended Group object to establish the identity of that Group object.
 The Microsoft Jet database engine predefines three Group objects named Admins, Users, and Guests.

You can refer to a Group object that you create and append to a Groups collection by its Name property setting using this syntax:

Groups("name")

To create a new Group object, use the CreateGroup method on a User or Workspace object.

Properties

Name Property, PID Property.

Methods

CreateUser Method.

See Also

CreateGroup Method; Appendix, "Data Access Object Hierarchy."

Specifics (Microsoft Access)

You can create Group objects to establish and enforce permissions for Microsoft Access database objects as well as for data access objects. For example, you can set security for forms, reports, macros, and modules.

A Group object has a Name property that you can use in setting permissions for a Container or Document object. For example, you can assign the value of a Group object's Name property to the UserName property of a Container or Document object. You can then set the Permissions property of the Container or Document object to establish permissions for the group of users defined by the UserName property. Or you can read the Permissions property to determine existing permissions for that group.

Example

This example illustrates the use of the Group and User objects and the Groups and Users collections. First, it creates a new User object with the Name, PID, and Password property settings of "Pat Smith," "abc123DEF456," and "My Secret," and appends the object to the Users collection of the default Workspace object. Next, it creates a new Group object with the Name and PID property settings of "Accounting" and "UVW987xyz654" and appends the object to the Groups collection of the default Workspace object. Then the example adds user Pat Smith to the Accounting group. Finally, it enumerates the User and Group objects in the collections of the default Workspace object.

Function EnumerateUserGroup () As Integer
    Dim wrkDefault As Workspace
    Dim usrPatSmith As User, usrTemp As User, usrGroupUser As User
    Dim grpAccount As Group, grpTemp As Group, grpMember As Group
    Dim intI As Integer, intJ As Integer

    Set wrkDefault = DBEngine.Workspaces(0)

' Create and append new user.
    Set usrPatSmith = wrkDefault.CreateUser("Pat Smith", _
        "abc123DEF456", "My Secret")
    wrkDefault.Users.Append usrPatSmith

' Create and append new group.
    Set grpAccount = wrkDefault.CreateGroup("Accounting", _
        "UVW987xyz654")
    wrkDefault.Groups.Append grpAccount

' Add new user to new group or converse; do one or the other, not both.
' Use Refresh because both collections are referred to in following
' code.
'    wrkDefault.Groups![Accounting].Users.Append usrGroupUser
'    wrkDefault.Users![Pat Smith].Groups.Refresh

' Or add group to user and refresh group.

' Create new group object for user Pat Smith
    Set grpMember = usrPatSmith.CreateGroup("Accounting")

'  wrkDefault.Users![Pat Smith].Groups.Append grpMember
'  wrkDefault.Groups![Accounting].Users.Refresh

' Enumerate all users.
    For intJ = 0 To wrkDefault.Users.Count - 1
        Set usrTemp = wrkDefault.Users(intJ)
        Debug.Print
        Debug.Print "Enumeration of Users: "; usrTemp.Name
        Debug.Print
' Enumerate groups.
        Debug.Print "    Groups: "
        For intI = 0 To usrTemp.Groups.Count - 1
            Debug.Print "    "; usrTemp.Groups(intI).Name
        Next intI
    Next intJ

' Enumerate all groups.
    Debug.Print "------------------------------------"
    For intJ = 0 To wrkDefault.Groups.Count - 1
        Set grpTemp = wrkDefault.Groups(intJ)
        Debug.Print
        Debug.Print "Enumeration of Groups: "; grpTemp.Name
        Debug.Print
' Enumerate users.
        Debug.Print "    Users: "
        For intI = 0 To grpTemp.Users.Count - 1
            Debug.Print "    "; grpTemp.Users(intI).Name
        Next intI
    Next intJ
    EnumerateUserGroup = True
End Function
Example (Microsoft Access)

The following example creates a new User object and appends it to the Users collection of a Workspace object. It then creates a new Group object and appends it to the Groups collection of the Workspace object. The new Group object is also appended to the Groups collection of the User object. The new group is then given modify and delete permissions for modules.

Note that in order to assign users to groups, you must either append a User object to the Users collection of a Group object, or append a Group object to the Groups collection of a User object. It doesn't matter which option you choose; either will result in the specified user being included in the specified group.

Sub NewModulesGroup()
    Dim wsp As Workspace, dbs As Database
    Dim usr As User, grp As Group, grpMember As Group

    Dim ctr As Container, doc As Document

    ' Get default Workspace object.
    Set wsp = DBEngine.Workspaces(0)
    ' Return Database variable pointing to current database.
    Set dbs = CurrentDb
    ' Create User object and append to Users collection
    ' of Workspace object.
    Set usr = wsp.CreateUser("Pat Smith", "123abc789xyz", "Password")
    wsp.Users.Append usr
    ' Create Group object and append to Groups collection
    ' of Workspace object.
    Set grp = wsp.CreateGroup("Programmers", "321xyz987abc")
    wsp.Groups.Append grp
    ' Append Group object to Groups collection of User object.
    Set grpMember = usr.CreateGroup("Programmers")
    usr.Groups.Append grpMember
    ' Refresh Groups collection of User object.
    usr.Groups.Refresh
    ' Return Container object.
    Set ctr = dbs.Containers!Modules
    ' Set UserName property of Container object.
    ctr.UserName = grpMember.Name
    'Add modify and delete permissions for new group on all modules.
    ctr.Permissions = ctr.Permissions Or acSecModWriteDef
End Sub


Groups Collection

Description

A Groups collection contains all stored Group objects of a Workspace or user account.

Remarks

You can append an existing Group object to the Groups collection in a User object or a Workspace object to establish membership of a user account in that Group object. Alternatively, you can append a User object to the Users collection in a Group object to give a user account the global permissions of that group. If you use a Groups or Users collection other than the one to which you just appended an object, you may need to use the Refresh method to refresh the collection with current information from the database.

You can refer to a Group object that you create and append to a Groups collection by its Name property setting using this syntax:

Groups("name")

To create a new Group object, use the CreateGroup method.

Properties

Count Property.

Methods

Append Method, Delete Method, Refresh Method.

See Also

Appendix, "Data Access Object Hierarchy."

Specifics (Microsoft Access)

See the Group object specifics (Microsoft Access).

Example

See the Group object example.

Example (Microsoft Access)

See the Group object example (Microsoft Access).


HelpContext, HelpFile Properties

Applies To

Error Object.

  • HelpContext — returns a context ID, as a Long variable, for a topic in a Microsoft Windows Help file.
  • HelpFile — returns a fully qualified path to the Help file.
Remarks

If a Microsoft Windows Help file is specified in HelpFile, the HelpContext property is used to automatically display the Help topic it identifies.

Note

You should write routines in your application to handle typical errors. When programming with an object, you can use the Help supplied by the object's Help file to improve the quality of your error handling, or to display a meaningful message to your user if the error is not recoverable.

See Also

Description Property, Number Property, Source Property.

Specifics (Microsoft Access)

The data access HelpContext and HelpFile properties apply to the Error object. You can set it only from Visual Basic.

Note

Don't confuse these properties with the Microsoft Access HelpContextID and HelpFile properties. These properties are similar, but they apply only to forms, reports, and controls. You can set them from Visual Basic, in a macro, or in the property sheet within form Design view or report Design view.

Example

This example uses the HelpContext and HelpFile properties of an Error object to start the Microsoft Windows Help system. By default, the HelpFile property contains the name of the Microsoft Jet database engine error message Help file.

On Error Resume Next    ' Suppress errors for demonstration purposes.
Err.Raise 3005    ' Use VBA to generate "Invalid database name" error.
Msg = "Press F1 or Help to see " & Errors(0).HelpFile & _
    " topic for this error"
MsgBox Msg, , "Error: " & Errors(0).Description & _
    Errors(0).HelpFile & Errors(0).HelpContext


Idle Method

Applies To

DBEngine Object.

Description

Suspends data processing, enabling the Microsoft Jet database engine to complete any pending tasks such as memory optimization or page timeouts.

Syntax

DBEngine.Idle [dbFreeLocks]

Remarks

You use the Idle method to provide the Jet database engine with the opportunity to perform background tasks that may not be up-to-date because of intense data processing. This is often true in multiuser, multitasking environments in which there isn't enough background processing time to keep all records in a recordset current.

Usually, read locks are removed and data in local dynaset-type Recordset objects is updated only when no other actions (including mouse movements) are occurring. If you periodically use the Idle method, you provide the database engine with time to catch up on background processing tasks by releasing unneeded read locks. If you specify the dbFreeLocks constant as an argument, processing is delayed until all read locks are released.

This method isn't needed in single-user environments unless multiple instances of an application are running. The Idle method may increase performance in a multiuser environment because it forces the database engine to flush data to disk, releasing locks on memory.

You can also release read locks by making operations part of a transaction. For example:

wspSession.BeginTrans
Set rstEmployees = rstEmployees.OpenRecordset("Employees")
wspSession.CommitTrans

Do Until rstEmployees.EOF
    ...
    ...
    ...
    rstEmployees.MoveNext
Loop


IgnoreNulls Property

Applies To

Index Object.

Description

Sets or returns a value that indicates whether records that have Null values in their index fields have index entries. This property is read/write for a new Index object not yet appended to a collection and read-only for an existing Index object in an Indexes collection.

Settings and Return Values

This property is a Boolean expression that indicates index entries. The data type is Boolean. True (-1) indicates that the fields with Null values don't have an index entry.

Remarks

To make searching for records using a field faster, you can define an index for the field. If you allow Null entries in an indexed field and expect many of the entries to be Null, you can set the IgnoreNulls property for the Index object to True to reduce the amount of storage space that the index uses.

The IgnoreNulls property setting and the Required property setting together determine whether a record with a Null index value has an index entry, as the following table shows.

IgnoreNulls | Required | Null in index field
True | False | Null value allowed; no index entry added
False | False | Null value allowed; index entry added
True or False | True | Null value not allowed; no index entry added

See Also

Required Property.

Example (Microsoft Access)

The following example adds a new index to a TableDef object, makes that index the current index, and invokes the Seek method based on that index. The names of the Field objects created and appended to the Fields collection of the Index object correspond to the names of current fields in the table.

Sub NewIndex()
    Dim dbs As Database, tdf As TableDef
    Dim idx As Index, fldID As Field, fldName As Field

    ' Return Database variable that points to current database.
    Set dbs = CurrentDb
    Set tdf = dbs.TableDefs!Products
    ' Return Index object that points to new index.
    Set idx = tdf.CreateIndex("IDName")
    ' Create and append index fields.
    Set fldID = idx.CreateField("ProductID")
    Set fldName = idx.CreateField("ProductName")
    idx.Fields.Append fldID
    idx.Fields.Append fldName
    ' Set index properties.
    idx.IgnoreNulls = True
    idx.Unique = True
    ' Append the new Index object to the Indexes collection.
    tdf.Indexes.Append idx
End Sub


Index Object

Description

Index objects specify the order of records accessed from database tables and whether or not duplicate records are accepted. Index objects also provide efficient access to data. For external databases, Index objects describe the indexes established for external tables.

Remarks

The Microsoft Jet database engine maintains all base table indexes automatically. Indexes are updated whenever you add, change, or delete records from the base table. Once the database is created, use the CompactDatabase method periodically to bring index statistics up-to-date.

The Jet database engine uses indexes when it joins tables and creates Recordset objects. Indexes determine the order of records returned by table-type Recordset objects, but they don't determine the order in which records are stored in the base table or the order of records returned from any other type of recordset.

When accessing a table-type Recordset object, you specify the order of records using the object's Index property. Set this property to the Name property setting of an existing Index object in the Indexes collection. This collection is contained by the TableDef object underlying the Recordset object that you're populating. For example, to order your table-type Recordset object by the ZIP_INDEX index, you could use the following code.

Set dbsBiblio = Workspaces(0).OpenDatabase("Biblio.mdb")
Set rstPublishers = dbsBiblio.OpenRecordset("Publishers", dbOpenTable)
rstPublishers.Index = "ZIP_INDEX"
Tip

You don't have to create indexes for a table, but for large, unindexed tables, accessing a specific record or processing joins can take a long time. Conversely, having too many indexes can slow down updates to the database as each of the table indexes is amended.

The Attributes property of each Field object in the index determines the order of records returned and consequently determines which access techniques to use for that index.

Each Field object in the Fields collection of an Index object is a component of the index. You define a new Index object by setting its properties before you append it to a collection, which makes the Index object available for subsequent use.

Note

You can modify the Name property setting of an existing Index object only if the Updatable property setting of the containing TableDef object is True.

Using an Index object and its properties, you can:

  • Use the Required property to determine whether the Field objects in the index require values that are not Null, then use the IgnoreNulls property to determine whether the Null values have index entries.
  • Use the Primary and Unique properties to determine the ordering and uniqueness of the Index object.
When you set a primary key for a table, the Jet database engine automatically defines it as the primary index. A primary index consists of one or more fields that uniquely identify all records in a table in a predefined order. Because the primary index field must be unique, the Jet database engine automatically sets the Unique property of the primary Index object to True. If the primary index consists of more than one field, each field can contain duplicate values, but the combination of values from all the indexed fields must be unique. A primary index consists of a key for the table and is always made up of the same fields as the primary key.

Important

Make sure your data complies with the attributes of your new index. If your index requires unique values, make sure that there are no duplicates in existing data records. If duplicates exist, the Jet database engine can't create the index, resulting in a trappable error when you attempt to use the Append method on the new index.

When you create a relationship that enforces referential integrity, the Jet database engine automatically creates an index with the Foreign property, set as the foreign key in the referencing table. After you've established a table relationship, the Jet database engine prevents additions or changes to the database that violate that relationship. If you set the Attributes property of the Relation object to allow cascade update and cascade delete operations, the Jet database engine updates or deletes records in related tables automatically.

Note

The Clustered property is ignored for databases that use the Jet database engine, which doesn't support clustered indexes.

Properties

Clustered Property, DistinctCount Property, Foreign Property, IgnoreNulls Property, Name Property, Primary Property, Required Property, Unique Property.

Methods

CreateField Method, CreateProperty Method.

See Also

Attributes Property; CreateIndex Method; Index Property, OrdinalPosition Property; Appendix, "Data Access Object Hierarchy."

Example

This example creates a new TableDef object and two new Field objects, appends the Field objects to the Fields collection in the new TableDef, and appends the TableDef to the TableDefs collection in the database. Then it creates a new primary Index object, includes the two Field objects in it, and appends the Index to the Indexes collection of the TableDef. Finally, the example enumerates the Index objects in the current database.

Function EnumerateIndex () As Integer
Dim dbsDefault As Database, tdfTest As TableDef
Dim fldOne As Field, fldTwo As Field, idxPrimary As Index
Dim I As Integer
' Get workspace and database.
Set dbsDefault = _
DBEngine.Workspaces(0).OpenDatabase("Northwind.mdb")
' Create table with two fields.
Set tdfTest = dbsDefault.CreateTableDef("MyTable")
Set fldOne = tdfTest.CreateField("Field1", dbLong)
fldOne.Required = True ' No Null values allowed.
tdfTest.Fields.Append fldOne
Set fldTwo = tdfTest.CreateField("Field2", dbLong)
fldTwo.Required = True ' No Null values allowed.
tdfTest.Fields.Append fldTwo
dbsDefault.TableDefs.Append tdfTest
' Create primary index for those two fields.
Set idxPrimary = tdfTest.CreateIndex("MyIndex")
idxPrimary.Primary = True
Set fldOne = tdfTest.CreateField("Field1")
idxPrimary.Fields.Append fldOne

    Set fldTwo = tdfTest.CreateField("Field2")
    idxPrimary.Fields.Append fldTwo
    tdfTest.Indexes.Append idxPrimary
    ' Enumerate index and its fields.
    Debug.Print "Index: "; idxPrimary.Name
    Debug.Print "  Required: "; idxPrimary.Required
    Debug.Print "  IgnoreNulls: "; idxPrimary.IgnoreNulls
    Debug.Print "  Primary: "; idxPrimary.Primary
    Debug.Print "  Clustered: "; idxPrimary.Clustered
    Debug.Print "  Unique: "; idxPrimary.Unique
    Debug. Print "  Foreign: "; idxPrimary.Foreign
    Debug.Print
    Debug.Print "Fields in Index: ";
    For I = 0 To idxPrimary.Fields.Count - 1
        Debug.Print " "; idxPrimary.Fields(I).Name;
    Next I
    Debug.Print
    EnumerateIndex = True
End Function
This example opens a table-type Recordset and selects an index for the Recordset. By setting an index, the Microsoft Jet database engine returns records in the order specified by the index. Without an index, table-type Recordset objects return records from the database table in no particular order.

Dim dbsDefault As Database
Dim rstTitles as Recordset
' Get workspace and database.
Set dbsDefault = _
     DBEngine.Workspaces(0).OpenDatabase("Northwind.mdb")
Set rstTitles = dbsDefault.OpenRecordset("Titles")
rstTitles.Index = "MyIndex"
.
.
.
Example (Microsoft Access)

The following example creates a new index on an Employees table.

Sub NewIndex()
    Dim dbs As Database, tdf As TableDef, idx As Index
    Dim fld As Field

    ' Return Database object pointing to current database.
    Set dbs = CurrentDb
    Set tdf = dbs.TableDefs!Employees
    Set idx = tdf.CreateIndex("LastNameIndex")
    Set fld = idx.CreateField("LastName")
    idx.Fields.Append fld
    tdf.Indexes.Append idx
End Sub


Index Property

Applies To

Recordset Object, Table-Type Recordset Object.

Description

Sets or returns a value that indicates the name of the current Index object in a table-type Recordset object.

Settings and Return Values

The setting or return value is a string expression that evaluates to the name of an Index object in the Indexes collection of the Table or table-type Recordset object's TableDef object. The data type is String.

Remarks

Records in base tables aren't stored in any particular order. Setting the Index property changes the order of records returned from the database; it doesn't affect the order in which the records are stored.

For example, to set the Index property prior to using the Seek method on the Titles table:

Dim rstTitles as Recordset, dbsBiblio as Database
Set dbsBiblio = Workspaces(0).OpenDatabase("Biblio.mdb")
Set rstTitles = dbsBiblio.OpenRecordset("Titles",dbOpenTable)
rstTitles.Index = "PubID"
rstTitles.Seek "=", 3
The specified Index object must already be defined. If you set the Index property to an Index object that doesn't exist or if the Index property isn't set when you use the Seek method, a trappable error occurs.

Examine the Indexes collection of a TableDef object to determine what Index objects are available to table-type Recordset objects created from that TableDef object.

You can create a new index for the table by creating a new Index object, setting its properties, appending it to the Indexes collection of the underlying TableDef object, and then reopening the Recordset object.

Records returned from a table-type Recordset object can be ordered only by the indexes defined for the underlying TableDef object. To sort records in some other order, you can open a dynaset- or Snapshot-Type Recordset object using an SQL statement with an ORDER BY clause.

Tips

  • You don't have to create indexes for tables, but in large, unindexed tables, accessing a specific record or creating a Recordset object can take a long time. On the other hand, creating too many indexes slows down update, append, and delete operations as all indexes are automatically updated.
  • Records read from tables without indexes are returned in no particular sequence.
  • The Attributes property of each Field object in the Index object determines the order of records and consequently determines the access techniques to use for that index.
  • A unique index helps optimize finding records.
  • Indexes don't affect the physical order of a base table — indexes affect only how the records are accessed by the table-type Recordset object when a particular index is chosen or when the Microsoft Jet database engine creates Recordset objects.
See Also

Append Method, Index Object, Primary Property, Seek Method, Sort Property, TableDef Object.

Example

This example adds a new index to a TableDef object in the Biblio.mdb database, makes that index the current index, and invokes the Seek method based on that index. The names of the Field objects created and appended to the Fields collection of the Index object correspond to the names of current fields in the table.

Dim rstPublishers As Recordset, dbsBiblio As Database
Dim idxPubIDName As Index, fldPubID As Field, fldName As Field
Set dbsBiblio =  DBEngine.Workspaces(0).OpenDatabase("Biblio.mdb")
Set idxPubIDName = dbsBiblio.TableDefs("Publishers").CreateIndex _
    ("PubID Name")
Set fldPubID = idxPubIDName.CreateField("PubID")
idxPubIDName.Fields.Append fldPubID
Set fldName = idxPubIDName.CreateField("Name")
idxPubIDName.Fields.Append fldName
idxPubIDName.Unique = True
Debug.Print idxPubIDName.Fields    ' Show Fields property.
' Append the new Index to the Indexes collection.
dbsBiblio.TableDefs("Publishers").Indexes.Append idxPubIDName
'Open the table.
Set rstPublishers = dbsBiblio.OpenRecordset("Publishers",dbOpenTable)
rstPublishers.Index = "PubID Name"    ' Set table's current index.
rstPublishers.Seek "=", "27", "Yourdon Press"  ' Look for Publisher.
If rstPublishers.NoMatch Then
    rstPublishers.MoveFirst
    Debug.Print "Not found"
Else
    Debug.Print rstPublishers!Name
End If

rstPublishers.Close
This example sets the index for rstOrders to the primary key. (PrimaryKey is the default name of an Index object if the primary key is set in the table's Design view.) Next, it locates the record with a matching key field value of 10,050. Notice that the current index must be set before certain operations, such as the Seek method, can be performed.

Dim dbsNorthwind As Database, rstOrders As Recordset
Set dbsNorthwind =  DBEngine.Workspaces(0).OpenDatabase("Northwind.mdb")
Set rstOrders = dbsNorthwind.OpenRecordset("Orders", dbOpenTable)
rstOrders.Index = "PrimaryKey"    ' Set current index.
rstOrders.Seek "=", 10050    ' Locate record.
...
rstOrders.Close    ' Close recordset.
dbsNorthwind.Close    ' Close database.
Example (Microsoft Access)

The following example sets the index for a table-type Recordset object to the primary key. "PrimaryKey" is the default name of an Index object if the index corresponds to the primary key set in table Design view. Next, the procedure asks the user for a value to search on and locates the record with a matching key field value. Note that the current index must be set before certain operations, such as the Seek method, can be performed on a table-type Recordset object.

Sub UsePrimaryKey()
    Dim dbs As Database, rst As Recordset
    Dim fld as Field, strInput as String

    ' Return Database variable that points to current database.
    Set dbs = CurrentDb
    Set rst = dbs.OpenRecordset("Orders", dbOpenTable)
    ' Set current index.
    rst.Index = "PrimaryKey"
    strInput = InputBox("Enter the OrderID on which to search.")
    ' Locate record.
    rst.Seek "=", strInput
    If Not rst.NoMatch Then
        For Each fld in rst.Fields
            Debug.Print fld.Name; "   "; fld.Value
        Next fld
    End If
    ' Close Recordset object.
    rst.Close
End Sub


Indexes Collection

Description

An Indexes collection contains all the stored Index objects of a TableDef object.

Remarks

Once created, a new Index object should be added to the TableDef object's Indexes collection using the Append method.

When accessing a table-type Recordset object, you specify the order of records using the object's Index property. Set this property to the Name property setting of an existing Index object in the Indexes collection. This collection is contained by the TableDef object underlying the Recordset object that you're populating. For example, to order your table-type Recordset by the ZIP_INDEX index, you could use the following code.

Set dbsBiblio = Workspaces(0).OpenDatabase("Biblio.mdb")
Set rstPublishers = dbsBiblio.OpenRecordset("Publishers", dbOpenTable)
rstPublishers.Index = "ZIP_INDEX"

Note

You can use the Append or Delete method on an Indexes collection only if the Updatable property setting of the containing TableDef object is True.

If you attempt to create an Index object and your data doesn't comply with the attributes specified for the index, such as nonunique or Null values in an indexed field, a trappable error results when you attempt to use the Append method on the new index.

Properties

Count Property.

Methods

Append Method, Delete Method, Refresh Method.

See Also

Appendix, "Data Access Object Hierarchy."

Example

See the Index object example.

Example (Microsoft Access)

See the Index object example (Microsoft Access).


Inherit Property

Applies To

Container Object.

Description

Determines whether new Document objects will inherit a default Permissions property setting.

Return Values

The return values are Boolean data type.

Remarks

Use the Inherit property in conjunction with the Permissions property to define what permissions new documents will automatically be given when they're created. If you set the Inherit property to True (-1), and then set a permission on a container, then whenever a new document is created in that container, that permission will be set on the new document. This is a very convenient way of presetting permissions on an object.

Setting the Inherit property will not affect existing documents in the container — you can't modify all the permissions on all existing documents in a container by setting the Inherit property and a new permission. It will affect only new documents that are created after the Inherit property is set.

See Also

Document Object, Permissions Property.

Example

This example sets the Table container's Inherit property to True, and then sets the Permissions property to allow users to alter the security settings of documents.

Dim dbsNorthwind As Database, conTables As Container
Set dbsNorthwind =  DBEngine.Workspaces(0).OpenDatabase("Northwind.mdb")
Set conTables = dbsNorthwind.Containers("Tables")
conTables.Inherit = True
conTables.Permissions = dbSecWriteSec
dbsNorthwind.Close
Example (Microsoft Access)

The following example sets the Inherit property of the Forms Container object to True (-1), and then sets the Permissions property to give users full security access to all forms. All new Document objects of the Form type will inherit these permissions. The procedure then creates a new Form object and displays the permissions for that object.

Note that the Forms Container object is different from the Forms collection. The Forms Container object includes all Form Document objects in the database; the Forms collection contains only currently open forms.

Sub FormPermissions()
    Dim dbs As Database, ctrForms As Container
    Dim docForm As Document, frmNew As Form

    ' Return Database variable that points to current database.
    Set dbs = CurrentDb
    ' Return Container variable pointing to Forms Container object.
    Set ctrForms = dbs.Containers!Forms
    ' Set Inherit property.
    ctrForms.Inherit = True
    ' Set permissions to be inherited.
    ctrForms.Permissions = ctrForms.Permissions Or acSecFrmRptWriteDef
    ' Create new form.
    Set frmNew = CreateForm()

    ' Save form.
    DoCmd.Save , "OrderForm"
    ' Return Document object associated with new form.
    Set docForm = ctrForms.Documents!OrderForm
    ' Compare permissions for Container and Document objects.
    If docForm.Permissions <> ctrForms.Permissions Then
        MsgBox "Error!"
    Else
        MsgBox "Permissions successfully inherited."
    End If
End Sub


Inherited Property

Applies To

Property Object.

Description

Returns a value that indicates whether a Property object is inherited from an underlying object. This property setting is read-only. True (-1) indicates that the Property object is inherited. For built-in Property objects that represent predefined properties, False (0) is the only possible return value.

Remarks

You can use the Inherited property to determine whether a user-defined property was created for the object it applies to or whether the property was created for another object. For example, suppose you create a property for a QueryDef object and then open a Recordset object from the QueryDef object. This property will be part of the Recordset object's Properties collection, and its Inherited property will be set to True because the property was created for the QueryDef object, not the Recordset object.

See Also

CreateProperty Method, QueryDef Object.

Specifics (Microsoft Access)

Microsoft Access defines a number of properties which apply to data access objects. Because these properties are defined by Microsoft Access, the Microsoft Jet database engine doesn't recognize them automatically. To set one of these properties in Visual Basic, you must first create the property using the CreateProperty method and then append it to the Properties collection of the object. For more information, search the online index for the Property object topic.

When you create an object based on another object, the derived object inherits the properties of the original object. You can use the Inherited property to determine whether one of these properties was created for the object it is applied to, or if the property was inherited from another object.

For example, suppose you want to set the Microsoft Access DatasheetFontName property for a TableDef object. If you are setting this property for the first time, you will need to create a corresponding Property object and append it to the Properties collection of the TableDef object. The Inherited property of the new Property object returns False.

If you then create a new QueryDef object based on the table corresponding to the TableDef object, the DatasheetFontName property will be included in the Properties collection of the QueryDef object. The Inherited property of a Property object corresponding to this property returns True.

Example

This example creates a Recordset object from a QueryDef object, creates a new property, and indicates whether the property is inherited. Then the example prints the name of each field in the Recordset and, for each property of each field, it prints the Name, Type, Value, and Inherited property value settings.

Dim dbsDefault As Database, qdfTest As QueryDef
Dim rstTest As Recordset, prpMoose As Property
Dim intField As Integer, intProp As Integer
Set dbsDefault =  DBEngine.Workspaces(0).OpenDatabase("Northwind.mdb")
Set qdfTest = dbsDefault.QueryDefs(0)
Set prpMoose = qdfTest.CreateProperty("Moose",dbBoolean, True)
qdfTest.Properties.Append prpMoose
Set rstTest = qdfTest.OpenRecordset()
Debug.Print "Is qdfTest.Properties(""Moose"")inherited? "
Debug.Print qdfTest.Properties("Moose").Inherited
Debug.Print "Is rstTest.Properties(""Moose"")inherited? "
Debug.Print rstTest.Properties("Moose").Inherited
For intField = 0 To rstTest.Fields.Count - 1
    Debug.Print rstTest.Fields(intField).Name
    On Error Resume Next
    For intProp = 0 To rstTest.Fields(intField).Properties.Count - 1
        Debug.Print rstTest.Fields(intField).Properties(intProp).Name
        Debug.Print rstTest.Fields(intField).Properties(intProp).Type
        Debug.Print rstTest.Fields(intField).Properties(intProp).Value
        Debug.Print _
            rstTest.Fields(intField).Properties(intProp).Inherited
    Next intProp
Next intField
dbsDefault.Close
Example (Microsoft Access)

The following example creates a Property object in the Properties collection of a TableDef object, and then creates a new QueryDef object based on the same table. The Property object automatically exists in the Properties collection of the new QueryDef object. Next, the procedure checks the Inherited property for the Property objects in the Properties collections of both the TableDef and the QueryDef objects.

In the following example, the Microsoft Access DatasheetFontItalic property is created and appended to the Properties collection of the TableDef object. The DatasheetFontItalic property is defined by Microsoft Access rather than by the Microsoft Jet database engine. However, the property applies to data access objects. Therefore, in order to set it from Visual Basic code, you must first create a Property object corresponding to that property and append it to the Properties collection of the data access object. It is necessary to create the property only the first time you set it.

Sub CheckInherited()
    Dim dbs As Database, tdfOrders As TableDef, qdfOrders As QueryDef
    Dim prpTableDef As Property, prpQueryDef As Property
    Dim strSQL As String

    ' Return Database variable that points to current database.
    Set dbs = CurrentDb
    Set tdfOrders = dbs.TableDefs!Orders
    ' Create Property object and append to Properties collection.
    Set prpTableDef = tdfOrders.CreateProperty("DatasheetFontItalic", _
        dbBoolean, True)
    tdfOrders.Properties.Append prpTableDef
    Debug.Print prpTableDef.Inherited
    ' Create QueryDef based on Orders table.
    strSQL = "SELECT * FROM Orders WHERE ShipCountry = 'USA'"
    Set qdfOrders = dbs.CreateQueryDef("USAOrders", strSQL)
    ' Return Property object pointing to property.
     Set prpQueryDef = qdfOrders.Properties!DatasheetFontItalic
     Debug.Print prpQueryDef.Inherited
End Sub


IniPath Property

Applies To

DBEngine Object.

Description

Sets or returns the Microsoft Jet database part of the Windows Registry file. This is a change from earlier versions in which options were set in .ini files.

Settings and Return Values

The setting or return value is a string expression that points to a user-supplied portion of the Registry key containing Microsoft Jet database engine settings or parameters needed for installable ISAM databases. The data type is String.

Remarks

The Microsoft Jet engine can be configured with the Registry file. You can use the Registry to set options, such as installable ISAM DLLs.

For this option to have any effect, the IniPath property must be set before any other data access functions are invoked by your application. The scope of this setting is limited to your application and can't be changed without restarting your application.

You also use the Registry to provide initialization parameters for some installable ISAM database drivers. For example, to use Paradox version 4.0, set the IniPath property to a part of the Registry containing the appropriate parameters.

This property recognizes either HKEY_LOCAL_MACHINE or HKEY_LOCAL_USER. If no root key is supplied, the default is HKEY_LOCAL_MACHINE.

Example

This example sets the path in the IniPath property to an application's key in the Windows Registry.

Sub SetPathFirst()
Dim strPath As String
strPath = "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MyApp\3.0\KeyFolder"
DBEngine.IniPath = strPath
End Sub


IsolateODBCTrans Property

Applies To

Workspace Object.

Description

Sets or returns a value that indicates whether multiple transactions that involve the same ODBC database are isolated.

True (-1) indicates to isolate transactions involving the same ODBC database. False (0) (the default) indicates not to isolate transactions involving the same ODBC database.

Remarks

In some situations, you need to have multiple simultaneous transactions pending on the same ODBC database. To do this, you need to open a separate Workspace for each transaction. Although each Workspace can have its own ODBC connection to the database, this slows system performance. Because transaction isolation isn't normally required, ODBC connections from multiple Workspace objects opened by the same user are shared by default.

Example

This example opens a Workspace and sets IsolateODBCTrans to True before starting a transaction.

Dim wrkDefault As Workspace
Set wrkDefault = DBEngine.Workspaces(0)
wrkDefault.IsolateODBCTrans = True
wrkDefault.BeginTrans

' Execute query to ODBC database and complete transaction.
...
...


KeepLocal Property

Applies To

QueryDef Object, TableDef Object.

Description

Sets or returns a value on a TableDef or QueryDef object, or a table, query, form, report, macro, or module that you do not want made replicable when the database is converted to a replicable form.

Setting and Return Value

You set this property to the text string "T" to keep the object local while all other objects are made replicable when the database is made replicable. The KeepLocal property cannot be applied to objects after they have been converted into a replicable form.

Remarks

Local objects remain at the replica where they were created and are not propagated around the replica set. Each time you make a new replica in the set, all the replicable objects at the source replica are included in that new replica, but none of the local objects are included.

The object on which you are setting the KeepLocal property might have already inherited that property from another object. However, the value set by the other object has no affect on the behavior of the object you want to KeepLocal. You must directly set the property for each object.

See Also

Replicable Property.


LastModified Property

Applies To

Dynaset-Type Recordset Object, Recordset Object, Table-Type Recordset Object.

Description

Returns a bookmark indicating the most recently added or changed record.

Return Values

The return value is a Variant array of Byte data.

Remarks

You can use LastModified property to move to the most recently added or updated record. Use the LastModified property with Recordset objects. A record must be modified in the Recordset object itself in order for LastModified property to have a value.

See Also

Bookmark Property; Bookmarkable Property; DateCreated, LastUpdated Properties.

Specifics (Microsoft Access)

When you use the LastModified property in a Microsoft Access module, you must include an Option Compare Binary statement in the Declarations section of the module. The bookmark returned by the LastModified property is a Variant array of Byte data, so the string comparison method for the module must be binary. If a bookmark is evaluated with a text-based string comparison method, such as the Option Compare Text statement or the default setting for the Option Compare Database statement, the current record may be set to an incorrect record.

Example

See the AddNew method example.

Example (Microsoft Access)

The following example prints the value of the OrderDate field for the most recently modified record in a recordset.

' Include this statement in the Declarations section of the module.
Option Compare Binary

Sub LastChangedRecord()
    Dim dbs As Database, rst As Recordset, varBook As Variant

    ' Return Database variable that points to current database.
    Set dbs = CurrentDb
    ' Create Dynaset-Type Recordset object.
    Set rst = dbs.OpenRecordset("SELECT * FROM Orders " & _
        "ORDER BY [ShipCountry]")
    With rst
        ' Populate recordset.
        .MoveLast
        ' Move to first record and search.
        .MoveFirst
        .FindFirst "[ShipCountry] = 'UK'"
        ' Alter record and save changes.
        .Edit
        .[ShipCountry] = "USA"
        .Update
    End With
    ' Check to see if recordset supports bookmarks.
    If rst.Bookmarkable Then
        ' Set bookmark to most recently modified record.
        varBook = rst.LastModified
        ' Set currency to last modified record.
        rst.Bookmark = varBook
        ' Display changed value.
        Debug.Print rst.Fields!ShipCountry
    End If
End Sub


LastUpdated Property

See DateCreated, LastUpdated Properties.


LockEdits Property

Applies To

Dynaset-Type Recordset Object, Recordset Object, Table-Type Recordset Object.

Description

Sets or returns a value indicating the locking that is in effect during editing.

Settings and Return Values

The setting or return value is a Boolean expression that indicates the type of locking. The data type is Boolean.

The possible settings or return values are:

Setting/Value | Description
True (-1) | (Default) Pessimistic locking is in effect. The 2K page containing the record you're editing is locked as soon as you use the Edit method.
False (0) | Optimistic locking is in effect for editing. The 2K page containing the record is not locked until the Update method is executed.

Remarks

You can use the LockEdits property with dynaset- and Table-Type Recordset objects.

If a page is locked, no other user can edit records on the same page. If you set LockEdits to True and another user already has the page locked, an error occurs when you use the Edit method. Other users can read data from locked pages.

If you set the LockEdits property to False and later use Update method while the page is locked by another user, an error occurs. To see the changes made to your record by another user, set the Bookmark property of your Recordset object to itself. This approach results in your changes being lost.

When working with ODBC data sources, the LockEdits property is always set to False, or optimistic locking. The Microsoft Jet database engine has no control over the locking mechanisms used in external database servers.

See Also

Bookmark Property; Close Method; FindFirst, FindLast, FindNext, FindPrevious Methods; IsolateODBCTrans Property; MoveFirst, MoveLast, MoveNext, MovePrevious Methods.

Example

This example opens a Dynaset-Type Recordset and sets its LockEdits property to False. This enables optimistic locking so other users can change the database records at any time. Your application triggers a trappable error if the data changes before you use the Update method.

Sub ShowLockStatus()
Dim dbsNorthwind As Database, rstCustomers As Recordset

Set dbsNorthwind =  DBEngine.Workspaces(0).OpenDatabase("Northwind.mdb")
Set rstCustomers = dbsNorthwind.OpenRecordset("Customers", dbOpenDynaset)
rstCustomers.LockEdits = True
OnError Goto ErrorHandler
rstCustomers.Edit    ' Start editing.
    On Error GoTo 0
    rstCustomers.CancelUpdate
    rstCustomers.Close
    dbsNorthwind.Close
    Exit Sub

ErrorHandler:
    If Err = 3197 Then
        Debug.Print "data changed"
        Resume Next
    Else
        Debug.Print "some other error"
        Resume Next
    End If
End Sub
Example (Microsoft Access)

The following example opens a Dynaset-Type Recordset object and sets its LockEdits property to False (0). This enables optimistic locking so other users can change the database records at any time. Microsoft Access triggers a trappable error if the data changes before you use the Update method.

Sub ShowLockStatus()
    Dim dbs As Database, rst As Recordset

    ' Return Database variable that points to current database.
    Set dbs = CurrentDb
    Set rst = dbs.OpenRecordset("Customers", dbOpenDynaset)
    rst.LockEdits = False
    On Error Goto ErrorHandler
    ' Enable editing.
    rst.Edit
    .                    ' Change records.
    .
    .
    rst.Update            ' Try to post changes.
    rst.Close

    Exit Sub
    ErrorHandler:
        If Err.Number = 3197 Then
            MsgBox "Data changed by another user."
            Resume Next
        Else
            MsgBox "Some other error."
        End If
End Sub
Example (Microsoft Excel)

This example locks the Customer recordset in the NWINDEX.MDB database before updating the value in the CUSTMR_ID field of the first record with the value in cell A1 on Sheet1. Locking the recordset ensures that no other user modifies the record while it is being updated.

To create the NWINDEX.MDB database, run the Microsoft Excel example for the CreateDatabase method.

Dim db As Database, rs As Recordset
Sheets("Sheet1").Cells(1, 1).Value = "ACRIM"
databasePath = Application.Path & "\NWINDEX.MDB"
Set db = DBEngine.Workspaces(0).OpenDatabase(databasePath)
Set rs = db.OpenRecordset("Customer")
valueToAdd = Sheets("Sheet1").Cells(1, 1).Value
rs.LockEdits = False
rs.Edit
rs.fields("CUSTMR_ID").Value = valueToAdd
rs.Update
MsgBox "The new value of CUSTMR_ID is " & rs.fields("CUSTMR_ID").Value
rs.Close
db.Close


LoginTimeout Property

Applies To

DBEngine Object.

Description

Sets or returns the number of seconds before an error occurs when you attempt to log in to an ODBC database.

Settings and Return Values

The setting or return value is an Integer representing the number of seconds before a login timeout error occurs. The default LoginTimeout property setting is 20 seconds. When the LoginTimeout property is set to 0, no timeout occurs.

Remarks

When you're attempting to log into an ODBC database, such as SQL Server, the connection can fail as a result of network errors or because the server isn't running. Rather than waiting for the default 20 seconds to connect, you can specify how long the Microsoft Jet database engine waits before it produces an error. Logging on to the server happens implicitly as part of a number of different events, such as running a query on an external server database.

The default timeout value is determined by the current setting of the LoginTimeout property entry in the HKEY_LOCAL_MACHINE\SOFTWARE\Jet\3.0\ODBC key of the Windows Registry.

See Also

ODBCTimeout Property, QueryDef Object, QueryTimeout Property.

Example

This example sets the LoginTimeout property to 120 seconds and then creates and runs a query on a database on an ODBC server.

Dim dbsNorthwind As Database
Dim qdfCustomers As QueryDef, rstCustomers As Recordset
DBEngine.LoginTimeout = 120            ' Timeout in 2 minutes.
Set dbsNorthwind =  DBEngine.Workspaces(0).OpenDatabase("Northwind.mdb")
                                    ' Create query.
Set qdfCustomers = dbsNorthwind.CreateQueryDef("All Cust", _
    "SELECT * FROM Customers;")
qdfCustomers.Connect = "ODBC;DSN=Human Resources; " & _
    "DATABASE=HRSRVR; UID=Smith; PWD=Sesame"
                                    ' Log in to server and run query.
Set rstCustomers = qdfCustomers.OpenRecordset()
Example (Microsoft Access)

The following example sets the LoginTimeout property to 120 seconds, then creates a query, and runs it on a database on an ODBC server.

Sub Login()
    Dim dbs As Database
    Dim qdf As QueryDef, rst As Recordset

    ' Set timeout to 120 seconds.
    DBEngine.LoginTimeout = 120
    ' Return Database variable that points to current database.
    Set dbs = CurrentDb
    ' Create query.
    Set qdf = dbs.CreateQueryDef("All Employees", _
        "SELECT * FROM Employees;")
    qdf.Connect = "ODBC;DSN=Human Resources; " & _
        "DATABASE=HRSRVR; UID=Smith; PWD=Sesame"
    ' Log in to server and run query.
    Set rst = qdf.OpenRecordset()
End Sub


LogMessages Property

Applies To

QueryDef Object.

Description

Sets or returns a value that specifies if the messages returned from an ODBC database are recorded. This property is user-defined and is read/write once created and installed.

Note

The user must install this property using the CreateProperty method on a QueryDef object.

Settings and Return Values

The setting or return value is a Boolean expression that specifies whether messages are recorded. The data type is Boolean. True indicates that ODBC-generated messages are recorded.

Remarks

Some pass-through queries can return messages in addition to data. If you set the LogMessages property to True (-1), the Microsoft Jet database engine creates a table that contains returned messages. The table name is the user name concatenated with a hyphen (-) and a sequential number starting at 00. For example, because the default user name is ADMIN, the tables returned would be named ADMIN-00, ADMIN-01, and so on.

If you expect the query to return messages, create and append a user-defined LogMessages property for the QueryDef object, and set its type to Boolean and its value to True.

Once you've processed the results from these tables, you may want to delete them from the database along with the temporary query used to create them.


MakeReplica Method

Applies To

Database Object.

Description

Makes a new replica based on the current replicable database using the supplied filename.

Syntax

database.MakeReplica replica, description [, dbRepMakeReadOnly]

The MakeReplica Method syntax has the following parts.

Part | Description
database | An existing, replicable Database object variable.
replica | The path and file name to be given the new replica. If replica is an existing filename, then the method fails and returns an error message.
description | Text string describing the replica to be created.

If dbRepMakeReadOnly is supplied, then the replicable elements of the newly created database will not be modifiable.

Remarks

As with most of the replication methods and properties, the database has to be a replicable database for this method to work.

Note

The MakeReplica method can be used only if your application has Microsoft Access with Briefcase Replication installed.


Move Method

Applies To

Dynaset-Type Recordset Object, Recordset Object, Snapshot-Type Recordset Object, Table-Type Recordset Object.

Description

Moves the position of the current record in a Recordset object.

Syntax

recordset.Move rows[, start]

The Move method syntax has these parts.

Part | Description
recordset | The name of the Recordset object whose current record position is being moved.
rows | A signed Long value specifying the number of rows the position will move. If rows is greater than 0, the position is moved forward (toward the end of the file). If rows is less than 0, the position is moved backward (toward the beginning of the file).
start | A String value identifying a bookmark. If start is specified, the move begins relative to this bookmark. If start is not specified, Move begins from the current record.

Remarks

If using Move would move the position of the current record to a position before the first record, the position is moved to the beginning-of-file (BOF) position. If the Recordset contains no records and its BOF property is set to True, using this method to move backward produces a trappable run-time error. If either the BOF or EOF property is True and you attempt to use the Move method without a valid bookmark, a trappable error is triggered.

If using Move would move the position of the current record to a position after the last record, the position is moved to the end-of-file (EOF) position. If the Recordset is based on a query, then this approach forces the query to be run on the specified number of rows. If the Recordset contains no records and its EOF property is set to True, then using this method to move forward produces a trappable run-time error.

Notes

  • When you use Move on a forward-only scrolling snapshot, the rows argument must be a positive integer and bookmarks aren't allowed. This means you can only move forward.
  • To make the first, last, next, or previous record in a Recordset the current record, use the MoveFirst, MoveLast, MoveNext, or MovePrevious method.
 See Also

BOF, EOF Properties; Bookmark Property; MoveFirst, MoveLast, MoveNext, MovePrevious Methods.

Specifics (Microsoft Access)

When you use a bookmark in a Microsoft Access module, you must include an Option Compare Binary statement in the Declarations section of the module. A bookmark is a Variant array of Byte data, so the string comparison method for the module must be binary. If a bookmark is evaluated with a text-based string comparison method, such as the Option Compare Text statement or the default setting for the Option Compare Database statement, the current record may be set to an incorrect record.

Example

This example creates a function that moves the current record position in a Recordset forward or back a specified number of records and provides an optional offset.

Sub MoveRelative (lngDistance As Long, strDirection As String, _
    rstTarget As Recordset, varRelativeMark As Variant)
    Dim strHere As String
    strHere = rstTarget.Bookmark
    strDirection = UCase(strDirection)
    Select Case strDirection
        Case "FWD":  lngDistance = Abs(lngDistance)
        Case "BACK": lngDistance = Abs(lngDistance) * -1
        Case Else: MsgBox "Incorrect calling argument"
    End Select
    If UCase(varRelativeMark) = "HERE" Then

        rstTarget.Move lngDistance    ' Move current record position.
    Else
        ' Move relative to bookmark.
        rstTarget.Move lngDistance, varRelativeMark
    End If
    ' Move may not have been completed.
    If rstTarget.EOF Or rstTarget.BOF Then Beep
End Sub
Example (Microsoft Access)

The following example uses the Move method to move forward two rows in a Recordset object.

Sub MoveForward()
    Dim dbs As Database, rst As Recordset
    Dim strCriteria As String

    ' Return Database variable pointing to current database.
    Set dbs = CurrentDb
    ' Open Dynaset-Type Recordset object.
    Set rst = dbs.OpenRecordset("SELECT * FROM Orders " & _
        "ORDER BY [ShipCountry];")
    rst.MoveFirst
    ' Check number of records in Recordset object.
    If rst.RecordCount > 2 Then
        ' Move forward two rows.
        rst.Move 2
        Debug.Print rst!ShipCountry
    End If
End Sub
Example (Microsoft Excel)

This example prompts the user to select a record number. The example then copies the selected record from the Customer recordset in the NWINDEX.MDB database onto Sheet1.

Dim db As Database, rs As Recordset
Set db = Workspaces(0).OpenDatabase(Application.Path & "\NWINDEX.MDB")
Set rs = db.OpenRecordset("SELECT [CUSTMR_ID], [CONTACT], [REGION] " _
    & "FROM Customer")
Sheets("Sheet1").Activate
aDistance = Application.InputBox("What record # you want to copy", Type:=2)
If aDistance = False Then    ' user cancelled InputBox
    Exit Sub
End If
rs.MoveFirst
rs.Move aDistance
For i = 0 To 2
    ActiveCell.Offset(, i).Value = rs.Fields(i).Value
Next
rs.Close
db.Close


MoveFirst, MoveLast, MoveNext, MovePrevious Methods

Applies To

Dynaset-Type Recordset Object, Recordset Object, Snapshot-Type Recordset Object, Table-Type Recordset Object.

Description

Move to the first, last, next, or previous record in a specified Recordset object and make that record the current record.

Syntax

object.{MoveFirst | MoveLast | MoveNext | MovePrevious}

The object placeholder represents an object expression that evaluates to the name of an open Recordset object.

Remarks

Use the Move methods to move from record to record without applying a condition. Use the Find methods to locate records in a dynaset- or Snapshot-Type Recordset object that satisfy a certain condition. To locate a record in a Table-Type Recordset object, use the Seek method.

Caution

If you edit the current record, be sure you save the changes using the Update method before you move to another record. If you move to another record without updating, your changes are lost without warning.

When you open the recordset named by recordset, the first record is current and the BOF property is set to False. If the recordset contains no records, the BOF property is set to True, and there is no current record.

If the first or last record is already current when you use MoveFirst or MoveLast, the current record doesn't change.

If you use MovePrevious when the first record is current, the BOF property is set to True, and there is no current record. If you use MovePrevious again, an error occurs; BOF remains True.

If you use MoveNext when the last record is current, the EOF property is set to True, and there is no current record. If you use MoveNext again, an error occurs; EOF remains True.

If recordset refers to a Table-Type Recordset, movement follows the current index. You can set the current index using the Index property. If you don't set the current index, the order of returned records is undefined.

If you use MoveLast on a Recordset object based on an SQL query or QueryDef, the query is forced to completion and the Recordset object is fully populated.

Notes

  • You can't use the MoveFirst, MoveLast, or MovePrevious methods with a forward-only scrolling snapshot.
  • To move the position of the current record in a Recordset object a specific number of records forward or backward, use the Move method.
 See Also

AbsolutePosition Property; BOF, EOF Properties; FindFirst, FindLast, FindNext, FindPrevious Methods; Index Property; Move Method; RecordCount Property; Seek Method.

Example

This example changes the job title of all sales representatives in a table named Employees. After opening the table, it uses MoveFirst to locate the first record and MoveNext to move to the next record. For each record satisfying the title condition, the example changes the title and saves the change using the Update method.

It's far more efficient to use the WHERE clause of an SQL statement to request the records you want to update than to test each record one at a time. The whole operation could be accomplished by using a single UPDATE statement, as shown in the following example.

Dim dbsNorthwind As Database, rstEmployees As Recordset
Dim strSelect as String
Set dbsNorthwind = DBEngine.Workspaces(0).OpenDatabase("Northwind.mdb")
strSelect = "Select * FROM Employees WHERE Title = 'Sales Representative' "
' Open recordset.
Set rstEmployees = dbsNorthwind.OpenRecordset(strSelect)
Do Until rstEmployees.EOF    ' Begin loop.
    With rstEmployees
    .Edit    ' Enable editing.
    !Title = "Account Executive"    ' Change title.
    .Update    ' Save changes.
    .MoveNext    ' Locate next record.
    End With
Loop    ' End of loop.
rstEmployees.Close    ' Close table.
dbsNorthwind.Close
Tip

Using an update query to change job titles might be more efficient. For example, you could use the following code to achieve the same results:

Dim strSelect as String
strSelect = "Update Employees Set Title = 'Account Executive' " _
    "WHERE Title = 'Sales Representative' "
dbsNorthwind.Execute strSelect
Example (Microsoft Access)

The following example uses the MoveLast method to populate the Recordset object so the number of records can be counted. The MoveFirst method then moves the current record pointer to the first record in the Recordset object. The procedure prompts the user to enter a record number, then sets a bookmark for that record.

Sub MoveToRecord()
    Dim dbs As Database, rst As Recordset, intI As Integer
    Dim strNumber As String, strBookmark As String
    ' Return Database variable pointing to current database.
    Set dbs = CurrentDb
    Set rst = dbs.OpenRecordset("Orders")
    ' Populate Recordset object.
    rst.MoveLast
    ' Return to first record.
    rst.MoveFirst
    strNumber = InputBox("Please enter record number.")
    ' Check that number is within Recordset object.
    If strNumber <= rst.RecordCount And rst.Bookmarkable Then
        For intI = 1 To strNumber
            rst.MoveNext
        Next intI
        strBookmark = rst.Bookmark
    End If
End Sub
Example (Microsoft Excel)

This example replaces values in the CON_TITLE field of the records in the Customer recordset in the NWINDEX.MDB database, and then it displays how many replacements were made.

To create the NWINDEX.MDB database, run the Microsoft Excel example for the CreateDatabase method.

Dim db As Database, rs As Recordset, sQLText As String
Set db = Workspaces(0).OpenDatabase(Application.Path & "\NWINDEX.MDB")
sQLText = "SELECT * FROM  Customer WHERE " _
    & "CON_TITLE =  'Sales Representative';"
Set rs = db.OpenRecordset(sQLText)
i = 0
Do Until rs.EOF
    With rs
        .Edit
        .Fields("CON_TITLE").Value = "Account Executive"
        .Update
        .MoveNext
    End With
    i = i + 1
Loop
MsgBox i & " replacements were made."
rs.Close
db.Close


Name Property

Applies To

Container Object, Database Object, Document Object, Dynaset-Type Recordset Object, Field Object, Group Object, Index Object, Parameter Object, Property Object, QueryDef Object, Recordset Object, Relation Object, Snapshot-Type Recordset Object, Table-Type Recordset Object, TableDef Object, User Object, Workspace Object.

Description

Sets or returns a user-defined name for a data access object. For an object not appended to a collection, this property is read/write.

Settings and Return Values

The setting or return value is a string expression that specifies a name. The name must start with a letter and can contain a maximum of 64 characters. It can include numbers and underscore characters ( _ ) but can't include punctuation or spaces. The data type is String.

Remarks

TableDef and QueryDef objects can't share the same name, nor can User and Group objects.

The Name property of a Recordset object opened using an SQL statement is the first 256 characters of the SQL statement.

You can use an object's Name property with the Dim statement in code to create other instances of the object.

Note

For many of the Database objects, the Name property reflects the name as known to the Database object, as in the name of a TableDef, Field, or QueryDef object. There is no direct link between the name of the Database object and the object variable used to reference it.

The read/write usage of the Name property depends on the type of object it applies to, and whether or not the object is has been appended to a collection.

Object | Usage
Container | Read-only
Database | Read-only
Document | Read-only
Field |
Unappended | Read/write
Appended to Index | Read-only
Appended to QueryDef | Read-only
Appended to Recordset | Read-only
Appended to TableDef (native) | Read/write

Object | Usage
Field |
Appended to TableDef (linked) | Read-only
Appended to Relation | Read-only
Group |
Unappended | Read/write
Appended | Read only
Index |
Unappended | Read/write
Appended | Read only
Parameter | Read-only
Property |
Unappended | Read/write
Appended | Read-only
Built-in | Read-only
QueryDef |
Unappended | Read/write
Temporary | Read-only
Appended | Read/write
Recordset | Read-only
Relation |
Unappended | Read/write
Appended | Read-only
TableDef | Read/write
User |
Unappended | Read/write
Appended | Read-only
Workspace |
Unappended | Read/write
Appended | Read-only

See Also

CreateDatabase Method, CreateField Method, CreateIndex Method, CreateQueryDef Method.

Example

This example creates a TableDef object and then names it Parts ID.

Dim dbsNorthwind As Database, tdfPartsID As TableDef
Set dbsNorthwind =  DBEngine.Workspaces(0).OpenDatabase("Northwind.mdb")
Set tdfPartsID = dbsNorthwind.CreateTableDef()

tdfPartsID.Name = "Parts ID"
...    ' Create fields.
dbsNorthwind.TableDefs.Append tdfPartsID
Example (Microsoft Access)

The following example creates two new TableDef objects and names them. The name of the first TableDef object is included as an argument to the CreateTableDef method. The name of the second TableDef object is set using the Name property, after the TableDef object has been created.

Note that you must define fields in the table before the TableDef object can be appended to the TableDefs collection.

Sub NameNewTables()
    Dim dbs As Database
    Dim tdfDefinitions As TableDef, tdfSynonyms as TableDef

    ' Return Database variable that points to current database.
    Set dbs = CurrentDb
    ' Create and name TableDef object.
    Set tdfDefinitions = dbs.CreateTableDef("Definitions")
    ' Create second TableDef object.
    Set tdfSynonyms = dbs.CreateTableDef("")
    ' Set Name property for second TableDef object.
    tdfSynonyms.Name = "Synonyms"
    .                            ' Create fields.
    .
    .
    dbs.TableDefs.Append tdfDefinitions
    dbs.TableDefs.Append tdfSynonyms
End Sub
Example (Microsoft Excel)

This example enters in the active cell on Sheet1 the name of the first recordset in the NWINDEX.MDB database.

To create the NWINDEX.MDB database, run the Microsoft Excel example for the CreateDatabase method.

Dim db As Database, td As TableDef
Set db = Workspaces(0).OpenDatabase(Application.Path & "\NWINDEX.MDB")
Set td = db.TableDefs(0)
Sheets("Sheet1").Activate
ActiveCell.Value = td.Name
db.Close


NewPassword Method

Applies To

Database Object, User Object.

Description

Changes the password of an existing user account or Jet version 3.0 database.

Syntax

object.NewPassword oldpassword, newpassword

The NewPassword method syntax has these parts.

Part | Description
object | A variable of an object data type that represents the User object or a Jet 3.0 Database object whose Password property you want to change.
oldpassword | A string expression that is the current setting of the Password property of the User or Jet 3.0 Database object.
newpassword | A string expression that is the new setting of the Password property of the User or Jet 3.0 Database object.

Remarks

The oldpassword and newpassword strings can be up to 14 characters long and can include any characters except the ASCII character 0 (null). To clear the password, use a zero-length string ("") for newpassword.

Passwords are case-sensitive.

If object refers to a User object that is not an element of a Users collection, an error occurs. To set a new password, you must either be logged on as the user whose user account you're changing, or you must be a member of the Admins group. The Password property of a User object is write-only — users can't read the current value.

If object refers to a Jet version 3.0 Database object, this method offers a limited form of security in the form of password protection. When creating or opening a version 3.0 .mdb file, part of the Connect string describes the password; thus, no work is required of your DAO code.

If a database has no password, one will be created automatically by passing "" for the old password. If you lose your password, you can never open the database again.

See Also

Name Property, PID Property.

Example

This example changes the password of the existing user Pat Smith from My Secret to msMSApw. The user must be logged on as Pat Smith or as a member of the Admins group.

Workspaces(0).Users("Pat Smith").NewPassword "My Secret", "msMSApw"


NoMatch Property

Applies To

Dynaset-Type Recordset Object, Recordset Object, Snapshot-Type Recordset Object, Table-Type Recordset Object.

Description

Returns a value indicating whether a particular record was found using the Seek method or one of the Find methods. True (-1) indicates that the desired record was not found.

Remarks

You can use the NoMatch property with Recordset objects.

When you open or create a Recordset object, its NoMatch property is set to False (0).

To locate a record, use the Seek method on a Table-Type Recordset object or one of the Find methods on a dynaset- or Snapshot-Type Recordset object. Check the NoMatch property setting to see whether the record was found.

If the Seek or Find method is unsuccessful and the NoMatch property is True, the current record will no longer be valid. Be sure to obtain the current record's bookmark before using the Seek method or a Find method if you'll need to return to that record.

Note

Using any of the Move methods on a Recordset object won't affect its NoMatch property setting.

See Also

BOF, EOF Properties; FindFirst, FindLast, FindNext, FindPrevious Methods; Seek Method.

Example

This example changes the job title of all sales representatives in an Employees table. It creates a Dynaset-Type Recordset and then uses FindFirst and FindNext to locate every record satisfying the criteria for the title. It prepares each record for editing, changes the title, and saves the change with the Update method.

Dim strCriteria As String, varSaveHere As Variant
Dim dbsNorthwind As Database, rstEmployees As Recordset
strCriteria = "Title = 'Sales Representative'"    ' Define search
                        ' criteria.
Set dbsNorthwind =  DBEngine.Workspaces(0).OpenDatabase("Northwind.mdb")
' Create Recordset.
Set rstEmployees = dbsNorthwind.OpenRecordset("Employees", dbOpenDynaset)
varSaveHere = rstEmployees.Bookmark    ' Save Bookmark.
rstEmployees.FindFirst strCriteria    ' Locate first occurrence.
Do Until rstEmployees.NoMatch    ' Loop until no matching
                ' records.

    With rstEmployees
       .Edit        ' Enable editing.
       !Title = "Account Executive"    ' Change title.
       .Update    ' Save changes.
       .FindNext strCriteria    ' Locate next record.
    End With
Loop            ' End of loop.
rstEmployees.Bookmark = varSaveHere

Tip

In some situations, using an update query is faster.

Example (Microsoft Access)

The following example uses the NoMatch property to determine whether a FindFirst method process has been successful.

Function FindCountry() As Integer
    Dim intI As Integer, varRecord() As Variant
    Dim dbs As Database, rstOrders As Recordset
    Dim strCountry As String

    ' Return Database variable that points to current database.
    Set dbs = CurrentDb
    ' Create Dynaset-Type Recordset object.
    Set rstOrders = dbs.OpenRecordset("Orders", dbOpenDynaset)
    strCountry = InputBox("Please enter country name.")
    intI = 0
    rstOrders.FindFirst "[ShipCountry] = '" & strCountry & "'"
    If rstOrders.NoMatch Then
        FindCountry = False
        Exit Function
    Else
        Debug.Print rst!OrderID
    End If
    FindCountry = True
End Function
Example (Microsoft Excel)

This example adds all the names of contacts for the state of Washington to a list box on a new dialog sheet and then runs the dialog box. The data is drawn from the Customer recordset in the NWINDEX.MDB database.

To create the NWINDEX.MDB database, run the Microsoft Excel example for the CreateDatabase method.

Dim db As Database
Dim rs As Recordset
Set db = Workspaces(0).OpenDatabase(Application.Path & "\NWINDEX.MDB")
Set rs = db.OpenRecordset("SELECT * FROM Customer")
criteria = "[REGION] = 'WA'"
Set customDialog = DialogSheets.Add

Set list1 = customDialog.ListBoxes.Add(78, 42, 84, 80)
rs.FindFirst criteria
Do Until rs.NoMatch
    list1.AddItem (rs.fields("CONTACT").Value)
    rs.FindNext criteria
Loop
customDialog.Show
rs.Close
db.Close


Number Property

Applies To

Error Object.

Description

Returns a numeric value specifying an error. The Number property is the Error object's default property.

Return Values

The returned value is a Long Integer representing an error number.

Remarks

Use the Number property to determine the error that occurred. The value of the property corresponds to a unique trap number that corresponds to an error condition.

See Also

Description Property; HelpContext, HelpFile Properties; Source Property.

Example

See the Description property example.


ODBCTimeout Property

Applies To

QueryDef Object.

Description

Sets or returns the number of seconds the Microsoft Jet database engine waits before a timeout error occurs when a query is run on an ODBC database.

Settings and Return Values

The setting or return value is an integer representing the number of seconds that the Jet database engine waits before a timeout error occurs. The data type is Integer.

Remarks

When you're using an ODBC database, such as SQL Server, delays can occur because of network traffic or heavy use of the ODBC server. Rather than waiting indefinitely, you can specify how long the Jet database engine waits before it produces an error.

The default timeout value is 60 seconds. When the ODBCTimeout property is set to -1, the default value is used. When the ODBCTimeout property is set to 0, no timeout occurs.

The QueryTimeout property setting for a Database object overrides the default setting.

Setting the ODBCTimeout property of a QueryDef object overrides the values specified by the QueryTimeout property setting of the Database object containing the QueryDef object, but only for that QueryDef object.

See Also

QueryTimeout Property.

Example

This example sets the ODBCTimeout property to 120 seconds and then creates a query and runs it on a database on an ODBC server.

Dim dbsNorthwind As Database
Dim qdfCustomers As QueryDef, rstCustomers As Recordset
Set dbsNorthwind =  DBEngine.Workspaces(0).OpenDatabase("Northwind.mdb")
' Create query.
Set qdfCustomers = dbsNorthwind.CreateQueryDef("All Cust", _
    "SELECT * FROM Customers;")
qdfCustomers.Connect = "ODBC;DSN=Human Resources; SERVER=HRSRVR: " & _
    "UID=Smith; PWD=Sesame"
' Log in to server and run query.
qdfCustomers.ODBCTimeout = 120
Set rstCustomers = qdfCustomers.OpenRecordset()
Example (Microsoft Access)

The following example sets the ODBCTimeout property to 120 seconds, creates a query, and runs it on a database on an ODBC server.

Sub SetTimeout()
    Dim dbs As Database
    Dim qdfCustomers As QueryDef, rstCustomers As Recordset

    ' Return Database variable that points to current database.
    Set dbs = CurrentDb
    ' Create QueryDef.
    Set qdfCustomers = dbs.CreateQueryDef("All Cust", _
        "SELECT * FROM Customers;")
    qdfCustomers.Connect = "ODBC;DSN=HumanResources;SERVER=HRSRVR: " & _
        "UID=Smith; PWD=Sesame"
    ' Log in to server and run query.
    qdfCustomers.ODBCTimeout = 120
    Set rstCustomers = qdfCustomers.OpenRecordset()
End Sub


OpenDatabase Method

Applies To

Workspace Object.

Description

Opens a specified database in a session and returns a reference to the Database object that represents it. The open database is automatically added to the Databases collection.

Syntax

Set database = [workspace.]OpenDatabase(dbname[, exclusive[, read-only[, ú source]]])

The OpenDatabase method syntax has these parts.

Part | Description
database | A variable of a Database object data type that references the Database object that you're opening.
workspace | A variable of a Workspace object data type that references the existing Workspace object that will contain the database.
dbname | A string expression that is the name of an existing database file.
 | Some considerations apply when using dbname:
 | u If it refers to a database that is already open for exclusive access by another user, an error occurs.
 | u If it doesn't refer to an existing database or valid ODBC data source name, an error occurs. (See Remarks for more information on opening ODBC databases.)
 | u If it's a zero-length string ("") and source is "ODBC;", a dialog box listing all registered ODBC data source names is displayed so the user can select a database. (See Remarks for more information on opening ODBC databases.)
exclusive | A Boolean expression that is True if the database is to be opened for exclusive (nonshared) access and False if the database is to be opened for shared access. If you omit this argument, the database is opened for shared access.
read-only | A Boolean value that is True if the database is to be opened for read-only access and False if the database is to be opened for read/write access. If you omit this argument, the database is opened for read/write access.
source | A string expression used for opening the database, including databases with passwords. Note that the NewPassword method, when used on a Database object, changes the password parameter that appears in the "PWD=..." part of this argument. You must supply the exclusive and read-only arguments to supply a source string. See the Connect property for syntax, and see Remarks for more information on opening ODBC databases.

Remarks

To close a database, and thus remove its Database object from the Databases collection, use the Close method on the object.

Because attached tables on ODBC databases improve performance, it's preferable to use them rather than opening ODBC databases directly. To open an ODBC database directly, you must specify a registered ODBC data source name. If the filename has an extension, it's required. If your network supports it, you can also specify a network path, such as:

"\\MYSERVER\MYSHARE\MYDIR\MYDB.mdb"
For more information about ODBC drivers, such as SQL Server, see the Help file provided with the driver.

Note

The source argument is expressed in two parts: the database type, followed by a semicolon (;) and the optional arguments. The database type, such as "ODBC;" or "FoxPro 2.5" must be provided first. The optional arguments follow in no particular order, separated by semicolons. One of the parameters may be the password (if one is assigned). For example, .source = ("FoxPro 2.5; pwd=mypassword"). See the source argument, defined earlier in this topic, for more information.

See Also

Close Method, Connect Property.

Specifics (Microsoft Access)

In Microsoft Access, use the CurrentDb function to point a Database variable to the current database, rather than using the OpenDatabase method. For example, you can use the following code to get a variable that represents the current database.

Dim dbsCurrent as Database
set dbsCurrent = CurrentDb
Use the OpenDatabase method to open a database other than the current database.

Example

This example opens the Employees table in the database in the default Workspace object. If the database can't be opened (for example, if it has already been opened for exclusive access by another user in a multiuser environment), an error occurs and a message is displayed. Then the example updates the Title field of the Employees table.

Function UpdateNorthwind () As Integer
    Dim wspDefault As Workspace, dbsNorthwind As Database
    Dim rstEmployees As Recordset
    Dim intErrorCondition As Integer, intUpdateNorthwind As Integer
    intUpdateNorthwind = True
    intErrorCondition = False
    On Error GoTo DBErrorHandler    ' Enable error trapping.
    Set wspDefault = DBEngine.Workspaces(0)

    ' Open database.
    Set dbsNorthwind = wspDefault.OpenDatabase("Northwind.mdb")
    If intErrorCondition = False Then
        On Error GoTo TableErrorHandler    ' Enable error trapping.
        ' Open table.
        Set rstEmployees = dbsNorthwind.OpenRecordset("Employees")
        If intErrorCondition = False Then
            On Error GoTo EditErrorHandler    ' Enable error trapping.
            Do Until rstEmployees.EOF
                If rstEmployees![Title] = "Sales Representative" Then
                    rstEmployees.Edit    ' Enable editing.
                    rstEmployees![Title] = "Account Executive"
                    rstEmployees.Update    ' Save changes.
                End If
                rstEmployees.MoveNext    ' Move to next record.
            Loop
        End If
        dbsNorthwind.Close    ' Close database.
    End If
    On Error GoTo 0        ' Disable error trapping.
    Exit Function
DBErrorHandler:
    intErrorCondition = True
    intUpdateNorthwind = False
    MsgBox "Can't open database.", vbExclamation
    Resume Next
TableErrorHandler:
    intErrorCondition = True
    intUpdateNorthwind = False
    MsgBox "Can't open Employees table.", vbExclamation
    Resume Next
EditErrorHandler:
    intErrorCondition = True
    UpdateDb = False
    MsgBox "Can't edit Employees table.", vbExclamation
    Resume Next
End Function
Example (Microsoft Access)

The following example returns a Database variable that points to the current database. Then it opens a different database called Another.mdb, using the OpenDatabase method. The procedure then enumerates all TableDef objects in both databases.

Sub OpenAnother()
    Dim dbs as Database, dbsAnother as Database
    Dim tdf as TableDef

    ' Return Database variable representing current database.
    Set dbs = CurrentDb

    ' Return Database variable representing Another.mdb.
    Set dbsAnother = DBEngine.Workspaces(0).OpenDatabase("Another.mdb")
    ' Enumerate all TableDef objects in each database.
    For Each tdf in dbs.TableDefs
        Debug.Print tdf.Name
    Next tdf
    For Each tdf in dbsAnother.TableDefs
        Debug.Print tdf.Name
    Next tdf
End Sub
Example (Microsoft Excel)

This example displays a custom dialog box containing a list of all databases with the filename extension .MDB that are located in the Microsoft Excel folder, and then it opens the database selected by the user.

Dim a(100), db As Database
i = 0
ChDrive "C"
ChDir Application.Path
a(i) = Dir("*.MDB")
If a(i) = "" Then
    MsgBox "You have no databases in the Microsoft Excel directory"
    Exit Sub
End If
Do
    i = i + 1
    a(i) = Dir()
Loop Until a(i) = ""
Set theDialog = DialogSheets.Add
Set list1 = theDialog.ListBoxes.Add(78, 42, 84, 80)
For counter = 0 To i - 1
    list1.AddItem a(counter)
Next
Application.ScreenUpdating = True
theDialog.Show
Set db = Workspaces(0).OpenDatabase(a(list1.Value - 1))
MsgBox "The " & db.Name & " database is now open"
' use database here
db.Close


OpenRecordset Method

Applies To

Database Object, Dynaset-Type Recordset Object, QueryDef Object, Recordset Object, Snapshot-Type Recordset Object, Table-Type Recordset Object, TableDef Object.

Description

Creates a new Recordset object and appends it to the Recordsets collection.

Syntax

Set variable = database.OpenRecordset(source[, type[, options]])

Set variable = object.OpenRecordset([type[, options]])

The OpenRecordset method syntax has these parts.

Part | Description
variable | A variable that has been declared as an object data type Recordset.
database | The name of an existing Database object you want to use to create the new Recordset.
object | The name of an existing QueryDef, Recordset, or TableDef object you want to use to create the new Recordset. This argument can't be the name of a forward-only scrolling snapshot.
 | If object refers to a dynaset or Snapshot-Type Recordset object, the type of the new object is the same as that of the Recordset specified by object. If object refers to a Table-Type Recordset object, the type of the new object is a Dynaset-Type Recordset.
source | A String specifying the source of the records for the new Recordset. The source can be a table name, a query name, or an SQL statement that returns records. For Table-Type Recordset objects, the source can only be a table name.
type | If you don't specify a type, OpenRecordset creates a Table-Type Recordset if possible. If you specify an attached table or query, OpenRecordset creates a Dynaset-Type Recordset. This value can be one of the following Integer constants:
 | u dbOpenTable — to open a Table-Type Recordset object.
 | u dbOpenDynaset — to open a Dynaset-Type Recordset object.
 | u dbOpenSnapshot — to open a Snapshot-Type Recordset object.

Part | Description
options | Any combination (or none) of the following Integer constants specifying characteristics of the new Recordset, such as restrictions on other users' ability to edit and view it:
 | u dbAppendOnly — You can append only new records (Dynaset-Type Recordset only).
 | u dbForwardOnly — The Recordset is a forward-only scrolling snapshot. Note that Recordset objects created with this option cannot be cloned and only support the MoveNext method to move through the records.
 | u dbSQLPassThrough — SQL pass-through. Causes the SQL statement to be passed to an ODBC database for processing.
 | u dbSeeChanges — Generate a run-time error if another user is changing data you are editing.
 | u dbDenyWrite — Other users can't modify or add records.
 | u dbDenyRead — Other users can't view records (Table-Type Recordset only).
 | u dbReadOnly — You can only view records; other users can modify them.
 | u dbInconsistent — Inconsistent updates are allowed (Dynaset-Type Recordset only).
 | u dbConsistent — Only consistent updates are allowed (Dynaset-Type Recordset only).

Note

The constants dbConsistent and dbInconsistent are mutually exclusive. You can use one or the other, but not both in a given instance of OpenRecordset.

Remarks

If object refers to a QueryDef, or a dynaset- or Snapshot-Type Recordset, or if source refers to an SQL statement or a TableDef that represents an attached table, you can't use dbOpenTable for the type argument; if you do, a trappable error occurs.

If you want to use an SQL pass-through query on an attached table, you must first set the Connect property of the attached table's database to a valid ODBC connect string. For more information on this, see the Connect property.

Use the dbSeeChanges flag if you want to trap changes made by another user or another program on your machine when you're editing or deleting the same record. For example, if two users start editing the same record, the first user to execute the Update method succeeds. When the Update method is executed by the second user, a run-time error occurs. Similarly, if the second user tries to use the Delete method to delete the record, and it has already been changed by the first user, a run-time error also occurs.

Typically, if the user gets this error while updating, your code should refresh the contents of the fields and retrieve the newly modified values. If the error occurs in the process of deleting, your code could display the new record data to the user and a message indicating that the data has recently changed. At this point, your code can request a confirmation that the user still wants to delete the record.

Tip

Use the forward-only scrolling option (dbForwardOnly) to improve performance when your application makes a single pass through a Recordset opened from an ODBC data source.

When you close a Recordset using the Close method, it's automatically deleted from the Recordsets collection.

See Also

Connect Property, Type Property.

Example

See the Edit method example.

Example (Microsoft Access)

The following example opens a Dynaset-Type Recordset object and prints the number of records in the Recordset object.

Sub UKOrders()
    Dim dbs As Database, rst As Recordset
    Dim strSQL As String

    ' Return Database variable pointing to current database.
    Set dbs = CurrentDb
    strSQL = "SELECT * FROM Orders WHERE [ShipCountry] = 'UK'"
    Set rst = dbs.OpenRecordset(strSQL)
    rst.MoveLast
    Debug.Print rst.RecordCount
End Sub
Example (Microsoft Excel)

This example displays a custom dialog box containing a list of all available recordsets in the NWINDEX.MDB database. The example opens a new recordset based on the recordset selected by the user and then copies the records onto Sheet1.

To create the NWINDEX.MDB database, run the Microsoft Excel example for the CreateDatabase method.

Dim db As Database, rs1 As Recordset
Set db = Workspaces(0).OpenDatabase(Application.Path & "\NWINDEX.MDB")
Application.ScreenUpdating = False
Set theDialog = DialogSheets.Add
Set list1 = theDialog.ListBoxes.Add(78, 42, 84, 80)
Set label1 = theDialog.Labels.Add(78, 125, 240, 25)
label1.Text = "Recordsets for " & db.Name
i = 0

Do Until i = db.TableDefs.Count
    list1.AddItem (db.TableDefs(i).Name)
    i = i + 1
Loop
Sheets("Sheet1").Activate
Application.ScreenUpdating = True
If theDialog.Show = True Then
    If list1.Value = 0 Then
        MsgBox "You have not selected an item from the list."
    Else
        Set rs1 = db.OpenRecordset(db.TableDefs(list1.Value - 1).Name)
        ActiveCell.CopyFromRecordset rs1
    End If
End If
rs1.Close
db.Close


OrdinalPosition Property

Applies To

Field Object.

Description

Sets or returns the relative position of a Field object within the Fields collection to which it is appended. For an object not yet appended to the Fields collection, this property is read/write.

Settings and Return Values

The setting or return value is an integer that specifies the numeric order of fields. The default is 0. The data type is Integer.

Remarks

For a Field object, use of the OrdinalPosition property depends on the object that contains the Fields collection that the Field object is appended to, as shown in the following table.

Object appended to | Usage
Index | Not supported
QueryDef | Read-only
Recordset | Read-only
Relation | Not supported
TableDef | Read/write

Generally, the ordinal position of an object that you append to a collection depends on the order in which you append the object. The first appended object is in the first position (0), the second appended object is in the second position (1), and so on. The last appended object is in ordinal position count –1, where count is the number of objects in the collection as specified by the Count property setting.

Using the OrdinalPosition property, you can specify an ordinal position for new Field objects that differs from the order in which you append those objects to a collection. This enables you to specify a field order for your tables, queries, and recordsets when you use them in an application. For example, the order in which fields are returned in a SELECT * query would be determined by the current OrdinalPosition property values.

You can permanently reset the order in which fields are returned in recordsets by setting the OrdinalPosition property to any positive integer.

Two or more Field objects in the same collection can have the same OrdinalPosition property value, in which case they will be ordered alphabetically. For example, if you have a field named Age set to 4 and you set a second field named Weight to 4, Weight is returned after Age.

You can specify a number that is greater than the number of fields – 1. The field will be returned in an order relative to the largest number. For example, if you set a field's OrdinalPosition property to 20 (and there are only 5 fields) and you've set the OrdinalPosition property for two other fields to 10 and 30, respectively, the field set to 20 is returned between the fields set to 10 and 30.

After you change the OrdinalPosition property setting, you can use the property to return the current setting. However, the fields aren't reordered until the Fields collection is repopulated. For example:

TableDefs("Titles").Fields(0).OrdinalPosition = 3
This code changes which Field object is referenced in the fourth position (0 relative). Because Field(0) was Title, Field(2) now refers to Title, and Field(0) refers to the first (lowest) field in the sequence.

It is simpler to reference Field objects by their Name property. For example, this code assigns the AU_ID field to the third field position:

TableDefs("Titles").Fields("AU_ID").OrdinalPosition = 2

Note

Changing the OrdinalPosition property setting of a Field object in the Fields collection will not immediately change its position in the collection. You will need to use the Refresh method on the collection to force the Field into its new position. Further, the OrdinalPosition setting is not the same as the field's index within a collection, although they may be equal.

See Also

Count Property, QueryDef Object, Refresh Method.

Example (Microsoft Access)

The following example changes the setting of the OrdinalPosition property for the first field in a Products table.

Sub SetPosition()
    Dim dbs As Database, tdf As TableDef
    Dim fldFirst As Field, fld As Field

    Set dbs = CurrentDb
    Set tdf = dbs.TableDefs!Products
    ' Return Field object pointing to first field in table.
    Set fldFirst = tdf.Fields(0)
    ' Set OrdinalPosition property to last position in collection.
    fldFirst.OrdinalPosition = tdf.Fields.Count
    ' Refresh Fields collection.
    tdf.Fields.Refresh
    ' Enumerate all fields and print ordinal position.
    For Each fld In tdf.Fields
        Debug.Print fld.Name, fld.OrdinalPosition
    Next fld
End Sub


Owner Property

Applies To

Container Object, Document Object.

Description

Sets or returns a value that specifies the owner of the object.

Settings and Return Values

The setting or return value is a string expression that evaluates to either the name of a User object in the Users collection or the name of a Group object in the Groups collection. The data type is String.

Remarks

The owner of an object has certain access privileges denied to other users. The Owner property setting can be changed at any time by any individual user account (represented by a User object) or group of user accounts (represented by a Group object) having the appropriate permissions.

See Also

Permissions Property, User Object.

Example

This example changes the Owner property setting of a Document object after determining whether the current user has the appropriate permissions to do so.

Dim dbsNorthwind As Database, docTest As Document
Set dbsNorthwind =  DBEngine.Workspaces(0).OpenDatabase("Northwind.mdb")
Set docTest = dbsNorthwind.Containers(0).Documents(0)
If (docTest.Permissions And dbSecWriteOwner) <> 0  Then
    docTest.Owner = "SomebodyElse"
End If

Example (Microsoft Access)

The following example changes the Owner property setting of a Module Document object after determining whether the current user has the appropriate permissions to do so.

Note that the And operator performs a bitwise comparison to determine whether a certain permission is currently set.

Sub ChangeOwner()
    Dim dbs As Database, ctrModules As Container, docModule As Document

    ' Return Database variable that points to current database.
    Set dbs = CurrentDb
    ' Return Container variable that points to Modules container.
    Set ctrModules = dbs.Containers!Modules
    ' Return Document object that points to ValuableFunctions module.
    Set docModule = ctrModules.Documents!ValuableFunctions
    ' Compare current permissions with owner permissions.
    If (docModule.Permissions And dbSecWriteOwner) <> 0 Then
        docModule.Owner = "SomebodyElse"
    End If
End Sub


Parameter Object

Description

A Parameter object represents a parameter associated with a QueryDef object created from a parameter query.

Remarks

Using the properties of a Parameter object, you can set a query parameter that can be changed before the query is run. You can:

  • Check the Name property setting to determine the name of a parameter.
  • Check or set the Value property (default) of a parameter. For example:

qdfNewHires.Parameters(0) = 5
  • Check the Type property setting to determine the data type of the Parameter object.
 The Parameters collection provides information only about existing parameters. You can't append objects to, or delete objects from, the Parameters collection.

The only method supported by the Parameters collection is the Refresh method.

Properties

Name Property, Type Property, Value Property.

See Also

Appendix, "Data Access Object Hierarchy."

Example

This example sets two query parameters for a hypothetical parameter query named "ParamQuery," executes the query by opening a Recordset from the QueryDef, and then prints the properties of each parameter. Note that this query does not actually exist in the Northwind sample database. The parameter data types are of type Date.

Dim dbsCurrent As Database
Dim qdfParam As QueryDef, prmEnum As Parameter
Dim rstParam As Recordset
Dim X As Integer
Set dbsCurrent = DBEngine.Workspaces(0).OpenDatabase("Northwind.mdb")
Set qdfParam = dbsCurrent.QueryDefs("ParamQuery")    ' Open existing
                                                    ' QueryDef.
qdfParam.Parameters("Order Date") = "10/11/94"        ' Set parameters.
qdfParam.Parameters("Ship Date") = "11/4/94"
Set rstParam = qdfParam.OpenRecordset()                ' Open Recordset.
For X = 0 To qdfParam.Parameters.Count - 1
    Set prmEnum = qdfParam.Parameters(X)
    Debug.Print prmEnum.Name            ' Print parameter properties.
    Debug.Print prmEnum.Type
    Debug.Print prmEnum.Value
Next X
rstParam.Close
Example (Microsoft Access)

The following example creates a new parameter query and supplies values for the parameters.

Sub NewParameterQuery()
    Dim dbs As Database, qdf As QueryDef, rst As Recordset
    Dim prm As Parameter, strSQL As String

    ' Return Database object pointing to current database.
    Set dbs = CurrentDb
    ' Construct SQL string.
    strSQL = "PARAMETERS [Beginning OrderDate] DateTime, " & _
        "[Ending OrderDate] DateTime; SELECT * FROM Orders " & _
        "WHERE ([OrderDate] Between[Beginning OrderDate] " & _
        "And [Ending OrderDate]);"
    ' Create new QueryDef object.
    Set qdf = dbs.CreateQueryDef("ParameterQuery", strSQL)
    ' Supply values for parameters.
    qdf.Parameters![Beginning OrderDate] = #4-1-95#
    qdf.Parameters![Ending OrderDate] = #4-30-95#
End Sub


Parameters Collection

Description

A Parameters collection contains all the Parameter objects of a QueryDef object.

Remarks

The Parameters collection provides information only about existing parameters. You can't append objects to or delete objects from the Parameters collection.

The only method supported by the Parameters collection is the Refresh method.

Properties

Count Property.

Methods

Refresh Method.

See Also

Appendix, "Data Access Object Hierarchy."

Example

See the Parameter object example.

Example (Microsoft Access)

See the Parameter object example (Microsoft Access).


Password Property

Applies To

User Object.

Description

Sets the password for a user account. This property setting is write-only for new objects not yet appended to a collection, and is not available for existing objects.

Settings

The setting is a string expression that can be up to 14 characters long and can include any characters except the ASCII character 0 (null). The data type is String.

Remarks

Set the Password property along with the PID property when you create a new User object.

Use the NewPassword method to change the Password property setting for an existing User object. To clear a password, set the newpassword argument of the NewPassword method to a zero-length string ("").

Passwords are case-sensitive.

Note

If you don't have access permission, you can't change the password of any other user.

See Also

NewPassword Method, Permissions Property, PID Property, UserName Property.

Example

This example creates a new User object and sets the Name, PID, and Password properties for the new object before appending it to the Users collection.

Dim usrMyself As User, wrkDefault As Workspace
...
Set wrkDefault = DBEngine.Workspaces(0)   ' Get default workspace.
' Create, specify, and append new User object.
Set usrMyself = wrkDefault.CreateUser("Pat Smith")
usrMyself.PID = "abc123DEF456"
usrMyself.Password = "MySecret"
wrkDefault.Users.Append usrMyself


PercentPosition Property

Applies To

Recordset Object, Snapshot-Type Recordset Object, Table-Type Recordset Object.

Description

Sets or returns a value that indicates or changes the approximate location of the current record in the Recordset object based on a percentage of the records in the Recordset.

Settings and Return Values

The setting or return value is a number between 0.0 and 100.00. The data type is Single.

Remarks

To indicate or change the approximate position of the current record in a Recordset object, you can check or set the PercentPosition property. When working with a dynaset- or Snapshot-Type Recordset object, first populate the Recordset object by moving to the last record before you set or check the PercentPosition property. If you use the PercentPosition property before fully populating the Recordset object, the amount of movement is relative to the number of records accessed as indicated by the RecordCount property setting. You can move to the last record using MoveLast method.

Note

Using the PercentPosition property to move the current record to a specific record in a Recordset object isn't recommended — the Bookmark property is better suited for this task.

Once you set the PercentPosition property to a value, the record at the approximate position corresponding to that value becomes current, and the PercentPosition property is reset to a value that reflects the approximate position of the current record. For example, if your Recordset object contains only five records, and you set its PercentPosition property value to 77, the value returned from the PercentPosition property may be 80, not 77.

The PercentPosition property applies to all three types of Recordset objects, including tables without indexes. The only exceptions are that it does not apply to forward-only scrolling snapshots), or on a Recordset object opened from a pass-through query against a remote database.

You can use the PercentPosition property with a scroll bar on a form or text box to indicate the location of the current record in a Recordset object.

See Also

Bookmark Property; Index Property; Move Method; MoveFirst, MoveLast, MoveNext, MovePrevious Methods.

Example

This example displays the current position of a record in a Recordset in a message box.

Dim dbsNorthwind As Database, rstEmployees As Recordset
Set dbsNorthwind =  DBEngine.Workspaces(0).OpenDatabase("Northwind.mdb")
' Open table.
Set rstEmployees = dbsNorthwind.OpenRecordset("Employees")
' Set current index.
rstEmployees.Index = "Last Name"
...
...    ' Move among the records.
...
' Display current position.
MsgBox("Current position is " & rstEmployees.PercentPosition & " %.")
Example (Microsoft Access)

The following example expresses the current position of a record in a recordset as a percent, then displays it in a message box.

Sub PercentOfRecords()
    Dim dbs As Database, rstProducts As Recordset
    Dim strInput As String, strSQL As String

    strSQL = "SELECT * FROM Products ORDER BY ProductName;"
    ' Return Database variable that points to current database.
    Set dbs = CurrentDb
    ' Open table.
    Set rstProducts = dbs.OpenRecordset(strSQL, dbOpenDynaset)
    ' Populate recordset.
    rstProducts.MoveLast
    ' Return to start of recordset.
    rstProducts.MoveFirst
    ' Prompt user to input name of product.
    strInput = InputBox("Please enter the full product name.")
    ' Find first occurrence.
    rstProducts.FindFirst "[ProductName] = '" & strInput & "'"
    ' Display current position as a percent.
    MsgBox("The current position in the Recordset is " & _
        rstProducts.PercentPosition & "%.")
End Sub

Example (Microsoft Excel)

This example selects and changes records in the Customer recordset in the NWINDEX.MDB database, and then it copies the recordset onto Sheet1. The status bar shows the percentage of records changed.

To create the NWINDEX.MDB database, run the Microsoft Excel example for the CreateDatabase method.

Dim db As Database, rs As Recordset, sQLText as String
Set db = Workspaces(0).OpenDatabase(Application.Path & "\NWINDEX.MDB")
sQLText = "SELECT [CON_TITLE], [CONTACT], [COMPANY] FROM Customer " _
    & "WHERE [CON_TITLE] = 'Owner';"
Set rs = db.OpenRecordset(sQLText, dbOpenDynaset)
rs.MoveFirst
Sheets("Sheet1").Activate
Do While Not rs.EOF
    rs.Edit
    rs.Fields("CON_TITLE").Value = "Account Excecutive"
    rs.Update
    Application.StatusBar = rs.PercentPosition & "% of the" _
        & " records have been replaced."
    rs.MoveNext
Loop
Application.StatusBar = "Done"
rs.MoveFirst
numberOfRows = ActiveCell.CopyFromRecordset(rs)
MsgBox numberOfRows & " Records have been changed"
rs.Close
db.Close


Permissions Property

Applies To

Container Object, Document Object.

Description

Sets or returns a value that establishes the permissions for the user or group identified by the UserName property of the Container or Document object.

Settings and Return Values

The setting or return value is a constant that establishes permissions. Possible settings or return values are:

Constant | Description
dbSecNoAccess | No access to the object.
dbSecFullAccess | Full access to the object.
dbSecDelete | Can delete the object.

Constant | Description
dbSecReadSec | Can read the object's security-related information.
dbSecWriteSec | Can alter access permissions.
dbSecWriteOwner | Can change the Owner property setting.

For the Tables Container object or any Document object in a Documents collection, the possible settings or return values are:

Constant | Description
dbSecCreate | Can create new documents (valid only with a Container object).
dbSecReadDef | Can read the table definition including column and index information.
dbSecWriteDef | Can modify or delete the table definition including column and index information.
dbSecRetrieveData | Can retrieve data from the Document object.
dbSecInsertData | Can add records.
dbSecReplaceData | Can modify records.
dbSecDeleteData | Can delete records.

For the Databases Container object or any Document object in a Documents collection, the possible settings or return values are:

Constant | User or group
dbSecDBAdmin | Gives user permission to make a database replicable and change the database password.
dbSecDBCreate | Can create new databases (valid only on the databases Container object in the system database [Systen.mdw]).
dbSecDBExclusive | Exclusive access.
dbSecDBOpen | Can open the database.

Remarks

These constants are listed in the Data Access (DAO) object library in the Object Browser.

Use this property to establish or determine the type of read/write/modify permissions the user has for a Container or Document object.

A Document object inherits the permissions for users from its Container object, provided the Inherited property of the Container object is set for those users or for a group to which the users belong. By setting a Document object's Permissions and UserName properties later, you can further refine the access control behavior of your object.

See Also

Inherited Property, UserName Property.

Specifics (Microsoft Access)

Microsoft Access defines four types of Container objects in addition to those defined by the Microsoft Jet database engine. These include the Forms, Reports, Scripts, or Modules Container objects. Individual Form, Report, Script and Module Document objects belong to the Documents collections of these Container objects. For these Container and Document objects, you can also set the Permissions property to the following constants.

Constant | User or group can
acSecFrmRptReadDef | Open the form or report in Design view but not make any changes.
acSecFrmRptWriteDef | Modify or delete the form or report in Design view.
acSecFrmRptExecute | Open the form in Form view or Datasheet view; print or open the report in Sample Preview or Print Preview.
acSecMacReadDef | Open the Macro window and view a macro without making changes.
acSecMacWriteDef | Modify or delete the macro in the Macro window.
acSecModReadDef | Open the module but not make any changes.
acSecModWriteDef | Modify or delete the contents of a module.
acSecMacExecute | Run the macro.

Example

This example prints the Permissions property setting of a Document object for the current user.

Dim dbsNorthwind As Database, docTest As Document
Set dbsNorthwind =  DBEngine.Workspaces(0).OpenDatabase("Northwind.mdb")
Set docTest = dbsNorthwind.Containers(0).Documents("MyDoc")
Debug.Print docTest.Permissions
Example (Microsoft Access)

The following example adds a new user account by creating a User object and appending it to the Users collection of the default workspace. It then sets permissions for the new user for all tables in the database. The procedure first sets the UserName property of a Tables Container object to the name of the new user, then sets the Permissions property to the appropriate permissions. Note that the security constants used to set the Permissions property are Integer values, so the + (plus sign) operator is used to add them.

Sub SetPermissions()
    Dim dbs As Database, ctrTables As Container
    Dim wspDefault As Workspace, usrNew As User

    ' Return Workspace object pointing to default workspace.
    Set wspDefault = DBEngine.Workspaces(0)
    ' Create User object, specifying Name, PID, and Password.

    Set usrNew = wspDefault.CreateUser("Kevin Smith", "ABC123XYZ123",_
         "Password")
    ' Append to Users collection of default workspace.
    wspDefault.Users.Append usrNew
    ' Return Database variable pointing to current database.
    Set dbs = CurrentDb
    ' Return Container variable pointing to Tables Container object.
    Set ctrTables = dbs.Containers!Tables
    ctrTables.UserName = usrNew.Name
    ' Set new user's permissions for tables.
    ctrTables.Permissions = dbSecInsertData + dbSecReplaceData + _
        dbSecDeleteData
End Sub


PID Property

Applies To

Group Object, User Object.

Description

Sets the personal identifier (PID) for either a group or a user account. This property setting is write-only for new objects not yet appended to a collection, and is not available for existing objects.

Settings

The setting is a string expression containing 4–20 alphanumeric characters. The data type is String.

Remarks

Set the PID property along with the Name property when you create a new Group object. Set the PID property along with the Name and Password properties when you create a new User object.

See Also

Name Property, Password Property.

Example

This example creates a new User object and sets the Name, PID, and Password properties for the new object before appending it to the Users collection.

Dim usrMyself As User, wrkDefault As Workspace
...
Set wrkDefault = DBEngine.Workspaces(0)   ' Get default workspace.
' Create, specify, and append new User object.
Set usrMyself = wrkDefault.CreateUser("Pat Smith")
usrMyself.PID = "abc123DEF456"
usrMyself.Password = "MySecret"
wrkDefault.Users.Append usrMyself


Primary Property

Applies To

Index Object.

Description

Sets or returns a value that indicates whether an Index object represents a primary index for a table. The Primary property setting is read/write for a new Index object not yet appended to a collection and read-only for an existing Index object in an Indexes collection. If the Index object is appended to the TableDef object but the TableDef object isn't appended to the TableDefs collection, the Index property is read-write.

Settings and Return Values

The setting or return value is a Boolean expression that specifies a primary index. The data type is Boolean. True (-1) indicates that the Index object represents a primary index.

Remarks

A primary index consists of one or more fields that uniquely identify all records in a table in a predefined order. Because the index field must be unique, the Unique property of the Index object is set to True. If the primary index consists of more than one field, each field can contain duplicate values, but each combination of values from all the indexed fields must be unique. A primary index consists of a key for the table and usually contains the same fields as the primary key.

Tip

You don't have to create indexes for tables, but in large, unindexed tables, accessing a specific record can take a long time. The Attributes property of each Field object in the Index object determines the order of records and consequently determines the access techniques to use for that index. When you create a new table in your database, it's a good idea to create an index on one or more fields that uniquely identify each record, and then set the Primary property of the Index object to True.

When you set a primary key for a table, the primary key is automatically defined as the primary index for the table.

See Also

Attributes Property, Clustered Property, Unique Property.

Specifics (Microsoft Access)

In Microsoft Access, when you set a primary key for a table in table Design view, the primary key is automatically defined as the primary index.

Example

In the Biblio.mdb database, this example creates a new Table and primary key Index object and then adds the Table to the TableDefs collection of a Database.

Dim dbsBiblio As Database , tdfBookTypes As TableDef
Dim idxPrimaryKey As Index, fldTypeNum As Field, fldType As Field
    ' Open the Database.
Set dbsBiblio =  DBEngine.Workspaces(0).OpenDatabase("Biblio.mdb")
Set tdfBookTypes = dbsBiblio.CreateTableDef("Book Types")
    ' Create and Set fldTypeNum field Set fldTypeNum =
     ' tdfBookTypes.CreateField("TypeNum",dbLong)

    ' Add fldTypeNum field to TableDef.
    tdfBookTypes.Fields.Append fldTypeNum
    ' Create and Set fldType field properties.
Set fldType = tdfBookTypes.CreateField("Type",dbText)
fldType.Size = 15    ' Set Size property of text field.
    ' Add fldType field to TableDef.
tdfBookTypes.Fields.Append fldType
Set idxPrimaryKey = tdfBookTypes.CreateIndex("PrimaryKey")
With idxPrimaryKey        ' Set properties in new Index.
   .Name = "PrimaryKey"
   .Unique = True
   .Primary = True
   .Fields = "TypeNum"
End With
    ' Add Index to TableDefs collection.
idxPrimaryKey.fields.Append idxPrimaryKey.CreateField("TypeNum")
tdfBookTypes.Indexes.Append idxPrimaryKey
' Append TableDef to database.
dbsBiblio.TableDefs.Append tdfBookTypes
dbsBiblio.Close
Example (Microsoft Access)

The following example checks the Primary property of each index on a Products table, and prints the fields making up the primary key.

Sub SetIndex()
    Dim dbs As Database, tdf As TableDef, fld As Field
    Dim idx As Index

    ' Return Database variable that points to current database.
    Set dbs = CurrentDb
    Set tdf = dbs.TableDefs!Products
    ' Enumerate through Indexes collection of TableDef.
    For Each idx In tdf.Indexes
        ' Check Primary property of Recordset object.
        If idx.Primary Then
            For Each fld In idx.Fields
                Debug.Print fld.Name
            Next fld
            Exit Sub
        End If
    Next idx
    MsgBox "No primary key defined."
End Sub


Properties Collection

Description

A Properties collection contains all the Property objects for a specific instance of an object.

Remarks

Every data access object contains a Properties collection, which has certain built-in Property objects. These Property objects (which are often just called properties) uniquely characterize that instance of the object.

In addition to the built-in properties, some objects allow you to create and add your own user-defined properties. To add a user-defined property to an existing instance of an object, first define its characteristics with the CreateProperty method, then add it to the collection with the Append method.

You can use the Delete method to remove user-defined properties from the Properties collection, but you can't remove built-in properties.

Note

A user-defined property (Property object) is associated only with the specific instance of the object whose Properties collection you append it to. The property isn't defined for all instances of objects of the selected type.

You can use the Properties collection of an object to enumerate the object's built-in and user-defined properties. You don't need to know beforehand exactly which properties exist or what their characteristics (Name and Type properties) are to manipulate them. However, if you try to read a write-only property, an error occurs.

You can refer to an existing built-in or user-defined property by its Name property setting using this syntax:

object.Properties("name")

For a built-in property, you can also use this syntax:

object.name

You can also reference properties by their ordinal position. For example, this syntax refers to the first member of the Properties collection:

object.Properties(0)

Note

A user-defined property differs from a built-in property of a data access object in that you must refer to a user-defined property using the full Properties("name") syntax.

Properties

Count Property.

Methods

Append Method, Delete Method, Refresh Method.

See Also

Appendix, "Data Access Object Hierarchy."

Specifics (Microsoft Access)

Several types of properties exist in Microsoft Access. Each of these properties can be represented in Visual Basic code by a Property object variable, and each is a member of a Properties collection.

Properties that apply to data access objects

  • Built-in properties are defined by the Microsoft Jet database engine for each data access object.
  • User-defined properties can be added to some data access objects. These data access objects include Database, Index, QueryDef, and TableDef objects, and Field objects in the Fields collection of a QueryDef or TableDef object.
  • Some properties defined by Microsoft Access apply to data access objects. These properties can generally be set either in the Microsoft Access window or from Visual Basic. The Jet database engine cannot recognize these properties until corresponding Property objects are specifically created and appended to the Properties collection. The data access objects to which such properties may apply are QueryDef and TableDef objects, and Field objects in the Fields collection of a QueryDef or TableDef object. For lists of these Microsoft Access-defined properties, see the Specifics (Microsoft Access) sections in the topics for the TableDef, QueryDef, and Field objects.
 Microsoft Access-defined properties that apply to data access objects differ from properties defined by the Jet database engine in several ways.

To refer to a user-defined property or a property defined by Microsoft Access, you must explicitly refer to the Properties collection. The fastest way to refer to a Microsoft Access property is by the following syntax.

object.Properties!name
You can also use the following, slightly slower syntax.

object.Properties("name")
In contrast, to refer to properties defined by the Jet database engine, you can simply use the object.name syntax.

If you are setting the value of a Microsoft Access-defined property for the first time, you first need to create it using the CreateProperty method. For example, the Caption property of a Field object is a Microsoft Access-defined property. If you have not previously set the Caption property in table Design view, but are setting the property for the first time from Visual Basic code, you must first create that property using the CreateProperty method and append it to the Properties collection before you can set its value.

A Microsoft Access-defined property is automatically appended to the Properties collection the first time it is set in the Microsoft Access window, so if you have already set a property in the user interface, you don't need to create and append the property in code. For example, you can set the Caption property for a table in Datasheet view by clicking Font on the Format menu. This property is then included in the Properties collection of a TableDef object that points to the table.

Until you have set a Microsoft Access-defined property either in table Design view or from Visual Basic code, that property will not appear in the Properties collection. When you set these properties from Visual Basic, you should include error-handling code that checks to see if the property exists in the Properties collection, and creates and appends the property if it does not.

Properties that apply to Microsoft Access objects

Like data access objects, every Microsoft Access object contains a Properties collection, which has built-in Property objects. For example, Property objects that apply to a form are members of the Properties collection of the Form object.

You can also create user-defined properties for Microsoft Access objects. For example, you might create a property called TextType that applies to a text box control.

Property objects in the Properties collections of Form, Report, and Control objects differ from data access Property objects in that they do not have an Inherited property.

You can enumerate the Property objects in the Properties collections of Form, Report, and Control objects. However, the Microsoft Access Application object and the Screen object have Properties collections that can't be enumerated. Additionally, the properties of these objects are read-only.

Example

This example creates a user-defined property for the current database, sets its Type and Value properties, and appends it to the Properties collection of the database. Then the example enumerates all properties in the database.

Function EnumerateProperty () As Integer
    Dim wrkDefault As Workspace, dbsExample As Database
    Dim prpUserDefined As Property, prpEnum As Property
    Dim I As Integer
    ' Get default workspace and current database.
    Set wrkDefault = DBEngine.Workspaces(0)
    Set dbsExample = wrkDefault.OpenDatabase("Northwind.mdb")
    ' Create user-defined property.
    Set prpUserDefined = dbsExample.CreateProperty()
    ' Set properties of new property.
    prpUserDefined.Name = "UserDefinedProperty"
    prpUserDefined.Type = dbText
    prpUserDefined.Value = "This is a user-defined property."
    ' Append property to current database.

    dbsExample.Properties.Append prpUserDefined
    ' Enumerate all properties of current database.
    Debug.Print "Properties of Database "; dbsExample.Name
    For I = 0 To dbsExample.Properties.Count - 1
        Set prpEnum = dbsExample.Properties(I)
        Debug.Print
        Debug.Print " Properties("; I; ")"
        Debug.Print "  Name: "; prpEnum.Name
        Debug.Print "  Type: "; prpEnum.Type
        Debug.Print "  Value: "; prpEnum.Value
        Debug.Print "  Inherited: "; prpEnum.Inherited
    Next I
    Debug.Print
    EnumerateProperty = True
End Function
This example shows how you can set an application-defined property (or any user-defined property that may not yet exist) without causing a run-time error. The example sets an arbitrary property of a Field object. The return value of the function is True if the value was properly set. The return value is False if an unexpected error occurs when the property is set.

Function SetFieldProperty (fldPropVal As Field, strName As String, intType As Integer, varValue As Variant) As Integer
    Const ERR_PROPERTY_NONEXISTENT = 3270
    Dim prpUserDefined As Property
    On Error Resume Next    ' Function handles errors.
    SetFieldProperty = True
    fldPropVal.Properties(strName) = varValue
    If Err <> 0 Then    ' Error occurred when value was set.
        If Err <> ERR_PROPERTY_NONEXISTENT
            On Error GoTo 0
            SetFieldProperty = False
        Else
            ' Create Property object, setting its Name, Type, and Value
            ' properties.
            On Error Resume Next
            Set prpUserDefined = fldPropVal.CreateProperty(strName, _
                intType, varValue)
            fldPropVal.Properties.Append prpUserDefined
            If Err <> 0 Then
                SetFieldProperty = False
            End If
            On Error GoTo 0
        End If
    End If
End Function
Example (Microsoft Access)

The following example creates a new user-defined property, sets its initial value, and appends it to the Properties collection of a TableDef object.

Sub CreateNewProperty()
    Dim dbs As Database, tdf As TableDef
    Dim prp As Property
    ' Return Database object pointing to current database.
    Set dbs = CurrentDb
    Set tdf = dbs.TableDefs!Orders
    ' Create new property, denote type, and set initial value.
    Set prp = tdf.CreateProperty("LastSaved", dbText, "New")
    ' Append to Properties collection of TableDef object.
    tdf.Properties.Append prp
End Sub
The next example creates a property that is defined by Microsoft Access, but applies to data access objects. Because the Microsoft Jet database engine cannot recognize properties defined by Microsoft Access, you must create a new Property object and append it to the Properties collection if you are setting the property for the first time.

Note that you must specify the correct constant for the type argument when you create the property. If you're not certain which data type you should use, see the topic for the individual property.

Sub CreateAccessProperty()
    Dim dbs As Database, tdf As TableDef
    Dim prp As Property

    ' Return Database object pointing to current database.
    Set dbs = CurrentDb
    Set tdf = dbs.TableDefs!Orders
    ' Create property, denote type, and set initial value.
    Set prp = tdf.CreateProperty("DatasheetFontItalic", dbBoolean, True)
    ' Append Property object to Properties collection.
    tdf.Properties.Append prp
End Sub


Property Object

Description

A Property object represents a built-in or user-defined characteristic of a data access object.

Remarks

Every data access object contains a Properties collection, which has certain built-in Property objects. These Property objects (which are often just called properties) uniquely characterize that instance of the object. You specify built-in properties when you create a new data access object. You can set the properties of some existing data access objects using an assignment statement.

The Property object also has four built-in properties:

  • The Name property, a String that uniquely identifies the property.
  • The Type property, an Integer that specifies the property data type.
  • The Value property, a Variant that contains the property setting.
  • The Inherited property, a Boolean flag that indicates whether the property is inherited from another object. For example, a Field object in a Fields collection of a Recordset object can inherit properties from the underlying TableDef or QueryDef object.
 In addition to these built-in properties, you can create and add your own user-defined properties to these objects:

  • Database, Index, QueryDef, and TableDef objects
  • Field objects in Fields collections of QueryDef and TableDef objects
 To add a user-defined property, use the CreateProperty method to create a Property object with a unique Name property setting. Set the Type and Value properties of the new Property object, and then append it to the Properties collection of the appropriate object. The object to which you are adding the user-defined property must already be saved to disk (that is, it must be appended to a collection).

You can delete user-defined properties from the Properties collection, but you can't delete built-in properties.

Note

A user-defined property (Property object) is associated only with the specific instance of the object whose Properties collection you append it to. The property isn't defined for all instances of objects of the selected type.

You can use the Properties collection of an object to enumerate the object's built-in and user-defined properties. You don't need to know beforehand exactly which properties exist or what their characteristics (Name and Type properties) are to manipulate them. However, if you try to read a write-only property (such as the Password property of a Workspace object), an error occurs.

You can refer to an existing built-in or user-defined property by its Name property setting using this syntax:

object.Properties("name")

For a built-in property, you can also use this syntax:

object.name

You can also reference properties by their ordinal position using this syntax, which refers to the first member of the Properties collection:

object.Properties(0)

A user-defined property differs from a built-in property of a data access object in the following ways:

  • You must refer to a user-defined property using the full Properties("name") syntax.
  • If you haven't previously set the property's value, you need to create it first using the CreateProperty method.
 Properties

Inherited Property, Name Property, Type Property, Value Property.

See Also

CreateProperty Method; Database Object; Appendix, "Data Access Object Hierarchy."

Specifics (Microsoft Access)

See the Properties collection specifics (Microsoft Access).

Example

See the Properties collection example.

Example (Microsoft Access)

See the Properties collection example (Microsoft Access).


QueryDef Object

Description

A QueryDef object is a stored definition of a query in a Microsoft Jet database.

Remarks

The QueryDef object corresponds to a stored query definition in a database. You can think of a saved query as a compiled SQL statement.

You can use the properties of a QueryDef object to define a query. For example, you can:

  • Check and modify the SQL property setting, set its parameters, and then run the query.
  • Set query parameters using the QueryDef object's Parameters collection.
  • Set or check the Type property to determine whether the query selects records from an existing table, makes a new table, inserts records from one table into another table, deletes records, or updates records.
  • Retrieve data from an ODBC data source by setting the ODBCTimeout and Connect properties and, if the query isn't a select query, setting the ReturnsRecords property to False.
  • Indicate the query is to be passed to an external ODBC server by setting the Connect property, making it an SQL pass through query.
  • Use the ReturnsRecords property to indicate that the query returns records. The ReturnsRecords property is only valid on SQL pass through queries.
  • Use the ODBCTimeout property to indicate how long to wait before the query returns records. The ODBCTimeout property applies to any query that accesses ODBC data.
 Queries executed from QueryDef objects run faster than queries specified by the OpenRecordset method because the Microsoft Jet database engine doesn't need to compile the query before executing it.

The preferred way to use the native SQL dialect of an external database engine is by using QueryDef objects. For example, you can create a Transact SQL query (as used with Microsoft SQL Server) and store it in a QueryDef object. When you need to use a non-Jet database engine SQL query, you must provide a Connect property string that points to the external data source. Queries with valid Connect properties bypass the Jet database engine and pass the query directly to the external database server for processing.

To create a new QueryDef object, use the CreateQueryDef method.

Properties

Connect Property; DateCreated, LastUpdated Properties; KeepLocal Property; LogMessages Property; Name Property; ODBCTimeout Property; RecordsAffected Property; Replicable Property; ReturnsRecords Property; SQL Property; Type Property; Updatable Property.

Methods

CreateProperty Method, Execute Method, OpenRecordset Method.

See Also

CreateQueryDef Method; Appendix, "Data Access Object Hierarchy."

Specifics (Microsoft Access)

In addition to the properties defined by the Microsoft Jet database engine, a QueryDef object may also contain these Microsoft Access application-defined properties. For details on checking and setting these properties, see the topics for the individual properties and the Property object.

DatasheetFontHeight | FrozenColumns
DatasheetFontItalic | LogMessages
DatasheetFontName | RecordLocks
DatasheetFontUnderline | RowHeight
DatasheetFontWeight | ShowGrid
Description |

Example

This example creates a new QueryDef object and appends it to the QueryDefs collection in the current database. Then the example enumerates all the QueryDef objects in the database and all the properties of the new QueryDef.

Function EnumerateQueryDef () As Integer
    Dim wrkCurrent As Workspace, dbsExample As Database, qdfTest As _
        QueryDef
    Dim I As Integer
    Set wrkCurrent = DBEngine.Workspaces(0)
    Set dbsExample = wrkCurrent.OpenDatabase("Northwind.mdb")
    Set qdfTest = dbsExample.CreateQueryDef("This is a test")
    Debug.Print
    ' Enumerate QueryDef objects.
    Debug.Print
    For I = 0 To dbsExample.QueryDefs.Count - 1
        Debug.Print dbsExample.QueryDefs(I).Name
    Next I
    ' Enumerate built-in properties of qdfTest.
    Debug.Print
    Debug.Print "qdfTest.Name: "; qdfTest.Name
    Debug.Print "qdfTest.DateCreated: "; qdfTest.DateCreated
    Debug.Print "qdfTest.LastUpdated: "; qdfTest.LastUpdated
    Debug.Print "qdfTest.SQL: "; qdfTest.SQL
    Debug.Print "qdfTest.ODBCTimeout: "; qdfTest.ODBCTimeout
    Debug.Print "qdfTest.Updatable: "; qdfTest.Updatable
    Debug.Print "qdfTest.Type: "; qdfTest.Type
    Debug.Print "qdfTest.Connect: "; qdfTest.Connect
    Debug.Print "qdfTest.ReturnsRecords: "; qdfTest.ReturnsRecords
    dbsExample.QueryDefs.Delete "This is a test"
    EnumerateQueryDef = True
End Function
Example (Microsoft Access)

The following example checks to see if there is a query called RecentHires in the current database, and deletes it from the QueryDefs collection if it exists. Then the procedure creates a new QueryDef object and opens it in Datasheet view.

Sub NewQuery()
    Dim dbs As Database, qdf As QueryDef
    Dim strSQL As String

    ' Return Database object pointing to current database.
    Set dbs = CurrentDb
    ' Refresh QueryDefs collection.
    dbs.QueryDefs.Refresh
    ' If RecentHires query exists, delete it.
    For Each qdf in dbs.QueryDefs
        If qdf.Name = "RecentHires" Then
            dbs.QueryDefs.Delete qdf.Name
        End If
    Next qdf
    ' Create SQL string to select employees hired after 1-1-95.
    strSQL = "SELECT * FROM Employees WHERE HireDate >= #1-1-95#;"
    ' Create new QueryDef object.
    Set qdf = dbs.CreateQueryDef("RecentHires", strSQL)
    ' Open query in Datasheet view.
    DoCmd.OpenQuery qdf.Name
End Sub


QueryDefs Collection

Description

A QueryDefs collection contains all QueryDef objects in a Database object.

Remarks

The QueryDef object corresponds to a stored query definition in a database. When you create a QueryDef object, you can add it to the QueryDefs collection using the Append method so it will be saved when you close the Database object.

To remove a QueryDef object from the collection, use the Delete method.

Properties

Count Property.

Methods

Append Method, Delete Method, Refresh Method.

See Also

Appendix, "Data Access Object Hierarchy."

Specifics (Microsoft Access)

See the QueryDef object specifics (Microsoft Access).

Example

See the QueryDef object example.

Example (Microsoft Access)

See the QueryDef object example (Microsoft Access).


QueryTimeout Property

Applies To

Database Object.

Description

Sets or returns a value that specifies the number of seconds the Microsoft Jet database engine waits before a timeout error occurs when a query is executed on an ODBC database.

Settings and Return Values

The setting or return value is an integer representing the number of seconds the Jet database engine waits before timing out and returning an error. The data type is Integer.

Remarks

When you're using an ODBC database, such as SQL Server, there may be delays due to network traffic or heavy use of the ODBC server. Rather than waiting indefinitely, you can specify how long to wait before the Jet database engine produces an error.

When used with a Database object, the QueryTimeout property specifies a global value for all queries associated with the database.

The timeout value is taken from the Windows Registry. If there is no Windows Registry setting, the default value is 60 seconds. Once this property is set, however, it overrides any Windows Registry setting or default value.

See Also

ODBCTimeout Property.

Example

This example opens the specified database and sets the QueryTimeout property to 120 seconds.

Dim dbsNorthwind As Database
Set dbsNorthwind =  DBEngine.Workspaces(0).OpenDatabase("Northwind.mdb")
dbsNorthwind.QueryTimeout = 120
Example (Microsoft Access)

The following example opens the specified database and sets the QueryTimeout property to 120 seconds.

Sub SetTimeout()
    Dim dbs As Database
    ' Return Database variable that points to current database.
    Set dbs = CurrentDb
    dbs.QueryTimeout = 120
End Sub


RecordCount Property

Applies To

Dynaset-Type Recordset Object, Recordset Object, Snapshot-Type Recordset Object, Table-Type Recordset Object, TableDef Object.

Description

Returns the number of records accessed in a Dynaset-type or Snapshot-type Recordset object, or the total number of records in a Table-type Recordset or TableDef object. This property setting is read-only.

Return Values

The return value is a Long Integer.

Remarks

Use the RecordCount property to find out how many records in a Recordset or TableDef object have been accessed. The RecordCount property doesn't indicate how many records are contained in a dynaset- or snapshot-type Recordset object until all records have been accessed.

Once the last record has been accessed, the RecordCount property indicates the total number of undeleted records in the Recordset or TableDef object. To force the last record to be accessed, use the MoveLast method on the Recordset object. You can also use an SQL Count function to determine the approximate number of records your query will return.

As your application deletes records in a dynaset-type Recordset object, the value of the RecordCount property decreases. However, records deleted by other users aren't reflected by the RecordCount property until the current record is positioned to a deleted record. If you execute a transaction that affects the RecordCount property setting and subsequently rolls back the transaction, the RecordCount property won't reflect the actual number of remaining records.

The RecordCount property of a snapshot-type Recordset object isn't affected by changes in the underlying tables.

A Recordset or TableDef object with no records has a RecordCount property setting of 0.

When working with attached TableDef objects, the RecordCount property setting is always –1.

Using the Requery method on a Recordset object resets the RecordCount property just as if the query were re-executed.

See Also

MoveFirst, MoveLast, MoveNext, MovePrevious Methods; Requery Method.

Example

This example creates a Recordset object based on the Employees table and then determines the number of records in the Recordset.

Dim dbsNorthwind As Database, rstEmployees As Recordset
Dim lngTotal As Long
Set dbsNorthwind =  DBEngine.Workspaces(0).OpenDatabase("Northwind.mdb")

Set rstEmployees = dbsNorthwind.OpenRecordset("Employees")
rstEmployees.MoveLast
lngTotal = rstEmployees.RecordCount
If lngTotal = -1 Then
    Debug.Print "Count not available."
End If
Example (Microsoft Access)

The following example creates a Recordset object based on the Orders table and then determines the number of records in the Recordset object.

Sub CountRecords()
    Dim dbs As Database, rstOrders As Recordset
    Dim lngTotal As Long

    ' Return Database variable that points to current database.
    Set dbs = CurrentDb
    ' Open table-type Recordset object.
    Set rstOrders = dbs.OpenRecordset("Orders")
    ' Fully populate Recordset object.
    rstOrders.MoveLast
    Debug.Print rstOrders.RecordCount
End Sub
Example (Microsoft Excel)

This example displays the number of records in the Customer recordset in the NWINDEX.MDB database.

To create the NWINDEX.MDB database, run the Microsoft Excel example for the CreateDatabase method.

Sub CountRecords()
    Dim db As Database, rs As Recordset
    Set db = Workspaces(0).OpenDatabase(Application.Path _
        & "\NWINDEX.MDB")
    Set rs = db.OpenRecordset("Customer")
    On Error GoTo errorHandler
    rs.MoveLast
    MsgBox "There are " & rs.RecordCount & " records in " _
        & rs.Name
    rs.Close
    db.Close
    Exit Sub
errorHandler:
    MsgBox "There are no records in " & rs.Name
    rs.Close
    db.Close
End Sub


RecordsAffected Property

Applies To

Database Object, QueryDef Object.

Description

Returns the number of records affected by the most recently invoked Execute method.

Return Values

The return value is an integer from 0 to the number of records affected by the most recently invoked Execute method on either a Database or QueryDef object. The data type is Long.

Remarks

The RecordsAffected property contains the number of records deleted, updated, or inserted when running an action query. When you use the Execute method to run a QueryDef object, the RecordsAffected property setting is the number of records affected.

Note

The RecordsAffected property setting is the same as the value returned by the ExecuteSQL method.

Example

This example prints the number of records updated by an action query.

Dim dbsBiblio As Database, lngResults As Long
Set dbsBiblio =  DBEngine.Workspaces(0).OpenDatabase("Biblio.mdb")
dbsBiblio.Execute "Update Titles Set [Year Published] = 1994 " _
    & " WHERE Title = 'To Kill an SQL Query' "
lngResults = dbsBiblio.RecordsAffected
Debug.Print lngResults & " records were changed."
dbsBiblio.Close
Example (Microsoft Access)

The following example prints the number of records updated by an action query.

Sub RecordsUpdated()
    Dim dbs As Database, qdf As QueryDef
    Dim strSQL As String

    ' Return Database variable that points to current database.
    Set dbs = CurrentDb
    strSQL = "UPDATE Employees SET Title = " & _
        "'Senior Sales Representative' " & _
        "WHERE Title = 'Sales Representative';"
    ' Create new QueryDef.
    Set qdf = dbs.CreateQueryDef("UpdateTitles", strSQL)
    ' Execute QueryDef object.
    qdf.Execute
    Debug.Print qdf.RecordsAffected
End Sub


Recordset Object

Description

A Recordset object represents the records in a base table or the records that result from running a query.

Remarks

When you use data access objects, you interact with data almost entirely using Recordset objects. All Recordset objects are constructed using records (rows) and fields (columns).

There are three types of Recordset objects:

  • Table-type Recordset — a representation in code of a base table that you can use to add, change, or delete records from a single database table.
  • Dynaset-type Recordset — the result of a query that can have updatable records. A dynaset-type Recordset object is a dynamic set of records that you can use to add, change, or delete records from an underlying database table or tables. A dynaset-type Recordset object can contain fields from one or more tables in a database.
  • Snapshot-type Recordset — a static copy of a set of records that you can use to find data or generate reports. A snapshot-type Recordset object can contain fields from one or more tables in a database but can't be updated.
 You can choose the type of Recordset object you want to create using the type argument of the OpenRecordset method. If you don't specify a type, the Microsoft Jet database engine attempts to create a table-type Recordset object. If this isn't possible, the Jet database engine attempts a dynaset-type and then a snapshot-type Recordset object.

When creating a Recordset object using a nonattached TableDef object, table-type Recordset objects are created. Only dynaset-type or snapshot-type Recordset objects can be created with attached tables or tables in external ODBC databases.

The Type property indicates the type of Recordset object created, and the Updatable property indicates whether you can change the object's records.

A new Recordset object is automatically added to the Recordsets collection when you open the object, and is automatically removed when you close it.

Information about the structure of a base table, such as the names and data types of each Field object and any Index objects, is stored in a TableDef object.

Note

If you use variables to represent a Recordset object and the Database object that contains the recordset, make sure the variables have the same scope, or lifetime. For example, if you declare a global variable that represents a Recordset object, make sure the variable that represents the database containing the recordset is also global, or is declared in a Sub or Function procedure using the Static keyword.

Your application can create as many Recordset object variables as needed. A Recordset object can refer to one or more tables or queries, or can be an SQL statement. You can also have a Recordset object that refers to some or all of the fields or records in other Recordset objects.

Dynaset- and snapshot-type Recordset objects are stored in local memory. If there isn't enough space in local memory to store the data, the Jet database engine saves the additional data to TEMP disk space. If this space is exhausted, a trappable error occurs.

The default collection of a Recordset object is the Fields collection, and the default property of a Field object is the Value property. You can simplify your code by using these defaults. For example, the following lines of code all set the value of the PubID field in the current record of a Recordset object.

rstPublishers!PubID = 99
rstPublishers("PubID") = 99
rstPublishers.Fields("PubID").Value = 99
When you create a Recordset object, the current record is positioned to the first record if there are any records. If there are no records, the RecordCount property setting is 0, and the BOF and EOF property settings are True.

You can use the MoveNext, MovePrevious, MoveFirst, and MoveLast methods to reposition the current record. For dynaset- and snapshot-type Recordset objects, you can also use the Find methods, such as FindFirst, to locate a specific record based on criteria. If the record isn't found, the NoMatch property is set to True. For table-type Recordset objects, you can scan records using the Seek function.

To cycle through all records, you can use the BOF and EOF properties to check for the beginning or end of the Recordset object. However, it may run faster to with an SQL query that performs operations that apply to an entire set of records.

Properties

AbsolutePosition Property; BOF, EOF Properties; Bookmark Property; Bookmarkable Property; CacheSize, CacheStart Properties; DateCreated, LastUpdated Properties; EditMode Property; Filter Property; Index Property; LastModified Property; LockEdits Property; Name Property; NoMatch Property; PercentPosition Property; RecordCount Property; Restartable Property; Sort Property; Transactions Property; Type Property; Updatable Property; ValidationRule Property; ValidationText Property.

Methods

AddNew Method; CancelUpdate Method; Clone Method; Close Method; CopyQueryDef Method; Delete Method; Edit Method; FillCache Method; FindFirst, FindLast, FindNext, FindPrevious Methods; GetRows Method; Move Method; MoveFirst, MoveLast, MoveNext, MovePrevious Methods; OpenRecordset Method; Requery Method; Seek Method; Update Method.

See Also

Dynaset-Type Recordset Object; Index Object; OpenRecordset Method; Snapshot-Type Recordset Object; Table-Type Recordset Object; Appendix, "Data Access Object Hierarchy."

Example

This example creates a new Recordset object and opens it (thereby appending it to the Recordsets collection) in the default database. Then the example enumerates all the Recordset objects in the current database and all the fields in each Recordset object and closes the new Recordset.

Function EnumerateRecordset () As Integer
    Dim dbsExample As Database, rstOrders As Recordset
    Dim rstTemp As Recordset
    Dim I As Integer, J As Integer
    Set dbsExample = _
        DBEngine.Workspaces(0).OpenDatabase("Northwind.mdb")
    Set rstOrders = dbsExample.OpenRecordset("Orders", dbOpenSnapshot)
    Debug.Print
    ' Enumerate all Recordset objects.
    For J = 0 To dbsExample.Recordsets.Count - 1
        Set rstTemp = dbsExample.Recordsets(J)
        Debug.Print
        Debug.Print "Enumeration of Recordset objects("; J; "): "; _
            rstTemp.Name
        Debug.Print
        ' Enumerate fields.
        Debug.Print "Fields: Name, Type, Value"
        For I = 0 To rstTemp.Fields.Count - 1
            Debug.Print "  "; rstTemp.Fields(I).Name;
            Debug.Print ", "; rstTemp.Fields(I).Type;
            If rstTemp.Fields(I).Type = dbText Then
                Debug.Print ", "; rstTemp.Fields(I).Value
            End if
        Next I
    Next J
    dbsExample.Close
    EnumerateRecordset = True
End Function
Example (Microsoft Access)

The following example opens a table-type Recordset object, a dynaset-type Recordset object, and a snapshot-type Recordset object. Then it displays the value of the Updatable property for the Recordset objects.

Sub NewRecordsets()
    Dim dbs As database, rst As Recordset
    Dim rstEmployees As Recordset, rstOrders As Recordset
    Dim rstProducts As Recordset, strSQL As String

    ' Return Database object pointing to current database.
    Set dbs = CurrentDb
    ' Create table-type Recordset object.
    Set rstEmployees = dbs.OpenRecordset("Employees", dbOpenTable)
    ' Construct SQL string.
    strSQL = "SELECT * FROM Orders WHERE OrderDate >= #1-1-95#;"
    ' Create dynaset-type Recordset object.
    Set rstOrders = dbs.OpenRecordset(strSQL, dbOpenDynaset)
    ' Create snapshot-type Recordset object.
    Set rstProducts = dbs.OpenRecordset("Products", dbOpenSnapshot)
    ' Print value of Updatable property for each Recordset object.
    For Each rst In dbs.Recordsets
        Debug.Print rst.Name; "   "; rst.Updatable
    Next rst
End Sub


Recordsets Collection

Description

The Recordsets collection contains all open Recordset objects in a Database object.

Remarks

When you use data access objects, you interact with data almost entirely using Recordset objects.

A new Recordset object is automatically added to the Recordsets collection when you open the Recordset object, and is automatically removed when you close it.

Your application can create as many Recordset object variables as needed. A Recordset object can refer to one or more tables, queries alone, or queries referenced by other Recordset objects in any combination. You can also have a Recordset object that refers to some or all of the fields or records in other Recordset objects.

Properties

Count Property.

Methods

Refresh Method.

See Also

Appendix, "Data Access Object Hierarchy."

Example

See the Recordset object example.

Example (Microsoft Access)

See the Recordset object example (Microsoft Access).


Refresh Method

Applies To

Databases Collection, Documents Collection, Errors Collection, Fields Collection, Groups Collection, Indexes Collection, Parameters Collection, Properties Collection, QueryDefs Collection, Recordsets Collection, Relations Collection, TableDefs Collection, Users Collection, Workspaces Collection.

Description

Updates the objects in a collection to reflect the current database's schema.

Syntax

collection.Refresh

Remarks

The Refresh method can't be used with collections that aren't persistent, such as Databases, Recordsets, or Workspaces.

Note

To determine the position that the Microsoft Jet database engine uses for Field objects in the Fields collection of a QueryDef, Recordset, or TableDef object, use the OrdinalPosition property of each Field object. The Refresh method may change the order of objects within the Fields collection, if the OrdinalPosition property of a Field object in the collection has been changed.

Use the Refresh method in multiuser environments in which other users may change the database. You may also need to use it on any collections that are indirectly affected by changes to the database. For example, if you change a Users collection, you may need to refresh a Groups collection before using the Groups collection.

Tip

A collection is filled with objects the first time it's referred to and won't automatically reflect subsequent changes made to it by other users. If it's likely that a collection has been changed by another user, use the Refresh method on the collection immediately before carrying out any task in your application that assumes the presence or absence of a particular object in the collection. This will ensure that the collection is as up-to-date as possible.

See Also

Append Method, Close Method, Delete Method, OrdinalPosition Property, Requery Method.

Example

This example refreshes the Tables collection in a database in a multiuser environment in case another user has made changes.

Dim wspDefault As Workspace, dbsNorthwind As Database
' Get default workspace.
Set wspDefault = DBEngine.Workspaces(0)
' Open database.
Set dbsNorthwind = wspDefault.OpenDatabase("Northwind.mdb")
...

' Refresh possibly changed collection.
dbsNorthwind.Containers("Tables").Documents.Refresh
Example (Microsoft Access)

The following example refreshes the Indexes collection of a TableDef object. In a database in a multiuser environment, you can use the Refresh method to show changes made by other users.

Sub RefreshIndex()
    Dim dbs As Database, tdf As TableDef
    Dim idx As Index, fld As Field

    ' Return Database variable pointing to current database.
    Set dbs = CurrentDb
    Set tdf = dbs.TableDefs!Employees
    tdf.Indexes.Refresh
    For Each idx In tdf.Indexes
        Debug.Print idx.Name; ":"
        For Each fld In idx.Fields
            Debug.Print "   "; fld.Name
        Next fld
    Next idx
End Sub


RefreshLink Method

Applies To

TableDef Object.

Description

Updates the connection information for an attached table.

Syntax

tabledef.RefreshLink

The tabledef placeholder specifies the TableDef object representing the attached table whose connection information you want to update.

Remarks

You change the connection information for an attached table by resetting the Connect property of the corresponding TableDef object and then using the RefreshLink method to update the information. When you use RefreshLink, the attached table's properties and Relation objects aren't changed.

To force this connection information to exist in all collections associated with the TableDef object that represents the attached table, you must also use the Refresh method on each collection.

See Also

Connect Property, Refresh Method.

Example

This example attaches a Paradox table named PDX_Author to a database opened for exclusive use, moves the connection to a different directory, and then refreshes the connection information.

Dim dbsPublishers As Database, tdfPDX_Author As TableDef
' Open database.
Set dbsPublishers = DBEngine.Workspaces(0).OpenDatabase _
    ("C:\CONTACTS\Biblio.mdb")
Set tdfPDX_Author = dbsPublishers.CreateTableDef _
    ("PDX_Author", dbAttachExclusive)
tdfPDX_Author.SourceTableName = "Author"
tdfPDX_Author.Connect = "Paradox 3.x; " _
    & "DATABASE=C:\PDX\PUBS; PWD=books"
' Append to TableDefs collection.
dbsPublishers.TableDefs.Append tdfPDX_Author
' Move to new directory.
dbsPublishers.TableDefs!PDX_Author.Connect = "Paradox 3.x; " _
    & "DATABASE=N:\PDX\PUBS; PWD=books"
' Refresh connection information.
dbsPublishers.TableDefs!PDX_Author.RefreshLink


RegisterDatabase Method

Applies To

DBEngine Object.

Description

Enters connection information for an ODBC data source in the ODBC.INI file. The ODBC driver needs connection information when the Microsoft Jet database engine opens the data source during a session.

Syntax

DBEngine.RegisterDatabase dbname, driver, silent, attributes

The RegisterDatabase method syntax has these parts.

Part | Description
dbname | A string expression that is the name used in the OpenDatabase method that refers to a block of descriptive information about the data source. For example, if the data source is an ODBC remote database, it could be the name of the server.
driver | A string expression that is the name of the ODBC driver. This isn't the name of the ODBC driver DLL file. For example, SQL Server is a driver name, but SQLSRVR.dll is the name of a DLL file. You must have ODBC and the appropriate driver already installed.

Part | Description
silent | A numeric expression that is True if you don't want to display the ODBC driver dialog boxes that prompt for driver-specific information or False if you do want to display the ODBC driver dialog boxes. If silent is True, attributes must contain all the necessary driver-specific information or the dialog boxes are displayed anyway.
attributes | A string expression that is a list of keywords to be added to the ODBC.INI file. The keywords are in a carriage-return–delimited string.

Remarks

If the database is already registered (connection information is already entered) in the ODBC.INI file when you use the RegisterDatabase method, the connection information is updated.

In 32-bit installations, most of the ODBC registration information is maintained in the Windows registration database and not in the ODBC.INI file.

If the RegisterDatabase method fails for any reason, no changes are made to the ODBC.INI file, and an error occurs.

For more information about ODBC drivers such as SQL Server, see the Help file provided with the driver.

You are encouraged to use the Windows Control Panel ODBC setup icon to add new data sources, or to make changes to existing entries. However, if you choose to use the RegisterDatabase method, you are encouraged to set the silent option to True.

See Also

Database Object, OpenDatabase Method.

Example

This example registers a SQL Server data source named PtLudlow and then opens the database MySQLDb on that server.

Using the Windows ODBC control panel icon is the preferred way to create, modify, or delete data source names.

Dim dbsLudlow As Database
Dim strAttribs As String
' Build keywords string.
strAttribs = "Description=SQL Server on server PtLudlow" & _
    Chr$(13) & "OemToAnsi=No" & Chr$(13) & "Network=DBNMP3" & _
    Chr$(13) & "Address=\\PTLUDLOW\PIPE\SQL\QUERY" & Chr$(13) & _
    "Database=MySQLDb"
' Update ODBC.INI.
DBEngine.RegisterDatabase "PtLudlow", "SQL Server 32", True, strAttribs
' Open the database.
Set dbsLudlow = DBEngine.Workspaces(0).OpenDatabase("PtLudlow", _
    False, False, "ODBC;")


Relation Object

Description

A Relation object represents a relationship between fields in tables or queries.

Remarks

You can use the Relation object to create new relationships and examine existing relationships in your database. By setting the Attributes property, you can also use the Microsoft Jet database engine to enforce referential integrity.

Any changes you make to the database that violate the relationships established for the database result in a trappable error. If you request cascade update or cascade delete operations, the Jet database engine also modifies the primary or foreign key tables to enforce the relationships you establish.

An example of a typical relationship can be found between the NameAddress table and the ValidStateCodes table. The State field of the NameAddress table is the primary key, and the State field of the ValidStateCodes table is the foreign key. For a new record to be accepted in the NameAddress table, the Jet database engine searches the ValidStateCodes table for a match on the State field of the NameAddress table. If no match is found, the Jet database engine doesn't accept the new record, and a trappable error occurs.

Using a Relation object and its properties, you can:

  • Specify an enforced relationship between fields in base tables (but not a relationship that involves a query or an attached table).
  • Establish unenforced relationships between any type of table or query— native or attached.
  • Use the Name property to refer to the relationship between the fields in the referenced primary table and the referencing foreign table.
  • Use the Attributes property to determine whether the relationship between fields in the table is one-to-one or one-to-many and how to enforce referential integrity.
  • Use the Attributes property to determine whether the Jet database engine can perform cascade update and cascade delete operations on primary and foreign tables.
  • Use the Attributes property to determine whether the relationship between fields in the table is left join or right join.
  • The Name property settings of all Field objects in the Fields collection of a Relation object represent the names of the fields in the primary key of the referenced table. The ForeignName property settings of the Field objects represent the names of the fields in the foreign key of the referencing table.
  • When you enforce referential integrity, a unique index must already exist for the key field of the referenced table. The Jet database engine automatically creates an index with the Foreign property set to act as the foreign key in the referencing table.
 To create a new Relation object, use the CreateRelation method.

Properties

Attributes Property, ForeignTable Property, Name Property, Table Property.

Methods

CreateField Method.

See Also

CreateRelation Method; Foreign Property; Appendix, "Data Access Object Hierarchy."

Example

This example creates a one-to-many relationship between single fields in two tables. Because referential integrity is enforced for the relationship, an index is created for the primary table.

Function EnumerateRelation () As Integer
    Dim dbsExample As Database
    Dim tdfReferenced As TableDef, tdfReferencing As TableDef
    Dim fldPrimeKey As Field, idxUnique As Index, relEnforced As _
        Relation
    Dim I As Integer
    ' Get database.
    Set dbsExample = _
        DBEngine.Workspaces(0).OpenDatabase("Northwind.mdb")
    ' Create referenced table with primary key.
    Set tdfReferenced = dbsExample.CreateTableDef("Referenced")
    Set fldPrimeKey = tdfReferenced.CreateField("PrimaryKey", dbLong)
    tdfReferenced.Fields.Append fldPrimeKey
    ' Create unique index for enforced referential integrity.
    Set idxUnique = tdfReferenced.CreateIndex("UniqueIndex")
    idxUnique.Primary = True ' No Null values allowed.

    Set fldPrimeKey = tdfReferenced.CreateField("PrimaryKey")
    idxUnique.Fields.Append fldPrimeKey
    tdfReferenced.Indexes.Append idxUnique
    dbsExample.TableDefs.Append tdfReferenced

    ' Create referencing table with foreign key.
    Set tdfReferencing = dbsExample.CreateTableDef("Referencing")
    Set fldPrimeKey = tdfReferencing.CreateField("ForeignKey", dbLong)
    tdfReferencing.Fields.Append fldPrimeKey
    dbsExample.TableDefs.Append tdfReferencing
    ' Create one-to-many relationship and enforce referential integrity.
    Set relEnforced = dbsExample.CreateRelation("EnforcedOneToMany")
    relEnforced.Table = "Referenced"
    relEnforced.ForeignTable = "Referencing"
    ' Don't set either dbRelationUnique or dbRelationDontEnforce.
    relEnforced.Attributes = 0
    Set fldPrimeKey = relEnforced.CreateField("PrimaryKey")
    fldPrimeKey.ForeignName = "ForeignKey"
    relEnforced.Fields.Append fldPrimeKey
    dbsExample.Relations.Append relEnforced
    ' Enumerate relation and its fields.
    Debug.Print "Relation: "; relEnforced.Name
    Debug.Print "  Primary Table: "; relEnforced.Table
    Debug.Print "  Foreign Table: "; relEnforced.ForeignTable
    Debug.Print "  Attributes: "; relEnforced.Attributes
    Debug.Print "Fields in Relation: Primary, Foreign";
    For I = 0 To relEnforced.Fields.Count - 1
        Set fldPrimeKey = relEnforced.Fields(I)
        Debug.Print "  "; fldPrimeKey.Name;
        Debug.Print ", "; fldPrimeKey.ForeignName
    Next I
    Debug.Print
    dbsExample.Relations.Delete "EnforcedOneToMany"
    dbsExample.TableDefs.Delete "Referenced"
    dbsExample.TableDefs.Delete "Referencing"
    EnumerateRelation = True
End Function
Example (Microsoft Access)

The following example creates a new Relation object representing the relationship between an Employees table and an Orders table.

To test the following example in Microsoft Access, open the Northwind sample database and choose Relationships from the Tools menu. Delete the relationship between the Employees table and the Orders table, and close the Relationships window. Then, run the following function from a standard module, and view the Relationships window again to see the new relationship.

Sub NewRelation()
    Dim dbs As Database
    Dim fld As Field, rel As Relation

    ' Return Database variable that points to current database.
    Set dbs = CurrentDb

    ' Create new relationship and set its properties.
    Set rel = dbs.CreateRelation("EmployeesRelation", "Employees", _
        "Orders")
    ' Set Relation object attributes to enforce referential integrity.
    rel.Attributes = dbRelationDeleteCascade + dbRelationUpdateCascade
    ' Create field in Fields collection of Relation.
    Set fld = rel.CreateField("EmployeeID")
    ' Provide name of foreign key field.
    fld.ForeignName = "EmployeeID"
    ' Append field to Relation and Relation to database.
    rel.Fields.Append fld
    dbs.Relations.Append rel
End Sub


Relations Collection

Description

A Relations collection contains stored Relation objects of a Database object.

Remarks

You can use the Relation object to create new relationships and examine existing relationships in your database. You can add a Relation object to the Relations collection using the Append method so it will be saved when you close the Database object. To remove a Relation object from the collection, use the Delete method.

Properties

Count Property.

Methods

Append Method, Delete Method, Refresh Method.

See Also

Appendix, "Data Access Object Hierarchy."

Example

See the Relation object example.

Example (Microsoft Access)

See the Relation object example (Microsoft Access).


RepairDatabase Method

Applies To

DBEngine Object.

Description

Attempts to repair a corrupted database that accesses the Microsoft Jet database engine.

Syntax

DBEngine.RepairDatabase dbname

The dbname placeholder represents a string expression that is the path and filename for an existing Jet engine database file. If you omit the path, only the current directory is searched. If your system supports the uniform naming convention (UNC), you can also specify a network path, such as: "\\MYSERVER\MYSHARE\MYDIR\MYDB.mdb".

Remarks

You must close the database specified by dbname before you repair it. In a multiuser environment, other users can't have dbname open while you're repairing it. If dbname isn't closed or isn't available for exclusive use, an error occurs.

This method attempts to repair a database that was marked as possibly corrupt by an incomplete write operation. This can occur if an application using the Jet database engine is closed unexpectedly because of a power outage or computer hardware problem. The database won't be marked as possibly corrupt if you use the Close method or if you quit your application in a usual way.

The RepairDatabase method also attempts to validate all system tables and all indexes. Any data that can't be repaired is discarded. If the database can't be repaired, a trappable error occurs.

When you attempt to open or compact a corrupted database, a trappable error usually occurs. In some situations, however, a corrupted database may not be detected, and no error occurs. It's a good idea to provide your users with a way to use the RepairDatabase method in your application if their database behaves unpredictably.

Some types of databases can become corrupted if a user ends an application without closing Database or Recordset objects and the Jet database engine; Microsoft Windows or MS-DOS® doesn't have a chance to flush data caches. To avoid corrupt databases, establish procedures for closing applications and shutting down systems that ensure that all cached pages are saved to the database. In some cases, power supplies that can't be interrupted may be necessary to prevent accidental data loss during power fluctuations.

Tip

After repairing a database, it's also a good idea to compact it using the CompactDatabase method to defragment the file and to recover disk space.

See Also

Close Method, CompactDatabase Method, Database Object.

Example

This example attempts to repair a database named Northwind.mdb.

DBEngine.RepairDatabase "C:\Northwind.mdb"


Replicable Property

Applies To

Database Object, QueryDef Object, TableDef Object.

Description

Sets or returns a value that determines whether a database or object in a database can be replicated.

  • On a Database object, this property adds fields, tables, and properties to a database.
  • On a TableDef or QueryDef object, or table, query, form, report, macro, or module in a database, this property changes the object from local to replicable.
 Setting and Return Values

  • On a Database object, setting this property to the text string "T" makes the database replicable. Once the property is set to "T", it cannot be changed; setting the property to "F" (or any value other than "T") returns an error message.
  • On an object in a database, setting this property to the text string "T" makes the object (and subsequent changes to the object) available at all replicas in the replica set. You can also set this property in the object's property sheet in Microsoft Access.
 Remarks

When you create a new table, query, form, report, macro, or module at a replica, the object is considered "local" and is stored only at that replica. If you want users at other replicas to be able to use the object, you must change it from local to replicable. Either create the object at, or import it into, the Design Master and then set the Replicable property to "T".

The object on which you are setting the Replicable property might have already inherited that property from another object. However, the value set by the other object has no affect on the behavior of the object you want to make replicable. You must directly set the property for each object.

See Also

KeepLocal Property, MakeReplica Method.


ReplicaID Property

Applies To

Database Object.

Description

Returns a 16-byte, OLE 2 GUID that provides each database replica with a unique identification.

Setting and Return Values

This property is read-only and the value is created by the Microsoft Jet database engine.

Remarks

In addition to providing a unique identifier for each database replica, the ReplicaID property is used to identify the Design Master for the replica set. The ReplicaID property of the Design Master is stored in the MSysReplicas system table. Setting the DesignMasterID property gives a specific replica in the replica set design-master status. The DesignMasterID property can be set only if you are at the current Design Master. Under extreme circumstances, for example, the loss of the original Design Master, you can set the value at another replica. However, setting this value at a replica, when there is already another Design Master, might partition your replica set into two irreconcilable sets and prevent any further synchronization of data.

See Also

DesignMasterID Property.


Requery Method

Applies To

Dynaset-Type Recordset Object, Recordset Object, Snapshot-Type Recordset Object.

Description

Updates the data in a Recordset object by re-executing the query on which the object is based.

Syntax

object.Requery [NewQuerydef]

The Requery method syntax has the following parts.

Part | Description
object | The name of an existing table-type Recordset object that has a defined index as specified by the Recordset object's Index property.
NewQuerydef | A Querydef object, which is an optional parameter.

Remarks

Use this method to make sure that a Recordset contains the most recent data. This method re-populates the current Recordset by either using the currrent query parameters or the new ones supplied by the NewQuerydef argument.

  • If the original Querydef is supplied, then the Recordset is requeried using the parameters specified by the Querydef (for example, myquerydef.OpenRecordset()).
  • If a Querydef was not used to create the recordset, or if a different Querydef is specified than what was originally used to create the Recordset, then the Recordset is essentially re-created from scratch.
 When you use Requery, all changes made to the data in the underlying table by other users are displayed in the Recordset, and the first record in the Recordset becomes the current record.

You can't use the Requery method on dynaset- or snapshot-type Recordset objects whose Restartable property is set to False, nor can you use it on a table-type Recordset. However, if you supply the optional NewQueryDef argument, the Restartable property is ignored.

If both the BOF and EOF property settings of the Recordset object are True after you use the Requery method, the query didn't return any records and the Recordset will contain no data.

See Also

BOF, EOF Properties; QueryDef Object, Requery Method.

Example

This example determines the Restartable property setting of a dynaset-type Recordset and then uses the Requery method on the Recordset.

Dim dbsNorthwind As Database, rstChangeOften As Recordset
Set dbsNorthwind =  DBEngine.Workspaces(0).OpenDatabase("Northwind.mdb")
Set rstChangeOften = dbsNorthwind.OpenRecordset _
    ("Table That Changes Often", dbOpenDynaset)
If rstChangeOften.Restartable = True Then
    rstChangeOften.Requery
End If
dbsNorthwind.Close
Example (Microsoft Access)

The following example checks the Restartable property setting of a dynaset-type Recordset object and then uses the Requery method on the Recordset object.

Sub RequerySource()
    Dim dbs As Database, rstOrders As Recordset

    ' Return Database variable that points to current database.
    Set dbs = CurrentDb
    Set rstOrders = dbs.OpenRecordset("Orders", dbOpenDynaset)
    If rstOrders.Restartable = True Then
        rstOrders.Requery
    Else
        rstOrders.Close
    End If
End Sub


Required Property

Applies To

Field Object, Index Object.

Description

Sets or returns a value that indicates whether a Field object requires a non-Null value or whether all the fields in an Index object must be filled in. For an object not yet appended to a collection, this property is read/write. For an Index object, this property setting is read-only for objects appended to Indexes collections in Recordset and TableDef objects.

Settings and Return Values

The setting or return value is a Boolean expression indicating whether an object requires a non-Null value. True indicates that a Null value is not allowed.

Remarks

For a Field object, use of the Required property depends on its parent object, as shown in the following table.

Parent Object | Usage
Index | Not supported
QueryDef | Read-only
Recordset | Read-only
Relation | Not supported
TableDef | Read/write

For a Field object, you can use the Required property along with the AllowZeroLength, ValidateOnSet, or ValidationRule property to determine the validity of the Value property setting for that Field object. If the Required property is set to False (0), the field can contain Null values as well as values that meet the conditions specified by the AllowZeroLength and ValidationRule property settings.

Tip

When you can set this property for either an Index object or a Field object, set it for the Field object. The validity of the property setting for a Field object is checked before that of an Index object.

See Also

AllowZeroLength Property, QueryDef Object, Required Property, ValidateOnSet Property, ValidationRule Property, ValidationText Property, Value Property.

Example (Microsoft Access)

The following example creates a new Index object on an Employees table and sets the Required property for the index. The new index consists of two fields, LastName and FirstName.

Sub NewIndex()
    Dim dbs As Database, tdf As TableDef, idx As Index
    Dim fldLastName As Field, fldFirstName As Field, rst As Recordset

    ' Return Database variable that points to current database.
    Set dbs = CurrentDb
    Set tdf = dbs.TableDefs!Employees
    ' Return Index object that points to new index.
    Set idx = tdf.CreateIndex("FullName")
    ' Create and append index fields.
    Set fldLastName = idx.CreateField("LastName", dbText)
    Set fldFirstName = idx.CreateField("FirstName", dbText)
    idx.Fields.Append fldLastName
    idx.Fields.Append fldFirstName
    ' Ensure value is entered for each field in the index.
    idx.Required = True
    ' Append Index object.
    tdf.Indexes.Append idx
End Sub


Restartable Property

Applies To

Dynaset-Type Recordset Object, Recordset Object, Snapshot-Type Recordset Object, Table-Type Recordset Object.

Description

Returns a value that indicates whether a Recordset object supports the Requery method, which re-executes the query on which the Recordset object is based.

Return Values

The possible return values are:

Value | Description
True | The Recordset object supports the Requery method.
False | The Recordset object doesn't support the Requery method. Table-type Recordset objects always return False (0).

Remarks

Check the Restartable property before using the Requery method on a Recordset object. If the object's Restartable property is set to False, use the OpenRecordset method on the underlying QueryDef object to re-execute the query.

You can use the Requery method to update a Recordset object's underlying parameter query after the parameter values have been changed.

See Also

OpenRecordset Method, QueryDef Object, Requery Method.

Example

See the Requery property example.

Example (Microsoft Access)

See the Requery property example (Microsoft Access).


ReturnsRecords Property

Applies To

QueryDef Object.

Description

Sets or returns a value that indicates whether an SQL pass through query to an external database returns records.

Settings and Return Values

A Boolean expression that indicates whether records are returned. The data type is Boolean. True (-1) (the default) indicates that a pass-through query returns records.

Remarks

Not all SQL pass-through queries to external databases return records. For example, an SQL UPDATE statement updates records without returning records, while an SQL SELECT statement does return records. If the query returns records, set the ReturnsRecords property to True; if the query doesn't return records, set the ReturnsRecords property to False (0).

Note

The Connect property must be set before the ReturnsRecords property is set.

See Also

Connect Property, QueryTimeout Property, SQL Property.

Example

The following example creates an SQL pass-through query that returns records from an external database.

Dim dbsNorthwind As Database, qdfPassThrough As QueryDef
Set dbsNorthwind =  DBEngine.Workspaces(0).OpenDatabase("Northwind.mdb")
Set qdfPassThrough = dbsNorthwind.CreateQueryDef("October " & _
    "Orders","SELECT * From Orders WHERE ShipCity = 'London'")
dbsNorthwind.Connect = "ODBC; DSN=MySQLDBDSN;  " _
    & " UID=Chrissy;PWD=FourOh;"
qdfPassThrough.ReturnsRecords = True
Example (Microsoft Access)

The following example creates an SQL pass-through query that returns records from an external database.

Sub CreatePassThrough()
    Dim dbs As Database, qdfPassThrough As QueryDef

    ' Return Database variable that points to current database.
    Set dbs = CurrentDb
    Set qdfPassThrough = dbs.CreateQueryDef("OctoberOrders", _
        "SELECT * From Orders WHERE ShipCity = 'London'")
    dbs.Connect = "ODBC; DSN=MySQLDBDSN;  " _
        & " UID=Chrissy;PWD=FourOh;"
    qdfPassThrough.ReturnsRecords = True
End Sub


Rollback Method

See BeginTrans, CommitTrans, Rollback Methods.


Seek Method

Applies To

Recordset Object, Table-Type Recordset Object.

Description

Locates the record in an indexed table-type Recordset object that satisfies the specified criteria for the current index and makes that record the current record.

Syntax

table.Seek comparison, key1, key2...

The Seek method syntax has the following parts.

Part | Description
table | The name of an existing table-type Recordset object that has a defined index as specified by the Recordset object's Index property.
comparison | One of the following string expressions: <, <=, =, >=, or >.
key1, key2... | One or more values corresponding to fields in the Recordset object's current index, as specified by its Index property setting.

Remarks

You must set the current index with the Index property before you use Seek. If the index identifies a nonunique key field, Seek locates the first record that satisfies the criteria.

Caution

If you edit the current record, be sure you save the changes using the Update method before you move to another record. If you move to another record without using Update, your changes are lost without warning.

The Seek method searches through the specified key fields and locates the first record that satisfies the criteria specified by comparison and key1. Once found, it makes that record current and the NoMatch property is set to False. If the Seek method fails to locate a match, the NoMatch property is set to True, and the current record is undefined.

If comparison is equal (=), greater than or equal (>=), or greater than (>), Seek starts at the beginning of the index. If comparison is greater than (<) or greater than or equal (<=), Seek starts at the end of the index and searches backward unless there are duplicate index entries at the end. In this case, Seek starts at an arbitrary entry among the duplicate index entries at the end of the index.

You must specify values for all fields defined in the index. If you use Seek with a multi-column index, and you don't specify a comparison value for every field in the index, then you cannot use the equal (=) operator in the comparison. That's because some of the criteria fields (key2, key3, and so on) will default to NULL, which will probably not match. Therefore, the equal operator will work correctly only if you have a record which is all NULL except the key you're looking for. It's recommended that you use the greater than or equal operator instead.

The key1 argument must be of the same field data type as the corresponding field in the current index. For example, if the current index refers to a number field (such as Employee ID), key1 must be numeric. Similarly, if the current index refers to a Text field (such as Last Name), key1 must be a string.

There doesn't have to be a current record when you use Seek.

You can use the Indexes collection to enumerate the existing indexes.

Notes

  • Always check the value of the NoMatch property setting to determine whether the Seek method has succeeded. If it fails, NoMatch is set to True and the current record is undefined.
  • To locate a record in a dynaset- or snapshot-type Recordset that satisfies a specific condition, use the Find methods. To include all records, not just those that satisfy a specific condition, use the Move methods to move from record to record.
 You can't use the Seek method on an attached table of any type because attached tables must be opened as dynaset- or snapshot-type Recordset objects, which don't support the Seek method. However, if you use the OpenDatabase method to directly open an installable ISAM database, you can use Seek on tables in that database.

See Also

AbsolutePosition Property; BOF, EOF Properties; FindFirst, FindLast, FindNext, FindPrevious Methods; Index Object; Index Property; Move Method; MoveFirst, MoveLast, MoveNext, MovePrevious Methods; NoMatch Property; OpenDatabase Method.

Example

This example uses Seek to locate the first record in the Publishers table where the PubID field is 3, using the existing primary key index.

Dim dbsBiblio As Database, rstPublishers As Recordset
' Open a database.
Set dbsBiblio = DBEngine.Workspaces(0).OpenDatabase("Biblio.mdb")
' Open a table.
Set rstPublishers = dbsBiblio.OpenRecordset("Publishers")
rstPublishers.Index = "PrimaryKey"    ' Define current index.
rstPublishers.Seek "=", 3    ' Seek record.

If rstPublishers.NoMatch Then...
This example uses the OpenDatabase method to directly open an installable ISAM database and then uses Seek to locate a record in a table in that database.

Dim dbsFoxData as Database, rstParts as Recordset
Dim varSaveHere as Variant
Set dbsFoxData = OpenDatabase("C:\FoxData", False, False,"Fox 2.5")
Set rstParts = dbsFoxData.OpenRecordset("PARTS.dbf", dbOpenTable)
' Choose record order and Seek index.
rstParts.Index = "PartNameIndex"
varSaveHere = rstParts.BookMark    ' Save current location.
' Search for first instance of a chosen part.
rstParts.Seek "=", "Framis Lever"
If rstParts.NoMatch then     ' Test for success.
    rstParts.BookMark = varSaveHere    ' Seek not successful.
    ...
Else    ' Seek worked; use current record.
    Debug.Print rstParts!PartName
End If
Example (Microsoft Access)

The following example creates a new Index object on an Employees table. The new index consists of two fields, LastName and FirstName. The procedure then uses the Seek method to find a specified record.

Sub NewIndex()
    Dim dbs As Database, tdf As TableDef, idx As Index
    Dim fldLastName As Field, fldFirstName As Field, rst As Recordset

    ' Return Database variable pointing to current database.
    Set dbs = CurrentDb
    Set tdf = dbs.TableDefs!Employees
    ' Return Index object that points to new index.
    Set idx = tdf.CreateIndex("FullName")
    ' Create and append index fields.
    Set fldLastName = idx.CreateField("LastName", dbText)
    Set fldFirstName = idx.CreateField("FirstName", dbText)
    idx.Fields.Append fldLastName
    idx.Fields.Append fldFirstName
    ' Append Index object.
    tdf.Indexes.Append idx
    ' Open table-type Recordset object.
    Set rst = dbs.OpenRecordset("Employees")
    ' Set current index to new index.
    rst.Index = idx.Name
    ' Specify record to find.
    rst.Seek "=", "Fuller", "Andrew"
    If rst.NoMatch Then
        Debug.Print "Seek unsuccessful!"
    Else

        Debug.Print "Seek successful."
    End If
End Sub
Example (Microsoft Excel)

This example opens PRODUCT.DBF (a dBASE IV table located in the \Program Files\Common Files\Microsoft Shared\MSquery folder), locates a record, and then copies the values into cells B2:C2 on Sheet1. (On Windows NT™, PRODUCT.DBF is located in the WINDOWS\MSAPPS\MSQUERY folder.)

Const sourceDir = "C:\Program Files\Common Files\Microsoft Shared\" _
    & "MSquery"
Dim db As Database, rs As Recordset
Sheets("Sheet1").Activate
Set db = OpenDatabase(sourceDir, False, False, "dBASE IV")
Set rs = db.OpenRecordset("PRODUCT.DBF", dbOpenTable)
rs.Index = "PRODUCT"
rs.Seek "=", "1"
If rs.NoMatch Then
    MsgBox "Couldn't find any records"
Else
    ActiveSheet.Cells(2, 2) = rs.Fields("CATEGORY").Value
    ActiveSheet.Cells(3, 2) = rs.Fields("PROD_NAME").Value
End If
rs.Close
db.Close


Size Property

Applies To

Field Object.

Description

Returns a value that indicates the maximum size, in bytes, of a Field object. For Text fields, you can also use it to set the maximum size of data that the Field object can hold. For an object not yet appended to the Fields collection, this property is read/write.

Settings and Return Values

The setting or return value indicates the maximum size of a Field object. The data type is Long. The setting depends on the Type property setting of the Field object and can be one of these integer values.

Type | Size | Description
dbBoolean | 1 | Boolean
dbByte | 1 | Byte

Type | Size | Description
dbInteger | 2 | Integer
dbLong | 4 | Long
dbCurrency | 8 | Currency
dbSingle | 4 | Single
dbDouble | 8 | Double
dbDate | 8 | Date/Time
dbText | 1–255 | Text
dbLongBinary | 0 | Long Binary (OLE Object)
dbMemo | 0 | Memo
dbGUID | 16 | GUID

Remarks

These constants are listed in the Data Access (DAO) object library in the Object Browser.

Use of the Size property depends on the object that contains the Fields collection that the Field object is appended to, as shown in the following table.

Object appended to | Usage
Index | Not supported
QueryDef | Read-only
Recordset | Read-only
Relation | Not supported
TableDef | Read-only

When you create a Field object with a data type other than Text, the Type property setting automatically determines the Size property setting, and you don't need to set the Size property. For a Field object with the Text data type, however, Size can be set to any integer up to the maximum text size (for Microsoft Jet databases that maximum is 255). If you do not set the size, the field will be as large as the database allows.

For OLE Object and Memo Field objects, Size is always set to 0. Use the FieldSize method of the Field object to determine the size of the data in a specific record. The maximum size of an OLE Object or Memo field is limited only by your system resources or the maximum size that the database allows.

See Also

Attributes Property, Index Object, QueryDef Object, Type Property.

Specifics (Microsoft Access)

The Size property is equivalent to the FieldSize property in table Design view. You can't set the FieldSize property in Visual Basic; you must use the Size property instead.

In Microsoft Access, the Memo data type field can contain up to 1.2 gigabytes of information. However, Microsoft Access only displays the first 32K of data in a control on a form or report.

Example

This example creates a new Field object with a Text field type, sets its Name property to Fax Phone and its Size property to 20, and appends the new object to the Fields collection of the Employees table in the TableDefs collection of the database.

Function SizeType() As Integer
    Dim dbsNorthwind As Database
    Dim fldFaxPhone As Field, tdfEmployees As TableDef
    ' Open database.
    Set dbsNorthwind = _
        DBEngine.Workspaces(0).OpenDatabase("Northwind.mdb")
    ' Get existing table reference.
    Set tdfEmployees = dbsNorthwind.TableDefs("Employees")
    ' Create Field object.
    Set fldFaxPhone = tdfEmployees.CreateField("Fax Phone")
    ' Set field properties.
    fldFaxPhone.Type = dbText
    fldFaxPhone.Size = 20
    ' Append fldFaxPhone to Fields collection.
    tdfEmployees.Fields.Append fldFaxPhone
    SizeType = True
End Function
You can also use the CreateField method if you provide name, type, and size as arguments.

Set fldFaxPhone = tdfEmployees.CreateField("Fax Phone", dbText, 20)
Example (Microsoft Access)

The following example creates a new Field object and sets its Size and Type properties. The procedure then appends the new object to the Fields collection of the Employees table in the TableDefs collection of the database.

Sub NewField()
    Dim dbs As Database, tdf As TableDef
    Dim fld As Field

    ' Return Database object that points to current database.
    Set dbs = CurrentDb
    ' Return TableDef variable pointing to Employees table.
    Set tdf = dbs.TableDefs!Employees
    ' Create Field object.
    Set fld = tdf.CreateField("DaysOfVacation")
    ' Set field properties.
    fld.Type = dbText
    fld.Size = 20

    ' Append fld to Fields collection.
    tdf.Fields.Append fld
End Sub
You can also use the CreateField method to set the Name, Type, and Size properties if you provide name, type, and size as arguments.

Set fld = tdfEmployees.CreateField("DaysOfVacation", dbText, 20)
Example (Microsoft Excel)

This example copies onto Sheet1 all fields of the Double type from ORDDTAIL.DBF, a dBASE IV table located in the C:\Program Files\Common Files\Microsoft Shared\MSquery folder. (On Windows NT, ORDDTAIL.DBF is located in the \WINDOWS\MSAPPS\MSQUERY folder.)

Const sourceDir = "C:\Program Files\Common Files\Microsoft Shared\" _
    & "MSquery"
Dim db As Database, recordsToCopy As Recordset, tDef As Recordset
Dim fieldsToStore(1000), fileName As String
fileName = "ORDDTAIL.DBF"
Set db = Workspaces(0).OpenDatabase(sourceDir, _
    False, False, "dBASE IV")
Set tDef = db.OpenRecordset(fileName)
n = 0
Sheets("Sheet1").Activate
For i = 0 To tDef.Fields.Count - 1
    If tDef.Fields(i).Type = dbDouble Then
        fieldsToStore(n) = tDef.fields(i).Name
        n = n + 1
    End If
Next
If fieldsToStore(0) = "" Then
    MsgBox "There are no number fields in this table."
    Exit Sub
End If
For i = 0 To n - 1
    records = "SELECT " & "[" & fieldsToStore(i) & "]" _
        & " from " & db.Recordsets(fileName).Name & ";"
    Set recordsToCopy = db.OpenRecordset(records)
    With ActiveSheet.Cells(1, i + 1)
        .CopyFromRecordset recordsToCopy
        .ColumnWidth = recordsToCopy.fields(0).Size
    End With
Next
recordsToCopy.Close
tDef.Close
db.Close


Snapshot-Type Recordset Object

Description

A snapshot-type Recordset object is a static set of records that you can use to examine data in an underlying table or tables. A snapshot-type Recordset object can contain fields from one or more tables in a database but can't be updated.

Remarks

When you create a snapshot-type Recordset object, data values for all fields (except Memo and OLE Object field data types in .mdb files) are brought into memory. Once loaded, changes made to base table data aren't reflected in the snapshot-type Recordset object data. To reload the snapshot-type Recordset object with current data, use the Requery method, or re-execute the OpenRecordset method.

The order of snapshot-type Recordset object data doesn't necessarily follow any specific sequence. To order your data, use an SQL statement with an ORDER BY clause to create the Recordset object. You can also use this technique to filter the records so that only certain records are added to the Recordset object. For example, the following code selects only titles whose name contains the string "VBSQL" and sorts the resulting records by ISBN:

Dim dbsBiblio As Database, rstTitles As Recordset
Dim strSelect As String
Set dbsBiblio = Workspaces(0).OpenDatabase("Biblio.mdb")
strSelect = "SELECT * FROM Titles WHERE Title like '*VBSQL*' " & _
    "ORDER BY ISBN;"
Set rstTitles = dbsBiblio.OpenRecordset(strSelect,dbOpenSnapshot)
Using this technique instead of using the Filter or Sort properties or testing each record individually generally results in faster access to your data.

To create a snapshot-type Recordset object, use the OpenRecordset method on an open database, on another dynaset- or snapshot-type Recordset object, or on a QueryDef object.

Snapshot-type Recordset objects are generally faster to create and access than dynaset-type Recordset objects because their records are either in memory or stored in TEMP disk space, and the Microsoft Jet database engine doesn't need to lock pages or handle multiuser issues. However, snapshot-type Recordset objects use more resources than dynaset-type Recordset objects because the entire record is downloaded to local memory.

Properties

AbsolutePosition Property; BOF, EOF Properties; Bookmark Property; Bookmarkable Property; Filter Property; Name Property; NoMatch Property; PercentPosition Property; RecordCount Property; Restartable Property; Sort Property; Transactions Property; Type Property; Updatable Property; ValidationRule Property; ValidationText Property.

Methods

Clone Method; Close Method; CopyQueryDef Method; FindFirst, FindLast, FindNext, FindPrevious Methods; GetRows Method; Move Method; MoveFirst, MoveLast, MoveNext, MovePrevious Methods; OpenRecordset Method; Requery Method.

See Also

OpenRecordset Method, Recordset Object; Appendix, "Data Access Object Hierarchy."

Example

This example creates a new snapshot-type Recordset object and opens it, appending it to the Recordsets collection in the default database. It then finds a record and prints it.

Function ShowVBSQL () As Integer
    Dim dbsPublish As Database, rstTitles As Recordset
    Dim I As Integer, J As Integer
    Set dbsPublish = DBEngine.Workspaces(0).OpenDatabase("Biblio.mdb")
    Set rstTitles = dbsPublish.OpenRecordset("Titles", dbOpenSnapshot)
    If rstTitles.RecordCount > 0 Then
        rstTitles.FindFirst "Title Like '*VBSQL*'"  ' Any title on VBSQL
            Do until rstTitles.NoMatch = True
                Debug.Print rstTitles!Title
                rstTitles.FindNext "Title Like '*VBSQL*'"
            Loop
    Else
        Debug.Print "No such title"
    End If
    dbsPublish.Close
    ShowVBSQL = True
End Function
Example (Microsoft Access)

The following example creates a snapshot-type Recordset object from an SQL statement, then prints the value of the Updatable property for the Recordset object. Since snapshot-type Recordset objects are never updatable, the value of this property will always be False (0).

Sub LongTermEmployees()
    Dim dbs As Database, qdf As QueryDef, rst As Recordset
    Dim strSQL As String

    ' Return Database object pointing to current database.
    Set dbs = CurrentDb
    strSQL = "SELECT * FROM Employees WHERE HireDate <= #1-1-95#;"
    Set rst = dbs.OpenRecordset(strSQL, dbOpenSnapshot)
    Debug.Print rst.Updatable
End Sub


Sort Property

Applies To

Dynaset-Type Recordset Object, Recordset Object, Snapshot-Type Recordset Object.

Description

Sets or returns the sort order for records in a Recordset object.

Settings and Return Values

The setting or return value is a string expression that contains the ORDER BY clause of an SQL statement without the reserved words ORDER BY. (Data type is String.)

Remarks

You can use the Sort property with dynaset- and snapshot-type Recordset objects.

When you set this property for an object, sorting occurs when a subsequent Recordset object is created from that object. The Sort property setting overrides any sort order specified for a QueryDef object.

The default sort order is ascending (A to Z or 0 to 100). The following examples show how you can set the sort order to ascending or descending (Z to A or 100 to 0):

rstOrders.Sort = "ShipCountry"    ' Defaults to ascending.
rstOrders.Sort = "ShipCountry Asc"    ' Ascending.
rstOrders.Sort = "ShipCountry Desc"    ' Descending.
The Sort property doesn't apply to table-type Recordset objects. To sort a table-type Recordset object, use the Index property.

Tip

In many cases, it's faster to open a new Recordset object using an SQL statement that includes the sorting criteria.

See Also

Filter Property, Index Property, QueryDef Object, SQL Property.

Example

This example uses the Sort property to set the sort order of a dynaset-type Recordset based on an Orders table. The records in rstSorted will be in ascending Ship Country order.

Dim dbsNorthwind As Database
Dim rstOrders As Recordset, rstSorted As Recordset
Set dbsNorthwind =  DBEngine.Workspaces(0).OpenDatabase("Northwind.mdb")
Set rstOrders = dbsNorthwind.OpenRecordset("Orders", dbOpenDynaset)
rstOrders.Sort = "ShipCountry"    ' Set sort order.
Set rstSorted = rstOrders.OpenRecordset()    ' Create second dynaset.

Tip

In some situations, it may be more efficient to create the second Recordset object with the conditions you want in one step. As a general rule, when you know the data you want to select, it's usually more efficient to create a Recordset with an SQL statement. This example shows how you can create just one Recordset and obtain the same results as in the preceding example.

Dim dbsNorthwind As Database, rstOrders As Recordset
Dim strSelect As String
Set dbsNorthwind =  DBEngine.Workspaces(0).OpenDatabase("Northwind.mdb")
strSelect = "SELECT * FROM Orders ORDER BY ShipCountry;"
Set rstOrders = dbsNorthwind.OpenRecordset(strSelect)

Example (Microsoft Access)

The following example uses the Sort property to set the sort order of a dynaset-type Recordset object based on an Orders table. The records in the rstSorted recordset variable will be ordered alphabetically by ship country.

Note that you first create a dynaset-type Recordset object and set its Sort property, then open a second dynaset-type Recordset object based on the first. Setting the Sort property of the first Recordset object doesn't actually affect the order of the records that it contains, so you need to create a second Recordset object in order to see the effects of the sort.

Sub SortByCountry()
    Dim dbs As Database
    Dim rstOrders As Recordset, rstSorted As Recordset

    ' Return Database variable that points to current database.
    Set dbs = CurrentDb
    ' Create dynaset-type Recordset object on Orders table.
    Set rstOrders = dbs.OpenRecordset("Orders", dbOpenDynaset)
    ' Set sort order.
    rstOrders.Sort = "ShipCountry"
    ' Create second dynaset-type Recordset object.
    Set rstSorted = rstOrders.OpenRecordset()
End Sub

Tip

In most situations, it is more efficient to create the second Recordset object with the desired conditions in one step. As a general rule, when you know the data you want to select, it's usually more efficient to create a Recordset object with an SQL statement. The following example shows how you can create just one Recordset object and obtain the same results as in the preceding example.

Dim dbs As Database, rstOrders As Recordset
Dim strSelect As String
Set dbs = CurrentDb
strSelect = "SELECT * FROM Orders ORDER BY [ShipCountry];"
Set rstOrders = dbs.OpenRecordset(strSelect)

Example (Microsoft Excel)

This example creates a new recordset from the Supplier recordset in the NWINDEX.MDB database, and then it copies the new recordset onto Sheet1. The new recordset is sorted on the COUNTRY field, in ascending order.

To create the NWINDEX.MDB database, run the Microsoft Excel example for the CreateDatabase method.

Dim db As Database, rs As Recordset, sortedSet As Recordset
Set db = Workspaces(0).OpenDatabase(Application.Path & "\NWINDEX.MDB")
Set rs = db.OpenRecordset("Supplier", dbOpenDynaset)
rs.Sort = "[COUNTRY]"
Set sortedSet = rs.OpenRecordset()
Sheets("Sheet1").Activate
ActiveCell.CopyFromRecordset sortedSet
sortedSet.Close
rs.Close
db.Close


Source Property

Applies To

Error Object.

Description

Returns the name of the object or application that originally generated the error.

Return Values

The return value is a string expression representing the object or application that generated the error.

Remarks

The Source property specifies a string expression representing the object that originally generated the error; the expression is usually the object's class name or programmatic ID. Use the Source property to provide your users with information when your code is unable to handle an error generated in an accessed object. For example, if you access Microsoft Excel and it generates a Division by zero error, Microsoft Excel sets Error.Number to its error code for that error and sets the Source property to Excel.Application. Note that if the error is generated in another object called by Microsoft Excel, Microsoft Excel intercepts the error and sets Error.Number to its own code for Division by zero. However, it leaves the other Error object properties (including the Source property) as set by the object that generated the error. The Source property always contains the name of the object that originally generated the error — your code can try to handle the error according to the error documentation of the object you accessed. If your error handler fails, you can use the Error object information to describe the error to your user, using the Source property and the other Error properties to inform the user which object originally caused the error, its description of the error, and so forth.

Note

The On Error Resume Next construct may be preferable to On Error GoTo when dealing with errors generated during access to other objects. Checking the Error object property after each interaction with an object removes ambiguity about which object your code was accessing when the error occurred. Thus, you can be sure which object placed the error code in Error.Number, as well as which object originally generated the error (the one specified in Error.Source).

See Also

Description Property.

Specifics (Microsoft Access)

The data access Source property applies to the Error object and can be read only from Visual Basic.

Note

Don't confuse this property with the Microsoft Access Source property, which applies to a query and specifies the source connection string and source database for the query's input table or query.

Example

See the Decription property example.


SourceField, SourceTable Properties

Applies To

Field Object.

  • SourceField — returns a value that indicates the name of the field that is the original source of the data for a Field object.
  • SourceTable — returns a value that indicates the name of the table that is the original source of the data for a Field object.
 This property is not available at design time and is read-only at run time.

Return Values

The return value is a string expression specifying the name of the field or table that is the source of data. The data type is String.

Remarks

For a Field object, use of the SourceField and SourceTable properties depends on the object that contains the Fields collection that the Field object is appended to, as shown in the following table.

Object appended to | Usage
Index | Not supported
QueryDef | Read-only

Object appended to | Usage
Recordset | Read-only
Relation | Not supported
TableDef | Read-only

These properties indicate the original field and table names associated with a Field object. For example, you could use these properties to determine the original source of the data in a query field whose name is unrelated to the name of the field in the underlying table.

See Also

QueryDef Object, SourceTableName Property.

Example

This example creates a Recordset object using an SQL statement that creates aliases for fields in two different tables in the database. The example then prints the name of the field, the original table, and the original field.

Function SourceInfo () As Integer
    Dim dbsNorthwind As Database
    Dim rstEmployCustID As Recordset, fldEnum As Field
    Dim strSelect As String, intStep As Integer
    ' Open database.
    Set dbsNorthwind = _
        DBEngine.Workspaces(0).OpenDatabase("Northwind.mdb")
    ' Construct SQL statement.
    strSelect = "SELECT EmployeeID As EmpID, CustomerID As " & _
        "CustID FROM Employees, Customers;"
    Set rstEmployCustID = dbsNorthwind.OpenRecordset(strSelect)
    For intStep = 0 To rstEmployCustID.Fields.Count - 1
        Set fldEnum = rstEmployCustID.Fields(intStep)
        Debug.Print fldEnum.Name            ' Print field name.
        Debug.Print fldEnum.SourceTable    ' Print original table name.
        Debug.Print fldEnum.SourceField    ' Print original field name.
    Next intStep
    SourceInfo = True
End Function
Example (Microsoft Access)

The following example creates a Recordset object using an SQL statement that creates aliases for fields in two different tables in the database. The example then prints the name of the field, the original table, and the original field.

Sub SourceInfo()
    Dim dbs As Database, rst As Recordset, fld As Field
    Dim strSQL As String

    ' Return Database object that points to current database.
    Set dbs = CurrentDb
    ' Construct SQL statement.
    strSQL = "SELECT ProductID As ProductCode, " & _
        "CategoryName As TypeOfProduct FROM Products, Categories;"

    Set rst = dbs.OpenRecordset(strSQL)
    For Each fld in rst.Fields
        Debug.Print fld.Name        ' Print field name.
        Debug.Print fld.SourceTable    ' Print original table name.
        Debug.Print fld.SourceField    ' Print original field name.
        Debug.Print
    Next fld
End Sub


SourceTableName Property

Applies To

TableDef Object.

Description

Sets or returns a value that specifies the name of an attached table or the name of a base table. This property setting is read-only for a base table and read/write for an attached table or an object not appended to a collection.

Settings and Return Values

The setting or return value is a string expression that specifies a table name. For a base table, the setting is a zero-length string (""). The data type is String.

See Also

Connect Property; OpenDatabase Method; RefreshLink Method; SourceField, SourceTable Properties.

Example

See the Connect property example.

Example (Microsoft Access)

See the Connect property example (Microsoft Access).

Example (Microsoft Excel)

See the Connect property example (Microsoft Excel).


SQL Property

Applies To

QueryDef Object.

Description

Sets or returns the SQL statement that defines the query executed by a QueryDef object.

Settings and Return Values

The setting or return value is a string expression that contains an SQL statement. The data type is String.

Remarks

The SQL property contains the SQL statement that determines how records are selected, grouped, and ordered when you execute the query. You can use the query to select records to include in a dynaset- or snapshot-type Recordset object. You can also define bulk queries to modify data without returning records.

Using the ORDER BY or WHERE clause to sort or filter a Recordset object is more efficient than using the Sort and Filter properties.

The SQL syntax used in a query must conform to the SQL dialect as defined by the Microsoft Jet database engine unless you create an SQL pass through query.

Using a QueryDef object is the preferred way to perform SQL pass through operations on ODBC databases. By setting the QueryDef object's Connect property to an ODBC data source, you can specify non-Microsoft Jet database SQL in the query passed to the external server. For example, you can use TRANSACT SQL statements (with Microsoft SQL Server or Sybase SQL Server databases) in the value argument, which won't be processed by the Jet database engine.

If the SQL statement includes parameters for the query, you must set these before you execute the query. Until you reset the parameters, the same parameter values are applied each time you execute the query. Set the parameters by accessing the Parameters collection of the QueryDef object using the following code.

qdfOrders.Parameters("Order Date") = "10/11/94"   ' Set parameters.
qdfOrders.Parameters("Ship Date") = "11/4/94"
See Also

CreateQueryDef Method, Filter Property, OpenRecordset Method, Parameter Object, Recordset Object, Sort Property.

Example

This example creates a query based on an Orders table. The query selects all orders that have a Freight value greater than 10.

Dim dbsNorthwind As Database, qdfLargeFrt As QueryDef
Dim rstFromQuery As Recordset
Set dbsNorthwind =  DBEngine.Workspaces(0).OpenDatabase("Northwind.mdb")
Set qdfLargeFrt = dbsNorthwind.CreateQueryDef("Large Freight")
qdfLargeFrt.SQL = "SELECT * FROM Orders WHERE Freight > 10;"
Set rstFromQuery = qdfLargeFrt.OpenRecordset(dbOpenSnapshot)
Example (Microsoft Access)

The following example creates a parameter query based on an Orders table. The query selects all orders for which the order date falls between the dates entered by the user.

Sub RangeOfOrders()
    Dim dbs As Database, qdf As QueryDef, rst As Recordset

    ' Return Database variable that points to current database.
    Set dbs = CurrentDb
    Set qdf = dbs.CreateQueryDef("RangeOfOrders")
    ' Construct SQL statement including parameters.
    qdf.SQL = "PARAMETERS [Start] DATETIME, [End] DATETIME; " & _
        "SELECT * FROM Orders WHERE [OrderDate] BETWEEN " & _
        "[Start] AND [End];"
    qdf.Parameters("Start") = #1/1/95#
    qdf.Parameters("End") = #1/31/95#
    ' Create snapshot-type Recordset object from QueryDef object.
    Set rst = qdf.OpenRecordset(dbOpenSnapshot)
End Sub
Example (Microsoft Excel)

See the CreateQueryDef method example.


Synchronize Method

Applies To

Database Object.

Description

Synchronizes the current database object with the database in the .mdb file corresponding to pathname. Various types of exchanges can be performed as specified by the exchange argument. If no argument is provided, the exchange is bidirectional (import and export).

Syntax

database.Synchronize pathname [,exchange]

The Synchronize method syntax has the following parts.

Part | Description
database | An existing, replicable Database object variable that you want synchronized.
pathname | Path to the target database with which database will be synchronized. The trailing .mdb can be optionally omitted.
exchange | A constant indicating which direction to synchronize changes between the two databases. This can be one of the following Integer constants:
 | u dbRepExportChanges — Send changes from current database to pathname.
 | u dbRepImportChanges — Receive changes from pathname.
 | u dbRepImpExpChanges — (Default) Bidirectional exchange.

Remarks

This method causes an exchange of data and schema changes between the database and the .mdb identified by pathname. Schema changes are always done first. Both databases must be at the same schema level before data can be exchanged. For example, an exchange of type dbRepExportChanges might cause schema changes to be made at the current replica even though data changes flow only from the current replica to the designated target.

The replica identified in pathname must be part of the same replica set. If both replicas have the same ReplicaID property setting or have design-master status, the synchronization fails.

Note

The Synchronize method can be used only if your application has Microsoft Access with Briefcase Replication installed.


Table Property

Applies To

Relation Object.

Description

Sets or returns a value that specifies the name of a Relation object's primary table. This name is the Name property setting of a TableDef or QueryDef object. The Table property setting is read/write for a new Relation object not yet appended to a collection and read-only for an existing Relation object in a Relations collection.

Settings and Return Values

The setting or return value is a string expression that evaluates to the name of a table in the TableDefs collection. The data type is String.

Remarks

Use the Table property with the ForeignTable property to define a Relation object, which represents the relationship between fields in two tables or queries. Set the Table property to the Name property setting of the primary TableDef or QueryDef object, and set the ForeignTable property to the Name property setting of the foreign (referencing) TableDef or QueryDef object. The Attributes property determines the type of relationship between the two objects.

For example, if you had a list of valid part codes (in a field named PartNo) and stored in a ValidParts table, you could establish a relationship with an OrderItem table such that if a part code was entered into the OrderItem table, it must exist in the ValidParts table. If the part code didn't exist in the ValidParts table and you had not indicated No Enforcement in the Attributes property, a trappable error would occur.

In this case, the ValidParts table is an example of a foreign table, so the ForeignTable property of the Relation object would be set to ValidParts and the Table property of the Relation object would be set to the OrderItem table. The Name property and ForeignName property of the Field object would both be set to PartNo.

The following illustration shows how the ValidParts table is primary because it's referenced by the OrderItem table.

See Also

Attributes Property, Field Object, ForeignTable Property, Name Property, QueryDef Object.

Example

See the ForeignName property example.

Example (Microsoft Access)

See the ForeignName property example (Microsoft Access).


Table-Type Recordset Object

Description

A table-type Recordset object is a representation in code of a base table you can use to add, change, or delete records from a table. Only the current record is loaded into memory. A predefined index is used to determine the order of the records in the Recordset object.

Remarks

To create a table-type Recordset object, use the OpenRecordset method on an open Database object.

A table-type Recordset object can be created with a base table of a Microsoft Jet database, but not with an ODBC or attached table. The table-type Recordset object can be used with ISAM databases (like FoxPro, dBASE, Paradox, or Btrieve) when opened directly.

Unlike dynaset- or snapshot-type Recordset objects, the table-type Recordset object can't refer to more than one base table, and it can't be accessed using an SQL statement that filters or sorts the data. Generally, when you access a table-type Recordset object, you specify one of the predefined indexes for the table, which orders the data returned to your application. If the table doesn't have an index, the order of the data returned can't be guaranteed. If necessary, your application can create an index that returns records in a specific order. To choose a specific order for your table-type Recordset object, set the Index property to a valid index.

To maintain data integrity, table-type Recordset objects are locked during the Edit and Update methods operations so that only one user can update a particular record at a time. When the Microsoft Jet database engine locks a record, it locks the entire 2K page containing the record.

Two kinds of locking are used with non-ODBC tables — pessimistic and optimistic. ODBC-accessed tables always use optimistic locking. The locking conditions in effect during editing are determined by the LockEdits property.

Properties

BOF, EOF Properties; Bookmark Property; Bookmarkable Property; DateCreated, LastUpdated Properties; EditMode Property; Index Property; LastModified Property; LockEdits Property; Name Property; NoMatch Property; PercentPosition Property; RecordCount Property; Restartable Property; Transactions Property; Type Property; Updatable Property; ValidationRule Property; ValidationText Property.

Methods

CancelUpdate Method; Clone Method; Close Method; Delete Method; Edit Method; GetRows Method; Move Method; MoveFirst, MoveLast, MoveNext, MovePrevious Methods; OpenRecordset Method; Seek Method; Update Method.

See Also

Index Object; OpenRecordset Method; Recordset Object; Appendix, "Data Access Object Hierarchy."

Example

This example opens a table-type Recordset and selects an index for the Recordset. By setting an index, the Microsoft Jet database engine returns records in the order specified by the index. Without an index, table-type Recordset objects return records from the database table in no particular order.

    Dim dbsExample As Database
    Dim rstTitles as Recordset
    ' Get workspace and database.

    Set dbsExample = DBEngine.Workspaces(0).OpenDatabase("Biblio.mdb")
    Set rstTitles = dbsExample.OpenRecordset("Titles", dbOpenTable)
    rstTitles.Index = "MyIndex"
    ...
    ...
    ...
Example (Microsoft Access)

The following example opens a table-type Recordset object, then prints the number of records in the Recordset object.

Sub CountEmployees()
    Dim dbs As Database, tdf As TableDef, rst As Recordset

    ' Return Database object pointing to current database.
    Set dbs = CurrentDb
    Set rst = dbs.OpenRecordset("Employees", dbOpenTable)
    rst.MoveLast
    Debug.Print rst.RecordCount
End Sub


TableDef Object

Description

A TableDef object represents the stored definition of a base table or an attached table.

Remarks

You manipulate a table definition using a TableDef object and its methods and properties. For example, you can:

  • Examine the field and index structure of any local, attached, or external table in a database.
  • Read or write the Connect and SourceTableName property settings for attached tables, and use the RefreshLink method to update connections to attached tables.
  • Read (or write, if the Updatable property is set to True (-1)) the ValidationRule and ValidationText property settings to find (or specify) validation conditions.
  • Use the OpenRecordset method to create a table-, dynaset-, or snapshot-type Recordset object, based on the table definition.
 The default collection of a Database object is the TableDefs collection, and the default collection of a TableDef object is the Fields collection. You can simplify your code by using these defaults. For example, the following statements are identical in that they both print the number corresponding to the field data type of a Field object in a TableDef object:

Debug.Print dbsCurrent.TableDefs("Publishers").Fields("PubID").Type
Debug.Print dbsCurrent("Publishers")("PubID").Type
The Name property of a TableDef object isn't necessarily the same as the name of an object variable to which it's assigned.

For base tables, the RecordCount property contains the number of records in the specified database table. For attached tables, the RecordCount property setting is always -1.

You refer to a TableDef object that you create and append to a TableDefs collection by its Name property setting using this syntax:

TableDefs("name")

To create a new TableDef object, use the CreateTableDef method.

You can delete a Field object from a TableDefs collection if it doesn't have any indexes assigned to it, but its underlying data is lost.

Properties

Attributes Property; ConflictTable Property; Connect Property; DateCreated, LastUpdated Properties; KeepLocal Property; Name Property; RecordCount Property; Replicable Property; SourceTableName Property; Updatable Property; ValidationRule Property; ValidationText Property.

Methods

CreateField Method, CreateIndex Method, CreateProperty Method, OpenRecordset Method, RefreshLink Method.

See Also

CreateTableDef Method; Appendix, "Data Access Object Hierarchy."

Specifics (Microsoft Access)

In addition to the properties defined by the Microsoft Jet database engine, a TableDef object may also contain the following Microsoft Access application-defined properties.

DatasheetFontHeight | Description
DatasheetFontItalic | FrozenColumns
DatasheetFontName | RowHeight
DatasheetFontUnderline | ShowGrid
DatasheetFontWeight |

Example

This example creates a new TableDef object, adds a Field object to it, and appends the TableDef to the TableDefs collection in the current database. Then the example enumerates all the TableDef objects in the current database and all the properties of the new TableDef.

Function EnumerateTableDef () As Integer
    Dim dbsExample As Database
    Dim tdfEnum As TableDef
    Dim fldDate As Field
    Dim I As Integer
    Set dbsExample = _
        DBEngine.Workspaces(0).OpenDatabase("Northwind.mdb")
    Set tdfEnum = dbsExample.CreateTableDef("MyTable")
    Set fldDate = tdfEnum.CreateField("Date", dbDate)
    tdfEnum.Fields.Append fldDate
    dbsExample.TableDefs.Append tdfEnum
    ' Get database name.
    Debug.Print "Database Name: "; dbsExample.Name

    ' Enumerate all fields in tdfEnum.
    Debug.Print "TableDef: Name; Field: Name"
    For I = 0 To tdfEnum.Fields.Count - 1
        Debug.Print "  "; tdfEnum.Name;
        Debug.Print "; "; tdfEnum.Fields(I).Name
    Next I
    Debug.Print
    ' Enumerate all indexes in tdfEnum.
    Debug.Print "TableDef: Name; Index: Name"
    For I = 0 To tdfEnum.Indexes.Count - 1
        Debug.Print "  "; tdfEnum.Name;
        Debug.Print "; "; tdfEnum.Indexes(I).Name
    Next I
    Debug.Print
    ' Enumerate built-in properties of tdfEnum.
    Debug.Print "tdfEnum.Name: "; tdfEnum.Name
    Debug.Print "tdfEnum.Attributes: "; tdfEnum.Attributes
    Debug.Print "tdfEnum.Connect: "; tdfEnum.Connect
    Debug.Print "tdfEnum.DateCreated: "; tdfEnum.DateCreated
    Debug.Print "tdfEnum.LastUpdated: "; tdfEnum.LastUpdated
    Debug.Print "tdfEnum.RecordCount: "; tdfEnum.RecordCount
    Debug.Print "tdfEnum.SourceTableName: "; tdfEnum.SourceTableName
    Debug.Print "tdfEnum.Updatable: "; tdfEnum.Updatable
    Debug.Print "tdfEnum.ValidationRule: "; tdfEnum.ValidationRule
    Debug.Print "tdfEnum.ValidationText: "; tdfEnum.ValidationText
    EnumerateTableDef = True
End Function
Example (Microsoft Access)

The following example creates a new TableDef object, defines a field within it, and appends it to the TableDefs collection of the current database.

Sub NewTable()
    Dim dbs As Database, tdf As TableDef, fld As Field

    ' Return Database object pointing to current database.
    Set dbs = CurrentDb
    Set tdf = dbs.CreateTableDef("Contacts")
    Set fld = tdf.CreateField("ContactName", dbText, 30)
    tdf.Fields.Append fld
    dbs.TableDefs.Append tdf
End Sub


TableDefs Collection

Description

A TableDefs collection contains all stored TableDef objects in a database.

Remarks

You manipulate a table definition using a TableDef object and its methods and properties.

The default collection of a Database object is the TableDefs collection.

You refer to a TableDef object that you create and append to a TableDefs collection by its Name property setting using this syntax:

TableDefs("name")

Methods

Append Method, Delete Method, Refresh Method.

See Also

Appendix, "Data Access Object Hierarchy."

Specifics (Microsoft Access)

See the TableDef object specifics (Microsoft Access).

Example

See the TableDef object example.

Example (Microsoft Access)

See the TableDef object example (Microsoft Access).


Transactions Property

Applies To

Database Object, Dynaset-Type Recordset Object, Recordset Object, Snapshot-Type Recordset Object, Table-Type Recordset Object.

Description

Returns a value that indicates whether an object supports the recording of a series of changes that can later be rolled back (canceled) or committed (saved). True (-1) indicates that the object supports transactions. Snapshot-type Recordset objects always return False (0).

Remarks

You can use the Transactions property with dynaset- or snapshot-type Recordset objects.

If a dynaset or table is based on a Microsoft Jet database engine table, the Transactions property is True and you can use transactions. Other database engines may not support transactions. For example, you can't use transactions in a dynaset-type Recordset object based on a Paradox table.

Check the Transactions property before using the BeginTrans method on the Recordset object's Workspace object to make sure that transactions are supported. Using the BeginTrans, CommitTrans, or Rollback methods on a nonsupported object has no effect.

See Also

BeginTrans, CommitTrans, Rollback Methods.


Type Property

Applies To

Dynaset-Type Recordset Object, Field Object, Parameter Object, Property Object, QueryDef Object, Recordset Object, Snapshot-Type Recordset Object, Table-Type Recordset Object.

Description

Sets or returns a value that indicates the operational type or data type of an object. For a Field or Property object, this property is read/write until the object is appended to a collection or to another object, after which it's read-only. For a Parameter, QueryDef, or Recordset object, the property setting is read-only.

Settings and Return Values

The setting or return value is a constant that indicates an operational or data type. The data type is Integer.

For a Field, Parameter, or Property object, the possible settings and return values are:

Setting/Value | Description
dbBoolean | Boolean
dbByte | Byte
dbInteger | Integer
dbLong | Long
dbCurrency | Currency
dbSingle | Single
dbDouble | Double
dbDate | Date/Time
dbText | Text
dbLongBinary | Long Binary (OLE Object)
dbMemo | Memo
dbGUID | GUID

For a QueryDef object, the possible settings and return values are:

Setting/Values | Query type
dbQSelect | Select
dbQAction | Action
dbQCrosstab | Crosstab
dbQDelete | Delete
dbQUpdate | Update
dbQAppend | Append
dbQMakeTable | Make-table
dbQDDL | Data-definition
dbQSQLPassThrough | Pass-through
dbQSetOperation | Union
dbQSPTBulk | Used with dbQSQLPassThrough to specify a query that doesn't return records.

Note

To create an SQL pass through query, don't set the dbQSQLPassThrough constant. This is set automatically by the Microsoft Jet database engine when you create a QueryDef object and set the Connect property.

For a Recordset object, the possible settings and return values are:

Setting | Recordset type
dbOpenTable | Table
dbOpenDynaset | Dynaset
dbOpenSnapshot | Snapshot

Remarks

These constants are listed in the Data Access (DAO) object library in the Object Browser.

Depending on the object, the Type property indicates:

Object | Type indicates
Field, Parameter, Property | Object data type
QueryDef | Type of query
Recordset | Type of Recordset object

When you append a new Field, Parameter, or Property object to the collection of an Index, QueryDef, Recordset, or TableDef object, an error occurs if the underlying database doesn't support the data type specified for the new object.

Specifics (Microsoft Access)

In Microsoft Access, you can set the data type for a field in table Design view, and you can set the data type for a parameter in the Query Parameters dialog box. These actions are equivalent to setting the data access Type property for a Field object or a Parameter object from Visual Basic.

The following table lists the Type property constants and the corresponding Microsoft Access settings for field and parameter data types if you are setting them from table Design view or the Query Parameters dialog box.

When creating a table field with data type Number, set the FieldSize property to specify which of the six numeric data types the field will be. By default this property is set to Long Integer. The other settings are Byte, Integer, Single, Double, and ReplicationID.

Constant | Table field setting | Query parameter setting
dbBoolean | Yes/No | Yes/No
dbByte | Number (FieldSize = Byte) | Byte
dbCurrency | Currency | Currency
dbDate | Date/Time | Date/Time

Constant | Table field setting | Query parameter setting
dbDouble | Number (FieldSize = Double) | Double
dbGUID | Number or AutoNumber (FieldSize = ReplicationID) | Not supported
dbInteger | Number (FieldSize = Integer) | Integer
dbLong | Number (FieldSize = Long Integer) | Long Integer
 | AutoNumber (FieldSize = Long Integer) | Not supported
dbLongBinary | OLE Object | OLE Object
 | Not supported | Binary
dbMemo | Memo | Memo
dbSingle | Number (FieldSize = Single) | Single
dbText | Text | Text
Not supported | Not supported | Value

Note

The parameter data type Value doesn't correspond to a data type defined by the Microsoft Jet database engine. It corresponds to the SQL reserved word VALUE, which can be used to create a parameter query. In Microsoft Access or SQL queries, VALUE can be considered a valid synonym for the Visual Basic Variant data type.

Example

See the Size property example.

Example (Microsoft Access)

See the Size property example (Microsoft Access).

Example (Microsoft Excel)

See the Size property example (Microsoft Excel).


Unique Property

Applies To

Index Object.

Description

Sets or returns a value that indicates whether an Index object represents a unique (key) index for a table. For an Index object, this property setting is read/write until the object is appended to a collection, after which it's read-only.

Settings and Return Values

The setting or return value is a Boolean expression that specifies a unique index. The data type is Boolean. True (-1) indicates that the Index object represents a unique index.

Remarks

A unique index consists of one or more fields that logically arrange all records in a table in a unique, predefined order. If the index consists of one field, values in that field must be unique for the entire table. If the index consists of more than one field, each field can contain duplicate values, but each combination of values from all the indexed fields must be unique.

If both the Unique and Primary properties of an Index object are set to True, the index is unique and primary: It uniquely identifies all records in the table in a predefined, logical order. If the Primary property is set to False (0), the index is a secondary index. Secondary indexes (both key and nonkey) logically arrange records in a predefined order without serving as an identifier for records in the table.

Tips

  • You don't have to create indexes for tables, but in large, unindexed tables, accessing a specific record can take a long time.
  • Records read from tables without indexes are returned in no particular sequence.
  • The Attributes property of each Field object in the Index object determines the order of records and consequently determines the access techniques to use for that Index object.
  • A unique index helps optimize finding records.
  • Indexes don't affect the physical order of a base table — indexes affect only how the records are accessed by the table-type Recordset object when a particular index is chosen or when the Microsoft Jet database engine creates Recordset objects.
 See Also

Attributes Property, Clustered Property, Primary Property, Unique Property.

Example

See the Index property example.

Example (Microsoft Access)

See the IgnoreNulls property example (Microsoft Access).


Updatable Property

Applies To

Database Object, Dynaset-Type Recordset Object, QueryDef Object, Recordset Object, Snapshot-Type Recordset Object, Table-Type Recordset Object, TableDef Object.

Description

Returns a value that indicates whether changes can be made to a data access object. True (-1) indicates that the object can be changed or updated. (Snapshot-type Recordset objects always return False (0).)

Remarks

Depending on the object, if the Updatable property setting is True, the specified:

  • Database object can be changed.
  • QueryDef object query definition can be changed.
  • Recordset object records can be updated.
  • TableDef object table definition can be changed.
 You can use the Updatable property with all Recordset objects.

The Updatable property setting is always True for a newly created TableDef object and False for an attached TableDef object. A new TableDef object can be appended only to a database for which the current user has write permission.

Many types of objects can contain fields that can't be updated. For example, you can create a dynaset-type Recordset object in which only some fields can be changed. These fields can be fixed or contain data that increments automatically, or the dynaset can result from a query that combines updatable and nonupdatable tables.

If the object contains only nonupdatable fields, the value of the Updatable property is False. When one or more fields are updatable, the property's value is True. You can edit only the updatable fields. A trappable error occurs if you try to assign a new value to a nonupdatable field.

The Updatable property of a QueryDef object is set to True if the query definition can be updated, even if the resulting Recordset object isn't updatable.

Because an updatable object can contain nonupdatable fields, check the Fields collection of a Recordset object to check the DataUpdatable property of each field before you edit a record in the Recordset object.

See Also

Field Object.

Example

This example adds a record to a Recordset object if the object's Updatable property setting is True.

Dim dbsNorthwind As Database, rstUnknown As Recordset
Set dbsNorthwind =  DBEngine.Workspaces(0).OpenDatabase("Northwind.mdb")

Set rstUnknown = dbsNorthwind.OpenRecordset("Unfamiliar Table")
If rstUnknown.Updatable = True Then
    rstUnknown.AddNew
    rstUnknown("MyField") = "Some new data"
    rstUnknown.Update
End If
dbsNorthwind.Close
Example (Microsoft Access)

The following example adds a record to a Recordset object if the object's Updatable property setting is True.

Sub UpdateData()
    Dim dbs As Database, rstUnknown As Recordset

    ' Return Database variable that points to current database.
    Set dbs = CurrentDb
    Set rstUnknown = dbs.OpenRecordset("Unfamiliar Table")
    ' Check Updatable property before adding new record.
    If rstUnknown.Updatable = True Then
        With rstUnknown
            .AddNew
            !SomeField = "Some new data"
            .Update
        End With
    End If
    dbs.Close
End Sub
Example (Microsoft Excel)

This example prompts the user to select a cell that contains a value for the CONTACT field of the Customer recordset in the NWINDEX.MDB database. The example then checks to see whether the recordset can be updated. If so, the example adds a new record to the recordset, using the value in the selected cell.

To create the NWINDEX.MDB database, run the Microsoft Excel example for the CreateDatabase method.

Dim db As Database, rs As Recordset
Sheets("Sheet1").Activate
cellToCopy = Application.InputBox("What cell value do you want" _
    & " to update as contact?", Type:=8)
If cellToCopy = False Then    ' user cancelled InputBox
    Exit Sub
End If
Set db = Workspaces(0).OpenDatabase(Application.Path & "\NWINDEX.MDB")
Set rs = db.OpenRecordset("Customer")
If rs.Updatable = True Then
    rs.AddNew
    rs("CONTACT") = cellToCopy
    rs.Update
    rs.MoveLast

    MsgBox "The new contact is " & rs("CONTACT").Value
Else
    MsgBox "The recordset cannot be modified."
End If
rs.Close
db.Close


Update Method

Applies To

Dynaset-Type Recordset Object, Recordset Object, Table-Type Recordset Object.

Description

Saves the contents of the copy buffer to a specified dynaset- or table-type Recordset object.

Syntax

recordset.Update

The recordset placeholder represents the name of an open, updatable dynaset- or table-type Recordset object.

Remarks

Use Update to save the current record and any changes you've made to it.

Caution

Changes to the current record are lost if:

  • You use the Edit or AddNew method, and then move to another record without first using Update.
  • You use Edit or AddNew, and then use Edit or AddNew again without first using Update.
  • You set the Bookmark property to another record.
  • You close the recordset referred to by recordset without first using Update.
  • You cancel the Edit.
  • You move off the record.
 To edit a record, use the Edit method to copy the contents of the current record to the copy buffer. If you don't use Edit first, an error occurs when you use Update or attempt to change a field's value.

When the Recordset object's LockEdits property setting is True (pessimistically locked) in a multiuser environment, the record remains locked from the time Edit is used until the Update method is executed or the edit is canceled. If the LockEdits property setting is False (optimistically locked), the record is locked and compared with the pre-edited record just before it is updated in the database. If the record has changed since you used the Edit method, the Update operation fails with a trappable error (3197). Note that optimistic locking is always used on external database formats such as ODBC or installable ISAM. To continue the Update operation with your changes, use the Update method again. To revert to the record as the other user changed it, refresh the current record using the Move methods, or set the Bookmark property to itself, as shown in the following example:

' Error 3197 detected; Restore record from database (as changed).
rstEmployees.BookMark = rstEmployees.Bookmark
To add a new record to a recordset, use the AddNew method.

See Also

AddNew Method, LockEdits Property, OpenRecordset Method.

Specifics (Microsoft Access)

When you use a bookmark in a Microsoft Access module, you must include an Option Compare Binary statement in the Declarations section of the module. A bookmark is a Variant array of Byte data, so the string comparison method for the module must be binary. If a bookmark is evaluated with a text-based string comparison method, such as the Option Compare Text statement or the default setting for the Option Compare Database statement, the current record may be set to an incorrect record.

Example

See the Edit method example.

Example (Microsoft Access)

See the AddNew method example (Microsoft Access).

Example (Microsoft Excel)

This example opens PRODUCT.DBF (a dBASE IV table located in the \Program Files\Common Files\Microsoft Shared\MSquery folder), finds a record with the PRODUCT value 1, and then sets the CATEGORY field to the value in cell B2 on Sheet1. (On Windows NT, PRODUCT.DBF is located in the \WINDOWS\MSAPPS\MSQUERY folder.)

Const sourceDir = "C:\Program Files\Common Files\Microsoft " _
    & "Shared\MSquery"
Dim db As Database, rs As Recordset, categoryCell As Range
Sheets("Sheet1").Activate
Set categoryCell = ActiveSheet.Cells(2, 2)
categoryCell.Value = "BEVR"
Set db = OpenDatabase(sourceDir, False, False, "dBASE IV")
Set rs = db.OpenRecordset("PRODUCT.DBF", dbOpenTable)
With rs
    .Index = "PRODUCT"
    .Seek "=", "1"

    .Edit
    .Fields("CATEGORY").Value = categoryCell.Value
    .Update
End With
MsgBox "The field has been updated with " & categoryCell.Value
rs.Close
db.Close


User Object

Description

A User object represents a user account that has access permissions when a Workspace object operates as a secure workgroup.

Remarks

You use User objects to establish and enforce access permissions for the Document objects that represent databases, tables, and queries. Also, if you know the properties of a specific User object, you can create a new Workspace object that has the same access permissions as the User object.

You can append an existing User object to the Users collection of a Group object to give a user account the access permissions for that Group object. Alternatively, you can append the Group object to the Groups collection in a User object to establish membership of the user account in that group. If you use a Users or Groups collection other than the one to which you just appended an object, you may need to use the Refresh method.

Using the properties of a User object, you can:

  • Check the Name property setting of an existing User object to determine its name. You can't check the PID and Password property settings of an existing User object.
  • Set the Name, PID, and Password properties of a newly created, unappended User object to establish the identity of that User object. If you don't set the Password property, it's set to a zero-length string ("").
 The Microsoft Jet database engine predefines two User objects named Admin and Guest. The user Admin is a member of the Group object named Admins and Users; the user Guest is a member only of the Group object named Guests.

You can refer to any other User object that you create and append to a Users collection by its Name property setting using this syntax:

Workspaces(n)|Group.Users("name")

To create a new User object, use the CreateUser method.

Properties

Name Property, Password Property, PID Property.

Methods

CreateGroup Method, NewPassword Method.

See Also

CreateUser Method; Appendix, "Data Access Object Hierarchy."

Specifics (Microsoft Access)

You can create User objects to establish and enforce permissions for Microsoft Access database objects as well as for data access objects. For example, you can set security for forms, reports, macros, and modules.

A User object has a Name property that you can use in setting permissions for a Container or Document object. For example, you can assign the value of a User object's Name property to the UserName property of a Container or Document object. You can then set the Permissions property of the Container or Document object to establish permissions for the user defined by the UserName property. Or you can read the Permissions property to determine existing permissions for that user.

Example

See the Group object example.

Example (Microsoft Access)

The following example creates a new User object and appends it to the Users collection of a Workspace object. It then creates a new Group object and appends it to the Groups collection of the Workspace object. The new User object is also appended to the Users collection of the Group object. The new user is then given retrieval permissions on tables.

Note that in order to assign users to groups, you must either append a User object to the Users collection of a Group object, or append a Group object to the Groups collection of a User object. It doesn't matter which option you choose; either will result in the specified user being included in the specified group.

Sub NewTablesUser()
    Dim wsp As Workspace, dbs As Database
    Dim usr As User, grp As Group, usrMember As User
    Dim ctr As Container, doc As Document

    Set wsp = DBEngine.Workspaces(0)
    ' Return Database object pointing to current database.
    Set dbs = CurrentDb
' Create User object and append to Users collection of Workspace object.
    Set usr = wsp.CreateUser("Chris Jones", "123abc456DEF", "Password")
    wsp.Users.Append usr
    ' Create Group object and append to Groups collection of Workspace
    ' object.
    Set grp = wsp.CreateGroup("Marketing", "321xyz654EFD")
    wsp.Groups.Append grp
    ' Append new User object to Users collection of new Group object.
    Set usrMember = grp.CreateUser("Chris Jones")
    grp.Users.Append usrMember
    ' Refresh Users collection of Group object.

    grp.Users.Refresh
    ' Return Container object.
    Set ctr = dbs.Containers!Tables
    ' Set UserName property of Container object.
    ctr.UserName = usrMember.Name
    ' Add retrieve permissions for new user on all tables.
    ctr.Permissions = ctr.Permissions Or dbSecRetrieveData
End Sub


UserName Property

Applies To

Container Object, Document Object, Workspace Object.

Description

Sets or returns a value that represents a user or group of users or the owner of a Workspace object. For Container and Document objects, this property setting is read/write. For a Workspace object, this property setting is read/write for an object not yet appended to a collection and read-only for an existing Workspace object.

Settings and Return Values

The setting or return value is a string expression that evaluates to the name of a User object in the Users collection or a Group object in the Groups collection. (Data type is String.)

Remarks

Depending on the type of object, the UserName property represents:

  • A user or group of users when you manipulate the access permissions of a Container object or a Document object.
  • The owner of a Workspace object. For Container and Document objects, you use the UserName property with the Permissions property to establish read or write permissions.
 To find or set the permissions for a particular user or group of users, first set the UserName property to the user or group name that you want to examine. Then check the Permissions property setting to determine what permissions that user or group of users has, or set the Permissions property to change the permissions.

For a Workspace object, check the UserName property setting to determine the owner of the Workspace object. Set the UserName property to establish the owner of the Workspace object before you append the object to the Workspaces collection.

See Also

Append Method, Inherited Property, Password Property, Permissions Property.

Example

This example sets the access permissions for a table named MyTable in the specified database for a user named Millicent to read-only. The code then checks to see if Millicent has permission to add records.

Dim wrkDefault As Workspace, dbsNorthwind As Database
Dim docMyTable As Document
...
Set wrkDefault = DBEngine.Workspaces(0)
Set dbsNorthwind = wrkDefault.OpenDatabase("Northwind.mdb")
...
Set docMyTable = dbsNorthwind.Containers("Tables")![MyTable]
docMyTable.UserName = "Millicent"
docMyTable.Permissions = dbSecRetrieveData
If(docMyTable.Permissions and dbSecInsertData) > 0 Then
    Debug.Print "Millicent can insert data."
Else
    Debug.Print "Millicent can't insert data."
End If
...
Example (Microsoft Access)

See the Permissions property example (Microsoft Access)


Users Collection

Description

A Users collection contains all stored User objects of a Workspace or Group object.

Remarks

You can append an existing User object to the Users collection of a Group object to give a user account the access permissions for that Group object. Alternatively, you can append the Group object to the Groups collection in a User object to establish membership of the user account in that group. If you use a Users or Groups collection other than the one to which you just appended an object, you may need to use the Refresh method.

The Microsoft Jet database engine predefines two User objects named Admin and Guest. The user Admin is a member of the Group object named Admins and Users; the user Guest is a member only of the Group object named Guests.

You can refer to any other User object that you create and append to a Users collection by its Name property setting using this syntax:

Workspaces(n)|Group.Users("name")

Properties

Count Property.

Methods

Append Method, Delete Method, Refresh Method.

See Also

Appendix, "Data Access Object Hierarchy."

Specifics (Microsoft Access)

See the User object specifics (Microsoft Access).

Example

See the Group object example.

Example (Microsoft Access)

See the User object example (Microsoft Access).


V1xNullBehavior Property

Applies To

Database Object.

Description

Sets or returns a value that indicates whether zero-length strings ("") used in code to fill Text or Memo fields are converted to Null. This property applies to Microsoft Jet database engine version 1.x databases that have been converted to Jet database engine version 2.0 or 3.0 databases.

Note The Jet database engine automatically creates this property when it converts a version 1.x database to a version 2.0 or 3.0 database. A 2.0 database will retain this property when it is converted to a 3.0 database.

Settings and Return Values

The setting or return value is a Boolean expression that indicates whether zero-length strings are converted to Null. The data type is Boolean. True (-1) indicates that zero-length strings are converted to Null.

Remarks

If you change this property setting, you must close and then reopen the database for your change to take effect.

For fastest performance, modify code that sets any Text or Memo fields to zero-length strings so that the fields are set to Null instead, and remove the V1xNullBehavior property from the Properties collection.

See Also

Index Property.


ValidateOnSet Property

Applies To

Field Object.

Description

Sets or returns a value that specifies whether or not the value of a Field object is immediately validated when the object's Value property is set. Only Field objects in Recordset objects support the ValidateOnSet property as read/write.

Settings and Return Values

The setting or return value is a Boolean expression that indicates whether a value is validated, as described in Settings. The data type is Boolean. The possible settings or return values are:

Setting/Value | Description
True | Validate when the property is set.
False | Validate when the record is updated.

Remarks

When the ValidateOnSet property is set to True (-1), the validation rule specified by the ValidationRule property setting of the Field object is checked when you set the object's Value property.

When the ValidateOnSet property is set to False (0), you can set the Value property of each field independently and perform validation using the final value settings when the record is updated.

See Also

AllowZeroLength Property, QueryDef Object, Required Property, ValidationRule Property, ValidationText Property, Value Property.


ValidationRule Property

Applies To

Dynaset-Type Recordset Object, Field Object, Recordset Object, Snapshot-Type Recordset Object, Table-Type Recordset Object, TableDef Object.

Description

Sets or returns a value that validates the data in a field as it's changed or added to a table. For an object not yet appended to the Fields collection, this property is read/write. See Remarks for the more specific read/write characteristics of this property.

Settings and Return Values

The settings or return values is a string expression that describes a comparison in the form of an SQL WHERE clause without the WHERE reserved word. The data type is String.

Remarks

The ValidationRule property determines whether or not valid data is in the associated field. If the data is not legal, a trappable run-time error occurs. The returned error message is the text of the ValidationText property, if specified, or the text of the expression specified by ValidationRule.

For a Field object, use of the ValidationRule property depends on the object that contains the Fields collection that the Field object is appended to, as the following table shows.

Object appended to | Usage
Index | Not supported
QueryDef | Read-only
Recordset | Read-only
Relation | Not supported
TableDef | Read/write

For a Recordset object, use of the ValidationRule property is read-only. For a TableDef object, use of the ValidationRule property depends on the status of the TableDef object, as the following table shows.

TableDef | Usage
Base table | Read/write
Attached table | Read-only

Validation is supported only for databases that use the Microsoft Jet database engine.

The string expression specified by the ValidationRule property of a Field object can refer only to that Field. The expression can't refer to user-defined functions, SQL aggregate functions, or queries. To set a Field object's ValidationRule property when its ValidateOnSet property setting is True, the expression must successfully parse (with the field name as an implied operand) and evaluate to True. If its ValidateOnSet property setting is False, the ValidationRule property setting is ignored.

The ValidationRule property of a Recordset or TableDef object can refer to multiple fields in that object. The restrictions noted earlier in this topic for the Field object apply.

For a table-type Recordset object, the ValidationRule property takes the value of the ValidationRule property setting of the TableDef object that you use to create the table-type Recordset object.

For a TableDef object based on an attached table, the ValidationRule property takes the value of the underlying base table. If the underlying base table doesn't support validation, the value of this property is a zero-length string ("").

See Also

ValidateOnSet Property, ValidationText Property.

Specifics (Microsoft Access)

Use the data access ValidationRule property to set validation rules for a Field, Recordset, or TableDef object from Visual Basic.

You can also set validation rules for a field or control in the Microsoft Access user interface. Set the Microsoft Access ValidationRule property for a field or a table in table Design view. Set the ValidationRule property of a control in the property sheet in form Design view.

In Microsoft Access, the string expression specified by the ValidationRule property of a Field object can't refer to user-defined functions, domain aggregate functions, SQL aggregate functions, the CurrentUser function, the Eval function, or queries.

Example (Microsoft Access)

The following example sets the ValidationRule and ValidationText properties for two fields in an Order Details table. Once these properties have been set, you can view them in table Design view as well.

Sub SetValidation()
    Dim dbs As Database, tdf As TableDef
    Dim fldQuantity As Field, fldDiscount As Field

    ' Return Database variable that points to current database.
    Set dbs = CurrentDb
    Set tdf = dbs.TableDefs![Order Details]
    Set fldQuantity = tdf.Fields!Quantity
    Set fldDiscount = tdf.Fields!Discount
    ' Set ValidationRule and ValidationText.
    fldQuantity.ValidationRule = ">= 4"
    fldQuantity.ValidationText = "Quantity must be four or more items."
    fldDiscount.ValidationRule = "Between .05 and .30"
    fldDiscount.ValidationText = "Discount must be between 5% and 30%."
End Sub


ValidationText Property

Applies To

Dynaset-Type Recordset Object, Field Object, Recordset Object, Snapshot-Type Recordset Object, Table-Type Recordset Object, TableDef Object.

Description

Sets or returns a value that specifies the text of the message that your application displays if the value of a Field object doesn't satisfy the validation rule specified by the ValidationRule property setting.

For an object not yet appended to a collection, this property is read/write. For a Recordset object, this property setting is read-only. For a TableDef object, this property setting is read-only for an attached table and read/write for a base table.

Settings and Return Values

The setting or return value is a string expression that specifies the text displayed if an entered value is invalid. The data type is String.

Remarks

For a Field object, use of the ValidationText property depends on the object that contains the Fields collection that the Field object is appended to, as the following table shows.

Object appended to | Usage
Index | Not supported
QueryDef | Read-only
Recordset | Read-only
Relation | Not supported
TableDef | Read/write

See Also

AllowZeroLength Property, QueryDef Object, Required Property, ValidateOnSet Property, ValidationRule Property, Value Property.

Example (Microsoft Access)

See the ValidationRule property example (Microsoft Access).


Value Property

Applies To

Field Object, Parameter Object, Property Object.

Description

Sets or returns the value of an object.

Settings and Return Values

The setting or return value is an expression that evaluates to a value appropriate for the data type, as specified by the Type property of an object. The data type is Variant.

Remarks

Generally, the Value property is used to retrieve and alter data in Recordset objects.

The Value property is the default property of the Field, Parameter, and Property objects. Therefore, the following lines of code are equivalent (assuming Field1 is at the first ordinal position).

varX = rstProducts!Field1
varX = rstProducts!Field1.Value
varX = rstProducts(0)
varX = rstProducts(0).Value
varX = rstProducts("Field1").Value
varX = rstProducts("Field1")
F$ = "Field1" : varX = rstProducts(F$).Value
varX = rstProducts(F$)
See Also

Name Property, Updatable Property.


Version Property

Applies To

Database Object, DBEngine Object.

Description

Returns a value that indicates the version of the database or database engine associated with the object. This property setting is read-only.

Return Values

The return value is a string expression that evaluates to a value, depending on the object specified:

  • Database object — identifies the data format version of an open database.
  • DBEngine object — identifies the version number of the Microsoft Jet database engine.
 Remarks

For a Database object, this property identifies the version of the Jet database engine that created the database.

The setting of the Version property represents the version number in the form "major.minor"; for example, "3.0". The product version number (for example, 3.0) consists of the version number (2), a period, and the release number (0).

See Also

CreateDatabase Method.

Example

This example checks the version number of the Microsoft Jet database engine and splits it into the version number and release number. The example doesn't check for an invalid string.

Dim strDBVersion As String, strJetVersion As String
Dim strJetRelease As String
Dim intDot As Integer
...
strDBVersion = DBEngine.Version
intDot = InStr(strDBVersion, ".")
strJetVersion = Left$(strDBVersion, intDot - 1)
strJetRelease = Right$(strDBVersion, Len(strDBVersion) - intDot)
...


Workspace Object

Description

A Workspace object defines a session for a user. It contains open databases and provides mechanisms for simultaneous transactions and for a secure workgroup.

Remarks

Use the Workspace object to manage the current session or to start an additional session. In a session, you can open multiple databases, manage transactions, and establish security based on user names and passwords. For example, you can:

  • Create a Workspace object using the Name and UserName properties to establish a named, password-protected session. The session creates a scope in which you can open multiple databases and conduct one instance of nested transactions. Use the Close method to terminate a session.
  • Use the OpenDatabase method to open one or more existing databases on that Workspace.
  • Use the BeginTrans, CommitTrans, and Rollback methods to manage nested transaction processing within a Workspace and use several Workspace objects to conduct multiple, simultaneous, and overlapping transactions.
  • Use the IsolateODBCTrans property to isolate multiple transactions that involve the same ODBC database.
 When you start the Microsoft Jet database engine, you automatically create the default workspace, DBEngine.Workspaces(0). The settings of the Name and UserName properties of the default workspace are "#Default Workspace#" and "Admin," respectively. If security is enabled, the UserName property setting is the name of the user who logged on. If you use the OpenDatabase method without specifying a Workspace object, the default DBEngine.Workspaces(0) is used.

When you use transactions, all databases in the specified Workspace are affected — even if multiple Database objects are opened in the Workspace. For example, if you use a BeginTrans method, update several records in a database, and then delete records in another database, both the update and delete operations are rolled back when you use the Rollback method. You can create additional Workspace objects to manage transactions independently across Database objects.

Workspace objects are created using the CreateWorkspace method of the DBEngine object. After you create a new Workspace object, you must appended it to the Workspaces collection if you need to refer to it from the Workspaces collection. You can, however, use a newly created Workspace object without appending it to the Workspaces collection.

You can refer to any other Workspace object that you create and append to the collection by its Name property setting using this syntax:

Workspaces("name")

You can also refer to appended Workspace objects by their position in the Workspaces collection using this syntax (where n is the nth member of the Workspaces collection):

DBEngine.Workspaces(n)

Properties

IsolateODBCTrans Property, Name Property, UserName Property.

Methods

BeginTrans, CommitTrans, Rollback Methods; Close Method; CreateDatabase Method; CreateGroup Method; CreateUser Method; OpenDatabase Method.

See Also

CreateWorkspace Method; Transactions Property; Appendix, "Data Access Object Hierarchy."

Example

This example creates a new Workspace and appends it to the Workspaces collection. It assumes that the user JustAUser with a password of Secret has already been created. The example enumerates the collections of each Workspace object and finally closes the new Workspace. See the methods and properties of the Workspace object or Workspaces collection for additional examples.

Function EnumerateWorkspace () As Integer
    Dim wrkEnum As Workspace, wrkNew As Workspace
    Dim I As Integer, J As Integer
    ' Create new workspace and add it to collection.
    Set wrkNew = DBEngine.CreateWorkspace("NewWorkspace", "JustAUser", _
        "")
    DBEngine.Workspaces.Append wrkNew
    ' Enumerate all workspaces.
    For J = 0 To DBEngine.Workspaces.Count - 1
        Set wrkEnum = DBEngine.Workspaces(J)
        Debug.Print
        Debug.Print "Enumeration of Workspaces("; J; "): "; wrkEnum.Name
        Debug.Print
        ' Enumerate databases.
        Debug.Print "Databases: Name"
        For I = 0 To wrkEnum.Databases.Count - 1
            Debug.Print "  "; wrkEnum.Databases(I).Name
        Next I
        ' Enumerate all user accounts.
        Debug.Print "Users: Name"
        For I = 0 To wrkEnum.Users.Count - 1
            Debug.Print "  "; wrkEnum.Users(I).Name
        Next I
        Debug.Print
        ' Enumerate all group accounts.
        Debug.Print "Groups: Name"
        For I = 0 To wrkEnum.Groups.Count - 1
            Debug.Print "  "; wrkEnum.Groups(I).Name
        Next I
        Debug.Print
    Next J
    Debug.Print
    ' Enumerate built-in properties of wrkNew.
    Debug.Print "wrkNew.Name: "; wrkNew.Name
    Debug.Print "wrkNew.UserName: "; wrkNew.UserName

    Debug.Print
    wrkNew.Close
    EnumerateWorkspace = True
End Function


Workspaces Collection

Description

The Workspaces collection contains all active, unhidden Workspace objects of the DBEngine object. (Hidden Workspace objects are not appended to the collection and referenced by the variable to which they are assigned.)

Remarks

Use the Workspace object to manage the current session or to start an additional session.

When you start the Microsoft Jet database engine, you automatically create the default workspace, DBEngine.Workspaces(0).

New Workspace objects are created with the CreateWorkspace method of the DBEngine object. After you create a new Workspace object, you must appended it to the Workspaces collection if you need to refer to it from the Workspaces collection. You can, however, use a newly created Workspace object without appending it to the Workspaces collection.

You can refer to any other Workspace object that you create and append to the collection by its Name property setting using this syntax:

Workspaces("name")

You can also refer to appended Workspace objects by their position in the Workspaces collection using this syntax (where n is the nth member of the Workspaces collection):

DBEngine.Workspaces(n)

Properties

Count Property.

Methods

Append Method, Refresh Method.

See Also

Appendix, "Data Access Object Hierarchy."

Example

See the Workspace object example.


ALL, DISTINCT, DISTINCTROW, TOP Predicates

Description

Specifies records selected with SQL queries.

Syntax

SELECT [ALL | DISTINCT | DISTINCTROW | [TOP n [PERCENT]]]
FROM table

A SELECT statement containing these predicates has the following parts.

Part

Description

ALL

Assumed if you don't include one of the predicates. The Microsoft Jet database engine selects all of the records that meet the conditions in the SQL statement. The following two examples are equivalent and return all records from the Employees table:

SELECT ALL *
FROM Employees
ORDER BY EmployeeID;

SELECT *
FROM Employees
ORDER BY EmployeeID;
DISTINCT

Omits records that contain duplicate data in the selected fields. To be included in the results of the query, the values for each field listed in the SELECT statement must be unique. For example, several employees listed in an Employees table may have the same last name. If two records contain Smith in the Last Name field, the following SQL statement returns only one record that contains Smith:

SELECT DISTINCT
LastName
FROM Employees;
If you omit DISTINCT, this query returns both Smith records.

If the SELECT clause contains more than one field, the combination of values from all fields must be unique for a given record to be included in the results.

The output of a query that uses DISTINCT isn't updatable and doesn't reflect subsequent changes made by other users.

Part

Description

DISTINCTROW

Omits data based on entire duplicate records, not just duplicate fields. For example, you could create a query that joins the Customers and Orders tables on the Customer ID field. The Customers table contains no duplicate Customer ID fields, but the Orders table does because each customer can have many orders. The following SQL statement shows how you can use DISTINCTROW to produce a list of companies that have at least one order but without any details about those orders:

SELECT DISTINCTROW CompanyName
FROM Customers INNER JOIN Orders
ON Customers.CustomerID = Orders.CustomerID
ORDER BY CompanyName;
If you omit DISTINCTROW, this query produces multiple rows for each company that has more than one order.

DISTINCTROW has an effect only when you select fields from some, but not all, of the tables used in the query. DISTINCTROW is ignored if your query includes only one table, or if you output fields from all tables.

TOP

Returns a certain number of records that fall at the top or the bottom of a range specified by an ORDER BY clause. Suppose you want the names of the top 25 students from the class of 1994:

SELECT TOP 25
FirstName, LastName
FROM Students
WHERE GraduationYear = 1994
ORDER BY GradePointAverage DESC;
If you don't include the ORDER BY clause, the query will return an arbitrary set of 25 records from the Students table that satisfy the WHERE clause.

The TOP predicate doesn't choose between equal values. In the preceding example, if the twenty-fifth and twenty-sixth highest grade point averages are the same, the query will return 26 records.

Part

Description

TOP

You can also use the PERCENT reserved word to return a certain percentage of records that fall at the top or the bottom of a range specified by an ORDER BY clause. Suppose that, instead of the top 25 students, you want the bottom 10 percent of the class:

SELECT TOP 10 PERCENT
FirstName, LastName
FROM Students
WHERE GraduationYear = 1994
ORDER BY GradePointAverage ASC;

The ASC predicate specifies a return of bottom values. The value that follows TOP must be an unsigned Integer.

TOP doesn't affect the query's updatability.

table

The name of the table from which records are retrieved.

Specifics (Microsoft Access)

In Microsoft Access, using DISTINCT is equivalent to setting the UniqueValues property to Yes on the query property sheet in query Design view.

Using DISTINCTROW is equivalent to setting the UniqueRecords property to Yes (the default value) in the query property sheet in query Design view.

Using TOP is equivalent to setting the TopValues property on the query property sheet in query Design view, or entering a value in the Top Values list box on the toolbar in the Query window.

Using the PERCENT reserved word is equivalent to using the percent sign (%) with the TopValues property or in the Top Values list box.

Example

The following examples use two hypothetical tables, Customers and Orders.

Customers Table

First name | Customer ID
Bob | 1
Adam | 2
Beverly | 3
Bob | 4

Orders Table

Customer ID | Order ID
1 | 1
1 | 2

Customer ID | Order ID
2 | 3
2 | 4
2 | 5
4 | 6
4 | 7

SELECT ALL FirstName FROM Customers INNER JOIN Orders ON Customers.CustomerID = Orders.CustomerID;

Result | Updatable
Bob Bob Adam Adam Adam Bob Bob | Yes

SELECT DISTINCT FirstName FROM Customers INNER JOIN Orders ON Customers.CustomerID = Orders.CustomerID;

Result | Updatable
Bob Adam | No

SELECT DISTINCTROW FirstName FROM Customers INNER JOIN Orders ON Customers.CustomerID = Orders.CustomerID;

Result | Updatable
Bob Adam Bob | Yes

SELECT TOP 5 FirstName FROM Customers INNER JOIN Orders ON Customers.CustomerID = Orders.CustomerID ORDER BY Orders.OrderID;

Result | Updatable
Bob Bob Adam Adam Adam | Yes


ALTER TABLE Statement

Description

Modifies the design of a table after it has been created with the CREATE TABLE statement.

Note

The Microsoft Jet database engine doesn't support the use of ALTER TABLE, or any of the data definition language (DDL) statements, with non-Jet databases. Use the data access object Create methods instead.

Syntax

ALTER TABLE table {ADD {COLUMN field type[(size)] [CONSTRAINT index] |
CONSTRAINT multifieldindex} |
DROP {COLUMN field | CONSTRAINT indexname} }

The ALTER TABLE statement has these parts.

Part | Description
table | The name of the table to be altered.
field | The name of the field to be added to or deleted from table.
type | The data type of field.
size | The field size in characters (Text and Binary fields only).
index | The index for field. See the CONSTRAINT clause topic for more information on how to construct this index.
multifieldindex | The definition of a multiple-field index to be added to table. See the CONSTRAINT clause topic for more information on how to construct this clause.
indexname | The name of the multiple-field index to be removed.

Remarks

Using the ALTER TABLE statement, you can alter an existing table in several ways. You can:

  • Use ADD COLUMN to add a new field to the table. You specify the field name, data type, and (for Text and Binary fields) an optional size. For example, the following statement adds a 25-character Text field called Notes to the Employees table:

ALTER TABLE Employees ADD COLUMN Notes TEXT(25)
You can also define an index on that field. For more information on single-field indexes, see the CONSTRAINT Clause Topic.

  • Use the ADD constraint to add a multiple-field index. For more information on multiple-field indexes, see the CONSTRAINT Clause Topic.
  • Use DROP COLUMN to delete a field. You specify only the name of the field.
  • Use the DROP constraint to delete a multiple-field index. You specify only the index name following the CONSTRAINT reserved word.
 Notes

  • You can't add or delete more than one field or index at a time.
  • You can use the CREATE INDEX statement to add a single- or multiple-field index to a table, and you can use ALTER TABLE or the DROP statement to delete an index created with ALTER TABLE or CREATE INDEX.
 See Also

CONSTRAINT Clause, CREATE INDEX Statement, CREATE TABLE Statement, DROP Statement.

Example

The SQL statements shown below can be used on tables created with the CREATE TABLE statement.

This example adds a Salary field with a data type of Currency to the Employees table.

ALTER TABLE Employees ADD COLUMN Salary CURRENCY;
This example removes the Salary field from the Employees table.

ALTER TABLE Employees DROP COLUMN Salary;
This example adds a foreign key to the Orders table. The foreign key is based on the Employee ID field and refers to the Employee ID field of the Employees table. In this example, you don't have to list the Employee ID field after the Employees table in the REFERENCES clause because Employee ID is the primary key of the Employees table.

ALTER TABLE Orders ADD CONSTRAINT OrdersRelationship FOREIGN KEY (EmployeeID) REFERENCES Employees (EmployeeID);
This example removes the foreign key from the Orders table.

ALTER TABLE Orders DROP CONSTRAINT OrdersRelationship;


Avg Function

Description

Calculates the arithmetic mean of a set of values contained in a specified field on a query.

Syntax

Avg(expr)

The expr placeholder represents a string expression identifying the field that contains the numeric data you want to average or an expression that performs a calculation using the data in that field. Operands in expr can include the name of a table field, a constant, or a function (which can be either intrinsic or user-defined but not one of the other SQL aggregate or domain aggregate functions).

Remarks

The average calculated by Avg is the arithmetic mean (the sum of the values divided by the number of values). You could use Avg, for example, to calculate average freight cost.

The Avg function doesn't include any Null fields in the calculation.

You can use Avg in a query expression and in the SQL property of a QueryDef object or when creating a Recordset object based on an SQL query.

See Also

SQL Aggregate Functions.

Specifics (Microsoft Access)

In Microsoft Access, you can use the Avg function in the query design grid, in an SQL statement in SQL view of the Query window, or in an SQL statement within Visual Basic code. You can also use the Avg function in a calculated control on a form or report.

The Avg function is most useful in totals queries and crosstab queries. It functions the same way whether you create the query in the query design grid or as an SQL statement in SQL view.

In the query design grid, you can create a new totals query by clicking the Totals button on the toolbar. The Total row is then inserted in the grid. You can set the Total cell beneath a field to the aggregate function to perform on the data in that field.

For example, suppose you have an Orders table that has both a Freight field and a ShipCity field. You can create a query that displays the average freight cost for orders sent to each city to which your company ships. Create a new totals query, and drag the ShipCity field to the query design grid. The Total cell beneath the ShipCity field should be set to Group By. Drag the Freight field to the query design grid, and set the Total cell beneath it to Avg. When you run the query, it will display the average freight cost by city.

You can view the SQL statement for this query by switching to SQL view. In this example, Microsoft Access creates the following SQL statement.

SELECT DISTINCTROW Avg(Orders.Freight) AS AvgOfFreight, Orders.ShipCity
FROM Orders
GROUP BY Orders.ShipCity;

You can also use an SQL statement such as this one within Visual Basic code. For example, using the following code you can create a Recordset object based on the query defined by this SQL statement.

Dim dbs As DatabAse, rst As Recordset, strSQL As String
Set dbs = CurrentDb
strSQL = "SELECT DISTINCTROW Avg(Orders.Freight) AS AvgOfFreight, "_
    "Orders.ShipCity FROM Orders GROUP BY Orders.ShipCity;"
Set rst = dbs.OpenRecordset(strSQL)
To use the Avg function in a calculated control, set the control's ControlSource property to an expression containing the Avg function. For example, to display the average freight cost for a set of orders in a text box, enter the following expression in the ControlSource property of the text box.

= Avg([Freight])
If you use the Avg function in a calculated control, you can restrict the set of records against which the function is performed by setting the form's Filter property.

Example

This example uses the Orders table to calculate the average freight charges for orders with freight charges over $100.

SELECT Avg(Freight) AS [Average Freight] FROM Orders WHERE Freight > 100;
Example (Microsoft Access)

The following example assumes that you have an Orders table that contains a field called Freight. You can use the Avg function to calculate the average freight charges for orders with freight charges over $100. Enter the following expression in SQL view in the Query window.

SELECT Avg([Freight]) AS [AverageFreight] FROM Orders WHERE [Freight] > 100;
The next example creates a calculated control that displays the average freight charges for all of the underlying records in a form based on the same Orders table. Open a new form and set its RecordSource property to Orders. Enter this expression in a the ControlSource property of a text box on the form. To apply a condition that limits the calculation to only some records, such as those for orders greater than $100, set the form's Filter property.

= Avg([Freight])


Between...And Operator

Description

Determines whether the value of an expression lies within a specified range of values. This operator can be used within SQL statements.

Syntax

expr [Not] Between value1 And value2

The Between...And operator syntax has these parts.

Part | Description
expr | Expression identifying the field that contains the data you want to evaluate.
value1, value2 | Expressions against which you want to evaluate expr.

Remarks

If the value of expr is between value1 and value2 (inclusive), the Between...And operator returns True; otherwise, it returns False. You can include the Not logical operator to evaluate the opposite condition (that is, whether expr lies outside the range defined by value1 and value2).

You might use Between...And to determine whether the value of a field falls within a specified numeric range. The following example determines whether an order was shipped to a location within a range of ZIP codes. If the ZIP Code is between 98101 and 98199, the IIf function returns "Local." Otherwise, it returns "Nonlocal."

SELECT IIf(ZIP Between 98101 And 98199, "Local", "Nonlocal")
FROM Publishers
If expr, value1, or value2 is Null, Between...And returns a Null.

Because wildcards, such as *, are treated as literals, you cannot use them with the Between...And operator. For example, you cannot use 980* and 989* to find all postal codes that start with 980 to 989. Instead, you have two alternatives for accomplishing this. You can add an expression to the query that takes the left three characters of the text field and use Between...And on those characters. Or you can pad the high and low values with extra characters — in this case, 98000 to 98999, or 98000 to 98999 – 9999 if using extended ZIP codes. (You must omit the – 0000 off the low values because otherwise 98000 is dropped if some ZIP codes have extended sections and others do not.)

See Also

IN Clause, SQL Expressions.

Specifics (Microsoft Access)

In Microsoft Access, you can use the Between...And operator in a query expression or in a calculated control on a form or report.

You can use the Between...And operator in the Criteria field in the query design grid to create a parameter query. The Between...And operator enables you to prompt the user to enter a range of values by which the query is restricted. The expression supplied for the value1 argument serves as the prompt for the beginning of the range, and the expression supplied for the value2 argument serves as the prompt for the end of the range.

For example, suppose you have an Orders table that has an OrderDate field. Create a new query in the query design grid and drag the OrderDate field to the first Field cell in the grid. In the Criteria field, enter the following statement.

Between [Enter beginning date:] And [Enter ending date:]
When you run the query, you will first be prompted with a dialog box that says, "Enter the beginning date for the range." Once you enter a value in that dialog, you will be prompted by a second dialog box that says, "Enter the ending date for the range." Assuming you enter valid dates, your results will include all the values in the OrderDate field that either match or fall between the dates you specified as parameters.

You can also use the Between...And operator in a calculated control to determine whether the value of the control falls within a specified numeric range. The following example determines whether an order was shipped to a location within a range of zip codes. If the ZIP field is between 98101 and 98199, the IIf function returns "Local." Otherwise, it returns "Nonlocal."

= IIf([ZIP] Between "98101" And "98199", "Local", "Nonlocal")
If any of the arguments supplied for the Between...And expression is Null, Between...And returns a Null.


CONSTRAINT Clause

Description

A constraint is similar to an index, although it can also be used to establish a relationship with another table.

You use the CONSTRAINT clause in ALTER TABLE and CREATE TABLE statements to create or delete constraints. There are two types of CONSTRAINT clauses: one for creating a constraint on a single field and one for creating a constraint on more than one field.

Note

The Microsoft Jet database engine doesn't support the use of CONSTRAINT, or any of the data definition language (DDL) statements, with non-Jet databases. Use the data access object Create methods instead.

Syntax

Single-field index:

CONSTRAINT name {PRIMARY KEY |
UNIQUE |
REFERENCES foreigntable [(foreignfield1, foreignfield2)]}

Multiple-field index:

CONSTRAINT name
{PRIMARY KEY (primary1[, primary2 [, ...]]) |
UNIQUE (unique1[, unique2 [, ...]]) |
FOREIGN KEY (ref1[, ref2 [, ...]]) REFERENCES foreigntable [(foreignfield1 [, foreignfield2 [, ...]])]}

The CONSTRAINT clause has these parts.

Part | Description
name | The name of the constraint to be created.
primary1, primary2 | The name of the field or fields to be designated the primary key.
unique1, unique2 | The name of the field or fields to be designated as a unique key.
ref1, ref2 | The name of a foreign key field or fields that refer to fields in another table.
foreigntable | The name of the foreign table containing the field or fields specified by foreignfield.
foreignfield1, foreignfield2 | The name of the field or fields in foreigntable specified by ref1, ref2. You can omit this clause if the referenced field is the primary key of foreigntable.

Remarks

You use the syntax for a single-field constraint in the field-definition clause of an ALTER TABLE or CREATE TABLE statement immediately following the specification of the field's data type.

You use the syntax for a multiple-field constraint whenever you use the reserved word CONSTRAINT outside a field-definition clause in an ALTER TABLE or CREATE TABLE statement.

Using CONSTRAINT, you can designate a field as one of the following types of constraints:

  • You can use the UNIQUE reserved word to designate a field as a unique key. This means that no two records in the table can have the same value in this field. You can constrain any field or list of fields as unique. If a multiple-field constraint is designated as a unique key, the combined values of all fields in the index must be unique, even if two or more records have the same value in just one of the fields.
  • You can use the PRIMARY KEY reserved words to designate one field or set of fields in a table as a primary key. All values in the primary key must be unique and not Null, and there can be only one primary key for a table.
 Note

Don't set a PRIMARY KEY constraint on a table that already has a primary key; if you do, an error occurs.

  • You can use the FOREIGN KEY reserved words to designate a field as a foreign key. If the foreign table's primary key consists of more than one field, you must use a multiple-field constraint definition, listing all of the referencing fields, the name of the foreign table, and the names of the referenced fields in the foreign table in the same order that the referencing fields are listed. If the referenced field or fields are the foreign table's primary key, you don't have to specify the referenced fields — by default, the database engine behaves as if the foreign table's primary key is the referenced fields.
 See Also

ALTER TABLE Statement, CREATE INDEX Statement, CREATE TABLE Statement, DROP Statement.

Example

This example creates a new table called ThisTable with two Text fields.

CREATE TABLE ThisTable (FirstName TEXT, LastName TEXT);
This example creates a new table called MyTable with two Text fields, a Date/Time field, and a unique index made up of all three fields.

CREATE TABLE MyTable (FirstName TEXT, LastName TEXT, DateOfBirth     DATETIME, CONSTRAINT MyTableConstraint
    UNIQUE (FirstName, LastName, DateOfBirth));
This example creates a new table with two Text fields and an Integer field. The SSN field is the primary key.

CREATE TABLE NewTable (FirstName TEXT, LastName TEXT, SSN INTEGER CONSTRAINT MyFieldConstraint PRIMARY KEY);


Count Function

Description

Calculates the number of records returned by a query.

Syntax

Count(expr)

The expr placeholder represents a string expression identifying the field that contains the data you want to count or an expression that performs a calculation using the data in the field. Operands in expr can include the name of a table field or function (which can be either intrinsic or user-defined but not other SQL aggregate functions). You can count any kind of data, including text.

Remarks

You can use Count to count the number of records in an underlying query. For example, you could use Count to count the number of orders shipped to a particular country.

Although expr can perform a calculation on a field, Count simply tallies the number of records. It doesn't matter what values are stored in the records.

The Count function doesn't count records that have null fields unless expr is the asterisk (*) wildcard character. If you use an asterisk, Count calculates the total number of records, including those that contain null fields. Count(*) is considerably faster than Count([Column Name]). Don't enclose the asterisk in quotation marks (" "). The following example calculates the number of records in the Orders table:

SELECT Count(*)AS TotalOrders FROM Orders;
If expr identifies multiple fields, the Count function counts a record only if at least one of the fields is not Null. If all of the specified fields are Null, the record isn't counted. Separate the field names with an ampersand (&). The following example shows how you can limit the count to records in which either Shipped Date or Freight isn't Null:

SELECT Count('ShippedDate & Freight')
AS [Not Null] FROM Orders;
You can use Count in a query expression. You can also use this expression in the SQL property of a QueryDef object or when creating a Recordset object based on an SQL query.

See Also

SQL Aggregate Functions, Sum Function.

Specifics (Microsoft Access)

In Microsoft Access, you can use the Count function in the query design grid, in an SQL statement in SQL view of the Query window, or in an SQL statement within Visual Basic code. You can also use the Count function in a calculated control on a form or report.

The Count function is most useful in totals queries and crosstab queries. It functions the same way whether you create the query in the query design grid or as an SQL statement in SQL view.

In the query design grid, you can create a new totals query by clicking the Totals button on the toolbar. The Total row is then inserted in the grid. You can set the Total cell beneath a field to the aggregate function to perform on the data in that field.

The fastest way to count all the records in a query is to use the Count(*) function. You can use the Count(*) function in a calculated field in a query.

For example, suppose you have an Orders table that has both an OrderID field and a ShipCity field. You can create a query that displays the number of orders sent to each city. Create a new totals query, and drag the ShipCity field to the query design grid. Set the Total cell beneath the ShipCity field to Group By.

Next, create a calculated field by typing the following expression into a new Field cell.

CountOfOrders: Count(*)
Then, set the Total cell beneath this field to Expression. When you run the query, it will display the number of orders sent to each city.

You can view the SQL statement for this query by switching to SQL view. In this example, Microsoft Access creates the following SQL statement.

SELECT DISTINCTROW Count(*) AS CountOfOrders, Orders.ShipCity
FROM Orders
GROUP BY Orders.ShipCity;
You can achieve the same results by dragging the OrderID field to the query design grid, and choosing Count in the Total cell beneath it. This query will be slightly slower than the one that uses the Count(*) function. Note the differences between the following SQL statements.

SELECT DISTINCTROW Count(Orders.OrderID)
AS CountOfOrderID, Orders.ShipCity
FROM Orders
GROUP BY Orders.ShipCity;
You can also use an SQL statement such as this one within Visual Basic code. For example, using the following code you can create a Recordset object based on the query defined by this SQL statement.

Dim dbs As DatabAse, rst As Recordset, strSQL As String
Set dbs = CurrentDb
strSQL = "SELECT DISTINCTROW Count(*) AS CountOfOrders, Orders.ShipCity FROM Orders GROUP BY Orders.ShipCity;"

Set rst = dbs.OpenRecordset(strSQL)
To use the Count function in a calculated control, set the control's ControlSource property to an expression containing the Count function. For example, to display the number of orders in a set of orders in a text box, enter the following expression in the ControlSource property of the text box.

= Count([OrderID])
If you use the Count function in a calculated control, you can restrict the set of records against which the function is performed by setting the form's Filter property.

Example

This example uses the Orders table to calculate the number of orders shipped to the United Kingdom.

SELECT Count(ShipCountry)AS [UK Orders] FROM Orders
WHERE ShipCountry = 'UK';
Example (Microsoft Access)

The following example assumes that you have an Orders table that contains a field called ShipCountry. You can use the Count function to calculate the number of orders shipped to the United Kingdom. Enter the following expression in SQL view in the Query window.

SELECT Count([ShipCountry]) AS [UKOrders] FROM Orders
WHERE [ShipCountry] = 'UK';
The next example creates a calculated control that displays the number of orders in the same Orders table. Open a new form and set its RecordSource property to Orders. Enter the following expression in the ControlSource property of a text box on the form. To apply a condition that limits the count to only some records, such as those for orders shipped to the United Kingdom, set the form's Filter property.

= Count([ShipCountry])


CREATE INDEX Statement

Description

Creates a new index on an existing table.

Note

For non-Jet databases, the Microsoft Jet database engine doesn't support the use of CREATE INDEX (except to create a pseudo index on an ODBC attached table) or any of the data definition language (DDL) statements. Use the data access object Create methods instead. For more information, see the Remarks section.

Syntax

CREATE [ UNIQUE ] INDEX index
ON table (field [ASC | DESC ][, field [ASC | DESC ], ...])
[WITH { PRIMARY | DISALLOW NULL | IGNORE NULL }]

The CREATE INDEX statement has these parts.

Part | Description
index | The name of the index to be created.
table | The name of the existing table the index will be created on.
field | The name of the field or fields to be indexed. To create a single-field index, list the field name in parentheses following the table name. To create a multiple-field index, list the name of each field to be included in the index. To create descending indexes, use the DESC reserved word; otherwise, indexes are assumed to be ascending.

Remarks

To prohibit duplicate values in the indexed field or fields of different records, use the UNIQUE reserved word.

In the optional WITH clause, you can enforce data validation rules. You can:

  • Prohibit Null entries in the indexed field or fields of new records by using the DISALLOW NULL option.
  • Prevent records with Null values in the indexed field or fields from being included in the index by using the IGNORE NULL option.
  • Designate the indexed field or fields as the primary key by using the PRIMARY reserved word. This implies that the key is unique, so you can omit the UNIQUE reserved word.
 You can use CREATE INDEX to create a pseudo index on an attached table in an ODBC data source such as SQL Server that does not already have an index. You don't need permission or access to the remote server to create a pseudo index, and the remote database is unaware of and unaffected by the pseudo index. You use the same syntax for attached and native tables. This can be especially useful to create an index on a table that would ordinarily be read-only due to lack of an index.

You can also use the ALTER TABLE statement to add a single- or multiple-field index to a table, and you can use the ALTER TABLE statement or the DROP statement to remove an index created with ALTER TABLE or CREATE INDEX.

Note

Don't use the PRIMARY reserved word when you create a new index on a table that already has a primary key; if you do, an error occurs.

See Also

ALTER TABLE Statement, CONSTRAINT Clause, CREATE TABLE Statement, DROP Statement.

Example

This example creates an index consisting of the fields Home Phone and Extension in the Employees table.

CREATE INDEX NewIndex ON Employees (HomePhone, Extension);
This example creates an index on the Employees table using the Social Security Number field. No two records can have the same data in the SSN field, and no Null values are allowed.

CREATE UNIQUE INDEX CustID ON Customers (CustomerID) WITH DISALLOW NULL;
This example creates an index on a hypothetical ODBC linked table. The table's remote database is unaware of and unaffected by the new index.

CREATE UNIQUE INDEX OrderID ON OrderDetails (OrderID);


CREATE TABLE Statement

Description

Creates a new table.

Note

The Microsoft Jet database engine doesn't support the use of CREATE TABLE, or any of the data definition language (DDL) statements, with non-Jet database engine databases. Use the data access object Create methods instead.

Syntax

CREATE TABLE table (field1 type [(size)] [index1] [, field2 type [(size)]
ú[index2] [, ...]] [, multifieldindex [, ...]])

The CREATE TABLE statement has these parts.

Part | Description
table | The name of the table to be created.
field1, field2 | The name of field or fields to be created in the new table. You must create at least one field.
type | The data type of field in the new table.
size | The field size in characters (Text and Binary fields only).
index1, index2 | A CONSTRAINT clause defining a single-field index. See the CONSTRAINT clause topic for more information on how to create this index.
multifieldindex | A CONSTRAINT clause defining a multiple-field index. See the CONSTRAINT clause topic for more information on how to create this index.

Remarks

You can use the CREATE INDEX statement to create indexes on existing tables.

See Also

ALTER TABLE Statement, CONSTRAINT Clause, CREATE INDEX Statement, DROP Statement.

Example

This example creates a new table called ThisTable with two Text fields.

CREATE TABLE ThisTable (FirstName TEXT, LastName TEXT);
This example creates a new table called MyTable with two Text fields, a Date/Time field, and a unique index made up of all three fields.

CREATE TABLE MyTable (FirstName TEXT, LastName TEXT, DateOfBirth DATETIME,
CONSTRAINT MyTableConstraint UNIQUE (FirstName, LastName, DateOfBirth));
This example creates a new table with two Text fields and an Integer field. The SSN field is the primary key.

CREATE TABLE NewTable (FirstName TEXT, LastName TEXT, SSN INTEGER CONSTRAINT MyFieldConstraint PRIMARY KEY);


DELETE Statement

Description

Creates a delete query that removes records from one or more of the tables listed in the FROM clause that satisfy the WHERE clause.

Syntax

DELETE [table.*]
FROM table
WHERE criteria

The DELETE statement has these parts.

Part | Description
table | The optional name of the table from which records are deleted.
table | The name of the table from which records are deleted.
criteria | An expression that determines which records to delete.

Remarks

DELETE is especially useful when you want to delete many records.

To drop an entire table from the database, you can use the Execute method with a DROP statement. If you delete the table, however, the structure is lost. In contrast, when you use DELETE, only the data is deleted; the table structure and all of the table properties, such as field attributes and indexes, remain intact.

You can use DELETE to remove records from tables that are in a one-to-many relationship with other tables. Cascade delete operations cause the records in tables that are on the many side of the relationship to be deleted when the corresponding record in the one side of the relationship is deleted in the query. For example, in the relationship between the Customers and Orders tables, the Customers table is on the one side and the Orders table is on the many side of the relationship. Deleting a record from Customers results in the corresponding Orders records being deleted if the cascade delete option is specified.

A delete query deletes entire records, not just data in specific fields. If you want to delete values in a specific field, create an update query that changes the values to Null.

Important

  • After you remove records using a delete query, you can't undo the operation. If you want to know which records were deleted, first examine the results of a select query that uses the same criteria, and then run the delete query.
  • Maintain backup copies of your data at all times. If you delete the wrong records, you can retrieve them from your backup copies.
 See Also

DROP Statement, FROM Clause, IN Clause, INNER JOIN Operation, SELECT Statement, UPDATE Statement, WHERE Clause.

Specifics (Microsoft Access)

In Microsoft Access, no query output or datasheet is produced when you use the DELETE statement. If you want to know which records will be deleted, first view the datasheet of a select query that uses the same criteria, and then run a delete query.

Example

Some of the following examples assume the existence of a hypothetical Payroll table.

This example deletes all records for employees whose title is Trainee. When the FROM clause includes only one table, you don't have to list the table name in the DELETE statement.

DELETE * FROM Employees WHERE Title = 'Trainee';
This example deletes all records for employees whose title is Trainee and who also have a record in the Payroll table. The Employees and Payroll tables have a one-to-one relationship.

DELETE Employees.* FROM Employees INNER JOIN Payroll
ON Employees.EmployeeID = Payroll. EmployeeID
WHERE Employees.Title = 'Trainee';


DISTINCT, DISTINCTROW Predicates

See ALL, DISTINCT, DISTINCTROW, TOP Predicates.


DROP Statement

Description

Deletes an existing table from a database or deletes an existing index from a table.

Note

The Microsoft Jet database engine doesn't support the use of DROP, or any of the data definition language (DDL) statements, with non-Jet databases. Use the data access object Create methods instead.

Syntax

DROP {TABLE table | INDEX index ON table}

The DROP statement has these parts.

Part | Description
table | The name of the table to be deleted or the table from which an index is to be deleted.
index | The name of the index to be deleted from table.

Remarks

You must close the table before you can delete it or remove an index from it.

You can also use ALTER TABLE to delete an index from a table.

You can use CREATE TABLE to create a table and CREATE INDEX or ALTER TABLE to create an index. To modify a table, use ALTER TABLE.

See Also

ALTER TABLE Statement, CONSTRAINT Clause, CREATE INDEX Statement, CREATE TABLE Statement.

Example

The following examples assume the existence of a hypothetical MyIndex index and a hypothetical Trainees table. Note that these objects do not actually exist in the Northwind database.

This example deletes the index MyIndex from the Employees table.

DROP INDEX MyIndex ON Employees;
This example deletes the Trainees table from the database.

DROP TABLE [Trainees];


First, Last Functions

Description

Return a field value from the first or last record in the result set returned by a query.

Syntax

First(expr)
Last(expr)

The expr placeholder represents a string expression identifying the field that contains the data you want to use or an expression that performs a calculation using the data in that field. Operands in expr can include the name of a table field, a constant, or a function (which can be either intrinsic or user-defined but not one of the other SQL aggregate or domain aggregate functions).

Remarks

The First and Last functions can be thought of as analogous to the MoveFirst and MoveLast methods of a Recordset object. They simply return the value of a specified field in the first or last record, respectively, of the result set returned by a query. Since records are normally returned in no particular order (unless the query includes an ORDER BY clause), the records returned by these functions will be arbitrary.

See Also

SQL Aggregate Functions.

Specifics (Microsoft Access)

In Microsoft Access, you can use the First and Last functions in the query design grid, in an SQL statement in SQL view of the Query window, or in an SQL statement within Visual Basic code. You can also use the First and Last functions in a calculated control on a form or report.

The First and Last functions are most useful in calculated controls on a report. For example, if you have an Order report that is grouped on a ShipCountry field and sorted on an OrderDate field, you can use the First and Last functions in calculated controls to show the range of earliest to latest order dates for each grouping. To group on the ShipCountry field, click on the Sorting And Grouping button on the Reports toolbar. Choose ShipCountry in the Field/Expression column, and set the GroupHeader and GroupFooter properties to Yes. In Design view, create two new text boxes in the ShipCountry footer, and set the ControlSource property for both to the following expressions.

= First([OrderDate])
= Last([OrderDate])
When you switch to Print Preview, you will see the first and last order dates for each group of orders.

Note

In previous versions of Microsoft Access, the First and Last functions returned the first and last record created, respectively. If you want to return the first or last record in a set of records in Microsoft Access for Windows 95, you should create a query sorted as either Ascending or Descending and set the TopValues property to 1. For more information, see the TopValues property topic. From Visual Basic, you can also create a sorted results set of the query, and use the MoveFirst or MoveLast method to return the first or last record in a set of records.

Example

This example uses the Employees table to return the values from the LastName field of the first and last records returned from the table.

SELECT First(LastName), Last(LastName) FROM Employees;
The next two examples compare using the First and Last functions with simply using the Min and Max functions to find the earliest and latest birth dates of Employees.

SELECT First(BirthDate), Last(BirthDate) FROM Employees;

SELECT Min(BirthDate), Max(BirthDate) FROM Employees;


FROM Clause

Description

Specifies the tables or queries that contain the fields listed in the SELECT statement.

Syntax

SELECT fieldlist
FROM tableexpression [IN externaldatabase]

A SELECT statement containing a FROM clause has these parts.

Part | Description
fieldlist | The name of the field or fields to be retrieved along with any field-name aliases, SQL aggregate functions, selection predicates (ALL, DISTINCT, DISTINCTROW, or TOP), or other SELECT statement options.
tableexpression | An expression that identifies one or more tables from which data is retrieved. The expression can be a single table name, a saved query name, or a compound resulting from an INNER JOIN, LEFT JOIN, or RIGHT JOIN.
externaldatabase | The full pathname of an external database containing all the tables in tableexpression.

Remarks

FROM is required and follows any SELECT statement.

The order of the table names in tableexpression isn't important.

For improved performance and ease of use, it's recommended that you use an attached table instead of an IN clause to retrieve data from an external database.

The following example shows how you can retrieve data from the Employees table:

SELECT LastName, FirstName
FROM Employees;
See Also

IN Clause; INNER JOIN Operation; LEFT JOIN, RIGHT JOIN Operations; SQL Aggregate Functions; WHERE Clause.

Specifics (Microsoft Access)

If you include a query or table name in the FROM clause of a SQL statement, that query or table will be automatically added to the Query window.

Conversely, any table or query that you add to the Query window will be included in the FROM clause of the corresponding SQL statement.


GROUP BY Clause

Description

Combines records with identical values in the specified field list into a single record. A summary value is created for each record if you include an SQL aggregate function, such as Sum or Count, in the SELECT statement.

Syntax

SELECT fieldlist
FROM table
WHERE criteria
GROUP BY groupfieldlist

A SELECT statement containing a GROUP BY clause has these parts.

Part | Description
fieldlist | The name of the field or fields to be retrieved along with any field-name aliases, SQL aggregate functions, selection predicates (ALL, DISTINCT, DISTINCTROW, or TOP), or other SELECT statement options.
table | The name of the table from which records are retrieved. For more information, see the FROM clause.

Part | Description
criteria | Selection criteria. If the statement includes a WHERE clause, the Microsoft Jet database engine groups values after applying the WHERE conditions to the records.
groupfieldlist | The names of up to 10 fields used to group records. The order of the field names in groupfieldlist determines the grouping levels from the highest to the lowest level of grouping.

Remarks

GROUP BY is optional.

Summary values are omitted if there is no SQL aggregate function in the SELECT statement.

Null values in GROUP BY fields are grouped and aren't omitted. However, Null values aren't evaluated in any SQL aggregate function.

Use the WHERE clause to exclude rows you don't want grouped, and use the HAVING clause to filter records after they've been grouped.

Unless it contains Memo or OLE Object data, a field in the GROUP BY field list can refer to any field in any table listed in the FROM clause, even if the field isn't included in the SELECT statement, provided the SELECT statement includes at least one SQL aggregate function. The Jet database engine can't group on Memo or OLE Object fields.

All fields in the SELECT field list must either be included in the GROUP BY clause or be included as arguments to an SQL aggregate function.

See Also

HAVING Clause, ORDER BY Clause, SELECT Statement, SELECT...INTO Statement, SQL Aggregate Functions.

Specifics (Microsoft Access)

Including a GROUP BY clause in an SQL statement is equivalent to creating a totals query in the Query window and setting the Total cell to Group By for the appropriate field.

Example

Some of the following examples assume the existence of a hypothetical Department field in an Employees table.

This example creates a list of unique department names and the number of employees in each of those departments.

SELECT Department, Count([Department]) AS Tally FROM Employees
GROUP BY Department;
For each unique job title, this example calculates the number of Sales department employees who have that title.

SELECT Title, Count(Title) AS Tally FROM Employees
WHERE Department = 'Sales' GROUP BY Title;

This example calculates the number of items in stock for each combination of item number and color.

SELECT Item, Sum(Units) AS Tally FROM ItemsInStock GROUP BY Item, Color;


HAVING Clause

Description

Specifies which grouped records are displayed in a SELECT statement with a GROUP BY clause. After GROUP BY combines records, HAVING displays any records grouped by the GROUP BY clause that satisfy the conditions of the HAVING clause.

Syntax

SELECT fieldlist
FROM table
WHERE selectcriteria
GROUP BY groupfieldlist
HAVING groupcriteria

A SELECT statement containing a HAVING clause has these parts.

Part | Description
fieldlist | The name of the field or fields to be retrieved along with any field-name aliases, SQL aggregate functions, selection predicates (ALL, DISTINCT, DISTINCTROW, or TOP), or other SELECT statement options.
table | The name of the table from which records are retrieved. For more information, see the FROM clause.
selectcriteria | Selection criteria. If the statement includes a WHERE clause, the Microsoft Jet database engine groups values after applying the WHERE conditions to the records.
groupfieldlist | The names of up to 10 fields used to group records. The order of the field names in groupfieldlist determines the grouping levels from the highest to the lowest level of grouping.
groupcriteria | An expression that determines which grouped records to display.

Remarks

HAVING is optional.

HAVING is similar to WHERE, which determines which records are selected. After records are grouped with GROUP BY, HAVING determines which records are displayed:

SELECT CategoryID,Sum(UnitsIn Stock)
FROM Products
GROUP BY CategoryID
HAVING Sum(UnitsIn Stock) > 100 AND LIKE BOS*;
A HAVING clause can contain up to 40 expressions linked by logical operators, such as And and Or.

See Also

GROUP BY Clause, SELECT Statement, SELECT...INTO Statement, SQL Aggregate Functions.

Example

Some of the following examples assume the existence of a hypothetical Department field in an Employees table.

This example selects the job titles in the Production department assigned to more than 50 employees.

SELECT Title, Count(Title) FROM Employees
WHERE Department = 'Production' GROUP BY Title HAVING Count(Title) > 50;
This example selects departments with more than 100 employees.

SELECT Department, Count([Department]) FROM Employees
GROUP BY Department HAVING Count(Department) > 100;


IN Clause

Description

Identifies tables in any external database to which the Microsoft Jet database engine can connect, such as a dBASE or Paradox database or an external Jet database.

Syntax

To identify a destination table:

[SELECT | INSERT] INTO destination
IN{path | ["path" "type"] | ["" [type; DATABASE = path]]}

To identify a source table:

FROM tableexpression
IN {path | ["path" "type"] | ["" [type; DATABASE = path]]}

A SELECT statement containing an IN clause has these parts.

Part | Description
destination | The name of the external table into which data is inserted.
tableexpression | The name of the table or tables from which data is retrieved. This argument can be a single table name, a saved query, or a compound resulting from an INNER JOIN, LEFT JOIN, or RIGHT JOIN.
path | The full path for the directory or file containing table.
type | The name of the database type used to create table if a database isn't a Jet database (for example, dBASE III, dBASE IV, Paradox 3.x, Paradox 4.x, or Btrieve).

Remarks

You can use IN to connect to only one external database at a time.

In some cases, the path argument refers to the directory containing the database files. For example, when working with dBASE, FoxPro, or Paradox database tables, the path argument specifies the directory containing .dbf or .db files. The table filename is derived from the destination or tableexpression arguments.

To specify a non-Jet database, append a semicolon (;) to the name, and enclose it in single (' ') or double (" ") quotation marks. For example, either 'dBASE IV;' or "dBASE IV;" is acceptable.

You can also use the DATABASE reserved word to specify the external database. For example, the following lines specify the same table:

... FROM Table IN  "" [dBASE IV; DATABASE=C:\DBASE\DATA\SALES;];
... FROM Table IN "C:\DBASE\DATA\SALES" "dBASE IV;"
Notes

  • For improved performance and ease of use, use an attached table instead of IN.
  • You can also use the IN reserved word as a comparison operator in an expression. For more information, see the In operator.
 See Also

FROM Clause, INSERT INTO Statement, SELECT Statement, SELECT...INTO Statement, SQL Aggregate Functions.

Example

The following table shows how you can use the IN clause to retrieve data from an external database. In each example, assume the hypothetical Customers table is stored in an external database.

External database SQL statement
Microsoft Jet database.
MYDATA.mdb is the name of the Jet database that contains the Customers table.
SELECT CustomerID
FROM Customers
IN MYDATA.mdb
WHERE CustomerID Like "A*";
dBASE III or IV.
To retrieve data from a dBASE III table, substitute "dBASE III" for "dBASE IV;".
SELECT CustomerID
FROM Customer
IN "C:\DBASE\DATA\SALES" "dBASE IV;"
WHERE CustomerID Like "A*";
dBASE III or IV using DATABASE syntax.
To retrieve data from a dBASE III table, substitute "dBASE III" for "dBASE IV;".
SELECT CustomerID
FROM Customer
IN "" [dBASE IV; DATABASE=C:\DBASE\DATA\SALES;]
WHERE CustomerID Like "A*";
Paradox 3.x or 4.x.
To retrieve data from a Paradox version 3.x table, substitute "Paradox 3.x;" for "Paradox 4.x;".
SELECT CustomerID
FROM Customer
IN "C:\PARADOX\DATA\SALES" "Paradox 4.x;"
WHERE CustomerID Like "A*";
Paradox 3.x or 4.x using DATABASE syntax.
To retrieve data from a Paradox version 3.x table, substitute "Paradox 3.x;" for "Paradox 4.x;".
SELECT CustomerID
FROM Customer
IN "" [Paradox 4.x;DATABASE=C:\PARADOX\DATA\SALES;]
WHERE CustomerID Like "A*";


In Operator

Description

Determines whether the value of an expression is equal to any of several values in a
specified list.

Syntax

expr [Not] In(value1, value2, . . .)

Remarks

The In operator uses the following arguments.

Argument | Description
expr | Expression identifying the field that contains the data you want to evaluate.
value1, value2 | Expression or list of expressions against which you want to evaluate expr.

If expr is found in the list of values, the In operator returns True ( – 1); otherwise, it returns False (0). You can include the Not logical operator to evaluate the opposite condition (that is, whether expr is not in the list of values).

You might use In to determine which orders are shipped to a set of specified regions:

SELECT *
FROM Orders
WHERE ShipRegion In ('Avon','Glos','Som')
See Also

SQL Expressions.

Specifics (Microsoft Access)

In Microsoft Access, you can use the In operator in a query expression or in a calculated control on a form or report.

You can use the In operator in a query expression when you need to set a number of criteria. For example, suppose you have an Orders table with both a ShipCountry field and an OrderID field, and you want to create a query to show all orders sent to the United States, Canada, or the United Kingdom. Create a new query in the Query window and add the Orders table. Drag the OrderID field and the ShipCountry field to the query design grid. Enter the following expression in the Criteria cell below the ShipCountry field.

In('USA', 'Canada', 'UK')
When you run the query, you will see all orders shipped to one of these three countries.

You can achieve the same result by entering the following expression in the Criteria cell.

"USA" Or "Canada" Or "UK"
With a long list of criteria, it may be more convenient to use the In operator than the Or operator. In addition, the SQL statement for the expression containing the In operator is shorter.

You can use the In operator in a calculated control to determine whether the value of a field in the current record is within a set of values. For example, you might use the In operator with the IIf function to determine whether the value of a control is among a set of specified values. In the following example, if the ShipRegion is WA, OR, or ID, the IIf function returns "Local." Otherwise, it returns "Nonlocal."

= IIf([ShipRegion] In ('WA','OR','ID'), "Local", "Nonlocal")
Example

The following example uses the Orders table in the Northwind.mdb database to create a query that includes orders shipped to Avon, Gloucester, and Somerset.

SELECT * FROM Orders WHERE ShipRegion In ('Avon','Glos','Som');


INNER JOIN Operation

Description

Combines records from two tables whenever there are matching values in a common field.

Syntax

FROM table1 INNER JOIN table2 ON table1.field1 compopr table2.field2

The INNER JOIN operation has these parts.

Part | Description
table1, table2 | The names of the tables from which records are combined.
field1, field2 | The names of the fields that are joined. If they aren't numeric, the fields must be of the same data type and contain the same kind of data, but they don't have to have the same name.
compopr | Any relational comparison operator: =, <, >, <=, >=, or <>.

Remarks

You can use an INNER JOIN operation in any FROM clause. These are the most common type of join. They combine records from two tables whenever there are matching values in a field common to both tables.

You can use INNER JOIN with the Departments and Employees tables to select all the employees in each department. In contrast, to select all departments (even if some have no employees assigned to them) or all employees (even if some aren't assigned to a department), you can use a LEFT JOIN or RIGHT JOIN operation to create an outer join.

If you try to join fields containing Memo or OLE Object data, an error occurs.

You can join any two numeric fields of like types. For example, you can join on Counter and Long Integer fields because they are like types. However, you cannot join Single and Double types of fields.

The following example shows how you could join the Categories and Products tables on the Category ID field:

SELECT CategoryName, ProductName
FROM Categories INNER JOIN Products
ON Categories.CategoryID = Products.CategoryID;
In the preceding example, Category ID is the joined field, but it isn't included in the query output because it isn't included in the SELECT statement. To include the joined field, include the field name in the SELECT statement — in this case, Categories.CategoryID.

You can also link several ON clauses in a JOIN statement, using the following syntax:

SELECT fields
FROM table1 INNER JOIN table2
ON table1.field1 compopr table2.field1 AND
ON table1.field2 compopr table2.field2) OR
ON table1.field3 compopr table2.field3)];

You can also nest JOIN statements using the following syntax:

SELECT fields
FROM table1 INNER JOIN
(table2 INNER JOIN [( ]table3
[INNER JOIN [( ]tablex [INNER JOIN ...)]
ON table3.field3 compopr tablex.fieldx)]
ON table2.field2 compopr table3.field3)
ON table1.field1 compopr table2.field2;

A LEFT JOIN or a RIGHT JOIN may be nested inside an INNER JOIN, but an INNER JOIN may not be nested inside a LEFT JOIN or a RIGHT JOIN.

See Also

LEFT JOIN, RIGHT JOIN Operations; TRANSFORM Statement; UNION Operation.

Example

This example creates two equi-joins: one between the Order Details and Orders tables and another between the Orders and Employees tables. This is necessary because the Employees table doesn't contain sales data, and the Order Details table doesn't contain employee data. The query produces a list of employees and their total sales.

SELECT DISTINCTROW Sum(UnitPrice * Quantity)
AS [Sales], FirstName & " " & LastName AS Name FROM Employees
INNER JOIN(Orders INNER JOIN [Order Details]
ON Orders.OrderID = [Order Details].OrderID)
ON Employees.EmployeeID = Orders.EmployeeID
GROUP BY FirstName & " " & LastName;


INSERT INTO Statement

Description

Adds a record or multiple records to a table. This is referred as an append query.

Syntax

Multiple-record append query:

INSERT INTO target [IN externaldatabase] [(field1[, field2[, ...]])]
SELECT [source.]field1[, field2[, ...]
FROM tableexpression

Single-record append query:

INSERT INTO target [(field1[, field2[, ...]])]
VALUES (value1[, value2[, ...])

The INSERT INTO statement has these parts.have this part.

Part | Description
target | The name of the table or query to append records to.
externaldatabase | The path to an external database. For a description of the path, see the IN clause.
source | The name of the table or query to copy records from.
field1, field2 | Names of the fields to append data to, if following a target argument, or the names of fields to obtain data from, if following a source argument.
tableexpression | The name of the table or tables from which records are inserted. This argument can be a single table name or a compound resulting from an INNER JOIN, LEFT JOIN, or RIGHT JOIN operation or a saved query.
value1, value2 | The values to insert into the specific fields of the new record. Each value is inserted into the field that corresponds to the value's position in the list: value1 is inserted into field1 of the new record, value2 into field2, and so on. You must separate values with a comma, and enclose text fields in double quotation marks (" ").

Remarks

You can use the INSERT INTO statement to add a single record to a table using the single-record append query syntax as shown above. In this case, your code specifies the name and value for each field of the record. You must specify each of the fields of the record that a value is to be assigned to and a value for that field. When you don't specify each field, the default value or Null is inserted for missing columns. Records are added to the end of the table.

You can also use INSERT INTO to append a set of records from another table or query by using the SELECT... FROM clause as shown above in the multiple-record append query syntax. In this case, the SELECT clause specifies the fields to append to the target table specified.

The source or target table may specify a table or a query. If a query is specified, the Microsoft Jet database engine appends to any and all tables specified by the query.

INSERT INTO is optional but when included, precedes the SELECT statement.

If your destination table contains a primary key, make sure you append unique, non-Null values to the primary key field or fields; if you don't, the Jet database engine won't append the records.

If you append records to a table with a Counter field and you want to renumber the appended records, don't include the Counter field in your query. Do include the Counter field in the query if you want to retain the original values from the field.

Use the IN clause to append records to a table in another database.

To create a new table, use the SELECT... INTO statement instead to create a make-table query.

To find out which records will be appended before you run the append query, first execute and view the results of a select query that uses the same selection criteria.

An append query copies records from one or more tables to another. The tables that contain the records you append aren't affected by the append query.

Instead of appending existing records from another table, you can specify the value for each field in a single new record using the VALUES clause. If you omit the field list, the VALUES clause must include a value for every field in the table; otherwise, the INSERT will fail. Use an additional INSERT INTO statement with a VALUES clause for each additional record you want to create.

See Also

FROM Clause, WHERE Clause.

Specifics (Microsoft Access)

If you create an INSERT INTO...VALUES query in SQL view, save and close the query, and then reopen it, you'll see that Microsoft Access has converted the VALUES clause to a SELECT clause. This doesn't alter the results of the query.

Using the INSERT INTO statement is equivalent to setting the DestinationTable property in the query property sheet in query Design view.

Example

This example selects all records in a hypothetical New Customers table and adds them to the Customers table. (When individual columns are not designated, the SELECT table column names must match exactly those in the INSERT INTO table.)

INSERT INTO Customers SELECT [New Customers].* FROM [New Customers];
This example creates a new record in the Employees table.

INSERT INTO Employees (FirstName,LastName, Title)
VALUES ("Harry", "Washington", "Trainee");

This example selects all trainees from a hypothetical Trainees table who were hired more than 30 days ago and adds their records to the Employees table.

INSERT INTO Employees SELECT Trainees.* FROM Trainees
WHERE HireDate < Now() - 30;


LEFT JOIN, RIGHT JOIN Operations

Description

Combines source-table records when used in any FROM clause.

Syntax

FROM table1 [ LEFT | RIGHT ] JOIN table2
ON table1.field1 compopr table2.field2

The LEFT JOIN and RIGHT JOIN operations have these parts.

Part | Description
table1, table2 | The names of the tables from which records are combined.
field1, field2 | The names of the fields that are joined. The fields must be of the same data type and contain the same kind of data, but they don't need to have the same name.
compopr | Any relational comparison operator: =, <, >, <=, >=, or <>.

Remarks

Use a LEFT JOIN operation to create a left outer join. Left outer joins include all of the records from the first (left) of two tables, even if there are no matching values for records in the second (right) table.

Use a RIGHT JOIN operation to create a right outer join. Right outer joins include all of the records from the second (right) of two tables, even if there are no matching values for records in the first (left) table.

For example, you could use LEFT JOIN with the Departments (left) and Employees (right) tables to select all departments, including those that have no employees assigned to them. To select all employees, including those who aren't assigned to a department, you would use RIGHT JOIN.

The following example shows how you could join the Categories and Products tables on the Category ID field. The query produces a list of all categories, including those that contain no products:

SELECT CategoryName, ProductName
FROM Categories LEFT JOIN Products
ON Categories.CategoryID = Products.CategoryID;
In this example, Category ID is the joined field, but it isn't included in the query results because it isn't included in the SELECT statement. To include the joined field, enter the field name in the SELECT statement — in this case, Categories.CategoryID.

  • Notes
  • To create a query that includes only records in which the data in the joined fields is the same, use an INNER JOIN operation.
  • A LEFT JOIN or a RIGHT JOIN can be nested inside an INNER JOIN, but an INNER JOIN cannot be nested inside a LEFT JOIN or a RIGHT JOIN. See the discussion of nesting in the INNER JOIN topic to see how to nest joins within other joins.
  • You can link multiple ON clauses. See the discussion of clause linking in the INNER JOIN topic to see how this is done.
  • If you try to join fields containing Memo or OLE Object data, an error occurs.
 See Also

INNER JOIN Operation, UNION Operation.

Example

These examples assume the existence of hypothetical Department Name and Department ID fields in an Employees table.

This example selects all departments, including those without employees.

SELECT [Department Name], FirstName & " " & LastName AS Name
FROM Departments LEFT JOIN Employees
ON Departments.[Department ID] = Employees.[Department ID]
ORDER BY [Department Name];
This example selects all employees, including those not assigned to a department.

SELECT LastName & ", " & FirstName AS Name, [Department Name]
FROM Departments RIGHT JOIN Employees
ON Departments.[Department ID] = Employees.[Department ID]
ORDER BY LastName & ", " & FirstName;


Like Operator

Description

Used to compare a string expression to a pattern in an SQL expression.

Syntax

Expression Like "pattern"

The Like operator syntax has these parts.

Part | Description
expression | SQL expression used in a WHERE clause.
pattern | String or character string literal against which expression is compared.

Remarks

You can use the Like operator to find values in a field that match the pattern you specify. For pattern, you can specify the complete value (for example, Like "Smith"), or you can use wildcard characters like those recognized by the operating system to find a range of values (for example, Like "Sm*").

In an expression, you can use the Like operator to compare a field value to a string expression. For example, if you enter Like "C*" in an SQL query, the query returns all field values beginning with the letter C. In a parameter query, you can prompt the user for a pattern to search for.

The following example returns data that begins with the letter P followed by any letter between A and F and three digits:

Like "P[A-F]###"
See Also

SQL Expressions.

Specifics (Microsoft Access)

In Microsoft Access, you can use the Like operator in a query expression, in a macro or module, or in a calculated control on a form or report.

The case sensitivity and character sort order of the Like operator depend on the setting of the New Database Sort Order box on the General tab of the Options dialog box, available by clicking Options on the Tools menu. By default, the New Database Sort Order is set to General, which specifies a case-insensitive sort order for the database.

You can alter the sort order for an individual Visual Basic module by changing the Option Compare statement in the Declarations section of a module. By default the Declarations section is set to Option Compare Database, which specifies the same sort order that currently applies to the rest of the database. If the module doesn't contain an Option Compare statement, the default string-comparison method is Binary, which is case-sensitive.

You can use the Like operator to specify inexact criteria in the query design grid. For example, if you type Like "C*" in the Criteria row of the query design grid, the query returns all field values beginning with the letter C.

In a parameter query, you can use the Like operator to prompt the user for a pattern to search for. For example, suppose you have an Employees table that includes a LastName field. In the Query window, create a new query by adding the Employees table and dragging the LastName field to the grid. Enter the following expression in the Criteria row.

Like [Enter first few letters of name:]&"*"
When the query is run, a dialog box prompts the user with "Enter first few letters of name:". If the user types Sm in the dialog box, the query looks for the pattern Sm* — that is, all names beginning with the letters Sm.

You can use Like in an expression as a setting for the ValidationRule property or as a macro condition. For example, you can restrict data entered in a text box control to an inexact specification. In the ValidationRule property of the text box, enter the following expression.

Like "P[A-F]###"
Data entered in this text box must now begin with the letter P, followed by any letter between A and F and three digits.

Example

This example returns a list of employees whose names begin with the letters A through D.

SELECT * FROM Employees WHERE LastName Like "[A-D]*"
The following table shows how you can use Like to test expressions for different patterns.

Kind of match | Pattern | Match (returns True) | No match (returns False)
Multiple characters | "a*a" | "aa", "aBa", "aBBBa" | "aBC"
 | "*ab*" | "abc", "AABB", "Xab" | "aZb", "bac"
Special character | "a[*]a" | "a*a" | "aaa"
Multiple characters | "ab*" | "abcdefg", "abc" | "cab", "aab"
Single character | "a?a" | "aaa", "a3a", "aBa" | "aBBBa"
Single digit | "a#a" | "a0a", "a1a", "a2a" | "aaa", "a10a"
Range of characters | "[a-z]" | "f", "p", "j" | "2", "&"
Outside a range | "[!a-z]" | "9", "&", "%" | "b", "a"
Not a digit | "[!0-9]" | "A", "a", "&", "~" | "0", "1", "9"
Combined | "a[!b-m]#" | "An9", "az0", "a99" | "abc", "aj0"


Min, Max Functions

Description

Return the minimum or maximum of a set of values contained in a specified field on a query.

Syntax

Min(expr)

Max(expr)

The expr placeholder represents a string expression identifying the field that contains the data you want to evaluate or an expression that performs a calculation using the data in that field. Operands in expr can include the name of a table field, a constant, or a function (which can be either intrinsic or user-defined but not one of the other SQL aggregate or domain aggregate functions).

Remarks

You can use Min and Max to determine the smallest and largest values in a field based on the specified aggregation, or grouping. For example, you could use these functions to return the lowest and highest freight cost. If there is no aggregation specified, then the entire table is used.

You can use Min and Max in a query expression and in the SQL property of a QueryDef object or when creating a Recordset object based on an SQL query.

See Also

SQL Aggregate Functions.

Specifics (Microsoft Access)

In Microsoft Access, you can use the Min and Max functions in the query design grid, in an SQL statement in SQL view of the Query window, or in an SQL statement within Visual Basic code. You can also use the Min and Max functions in a calculated control on a form or report.

The Min and Max functions are most useful in totals queries and crosstab queries. They function the same way whether you create the query in the query design grid or as an SQL statement in SQL view.

In the query design grid, you can create a new totals query by clicking the Totals button on the toolbar. The Total row is then inserted in the grid. You can set the Total cell beneath a field to the aggregate function to perform on the data in that field.

For example, suppose you have an Orders table that has both a Freight field and a ShipCity field. You can create a query that displays the minimum freight cost for orders sent to each city. Create a new totals query, and drag the ShipCity field to the query design grid. The Total cell beneath the ShipCity field should be set to Group By. Drag the Freight field to the query design grid, and set the Total cell beneath it to Min. When you run the query, it will display the minimum freight cost for orders sent to each city.

You can view the SQL statement for this query by switching to SQL view. In this example, Microsoft Access creates the following SQL statement.

SELECT DISTINCTROW Min(Orders.Freight) AS MinOfFreight, Orders.ShipCity
FROM Orders
GROUP BY Orders.ShipCity;
You can also use an SQL statement such as this one within Visual Basic code. For example, using the following code you can create a Recordset object based on the query defined by this SQL statement.

Dim dbs As DatabAse, rst As Recordset, strSQL As String
Set dbs = CurrentDb
strSQL = "SELECT DISTINCTROW Min(Orders.Freight) AS MinOfFreight, "_
    & "Orders.ShipCity FROM Orders GROUP BY Orders.ShipCity;"
Set rst = dbs.OpenRecordset(strSQL)
To use the Min and Max functions in a calculated control, set the control's ControlSource property to an expression containing either of these functions. For example, to display the minimum freight cost for a set of orders in a text box, enter the following expression in the ControlSource property of the text box.

= Min([Freight])
If you use the Min or Max function in a calculated control, you can restrict the set of records against which the function is performed by setting the form's Filter property.

Example

This example uses the Orders table to return the lowest and highest freight charges for orders shipped to the United Kingdom.

SELECT Min(Freight) AS [Low Freight], Max(Freight) AS [High Freight] FROM Orders WHERE ShipCountry = 'UK';
Example (Microsoft Access)

The following example assumes that you have an Orders table that contains fields called Freight and ShipCountry. You can use the Min and Max functions to return the lowest and highest freight charges for orders shipped to the United Kingdom. Enter the following expressions in SQL view in the Query window.

SELECT Min([Freight]) AS [LowFreight] FROM Orders
WHERE [ShipCountry] = 'UK';
SELECT Max([Freight]) AS [HighFreight] FROM Orders
WHERE [ShipCountry] = 'UK';

The next example creates a calculated control that displays the lowest freight charge for all records in the same Orders table. Open a new form and set its RecordSource property to Orders. Enter the following expression in the ControlSource property of a text box on the form. To apply a condition that limits the search to only some records, such as those for orders shipped to the United Kingdom, set the form's Filter property.

= Min([Freight])


ORDER BY Clause

Description

Sorts a query's resulting records on a specified field or fields in ascending or descending order.

Syntax

SELECT fieldlist
FROM table
WHERE selectcriteria
ORDER BY field1 [ASC | DESC ][, field2 [ASC | DESC ][, ...]]

A SELECT statement containing an ORDER BY clause has these parts.

Part | Description
fieldlist | The name of the field or fields to be retrieved along with any field-name aliases, SQL aggregate functions, selection predicates (ALL, DISTINCT, DISTINCTROW, or TOP), or other SELECT statement options.
table | The name of the table from which records are retrieved. For more information, see the FROM clause.
selectcriteria | Selection criteria. If the statement includes a WHERE clause, the Microsoft Jet database engine orders values after applying the WHERE conditions to the records.
field1, field2 | The names of the fields on which to sort records.

Remarks

ORDER BY is optional. However, if you want your data displayed in sorted order, then you must use ORDER BY.

The default sort order is ascending (A to Z, 0 to 9). Both of the following examples sort employee names in last name order:

SELECT LastName, FirstName
FROM Employees
ORDER BY LastName;

SELECT LastName, FirstName
FROM Employees
ORDER BY LastName ASC;
To sort in descending order (Z to A, 9 to 0), add the DESC reserved word to the end of each field you want to sort in descending order. The following example selects salaries and sorts them in descending order:

SELECT LastName, Salary
FROM Employees
ORDER BY Salary DESC, LastName;
If you specify a field containing Memo or OLE Object data in the ORDER BY clause, an error occurs. The Jet database engine doesn't sort on fields of these types.

ORDER BY is usually the last item in an SQL statement.

You can include additional fields in the ORDER BY clause. Records are sorted first by the first field listed after ORDER BY. Records that have equal values in that field are then sorted by the value in the second field listed, and so on.

See Also

ALL, DISTINCT, DISTINCTROW, TOP Predicates; GROUP BY Clause; HAVING Clause; SELECT Statement; SELECT...INTO Statement; SQL Aggregate Functions.

Specifics (Microsoft Access)

In Microsoft Access, an ORDER BY clause sorts the displayed data on a specified field or fields in ascending or descending order. Using an ORDER BY clause is equivalent to selecting Ascending or Descending in a Sort cell in the query design grid.

Example

The SQL statements shown below use the ORDER BY clause to sort records alphabetically and then by category.

This example sorts the records by last name in descending order (Z to A).

SELECT LastName, FirstName FROM Employees ORDER BY LastName DESC;
This example sorts by category ID first, and then by product name.

SELECT CategoryID, ProductName, UnitPrice FROM Products
ORDER BY CategoryID, ProductName;


PARAMETERS Declaration

Description

Declares the name and data type of each parameter in a parameter query.

Syntax

PARAMETERS name datatype [, name datatype [, ...]]

The PARAMETERS declaration has these parts.

Part | Description
name | The name of the parameter. Assigned to the Name property of the Parameter object and used to identify this parameter in the Parameters collection. You can use name as a string that is displayed in a dialog box while your application runs the query. Use brackets ([ ]) to enclose text that contains spaces or punctuation. For example, [Low price] and [Begin report with which month?] are valid name arguments.
datatype | One of the primary Microsoft Jet SQL data types or their synonyms.

Remarks

For queries that you run regularly, you can use a PARAMETERS declaration to create a parameter query. A parameter query can help automate the process of changing query criteria. With a parameter query, your code will need to provide the parameters each time the query is run.

The PARAMETERS declaration is optional but when included precedes any other statement, including SELECT.

If the declaration includes more than one parameter, separate them with commas. The following example includes two parameters:

PARAMETERS [Low price] Currency, [Beginning date] DateTime;
You can use name but not datatype in a WHERE or HAVING clause. The following example expects two parameters to be provided and then applies the criteria to records in the Orders table:

PARAMETERS [Low price] Currency,[Beginning date] DateTime;
SELECT OrderID, OrderAmount
FROM Orders
WHERE OrderAmount > [Low price]
AND OrderDate >= [Beginning date];
Specifics (Microsoft Access)

With a parameter query, Microsoft Access prompts you for the criteria when the query is run. This eliminates the extra step of opening the query in Design view and changing the criteria.

The name argument that you supply with the PARAMETERS declaration provides the text that is displayed in a dialog box when you run the query. Microsoft Access automatically creates this dialog box for you.

Using the PARAMETERS declaration in SQL view is equivalent to defining parameters in the Criteria cell of the query design grid.

Example

This example requires you to provide an employee's last name and then uses that entry as the criteria for the query.

PARAMETERS [Enter a Last Name:] Text; SELECT * FROM Employees
WHERE LastName =  [Enter a Last Name:];
This example requires you to provide a category ID and then uses that entry as the criteria for the query.

PARAMETERS [Enter a Category ID:] Value;
SELECT DISTINCTROW CategoryID, ProductName,
Count([Order Details].OrderID)
AS Tally FROM Products INNER JOIN [Order Details]
ON Products.ProductID = [Order Details].ProductID
GROUP BY CategoryID, ProductName
HAVING CategoryID = [Enter a Category ID:];


PROCEDURE Clause

Description

Defines a name and optional parameters for a query.

Syntax

PROCEDURE name [param1 datatype[, param2 datatype[, ...]]

The PROCEDURE clause has these parts.

Part | Description
name | A name for the procedure. It must follow standard naming conventions.
param1, param2 | One or more field names or parameters. For example:

PROCEDURE Sales_By_Country [Beginning Date] DateTime, [Ending Date] DateTime;
For more information on parameters, see PARAMETERS.
datatype | One of the primary Microsoft Jet SQL data types or their synonyms.

Remarks

An SQL procedure consists of a PROCEDURE clause (which specifies the name of the procedure), an optional list of parameter definitions, and a single SQL statement. For example, the procedure Get_Part_Number might run a query that retrieves a specified part number.

Notes

  • If the clause includes more than one field definition (that is, param-datatype pairs), separate them with commas.
  • The PROCEDURE clause must be followed by an SQL statement (for example, a SELECT or UPDATE statement).
 Specifics (Microsoft Access)

When you copy a PROCEDURE clause into SQL view, Microsoft Access removes the clause from the SQL statement when you switch to another view. Removing the PROCEDURE clause doesn't affect the result of the query. If the PROCEDURE clause includes parameters, Microsoft Access replaces PROCEDURE and name with the PARAMETERS reserved word. The defined parameters aren't removed.

Example

This example names the query "Category_List."

PROCEDURE Category_List; SELECT DISTINCTROW CategoryName, CategoryID FROM Categories ORDER BY CategoryName;
This example names the query "Summary" and includes two parameters. The PROCEDURE clause is changed to the following PARAMETERS declaration:

PARAMETERS [Beginning Date] DateTime,
[Ending Date] DateTime;

PROCEDURE Summary [Beginning Date] DATETIME, [Ending Date] DATETIME; SELECT DISTINCTROW ShippedDate, OrderID, EmployeeID,
Format(ShippedDate, "yyyy") AS Year FROM Orders
WHERE ShippedDate Between [Beginning Date] And [Ending Date];


RIGHT JOIN Operation

See LEFT JOIN, RIGHT JOIN Operations.


SELECT Statement

Description

Instructs the Microsoft Jet database engine to return information from the database as a set of records.

Syntax

SELECT [predicate] { * | table.* | [table.]field1 [AS alias1] [, [table.]field2
[AS alias2] [, ...]]}
FROM tableexpression [, ...] [IN externaldatabase]
[WHERE... ]
[GROUP BY... ]
[HAVING... ]
[ORDER BY... ]
[WITH OWNERACCESS OPTION]

The SELECT statement has these parts.

Part | Description
predicate | One of the following predicates: ALL, DISTINCT, DISTINCTROW, or TOP. You use the predicate to restrict the number of records returned. If none is specified, the default is ALL.
* | Specifies that all fields from the specified table or tables are selected.
table | The name of the table containing the fields from which records are selected.
field1, field2 | The names of the fields to retrieve data from. If you include more than one field, they are retrieved in the order listed.
alias1, alias2 | The names to use as column headers instead of the original column names in table.
tableexpression | The name of the table or tables containing the data you want to retrieve.
externaldatabase | The name of the database containing the tables in tableexpression if not in the current database.

Remarks

To perform this operation, the Jet database engine searches the specified table or tables, extracts the chosen columns, selects rows that meet the criterion, and sorts or groups the resulting rows into the order specified.

SELECT statements don't change data in the database.

SELECT is usually the first word in an SQL statement. Most SQL statements are either SELECT or SELECT... INTO statements.

The minimum syntax for a SELECT statement is:

SELECT fields FROM table

You can use an asterisk (*) to select all fields in a table. The following example selects all of the fields in the Employees table:

SELECT * FROM Employees;

If a field name is included in more than one table in the FROM clause, precede it with the table name and the . (dot) operator. In the following example, the Department field is in both the Employees table and the Supervisors table. The SQL statement selects Department from the Employees table and SupvName from the Supervisors table:

SELECT Employees.Department, Supervisors.SupvName
FROM Employees INNER JOIN Supervisors
WHERE Employees.Department = Supervisors.Department;
When a Recordset object is created, the Jet database engine uses the table's field name as the Field object name in the Recordset object. If you want a different field name or a name isn't implied by the expression used to generate the field, use the AS reserved word. The following example uses the title Birth to name the returned Field object in the resulting Recordset object:

SELECT BirthDate
AS Birth FROM Employees;
Whenever you use aggregate functions or queries that return ambiguous or duplicate Field object names, you must use the AS clause to provide an alternate name for the Field object. The following example uses the title Head Count to name the returned Field object in the resulting Recordset object:

SELECT COUNT(EmployeeID)
AS HeadCount FROM Employees;
You can use the other clauses in a SELECT statement to further restrict and organize your returned data. For more information, see the topic for the clause you're working with.

See Also

ALL, DISTINCT, DISTINCTROW, TOP Predicates; DELETE Statement, FROM Clause, GROUP BY Clause, HAVING Clause, IN Clause, INSERT INTO Statement, ORDER BY Clause, SELECT...INTO Statement, SQL Aggregate Functions, UNION Operation, UPDATE Statement, WHERE Clause, WITH OWNERACCESS OPTION Declaration.

Specifics (Microsoft Access)

In Microsoft Access, if you are working in SQL view in the Query window, field names (field1, field2) are used as column headings in Datasheet view. To display a different column heading for a column in the Datasheet, use the AS reserved word. If you use the AS reserved word, then the alias1, alias2 arguments provide the column names to use in displaying the retrieved data in Datasheet view. Using the AS clause is equivalent to setting the Alias property in the field list property sheet in query Design view.

The following example uses the title "Birthday" to head the column in the resulting datasheet.

SELECT [BirthDate] AS Birthday FROM Employees;

When using aggregate functions or queries that return ambiguous or duplicate field names, you must use the AS clause to provide an alternate name for the field. The following example creates the column heading "Head Count" in Datasheet view.

SELECT COUNT([EmployeeID])
AS [HeadCount] FROM Employees;

If you are working with data access objects in Visual Basic code, the field1, field2 arguments are used to name the Field objects in the Recordset object returned by the query. If you include the AS keyword, then the alias1, alias2 arguments provide the column headings to return as Field object names in the resulting Recordset object.

Example

Some of the following examples assume the existence of a hypothetical Salary field in an Employees table.

This example selects the LastName and FirstName fields of all records in the Employees table.

SELECT LastName, FirstName FROM Employees;

This example selects all fields from the Employees table.

SELECT Employees.* FROM Employees;

This example counts the number of records that have an entry in the PostalCode field and names the returned field Tally.

SELECT Count(PostalCode) AS Tally FROM Customers;

This example shows what the salary would be if each employee received a 10 percent raise. It doesn't change the original salary amounts.

SELECT LastName, Salary AS Current, Salary * 1.1 AS Proposed
FROM Employees;

This example places the title Name at the top of the LastName column. The title Salary is displayed at the top of the Salary column.

SELECT LastName AS Name, Salary FROM Employees;

This example shows the number of employees and the average and maximum salaries.

SELECT Count(*) AS [Total Employees], Avg(Salary)
AS [Average Salary], Max(Salary) AS [Maximum Salary] FROM Employees;

For each record, this example shows the LastName and Salary in the first and last fields. The string "has a salary of" is returned as the middle field of each record.

SELECT LastName, 'has a salary of', Salary FROM Employees;


SELECT...INTO Statement

Description

Creates a make-table query.

Syntax

SELECT field1[, field2[, ...]] INTO newtable [IN externaldatabase]
FROM source

The SELECT...INTO statement has these parts.

Part | Description
field1, field2 | The name of the fields to be copied into the new table.
newtable | The name of the table to be created. It must conform to standard naming conventions. If newtable is the same as the name of an existing table, a trappable error will result.
externaldatabase | The path to an external database. For a description of the path, see the IN clause.
source | The name of the existing table from which records are selected. This can be single or multiple tables or a query.

Remarks

You can use make-table queries to archive records, make backup copies of your tables, or make copies to export to another database or to use as a basis for reports that display data for a particular time period. For example, you could produce a Monthly Sales by Region report by running the same make-table query each month.

Notes

  • You may want to define a primary key for the new table. When you create the table, the fields in the new table inherit the data type and field size of each field in the query's underlying tables, but no other field or table properties are transferred.
  • To add data to an existing table, use the INSERT INTO statement instead to create an append query.
  • To find out which records will be selected before you run the make-table query, first examine the results of a SELECT statement that uses the same selection criteria.
 See Also

ALL, DISTINCT, DISTINCTROW, TOP Predicates; FROM Clause; IN Clause; SELECT Statement; UNION Operation; WHERE Clause.

Example

Some of the following examples assume the existence of a hypothetical Salary field in a Payroll table.

This example selects all records in the Employees table and copies them into a new table named Emp Backup.

SELECT Employees.* INTO [Emp Backup] FROM Employees;
This example creates a new table called Trainees that contains only employee records that have the title Trainee.

SELECT Employees.FirstName, LastName INTO Trainees FROM Employees
WHERE Title = 'Trainee';
This example makes a copy of the Employees table and places the new table in the hypothetical database BACKUP.MDB.

SELECT Employees.* INTO Employees IN "BACKUP.MDB" FROM Employees;
This example creates a new table that contains employee and payroll data for all trainees. The Employees and Payroll tables have a one-to-one relationship. The new table contains all of the data from the Employees table plus the Salary field from the Payroll table.

SELECT Employees.*, Salary INTO Trainees FROM Employees
INNER JOIN Payroll ON Employees.EmployeeID = Payroll.EmployeeID
WHERE Title = 'Trainee';


SQL Aggregate Functions

Description

Using the SQL aggregate functions, you can determine various statistics on sets of values. You can use these functions in a query and aggregate expressions in the SQL property of a QueryDef object or when creating a Recordset object based on an SQL query.

SQL Aggregate Functions

Avg Function

Count Function

Min, Max Functions

StDev, StDevP Functions

Sum Function

Var, VarP Functions

Specifics (Microsoft Access)

The SQL aggregate functions are similar to the domain aggregate functions, but they are used in different contexts. In Microsoft Access, you can use the SQL aggregate functions in an SQL statement that you create in the SQL view of the Query window, or in an SQL statement within Visual Basic code. Conversely, domain aggregate functions can be called directly from Visual Basic code.

You can use both SQL aggregate and domain aggregate functions in query expressions in the query design grid. SQL aggregate functions are most useful in totals queries and crosstab queries.

You can also use both types of aggregate functions in a calculated control on a form or report.


SQL Expressions

Description

An SQL expression is a string that makes up all or part of an SQL statement. For example, the FindFirst method on a Recordset object uses an SQL expression, consisting of the selection criteria found in an SQL WHERE clause.

The Microsoft Jet Database Engine uses the Visual Basic for Applications (or VBA) expression service to perform simple arithmetic and function evaluation. All of the expressions operators used in Jet database engine SQL expressions (except Between, In, and Like) are defined by the VBA expression service. In addition, the VBA expression service offers over 100 VBA functions that can be used in SQL expressions. For example, an SQL query composed in the SQL View of the Microsoft Access Query Design window can use these VBA functions, and so can an SQL query used in the DAO OpenRecordset method in Microsoft Visual C++™, Microsoft Visual Basic, and Microsoft Excel code.

Specifics (Microsoft Access)

You can use many Visual Basic functions in SQL strings while in Visual Basic code, in SQL view of the Query window, or in the query design grid.

For example, you can include Visual Basic functions in an SQL statement that you use to define a QueryDef object or a dynaset-type or snapshot-type Recordset object. In the Microsoft Access query design grid, you can include Visual Basic functions in criteria expressions, or in a calculated field expression.

Example (Microsoft Access)

The following example creates a dynaset-type Recordset object from an SQL statement. The SQL statement includes the Year function in a WHERE clause to return only records for orders placed in 1995.

Sub Orders95()
    Dim dbs As Database, rst As Recordset, strSQL As String
    Dim fld As Field

    Set dbs = CurrentDb
    strSQL = "SELECT DISTINCTROW OrderID, OrderDate " & _
        "FROM Orders WHERE ((Year([OrderDate])=1995));"
    Set rst = dbs.OpenRecordset(strSQL, dbOpenDynaset)
    rst.MoveLast
    Debug.Print rst.RecordCount
End Sub
The next example shows how you can include a Visual Basic function in an SQL statement in SQL view in the Query window. The following SQL statement defines a query that displays the ShipName field from an Orders table, calculates the number of characters in that field for each record using the Len function, and displays that calculation in another column.

SELECT DISTINCTROW ShipName, Len([ShipName]) AS LengthOfShipName
FROM Orders;
You can create the same query in the query design grid. Create a new query and add the Orders table. Drag the ShipName field onto the Field cell in the first column in the grid. In another Field cell, create a calculated field expression by entering the following expression.

LengthOfShipName: Len([ShipName])


SQL Subqueries

Description

A subquery is a SELECT statement nested inside a SELECT, SELECT... INTO, INSERT...INTO, DELETE, or UPDATE statement or inside another subquery.

Syntax

You can use three forms of syntax to create a subquery:

comparison [ANY | ALL | SOME] (sqlstatement)

expression [NOT] IN (sqlstatement)

[NOT] EXISTS (sqlstatement)

A subquery has these parts.

Part | Description
comparison | An expression and a comparison operator that compares the expression with the results of the subquery.
expression | An expression for which the result set of the subquery is searched.
sqlstatement | A SELECT statement, following the same format and rules as any other SELECT statement. It must be enclosed in parentheses.

Remarks

You can use a subquery instead of an expression in the field list of a SELECT statement or in a WHERE or HAVING clause. In a subquery, you use a SELECT statement to provide a set of one or more specific values to evaluate in the WHERE or HAVING clause expression.

Use the ANY or SOME predicate, which are synonymous, to retrieve records in the main query that satisfy the comparison with any records retrieved in the subquery. The following example returns all products whose unit price is greater than that of any product sold at a discount of 25 percent or more:

SELECT * FROM Products
WHERE UnitPrice > ANY
(SELECT UnitPrice FROM OrderDetails
WHERE Discount >= .25);
Use the ALL predicate to retrieve only those records in the main query that satisfy the comparison with all records retrieved in the subquery. If you changed ANY to ALL in the above example, the query would return only those products whose unit price is greater than that of all products sold at a discount of 25 percent or more. This is much more restrictive.

Use the IN predicate to retrieve only those records in the main query for which some record in the subquery contains an equal value. The following example returns all products with a discount of 25 percent or more:

SELECT * FROM Products
WHERE ProductID IN
(SELECT ProductID FROM OrderDetails
WHERE Discount >= .25);
Conversely, you can use NOT IN to retrieve only those records in the main query for which no record in the subquery contains an equal value.

Use the EXISTS predicate (with the optional NOT reserved word) in true/false comparisons to determine whether the subquery returns any records.

You can also use table name aliases in a subquery to refer to tables listed in a FROM clause outside the subquery. The following example returns the names of employees whose salaries are equal to or greater than the average salary of all employees having the same job title. The Employees table is given the alias "T1."

SELECT LastName,FirstName, Title, Salary
FROM Employees AS T1
WHERE Salary >=(SELECT Avg(Salary)
FROM Employees
WHERE T1.Title = Employees.Title) Order by Title;
In the preceding example, the AS reserved word is optional.

Some subqueries are allowed in crosstab queries — specifically, as predicates (those in the WHERE clause). Subqueries as output (those in the SELECT list) are not allowed in crosstabs.

See Also

INNER JOIN Operation; LEFT JOIN, RIGHT JOIN Operations; SELECT Statement; SELECT...INTO Statement; UNION Operation.

Example

Some of the following examples assume the existence of a hypothetical Salary field in an Employees table.

This example lists the name, title, and salary of every sales representative whose salary is higher than that of all managers and directors.

SELECT LastName, FirstName, Title, Salary FROM Employees
WHERE Title LIKE "*Sales Rep*" AND Salary > ALL (SELECT Salary
FROM Employees
WHERE (Title LIKE "*Manager*") OR (Title LIKE "*Director*"));
This example lists the name and unit price of every product whose unit price is the same as that of Aniseed Syrup.

SELECT ProductName, UnitPrice FROM Products
WHERE UnitPrice = (SELECT UnitPrice FROM [Products]
WHERE ProductName = "Aniseed Syrup");
This example lists the company and contact of every customer who placed an order in the second quarter of 1995.

SELECT ContactName, CompanyName, ContactTitle, Phone
FROM Customers WHERE CustomerID IN (SELECT CustomerID FROM Orders
WHERE OrderDate BETWEEN #04/1/95# AND #07/1/95#);
This example lists employees whose salary is higher than the average salary for all employees.

SELECT LastName, FirstName, Title, Salary FROM Employees T1
WHERE Salary >= (SELECT AVG(Salary) FROM Employees
WHERE Employees.Title = T1.Title) ORDER BY Title;
This example selects the name of every employee who has booked at least one order. This could also be done with an INNER JOIN.

SELECT FirstName, LastName FROM Employees AS E
WHERE EXISTS (SELECT * FROM Orders AS O
WHERE O.EmployeeID = E.EmployeeID);


StDev, StDevP Functions

Description

Return estimates of the standard deviation for a population or a population sample represented as a set of values contained in a specified field on a query.

Syntax

StDev(expr)

StDevP(expr)

The expr placeholder represents a string expression identifying the field that contains the numeric data you want to evaluate or an expression that performs a calculation using the data in that field. Operands in expr can include the name of a table field, a constant, or a function (which can be either intrinsic or user-defined but not one of the other SQL aggregate or domain aggregate functions).

Remarks

The StDevP function evaluates a population, and the StDev function evaluates a population sample.

If the underlying query contains fewer than two records (or no records, for the StDevP function), these functions return a Null (which indicates that a standard deviation can't be calculated).

You can use the StDev and StDevP functions in a query expression. You can also use this expression in the SQL property of a QueryDef object or when creating a Recordset object based on an SQL query.

See Also

Avg Function, SQL Aggregate Functions, Sum Function.

Specifics (Microsoft Access)

In Microsoft Access, you can use the StDev and StDevP functions in the query design grid, in an SQL statement in SQL view of the Query window, or in an SQL statement within Visual Basic code. You can also use the StDev and StDevP functions in a calculated control on a form or report.

The StDev and StDevP functions are most useful in totals queries and crosstab queries. They function the same way whether you create the query in the query design grid or as an SQL statement in SQL view.

In the query design grid, you can create a new totals query by clicking the Totals button on the toolbar. The Total row is then inserted in the grid. You can set the Total cell beneath a field to the aggregate function to perform on the data in that field.

For example, suppose you have an Orders table that has both a Freight field and a ShipCity field. You can create a query that displays the standard deviation of freight cost for orders sent to each city. Create a new totals query, and drag the ShipCity field to the query design grid. The Total cell beneath the ShipCity field should be set to Group By. Drag the Freight field to the query design grid, and set the Total cell beneath it to StDev. When you run the query, it will display the standard deviation of freight cost for orders sent to each city.

You can view the SQL statement for this query by switching to SQL view. In this example, Microsoft Access creates the following SQL statement.

SELECT DISTINCTROW StDev(Orders.Freight) AS StDevOfFreight, Orders.ShipCity
FROM Orders
GROUP BY Orders.ShipCity;
You can also use an SQL statement such as this one within Visual Basic code. For example, using the following code you can create a Recordset object based on the query defined by this SQL statement.

Dim dbs As DatabAse, rst As Recordset, strSQL As String
Set dbs = CurrentDb
strSQL = "SELECT DISTINCTROW StDev(Orders.Freight) AS StDevOfFreight, "_
    & "Orders.ShipCity FROM Orders GROUP BY Orders.ShipCity;"
Set rst = dbs.OpenRecordset(strSQL)
To use the StDev and StDevP functions in a calculated control, set the control's ControlSource property to an expression containing either of these functions. For example, to display the standard deviation of freight costs for a set of orders in a text box, enter the following expression in the ControlSource property of the text box.

= StDev([Freight])
If you use the StDev or StDevP function in a calculated control, you can restrict the set of records against which the function is performed by setting the form's Filter property.

Example

This example uses the "Orders" table to estimate the standard deviation of the freight charges for orders shipped to the United Kingdom.

SELECT StDev(Freight) AS [Freight Dev] FROM Orders
WHERE ShipCountry = 'UK';

SELECT StDevP(Freight) AS [Freight DevP] FROM Orders
WHERE ShipCountry = 'UK';
Example (Microsoft Access)

The following example assumes that you have an Orders table that contains fields called Freight and ShipCountry. You can use the StDev and StDevP functions to return the standard deviation of freight charges for orders shipped to the United Kingdom. Enter the following expressions in SQL view in the Query window:

SELECT StDev([Freight]) AS [FreightDev] FROM Orders
WHERE [ShipCountry] = 'UK';
SELECT StDevP([Freight]) As [FreightDevP] FROM Orders
WHERE [ShipCountry] = 'UK';

The next example creates a calculated control that displays the standard deviation of freight charges for all records in the same Orders table. Open a new form and set its RecordSource property to Orders. Enter the following expression in the ControlSource property of a text box on the form. To apply a condition that limits the search to only some records, such as those for orders shipped to the United Kingdom, set the form's Filter property.

= StDev([Freight])


Sum Function

Description

Returns the sum of a set of values contained in a specified field on a query.

Syntax

Sum(expr)

The expr placeholder represents a string expression identifying the field that contains the numeric data you want to add or an expression that performs a calculation using the data in that field. Operands in expr can include the name of a table field, a constant, or a function (which can be either intrinsic or user-defined but not one of the other SQL aggregate or domain aggregate functions).

Remarks

The Sum function totals the values in a field. For example, you could use the Sum function to determine the total cost of freight charges.

The Sum function ignores records that contain Null fields. The following example shows how you can calculate the sum of the products of Unit Price and Quantity fields:

SELECT Sum(UnitPrice * Quantity)
AS [Total Revenue] FROM [Order Details];
You can use the Sum function in a query expression. You can also use this expression in the SQL property of a QueryDef object or when creating a Recordset based on an SQL query.

See Also

Count Function, SQL Aggregate Functions.

Specifics (Microsoft Access)

In Microsoft Access, you can use the Sum function in the query design grid, in an SQL statement in SQL view of the Query window, or in an SQL statement within Visual Basic code. You can also use the Sum function in a calculated control on a form or report.

The Sum function is most useful in totals queries and crosstab queries. It functions the same way whether you create the query in the query design grid or as an SQL statement in SQL view.

In the query design grid, you can create a new totals query by clicking the Totals button on the toolbar. The Total row is then inserted in the grid. You can set the Total cell beneath a field to the aggregate function to perform on the data in that field.

For example, suppose you have an Orders table that has both a Freight field and a ShipCity field. You can create a query that displays the sum of freight costs for orders sent to each city. Create a new totals query, and drag the ShipCity field to the query design grid. The Total cell beneath the ShipCity field should be set to Group By. Drag the Freight field to the query design grid, and set the Total cell beneath it to Sum. When you run the query, it will display the sum of freight costs by city.

You can view the SQL statement for this query by switching to SQL view. In this example, Microsoft Access creates the following SQL statement.

SELECT DISTINCTROW Sum(Orders.Freight) AS SumOfFreight, Orders.ShipCity
FROM Orders
GROUP BY Orders.ShipCity;
You can also use an SQL statement such as this one within Visual Basic code. For example, using the following code you can create a Recordset object based on the query defined by this SQL statement.

Dim dbs As DatabAse, rst As Recordset, strSQL As String
Set dbs = CurrentDb
strSQL = "SELECT DISTINCTROW Sum(Orders.Freight) AS SumOfFreight, "_
    & "Orders.ShipCity FROM Orders GROUP BY Orders.ShipCity;"
Set rst = dbs.OpenRecordset(strSQL)
To use the Sum function in a calculated control, set the control's ControlSource property to an expression containing the Sum function. For example, to display the sum of freight costs for a set of orders in a text box, enter the following expression in the ControlSource property of the text box.

= Sum([Freight])
If you use the Sum function in a calculated control, you can restrict the set of records against which the function is performed by setting the form's Filter property.

Example

This example uses the Orders table to calculate the total sales for orders shipped to the United Kingdom.

SELECT Sum(UnitPrice*Quantity) AS [Total UK Sales] FROM Orders
INNER JOIN [Order Details] ON Orders.OrderID = [Order Details].OrderID
WHERE (ShipCountry = 'UK');

Example (Microsoft Access)

The following example assumes that you have an Orders table that contains fields called OrderID and ShipCountry, and an OrderDetails table that contain fields called UnitPrice and Quantity. You can use the Sum function to calculate the total sales for orders shipped to the United Kingdom. Enter the following expression in SQL view in the Query window:

SELECT Sum([UnitPrice]*[Quantity]) AS [TotalUKSales]
FROM Orders INNER JOIN [OrderDetails]
ON Orders.[OrderID] = [OrderDetails].[OrderID]
WHERE ([ShipCountry] = 'UK');
The next example creates a calculated control that displays the total sales for records in the OrderDetails table. Open a new form and set its RecordSource property to Order Details. Enter the following expression in the ControlSource property of a text box on the form. To apply a condition that limits the search to only some records, such as those for orders shipped to the United Kingdom, set the form's Filter property.

= Sum([UnitPrice]*[Quantity])


TOP Predicate

See ALL, DISTINCT, DISTINCTROW, TOP Predicates.


TRANSFORM Statement

Description

Creates a crosstab query.

Syntax

TRANSFORM aggfunction
selectstatement
PIVOT pivotfield [IN (value1[, value2[, ...]])]

The TRANSFORM statement has these parts.

Part | Description
aggfunction | An SQL aggregate function that operates on the selected data.
selectstatement | A SELECT statement.
pivotfield | The field or expression you want to use to create column headings in the query's result set.
value1, value2 | Fixed values used to create column headings.

Remarks

When you summarize data using a crosstab query, you select values from specified fields or expressions as column headings so you can view data in a more compact format than with a select query.

TRANSFORM is optional but when included is the first statement in an SQL string. It precedes a SELECT statement that specifies the fields used as row headings and a GROUP BY clause that specifies row grouping. Optionally, you can include other clauses, such as WHERE, that specify additional selection or sorting criteria. You can also use subqueries as predicates — specifically, those in the WHERE clause — in a crosstab query.

The values returned in pivotfield are used as column headings in the query's result set. For example, pivoting the sales figures on the month of the sale in a crosstab query would create 12 columns. You can restrict pivotfield to create headings from fixed values (value1, value2 ) listed in the optional IN clause. You can also include fixed values for which no data exists to create additional columns.

See Also

FROM Clause, INNER JOIN Operation, ORDER BY Clause.

Example

This example creates a crosstab query that shows product sales by month for a user-specified year. The months are returned from left to right (pivoted) as columns, and the product names are returned from top to bottom as rows.

PARAMETERS [Sales for which year?] LONG;
TRANSFORM Sum([Order Details].Quantity * ([Order Details].UnitPrice -
    ([Order Details].Discount / 100) * [Order Details].UnitPrice))
AS Sales SELECT ProductName FROM Orders INNER JOIN(Products
INNER JOIN [Order Details]
ON Products.ProductID = [Order Details].ProductID)
ON Orders.OrderID = [Order Details].OrderID
WHERE DatePart("yyyy", OrderDate) = [Sales for which year?]
GROUP BY ProductName ORDER BY ProductName
PIVOT DatePart("m", OrderDate);
This example creates a crosstab query that returns product sales by quarter for each supplier for a user-specified year. The quarters are returned from left to right (pivoted) as columns, and the supplier names are returned from top to bottom as rows.

PARAMETERS [Sales for which year?] LONG;
TRANSFORM Sum([Order Details].Quantity * ([Order Details].UnitPrice -
    ([Order Details].Discount / 100) * [Order Details].UnitPrice)) AS Sales
SELECT CompanyName FROM Orders
INNER JOIN ((Suppliers INNER JOIN Products
ON Suppliers.SupplierID = Products.SupplierID)
INNER JOIN [Order Details]
ON Products.ProductID = [Order Details].ProductID)
ON Orders.OrderID = [Order Details].OrderID
WHERE DatePart("yyyy", OrderDate) = [Sales for which year?]

GROUP BY CompanyName ORDER BY CompanyName
PIVOT "Qtr " & DatePart("q", OrderDate) In ('Qtr 1', 'Qtr 2', 'Qtr 3',
'Qtr 4');


UNION Operation

Description

Creates a union query, which combines the results of two or more independent queries or tables.

Syntax

[TABLE] query1 UNION [ALL] [TABLE] query2
[UNION [ALL] [TABLE] query1–n [ ... ]]

The UNION operation has this part.

Part | Description
query1–n | A SELECT statement, the name of a stored query, or the name of a stored table preceded by the TABLE keyword.

Remarks

You can merge the results of two or more queries, tables, and SELECT statements, in any combination, in a single UNION operation. The following example merges an existing table named New Accounts and a SELECT statement:

TABLE [New Accounts] UNION ALL
SELECT *
FROM Customers
WHERE OrderAmount > 1000;
By default, no duplicate records are returned when you use a UNION operation; however, you can include the ALL predicate to ensure that all records are returned. This also makes the query run faster.

All queries in a UNION operation must request the same number of fields; however, the fields don't have to be of the same size or data type.

Use aliases only in the first SELECT clause because they are ignored in any others. In the ORDER BY clause, refer to fields by what they are called in the first SELECT clause.

Notes

  • You can use a GROUP BY and/or HAVING clause in each query argument to group the returned data.
  • You can use an ORDER BY clause at the end of the last query argument to display the returned data in a specified order.
 See Also

ALL, DISTINCT, DISTINCTROW, TOP Predicates; GROUP BY Clause; HAVING Clause; INNER JOIN Operation; LEFT JOIN, RIGHT JOIN Operations; ORDER BY Clause; SELECT Statement; SQL Subqueries; WHERE Clause.

Specifics (Microsoft Access)

In Microsoft Access, the arguments for the UNION operation (query1, query2,...queryn) can be a SELECT statement, the name of a stored Microsoft Access query, or the name of a stored Microsoft Access table preceded by the TABLE reserved word.

You can view a union query only in SQL view, not in the query design grid.

Example

This example retrieves the names and cities of all suppliers and customers in Brazil.

SELECT CompanyName, City FROM Suppliers WHERE Country = "Brazil" UNION SELECT CompanyName, City FROM Customers WHERE Country = "Brazil";
This example retrieves the names and cities of all suppliers and customers located in Brazil, using constants, an alias, and ordering by an alias.

SELECT CompanyName, City, "Supplier" AS Source FROM Suppliers
WHERE Country = "Brazil" UNION SELECT CompanyName, City, "Customer"
FROM Customers WHERE Country = "Brazil" ORDER BY City, Source;
This example retrieves the names and cities of all suppliers and customers in Brazil and the last names and cities of all employees in South America.

SELECT CompanyName, City FROM Suppliers WHERE Country = "Brazil" UNION SELECT CompanyName, City FROM Customers WHERE Country = "Brazil" UNION SELECT LastName, City FROM Employees WHERE Region = "South America";
This example retrieves the names and IDs of all suppliers and customers. This union assumes that there are the same number of columns in each table.

TABLE Customers UNION TABLE Suppliers;


UPDATE Statement

Description

Creates an update query that changes values in fields in a specified table based on specified criteria.

Syntax

UPDATE table
SET newvalue
WHERE criteria;

The UPDATE statement has these parts.

Part | Description
table | The name of the table whose data you want to modify.
newvalue | An expression that determines the value to be inserted into a particular field in the updated records.
criteria | An expression that determines which records will be updated. Only records that satisfy the expression are updated.

Remarks

UPDATE is especially useful when you want to change many records or when the records that you want to change are in multiple tables.

You can change several fields at the same time. The following example increases the Order Amount values by 10 percent and the Freight values by 3 percent for shippers in the United Kingdom:

UPDATE Orders
SET OrderAmount = OrderAmount * 1.1,
Freight = Freight * 1.03
WHERE ShipCountry = 'UK';
UPDATE doesn't generate a result set. If you want to know which records will be changed, first examine the results of a select query that uses the same criteria, and then run the update query.

Specifics (Microsoft Access)

Since the UPDATE statement doesn't generate a result set, there is no query datasheet for Microsoft Access to display a when you use this statement.

If you want to confirm each change, you can use the Replace command on the Edit menu of the form or datasheet rather than an update query.

Example

This example changes values in the ReportsTo field to 5 for all employee records that currently have ReportsTo values of 2.

UPDATE Employees SET ReportsTo = 5 WHERE ReportsTo = 2;
This example increases the UnitPrice for all nondiscontinued products from supplier 8 by 10 percent.

UPDATE Products SET UnitPrice = UnitPrice * 1.1
WHERE SupplierID = 8 AND Discontinued = No;
This example reduces the UnitPrice for all nondiscontinued products supplied by Tokyo Traders by 5 percent. The Products and Suppliers tables have a many-to-one relationship.

UPDATE Suppliers INNER JOIN Products ON Suppliers.SupplierID = Products.SupplierID SET UnitPrice = UnitPrice * .95
WHERE CompanyName = 'Tokyo Traders' AND Discontinued = No;


Var, VarP Functions

Description

Return estimates of the variance for a population or a population sample represented as a set of values contained in a specified field on a query.

Syntax

Var(expr)
VarP(expr)

The VarP function evaluates a population, and the Var function evaluates a population sample.

The expr placeholder represents a string expression identifying the field that contains the numeric data you want to evaluate or an expression that performs a calculation using the data in that field. Operands in expr can include the name of a table field, a constant, or a function (which can be either intrinsic or user-defined but not one of the other SQL aggregate or domain aggregate functions).

Remarks

If the underlying query contains fewer than two records, the Var and VarP functions return a Null (which indicates that a variance can't be calculated).

You can use the Var and VarP functions in a query expression or in an SQL statement.

Specifics (Microsoft Access)

In Microsoft Access, you can use the Var and VarP functions in the query design grid, in an SQL statement in SQL view of the Query window, or in an SQL statement within Visual Basic code. You can also use the Var and VarP functions in a calculated control on a form or report.

The Var and VarP functions are most useful in totals queries and crosstab queries. They function the same way whether you create the query in the query design grid or as an SQL statement in SQL view.

In the query design grid, you can create a new totals query by clicking the Totals button on the toolbar. The Total row is then inserted in the grid. You can set the Total cell beneath a field to the aggregate function to perform on the data in that field.

For example, suppose you have an Orders table that has both a Freight field and a ShipCity field. You can create a query that displays the variance of freight cost for orders sent to each city. Create a new totals query, and drag the ShipCity field to the query design grid. The Total cell beneath the ShipCity field should be set to Group By. Drag the Freight field to the query design grid, and set the Total cell beneath it to Var. When you run the query, it will display the variance of freight cost for orders sent to each city.

You can view the SQL statement for this query by switching to SQL view. In this example, Microsoft Access creates the following SQL statement.

SELECT DISTINCTROW Var(Orders.Freight) AS VarOfFreight, Orders.ShipCity
FROM Orders
GROUP BY Orders.ShipCity;
You can also use an SQL statement such as this one within Visual Basic code. For example, using the following code you can create a Recordset object based on the query defined by this SQL statement.

Dim dbs As DatabAse, rst As Recordset, strSQL As String
Set dbs = CurrentDb
strSQL = "SELECT DISTINCTROW Var(Orders.Freight) AS VarOfFreight, "_
    & "Orders.ShipCity FROM Orders GROUP BY Orders.ShipCity;"
Set rst = dbs.OpenRecordset(strSQL)
To use the Var and VarP functions in a calculated control, set the control's ControlSource property to an expression containing either of these functions. For example, to display the variance across freight costs in a text box, enter the following expression in the ControlSource property of the text box.

= Var([Freight])
If you use the Var or VarP function in a calculated control, you can restrict the set of records against which the function is performed by setting the form's Filter property.

Example

This example uses the Orders table to estimate the variance of freight costs for orders shipped to the United Kingdom.

SELECT Var(Freight) AS [UK Freight Variance] FROM Orders
WHERE ShipCountry = 'UK';

SELECT VarP(Freight) AS [UK Freight VarianceP] FROM Orders
WHERE ShipCountry = 'UK';
Example (Microsoft Access)

The following example assumes that you have an Orders table that contains a field called Freight. You can use the Var and VarP functions to estimate the variance of freight costs for orders shipped to the United Kingdom. Enter the following expressions in SQL view in the Query window:

SELECT Var([Freight]) AS [UKFreightVariance] FROM Orders
WHERE [ShipCountry] = 'UK';
SELECT VarP([Freight]) AS [UKFreightVarianceP] FROM Orders
WHERE [ShipCountry] = 'UK';

The next example creates a calculated control that displays the estimated variance for freight costs for records in the same Orders table. Open a new form and set its RecordSource property to Orders. Enter the following expression in the ControlSource property of a text box on the form. To apply a condition that limits the search to only some records, such as those for orders shipped to the United Kingdom, set the form's Filter property.

= Var([Freight])


WHERE Clause

Description

Specifies which records from the tables listed in the FROM clause are affected by a SELECT, UPDATE, or DELETE statement.

Syntax

SELECT fieldlist
FROM tableexpression
WHERE criteria;

A SELECT statement containing a WHERE clause has these parts.

Part | Description
fieldlist | The name of the field or fields to be retrieved along with any field-name aliases, selection predicates (ALL, DISTINCT, DISTINCTROW, or TOP), or other SELECT statement options.
tableexpression | The name of the table or tables from which data is retrieved.
criteria | An expression that records must satisfy to be included in the query results.

Remarks

The Microsoft Jet database engine selects the records that meet the conditions listed in the WHERE clause. If you don't specify a WHERE clause, your query returns all rows from the table. If you specify more than one table in your query and you haven't included a WHERE clause or a JOIN clause, your query generates a Cartesian product of the tables.

WHERE is optional, but when included, follows FROM. For example, you can select all employees in the sales department (WHERE Dept = 'Sales') or all customers between the ages of 18 and 30 (WHERE Age Between 18 And 30).

If you don't use a JOIN clause to perform SQL join operations on multiple tables, the resulting Recordset object won't be updatable.

WHERE is similar to HAVING. WHERE determines which records are selected. Similarly, once records are grouped with GROUP BY, HAVING determines which records are displayed.

Use the WHERE clause to eliminate records you don't want grouped by a GROUP BY clause.

Use various expressions to determine which records the SQL statement returns. For example, the following SQL statements select all employees whose salaries are more than $21,000:

SELECT LastName, Salary
FROM Employees
WHERE Salary > 21000;
A WHERE clause can contain up to 40 expressions linked by logical operators, such as And and Or.

When you specify the criteria argument, date literals must be in U.S. format, even if you're not using the U.S. version of the Jet database engine. For example, May 10, 1994, is written 10/5/94 in the United Kingdom and 5/10/94 in the United States. Be sure to enclose your date literals with the number sign (#) as shown in the following examples.

To find records dated May 10, 1994 in a United Kingdom database, you must use the following SQL statement:

SELECT *
FROM Orders
WHERE ShippedDate = #5/10/94#;
You can also use the DateValue function which is aware of the international settings established by Microsoft Windows. For example, for code in the United States, you can use:

SELECT *
FROM Orders
WHERE ShippedDate = DateValue('5/10/94');
For code in the United Kingdom, use:

SELECT *
FROM Orders
WHERE ShippedDate = DateValue('10/5/94');
See Also

IN Clause, ORDER BY Clause, SELECT Statement, SELECT...INTO Statement, SQL Aggregate Functions.

Specifics (Microsoft Access)

In Microsoft Access, the conditions that you establish in a WHERE clause in SQL view are the same as those you might enter in the Criteria field in the query design grid. If you enter criteria in the query design grid, you can change to SQL view to see the WHERE clause.

Conversely, if you enter a WHERE clause in an SQL statement in SQL view, you can change to Design view to see the criteria in the query design grid, unless you are creating a union query. Union queries can only be viewed in SQL view.

Example

Some of the following examples assume the existence of a hypothetical Salary field in an Employees table.

This example selects the LastName and FirstName fields of each record in which the last name is King.

SELECT LastName, FirstName FROM Employees WHERE LastName = 'King';
This example selects the LastName and FirstName fields for employees whose last names begin with the letter S.

SELECT LastName, FirstName FROM Employees WHERE LastName Like 'S*';
This example selects employees whose salaries are between $20,000 and $30,000, inclusive.

SELECT LastName, Salary FROM Employees
WHERE Salary Between 20000 And 30000;
This example selects employees whose last names fall in alphabetic order between Lon and Tol, inclusive. It doesn't retrieve Tolstoy because Tolstoy follows Tol and therefore is outside the specified range.

SELECT LastName, Salary FROM Employees
WHERE LastName Between 'Lon' And 'Tol';
This example selects orders placed during the first half of 1994.

SELECT OrderID, OrderDate FROM Orders
WHERE OrderDate Between #1-1-94# And #6-30-94#;
This example selects employees who live in Interlaken, New York, or Frankfurt.

SELECT LastName, FirstName, City FROM Employees
WHERE City In ('Interlaken', 'New York', 'Frankfurt');


WITH OWNERACCESS OPTION Declaration

Description

In a multiuser environment with a secure workgroup, use this declaration with a query to give the user who runs the query the same permissions as the query's owner.

Syntax

sqlstatement
WITH OWNERACCESS OPTION

Remarks

The WITH OWNERACCESS OPTION declaration is optional.

The following example enables the user to view salary information (even if the user doesn't otherwise have permission to view the Payroll table), provided that the query's owner does have that permission:

SELECT LastName,FirstName, Salary
FROM Employees
ORDER BY LastName
WITH OWNERACCESS OPTION;
If a user is otherwise prevented from creating or adding to a table, you can use WITH OWNERACCESS OPTION to enable the user to run a make-table or append query.

If you want to enforce workgroup security settings and users' permissions, don't include the WITH OWNERACCESS OPTION declaration.

This option requires you to have access to the System.mda file associated with the database. It's really useful only in secured multiuser implementations.

See Also

SELECT Statement.

Specifics (Microsoft Access)

You can include the WITH OWNERACCESS OPTION declaration in an SQL statement to allow users to run a query and view the results even if they don't have security permissions on the underlying tables. When this option is set, a user is granted the same permissions as the owner of the query.

For example, the owner of a query on an Employees table can include the WITH OWNERACCESS OPTION declaration in the definition of the query that returns all fields except those that give employees' addresses. A user who does not have read permissions on the Employees table can then run the query and view only those fields included in the query. Effectively, the user now has restricted read access to the table.

Using this declaration is equivalent to setting the RunPermissions property to Owner's in the query property sheet in query Design view. Omitting the declaration is equivalent to setting the RunPermissions property to User's, which is the default setting.


Part 3 Appendix

Appendix Data Access Object Hierarchy

This appendix contains a graphical representation of the Data Access Objects object model. For detailed information on individual objects, see the topic for the object or collection in Part 1 of this book.

Data Access Objects


Advanced VBA in MS Project

Presented by: Glenn Minch

Glenn Minch is president and founder of Critical Path Technical Services, Inc., a Microsoft Solution Provider specializing in developing custom solutions using Microsoft Project, Microsoft Office, and Visual Basic. Glenn can be reached at CPTS, Inc., PO Box 52771, Bellevue, WA 98005. CompuServe ID: 73513,403.

Overview

The addition of Microsoft® Visual Basic® for Applications to Microsoft Project planning software allows developers to quickly create powerful applications that use Microsoft Project as an integral component of the overall solution. In this section, we will take a look at some programming techniques that can be used to construct complex add-on applications for Microsoft Project.

We will also examine an application that was created with Microsoft Project, Microsoft Excel spreadsheet program and Visual Basic for Applications programming system. This application is a "real world" solution that was created to allow the customer to analyze project management data in a way not possible using only Microsoft Project. The resulting information provides a set of standards, or metrics, against which the progress of the project can be measured. Throughout the rest of this paper, we will refer to the sample application as the Project Metrics application.

The Project Metrics application will serve to illustrate the practical usage of Visual Basic for Applications programming techniques. Many of the code fragments included are taken from the Project Metrics application. Although the complete code of the application is not included here, one complete module from the Project Metrics application is included.

The code module included here contains procedures that manage the instance of Microsoft Excel required by the Project Metrics application.

Sample Files

Several sample files are included for this session. The sample files contain all of the code fragments used to illustrate the programming techniques discussed in this paper. The following sample files are included:

· PJ301A.MPP This Microsoft Project 4.0 file contains all of the code samples for this paper. In addition, it contains the complete code module used by the Project Metrics application to manage the instance of Microsoft Excel required for the application. The project schedule was copied from the ROLLOUT.MPT template that is included as a sample with Microsoft Project.

· PJ301B.XLS This is a Microsoft Excel file that contains the dialog box and code used by the GetXLPrefs() procedure. To run the sample code provided, you must copy PJ301B.XLS to the directory containing your Microsoft Project installation (i.e., the directory that contains WINPROJ.EXE).

· PJDEMO.EXE This is a Microsoft Visual Basic 3.0 application that acts as a dialog box for the FormatGantt() macro. This file must also be copied to the same location as WINPROJ.EXE.

· PJDEMO.FRM, PJDEMO.MAK Source code for PJDEMO.EXE.

· STATUS.MPP This Microsoft Project file is used to display status messages during the performance demonstrations.

Programming Techniques

Program Structures

Since this is intended to be an advanced discussion, we will not examine the basic program structures in this paper. However, it is worthwhile to consider the For Each ... Next statement, because there are special issues to be considered when using this statement with certain Microsoft Project object collections.

For Each ... Next

The For Each ... Next statement is used to iterate through a collection of objects. The For Each statement may also be used to iterate through an array. The main thing to keep in mind while using For Each with a Microsoft Project collection is that some collections may contain null members. An example of this can be seen in the following illustration:

{bmc ZCK0A.WPG}

In this illustration, task ID 4 is null. Because of this, the following code will fail with a run-time error 91, "Object variable not Set":

Sub ForEach()

Dim t As Task

For Each t In ActiveProject.Tasks

Debug.Print t.Name

Next t

End Sub

To correct this problem, you must test each member of the collection to be sure that it is valid before using it in an expression. Although the TypeName function could be used to perform the test to determine if an object is valid, it is generally quicker to test to see if the object Is Nothing. The following code illustrates this technique:

Sub ForEach()

Dim t As Task

For Each t In ActiveProject.Tasks

If Not (t Is Nothing) Then

Debug.Print t.Name

End If

Next t

End Sub

The following three collections may contain null members:

· Projects

· Tasks

· Resources

As mentioned above, the For Each statement may also be used to iterate through an array. The following example demonstrates this:

Sub ForEach_Array()

Dim v_array As Variant

Dim v As Variant

v_array = Array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)

For Each v In v_array

Debug.Print v

Next v

End Sub

Note the use of the Array function to create an array using the Variant data type. The For Each statement can be used with any array.

Activating Applications

You will often need to activate another application from your Visual Basic for Applications code. Generally, you’ll activate an application using the AppActivate method.

To use the AppActivate method, you must know the exact text (not case-sensitive) of the title of the application window that you want to activate. Since you won’t always have this information, you can use an application object to get the caption of the window. The following example demonstrates this technique:

''''''''''''''''''''

' Activates Microsoft Excel (Excel must already be running).

'

Sub ActivateExcel()

Dim oExcel As Object

Set oExcel = GetObject(, "Excel.Application.5")

AppActivate oExcel.Caption

End Sub

A more complex example involves checking to see if an instance of Microsoft Excel is already running, and if not, starting Microsoft Excel. Since an instance of Microsoft Excel might be running "invisibly" (that is, Microsoft Excel does not appear in the Microsoft Windows® Task List), we need a way to check for invisible instances of Microsoft Excel. To accomplish this, we’ll use the FindWindow function.

The FindWindow function is a Microsoft Windows API function that is declared as follows:

Declare Function FindWindow Lib "USER" (ByVal lpClassName _ As String, ByVal lpWindowName As Long) As Integer

The FindWindow function will retrieve the window handle of the window whose class name and window name match the arguments passed to FindWindow. If the class name parameter is null, all classes match; similarly, if the window name parameter is null, all window names match. We can take advantage of this fact by passing a null value for the window name parameter, and then passing the class name of the application we want to search for. Note that in the above declaration, the lpWindowName parameter is declared as the Long data type. This is because null pointers are passed as long integers with a value of zero (0&).

The class names for various applications are as follows. Although the class names presented here use a mixture of upper- and lower-case characters for readability, the FindWindow function is not case sensitive.

· Microsoft Project - "JWinproj-WhimperMainClass"

· Microsoft Excel - "XLMain"

· Microsoft Word - "OpusApp"

· Microsoft Access - "OMain"

If FindWindow doesn’t find a window that matches the specified window class name, it will return 0. The following code fragment (taken from the GetXLApp() function of the Project Metrics application) uses FindWindow to check for a current instance of Microsoft Excel.

Const XL_APPCLASS = "Excel.Application.5"

Const XL_WNDCLASS = "xlmain"

Const API_NULL = 0&

'Check to see if excel is running.

hWnd_xl = FindWindow(XL_WNDCLASS, API_NULL)

If hWnd_xl <> 0 Then

'There is at least one instance of Excel available; try 'to obtain obj ref

Set obj_xl_app = GetObject(, XL_APPCLASS)

Else

'Excel is not running. Start Excel and obtain obj ref.

Set obj_xl_app = CreateObject(XL_APPCLASS)

End If

Setting the Mouse Cursor

Unlike Visual Basic 3.0, Visual Basic for Applications does not provide a way to easily set the mouse cursor when you need to indicate that the application is busy. Microsoft Project will simply appear to "hang" during a lengthy operation. Using the Windows API functions LoadCursor and SetCursor, we can change the mouse cursor to the standard hourglass icon.

Include the following declarations and constants in your Visual Basic for Applications module:

Declare Function SetCursor Lib "USER" (ByVal hCursor As _ Integer) As Integer

Declare Function LoadCursor Lib "USER" (ByVal hInstance _ As Integer, ByVal lpCursorName As Any) As Integer

Const INT_NULL = 0

Const IDC_WAIT = 32514&

The following example shows how to set the cursor to the hourglass icon, then restore the cursor to the previous icon:

'''''''''''

' Sets the cursor to the Hourglass icon, then restores the

'previous cursor.

'

Sub SetMousePointer()

Dim hPrevCursor As Integer 'saves a handle to the previous

'cursor resource.

Dim lCounter As Long

Dim nRtn As Integer

' Set the cursor to hourglass and save the previous cursor

hPrevCursor = SetCursor(LoadCursor(INT_NULL, IDC_WAIT))

' Pause a moment so we can see the hourglass...

For lCounter = 1 To 1000000

Next lCounter

' Restore the previous cursor

nRtn = SetCursor(hPrevCursor)

End Sub

Modules

Visual Basic for Applications code is stored in code modules. Modules may be stored in the individual project file (*.MPP) or in the Global file (GLOBAL.MPT). Modules may contain variable and constant declarations in addition to procedures.

Choose an Effective Module Layout

The programmer has considerable latitude regarding the way that a module is organized. The way that a module is organized can help, or hinder, development efforts.

The following example illustrates an effective method of module organization. This example is taken from the Project Metrics application.

' This module contains the procs that are responsible for 'providing xl support functions to the other routines. None of 'the procs in this module manipulate project data.

'

' Procs contained in this module:

' Sub GoToMetrics()

' Function GetUserPref(oXL As Object, utPref As _

' utPrefStruct) As Boolean

' Function GetXLBook(oXLBook As Object, Status As _

' Integer, Optional sTemplate As Variant) As Boolean

' Function GetXLApp(oXLApp As Object) As Boolean

' Function KillXL(Optional xl_obj As Variant) As Boolean

' Sub MakeXLVisible()

The first few lines of each module are a brief description of the contents of the module. This description is important during the development of large projects, and it will assist maintenance programmers during future modifications to the application.

Following the module description is a section that contains the procedure header for every procedure in the module. It is important that the procedure headers exactly match the actual procedures. This header section serves several purposes:

· Immediately indicates what procedures are contained in a given module;

· Allows the programmer to quickly move to a given procedure, by clicking on the name of the procedure using the right mouse button and selecting "Procedure Definition";

· Provides a way to quickly look up the correct order and type of arguments to a given procedure.

The module declarations section should be placed immediately after the initial comments and list of procedures.

' **** BEGIN MODULE DECLARATIONS ****

Option Explicit

Option Compare Text ' Text comparisons are NOT case 'sensitive.

Private obj_xl_app As Object ' This is used to cache a 'reference to the current

'Excel application.

Private obj_xl_book As Object ' This is used to cache a 'reference to the current

'Excel metrics workbook.

' **** END MODULE DECLARATIONS ****

The declarations section should be clearly identified to set it apart from the procedures that follow. Typically, variables declared at the module or global level should have some sort of comment to indicate their purpose.

The Option Private Statement

The VBA_PJ.HLP file included with Microsoft Project states that "The Option Private statement is used at the module level to indicate that the entire module is private." This statement is somewhat misleading, since it implies that all of the data and procedures contained in a module will be private to that module if the Option Private statement is included in the module declarations.

The Option Private statement means that the procedures in a private module cannot be called from procedures located in a module in another project. Procedures contained in the private module can be called from any other modules in the project file where the private module is located.

If a variable is declared in a private module using the Public keyword, that variable will be visible to all other modules in the project. Furthermore, Sub procedures located in a private module will still appear in the list of macros under the Tools menu, Macros option.

The Option Private statement is useful for preventing name conflicts among procedures in different projects, but only if a reference exists between the projects.

Obtaining User Input

Visual Basic for Applications does not implement dialogs, so Microsoft Project does not support user-defined dialog boxes. The primary mechanism for obtaining user input is the InputBox function. Although the InputBox is useful for obtaining simple user input, it does not allow the use of common controls such as option buttons, check boxes, and list boxes.

One solution to this problem is to use a dialog box created in Microsoft Excel or Microsoft Visual Basic 3.0 to obtain user input for your macro. However, this creates a minor dilemma of sorts: How to pass information from the dialog box back to the Microsoft Project macro?

Using Microsoft Excel, you are able to pass arguments to a macro via the application-defined Macro method. Although Microsoft Project supports a Macro method, it does not allow you to pass arguments to the macro.

There are several ways to return user input to the Microsoft Project macro. You could use DDE, OLE, global memory blocks, the Clipboard, or even text files. The method we will examine here uses OLE, and although it is not the fastest method, it is simple to implement and reliable.

The following diagram illustrates the basic concept.

{bmc ZCK1A.WPG}

In this diagram, the following actions occur (in sequence):

1. A Microsoft Project macro uses the AppExecute method to launch a Visual Basic 3.0 form. The Visual Basic form will act as a dialog box to obtain user input for the Microsoft Project macro. The following code is from the example included with this paper:

Sub FormatGantt()

' Display the VB dialog to obtain user input.

AppExecute Command:=Application.Path & "\pjdemo.exe" _ ,Activate:=True

End Sub

2. The Visual Basic form handles the task of obtaining user input. When the user is finished and has selected the OK or Cancel buttons, the Visual Basic form establishes an OLE connection to Microsoft Project.

Dim oProj as Object

Set oProj = GetObject(, "msproject.application")

3. The Visual Basic form sets the value of certain pre-determined fields of the project summary task to the values obtained from the user. In the example provided with this paper (PJDEMO.EXE), the Visual Basic form sets the value of the Text 10 field.

If index = 0 Then 'OK button pressed

oProj.Activeproject.Text10 = cboColor.List(cboColor.ListIndex)

Else 'Cancel button pressed

oProj.Activeproject.Text10 = "Cancel"

End If

4. The Visual Basic form activates Microsoft Project. Then the Visual Basic form uses the Macro method to evoke a Microsoft Project macro that will process the user input. After the Microsoft Project macro is evoked, the Visual Basic form unloads itself from memory.

' Run the Microsoft Project macro to process the user's 'selection

AppActivate oProj.Caption

oProj.macro "DoFormatGantt"

End

5. The Microsoft Project macro examines the user input and takes the appropriate action.

''''''''''''''''

' This sub is called by the VB dialog to process the user's 'selection.

'

Sub DoFormatGantt()

Dim sMsg As String

Dim nColor As Integer

Const pjNoAction = -1

'Check the Text10 property of the project task to determine

'what to do next.

Select Case ActiveProject.Text10

Case "cancel"

sMsg = "User pressed the Cancel button."

nColor = pjNoAction

Case "black"

sMsg = "User selected Black."

nColor = pjBlack

Case "red"

sMsg = "User selected Red."

nColor = pjRed

Case "yellow"

sMsg = "User selected Yellow."

nColor = pjYellow

Case "blue"

sMsg = "User selected Blue."

nColor = pjBlue

Case "green"

sMsg = "User selected Green."

nColor = pjGreen

Case Else

sMsg = "The value returned from the dialog is not valid."

nColor = pjNoAction

End Select

If nColor <> pjNoAction Then GanttBarFormat middlecolor:=nColor

MsgBox sMsg, vbInformation + vbOKOnly, "Format Gantt Bar"

End Sub

This general method can be extended to work with applications other than Visual Basic 3.0. The XL code module included with PJ301A.MPP contains a procedure that calls a Microsoft Excel dialog to obtain user input. The procedure name is GetUserPref().

Project VBA Performance Issues

Measuring Performance

In order to address performance issues in your code, you need to be able to accurately measure the speed of your routines. The GetTickCount function will give us this capability.

GetTickCount is a Windows API function that returns the number of milliseconds that have elapsed since the current session of Windows was started. This function can be declared in a Project code module as:

Declare Function GetTickCount Lib "USER" () As Long

Calculating the difference between this function’s value at the beginning and end of a routine provides an excellent measure of the routine’s performance. The following example illustrates the use of this function in a simple case.

' This sub displays the number of milliseconds required

' to run through a simple For...Next loop.

Sub TimeLoop()

Dim lBegin As Long ' Beginning tick count

Dim lEnd As Long ' Ending tick count

Dim lIndex As Long ' Index for loop

lBegin = GetTickCount()

For lIndex = 1 To 60000

Next lIndex

lEnd = GetTickCount()

MsgBox "Elapsed time: " & (lEnd - lBegin) & " ms."

End Sub

We’ll be using this method throughout this session to illustrate code performance in different situations.

Screen Updating

One of the major performance hits you’ll encounter when creating Microsoft Project macro code is the inability to turn off screen updating while the macro executes. The Microsoft Project Application object does not include a ScreenUpdating property as Microsoft Excel does. Instead, Microsoft Project spends a lot of time refreshing its application window during the execution of your macro. If a graphically intense view such as the Gantt Chart happens to be displayed, this constant screen updating may result in a major performance loss.

To illustrate the effect the current view will have on your macro performance, try the following example. This example runs through the same loop four times, and in each case sets the Flag1 field of every task in the project to True. Each loop is executed while a different view is active. The difference in performance among the different views is displayed in a message box. Note that the test macros do not check for null tasks in order to simplify the code listing. A "real" macro must always check for null tasks.

' This sub sets the Flag1 field of all tasks to True

' in 4 different views.

Sub SetFlagTest1()

Dim tskIndex As Task ' Index for Tasks collection

Dim lBegin As Long ' Beginning tick count

Dim lEnd As Long ' Ending tick count

Dim lGantt As Long ' Time to execute in Gantt view

Dim lTSheet As Long ' Time to execute in Task Sheet view

Dim lRSheet As Long ' Time to execute in Resource Sheet view

Dim lEdit As Long ' Time to execute in Module Editor view

ViewApply "Gantt Chart"

lBegin = GetTickCount()

For Each tskIndex In ActiveProject.Tasks

tskIndex.Flag1 = True

Next tskIndex

lEnd = GetTickCount()

lGantt = lEnd - lBegin

ViewApply "Task Sheet"

lBegin = GetTickCount()

For Each tskIndex In ActiveProject.Tasks

tskIndex.Flag1 = True

Next tskIndex

lEnd = GetTickCount()

lTSheet = lEnd - lBegin

ViewApply "Resource Sheet"

lBegin = GetTickCount()

For Each tskIndex In ActiveProject.Tasks

tskIndex.Flag1 = True

Next tskIndex

lEnd = GetTickCount()

lRSheet = lEnd - lBegin

ViewApply "Module Editor"

lBegin = GetTickCount()

For Each tskIndex In ActiveProject.Tasks

tskIndex.Flag1 = True

Next tskIndex

lEnd = GetTickCount()

lEdit = lEnd - lBegin

MsgBox "Elapsed times:" & Chr(10) & _

"Gantt - " & lGantt / 1000 & " s." & Chr(10) & _

"Task Sheet - " & lTSheet / 1000 & " s." & Chr(10) & _

"Resource Sheet - " & lRSheet / 1000 & " s." & _ Chr(10) & "Editor - " & lEdit / 1000 & " s."

End Sub

Running this macro on the sample Rollout project that ships with Microsoft Project (ROLLOUT.MPT) will give results similar to this:

{bmc ZCK2A.WPG}

Note that since only task data is being updated, Microsoft Project repaints the window only when in a task view, hence the virtually equivalent execution times in the Module Editor and Resource Sheet views.

As an alternative to applying a different view, you may just want to minimize the application window. When minimized, Microsoft Project does not need to repaint its window and so your code executes at about the same rate as it would in the Module Editor view.

Try the following modification to the last example:

' This sub sets the Flag1 field of all tasks to True

' in 4 different views.

Sub SetFlagTest2()

Dim tskIndex As Task ' Index for Tasks collection

Dim lBegin As Long ' Beginning tick count

Dim lEnd As Long ' Ending tick count

Dim lGantt As Long ' Time to execute in Gantt view

Dim lTSheet As Long ' Time to execute in Task Sheet view

Dim lRSheet As Long ' Time to execute in Resource Sheet view

Dim lEdit As Long ' Time to execute in Module Editor view

' Minimize the Project application window

Application.WindowState = pjMinimized

ViewApply "Gantt Chart"

lBegin = GetTickCount()

For Each tskIndex In ActiveProject.Tasks

tskIndex.Flag1 = True

Next tskIndex

lEnd = GetTickCount()

lGantt = lEnd - lBegin

ViewApply "Task Sheet"

lBegin = GetTickCount()

For Each tskIndex In ActiveProject.Tasks

tskIndex.Flag1 = True

Next tskIndex

lEnd = GetTickCount()

lTSheet = lEnd - lBegin

ViewApply "Resource Sheet"

lBegin = GetTickCount()

For Each tskIndex In ActiveProject.Tasks

tskIndex.Flag1 = True

Next tskIndex

lEnd = GetTickCount()

lRSheet = lEnd - lBegin

ViewApply "Module Editor"

lBegin = GetTickCount()

For Each tskIndex In ActiveProject.Tasks

tskIndex.Flag1 = True

Next tskIndex

lEnd = GetTickCount()

lEdit = lEnd - lBegin

' Restore the Project application window

Application.WindowState = pjNormal

MsgBox "Elapsed times:" & Chr(10) & _

"Gantt - " & lGantt / 1000 & " s." & Chr(10) & _

"Task Sheet - " & lTSheet / 1000 & " s." & Chr(10) & _

"Resource Sheet - " & lRSheet / 1000 & " s." & _ Chr(10) & "Editor - " & lEdit / 1000 & " s."

End Sub

Running this variation on the same Rollout project gives the following results:

{bmc ZCK3A.WPG}

Note that while in this minimized state, the code executes at virtually the same speed in all cases.

A major drawback of minimizing Microsoft Project while executing your code is that the user is then provided with little or no visual feedback on the progress of the macro. At least while a task view is visible, the flickering screen redraws give some indication that the macro is still executing. For time consuming macros, users will generally prefer to trade a little speed for better visual feedback. A nice method for managing this tradeoff is to creatively use a dummy project.

Creating a dummy project that you can use to fill the application window provides you with two benefits: It eliminates excessive screen redraws and provides a nice medium for displaying status messages. To effectively use this method, you must first create the project you will use to provide the status messages. Take a look at the STATUS.MPP file provided. This project contains a single task and has been saved while a custom PERT view named "Macro Status" was active. While our macro is running, we open this file and use the single task box displayed to provide status messages to the user.

To illustrate this process, the following macro runs through every task in the active project twice, first setting the Flag1 field to True and then setting the Flag2 field as well.

Sub SetFlagTest3()

Dim tskIndex As Task ' Index for Tasks collection

Dim tskStatus As Task ' Task used to display progress

Dim prjStatus As Project ' Project used to display progress

Dim prjCurrent As Project ' Current project

Set prjCurrent = ActiveProject

FileOpen "status.mpp"

Set prjStatus = ActiveProject

Set tskStatus = prjStatus.Tasks(1)

ActiveWindow.Caption = "Macro Status"

tskStatus.Name = "Now setting task Flag1 fields..."

DoEvents ' Allows view to refresh

For Each tskIndex In prjCurrent.Tasks

tskIndex.Flag1 = True

tskStatus.Name = "Now processing task " & tskIndex.ID

Next tskIndex

tskStatus.Name = "Now setting task Flag2 fields..."

DoEvents ' Allows view to refresh

For Each tskIndex In prjCurrent.Tasks

tskIndex.Flag2 = True

tskStatus.Name = "Now processing task " & tskIndex.ID

Next tskIndex

FileClose pjDoNotSave

End Sub

Note that by taking advantage of the way Microsoft Project delays refreshing the displayed task box, the macro can actually display one message in the box while displaying another in the entry bar.

To determine how much impact these status messages are actually having on the macro’s performance, we can use the following code:

Sub SetFlagtest4()

Dim tskIndex As Task ' Index for Tasks collection

Dim lBegin As Long ' Beginning tick count

Dim lEnd As Long ' Ending tick count

Dim lMsgFlag1 As Long ' Time to set Flag1 with status messages

Dim lMinFlag1 As Long ' Time to set Flag1 while app minimized

Dim lMsgFlag2 As Long ' Time to set Flag2 with status messages

Dim lMinFlag2 As Long ' Time to set Flag2 while app minimized

Dim tskStatus As Task ' Task used to display progress

Dim prjStatus As Project ' Project used to display progress

Dim prjCurrent As Project ' Current project

Set prjCurrent = ActiveProject

FileOpen "status.mpp"

Set prjStatus = ActiveProject

Set tskStatus = prjStatus.Tasks(1)

ActiveWindow.Caption = "Macro Status"

lBegin = GetTickCount()

tskStatus.Name = "Now setting task Flag1 fields..."

DoEvents ' Allows view to refresh

For Each tskIndex In prjCurrent.Tasks

tskIndex.Flag1 = True

tskStatus.Name = "Now processing task " & tskIndex.ID

Next tskIndex

lEnd = GetTickCount()

lMsgFlag1 = lEnd - lBegin

lBegin = GetTickCount()

tskStatus.Name = "Now setting task Flag2 fields..."

DoEvents ' Allows view to refresh

For Each tskIndex In prjCurrent.Tasks

tskIndex.Flag2 = True

tskStatus.Name = "Now processing task " & tskIndex.ID

Next tskIndex

lEnd = GetTickCount()

lMsgFlag2 = lEnd - lBegin

FileClose pjDoNotSave

Application.WindowState = pjMinimized

lBegin = GetTickCount()

For Each tskIndex In prjCurrent.Tasks

tskIndex.Flag1 = True

Next tskIndex

lEnd = GetTickCount()

lMinFlag1 = lEnd - lBegin

lBegin = GetTickCount()

For Each tskIndex In prjCurrent.Tasks

tskIndex.Flag2 = True

Next tskIndex

lEnd = GetTickCount()

lMinFlag2 = lEnd - lBegin

Application.WindowState = pjNormal

MsgBox "Elapsed times with messages:" & Chr(10) & _

"Flag1 - " & lMsgFlag1 / 1000 & " s." & Chr(10) & _

"Flag2 - " & lMsgFlag2 / 1000 & " s." & Chr(10) & _

Chr(10) & "While minimized:" & Chr(10) & _

"Flag1 - " & lMinFlag1 / 1000 & " s." & Chr(10) & _

"Flag2 - " & lMinFlag2 / 1000 & " s."

End Sub

Running this macro on a project of 200 tasks, you should get results similar to this:

{bmc ZCK4A.WPG}

Note that providing status messages in this case increased execution time by about 30%. While this can represent a substantial increase in execution time on some projects, user’s will generally prefer to accept the performance drop in return for the continuous feedback.

Minimize Direct Object Manipulation

Another way to improve the performance of a Microsoft Project macro is to minimize, wherever possible, the direct manipulation of objects in code. Although it is often convenient to iterate through an entire collection of objects while performing some action, it is usually much quicker to use some of Microsoft Project’s built-in features to minimize the number of objects that must be examined. An example of this technique follows.

In this example (taken from the Project Metrics application) it is necessary to examine each of the tasks in the project to determine if there are any resources assigned to the task. The following code fragment accomplishes this by checking the count of resources assigned to each task in the current project’s task collection:

' Assign the dummy resource to any task that does not already 'have at least one resource already assigned. A maximum of 1,000 'assignments may be made.

tassign = 0

For Each t In ActiveProject.Tasks

If Not (t Is Nothing) Then

If t.Resources.Count < 1 Then

If tassign > 1000 Then Error err_assign_limit

t.Assignments.Add ResourceID:=oNewRes.ID

tassign = tassign + 1 'keeps track of the 'number of assignments made

End If

End If

Next t

The preceding code works, but the next example is much faster. The difference between the first example and the second is that the second example sets a task filter, which filters out all tasks that have resources assigned. This filtering operation is very fast and can improve the performance of this routine by over 300%.

The cpts_nores_filter constant refers to a task filter that is defined as follows:

Field Name Test Value(s) And/Or

Resource Names | Equals |  | And
Milestone | Equals | No | And
Summary | Equals | No |

tassign = 0

FilterApply cpts_nores_filter

SelectAll

If Not ActiveSelection.Tasks Is Nothing Then

For Each t In ActiveSelection.Tasks

With t

If tassign > 1000 Then Error err_assign_limit

.Assignments.Add ResourceID:=oNewRes.ID

tassign = tassign + 1 'keeps track of the number of 'assignments made

End With

Next t

End If

© 1995 Microsoft Corporation.
THESE MATERIALS ARE PROVIDED "AS-IS," FOR INFORMATIONAL PURPOSES ONLY.
NEITHER MICROSOFT NOR ITS SUPPLIERS MAKES ANY WARRANTY, EXPRESS OR IMPLIED WITH RESPECT TO THE CONTENT OF THESE MATERIALS OR THE ACCURACY OF ANY INFORMATION CONTAINED HEREIN, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. BECAUSE SOME STATES/JURISDICTIONS DO NOT ALLOW EXCLUSIONS OF IMPLIED WARRANTIES, THE ABOVE LIMITATION MAY NOT APPLY TO YOU.
NEITHER MICROSOFT NOR ITS SUPPLIERS SHALL HAVE ANY LIABILITY FOR ANY DAMAGES WHATSOEVER INCLUDING CONSEQUENTIAL INCIDENTAL, DIRECT, INDIRECT, SPECIAL, AND LOSS PROFITS. BECAUSE SOME STATES/JURISDICTIONS DO NOT ALLOW THE EXCLUSION OF CONSEQUENTIAL OR INCIDENTAL DAMAGES THE ABOVE LIMITATION MAY NOT APPLY TO YOU. IN ANY EVENT, MICROSOFT’S AND ITS SUPPLIERS’ ENTIRE LIABILITY IN ANY MANNER ARISING OUT OF THESE MATERIALS, WHETHER BY TORT, CONTRACT, OR OTHERWISE SHALL NOT EXCEED THE SUGGESTED RETAIL PRICE OF THESE MATERIALS.


Lesson 1: Creating and Recording Macros

Lesson Objectives

Upon completion of this lesson, the participant will be able to:

  • Create new macros.
  • Understand the different options available when creating macros.
  • Understand how to record a macro.
  • Understand how and where macros are stored.

Some Topics to be introduced in this lesson include:

  • Macro Menu List
  • Shortcut Keys
  • Macro Recorder
  • Row References (Relative and Absolute)
  • Column References (Relative and Absolute)

Creating and Running Macros

There are several reasons for creating a macro in Microsoft Project. You may want to automate a set of steps you repeat over and over or you may want to customize the way Microsoft Project performs some task.

In Visual Basic for Applications, a macro corresponds to a subprocedure.

Sub PrintMonthlyReport()

...

End Sub

So, the subprocedure PrintMonthlyReport can also be referred to as the macro PrintMonthlyReport.

Recording a Macro

The easiest way to automate a set of steps which you repeat over and over is to record a macro. The macro recorder records each action which is performed and places those commands in a macro.

To record a macro:

Choose Record Macro from the Tools menu.

Enter a name for the macro and a brief description. This description is displayed when the macro is selected in the Macros dialog.

Click the OK button or press ENTER.

The Record Macro dialog box

There are some advanced options which allow you to customize how Microsoft Project records certain events and where the macro is stored. By choosing the Options button in the Record Macro dialog, you can set these options.

The Record Macro dialog box with advanced options

Show in Macro Menu List: If this option is selected, the macro will appear in the macro menu list, if added to a menu.

Shortcut Key: This option is used to assign a Ctrl + <key> combination for running the macro.

Store Macro in:

Global File: When selected, the macro is saved to the GLOBAL.MPT file.

Current Project File: If this option is selected, the macro is saved in the project file, and is only available when this project is open.

Row References:

Relative: All row selections are recorded relative to the current row. For example, "select 3 rows up", or "select 2 rows down".

Absolute (ID): All row selections are recorded using ID numbers. For example, "select the row containing Task ID = 13" or "select the row containing Resource ID = 4".

Column References:

Absolute (Field): All column selections are recorded using the Field names. For example, "select the Work field", or "select the Name field".

Relative: All column selections are recorded relative to the current column. For example, "select 2 columns right", or "select 1 column left".

When you are finished performing the actions for the macro, choose Stop Recorder from the Tools menu to halt macro recording.

Manually Creating a Macro

Selecting the New button in the Macros dialog allows you to specify the same options for a new macro that are allowed when recording one. Instead of recording user actions, however, selecting New simply takes you to the Module Editor view where a new procedure heading is automatically added using your macro name. Code can then be entered manually in the procedure.

Running a Macro

Once a macro has been created, the next step is to run the macro. To run a macro:

Choose the Macros command from the Tools menu.

Select the macro in the Macro Name list. Note that the description for the macro will be displayed at the bottom of the dialog.

The Macros dialog box

To run the macro, choose the Run button. When testing a macro, it is sometimes helpful to step through the macro slowly. The Step button in the Macros dialog will run the macro one line at a time and display the Debug Window so that you can see the macro as it is being executed.

Editing a Macro

After running a macro, you may want to modify the macro to perform a slightly different task, enable it to loop through the same actions several times, or accept input from the user. To Edit a macro, choose the Macros command from the Tools menu. Select the macro in the Macro Name list and choose the Edit button. The macro is then displayed using the Module Editor view.

The Module Editor view in Microsoft Project

The Module Editor view gives you the same editing capabilities found in Visual Basic. Code is automatically checked for syntax as it is entered (as long as the option is turned on -- it is by default). It is formatted with different colors for keywords, identifiers, and comments. You can also set breakpoints and watch variables for debugging.

Integrating a Macro

After perfecting your macro, the next step may be to integrate it so that the macro appears to be a standard part of Microsoft Project. There are two easy ways of allowing quick access to your macro.

Toolbar

You can assign any macro or built-in command to a button on a toolbar. To customize a button, simply hold down the CTRL key and click on the button with the mouse. This will display the Customize Tool dialog.

The Customize Tool dialog box in Microsoft Project

In the Command box, enter ‘Macro’ followed by the name of your macro. You can also select from a list by clicking the down arrow to the right of the Command box.

The Description and ToolTip boxes allow you to provide additional information about the toolbar button. The Description will appear in the status bar when the button is pressed. The ToolTip appears when the user "hovers" their mouse over the button.

The Button Library allows you to choose between the different buttons supplied with Microsoft Project. To create your own button or to customize a supplied button, you can choose the Edit Button and draw your own.

After you have created the toolbar button, you can run the macro by simply clicking the button.

Menu Bar

Just as you can assign any macro or built-in command to a toolbar button, you can do the same for any menu item. Simply choose Customize from the Tools menu and then choose Menu Bars. In the Menu Bars dialog, choose the menu bar you want to edit. In most cases, this will be Standard. Then choose the Edit button to display the Menu Bar Definition dialog. In this dialog, the menu bar is displayed in an outline. You can add new commands or menus, or modify existing ones.

Macro Storage and Organization

Before creating macros, it is important to understand how and where Project stores macros. Each project file (.MPP) and the Global file (GLOBAL.MPT) are "Libraries" which can store Modules. Modules contain groups of Sub Procedures and Sub Functions. The organization is shown in the illustration below:

Lesson 1 Exercises

  1. Record a macro that creates five tasks and then makes the first task a summary task.

  2. Run the macro created above from a toolbar button, from a menu command, and from the Macros dialog.

  3. Record a macro that applies the Date Range filter. Does the resulting macro include the dates that you input? How could you workaround this?

    4. No, make the macro non-interactive and then use a combination of FilterEdit and FilterApply or use the SendKeys statement before the FilterApply method.

  4. Record a macro that prints the current view using the Print toolbar button. Does the resulting macro work properly? How do you workaround this?

    5. No, remove the Copies:= from the statement to make it read >> FilePrint 1. Also, changing any default settings will fix it, i.e. add the parameter Color:=True


Lesson 2: Programming Basics

Lesson Objectives

Upon completion of this lesson, the participant will be able to:

  • Use procedures to structure and segment code for effectively designed applications.
  • Describe the difference between Sub and Function procedures and explain when the use of each type is appropriate.
  • Customize the programming environment by changing the size and color of code text and the tab width.
  • Explain the various data types available in Visual Basic and utilize them when declaring data.
  • Declare variables that are accessible within a procedure, within a module or within a workbook.
  • Describe the difference between variable scope and lifetime.
  • Describe why explicit variable declarations make code more efficient and less error prone.
  • Practice effective variable declaration using the Require Variable Declaration option.
  • Explain the difference between variables and constants.
  • Create arrays and use them to store different types of data.
  • Use the conversion functions to change the data type of a variable.
  • Manipulate text strings using Visual Basic functions such as Left, Mid, Right and others.
  • Accept user input using the MsgBox and InputBox functions and use the values returned from these function in VB code.
  • Describe the Auto_Open and Auto_Close sub procedures.

Some Topics to be introduced in this lesson include:

  • Procedures
  • Sub vs. Function Procedures
  • Auto_Open and Auto_Close
  • Creating and calling a procedure
  • The Module Sheet
  • Customizing the programming environment
  • Declaring data - Data types
  • Scope and lifetime
  • Variables and constants
  • Converting data types
  • Text string manipulation
  • Directory and file control
  • Interaction (MsgBox,InputBox)

Programming Basics

Module Structure

Code within a Module is broken up into a series of procedures. Procedures are blocks of code that perform a task or tasks which together make up a full application An application is usually written using a series of procedures, dividing the code into more manageable units. This code is more easily shared with other procedures and is easier to debug. Procedures can also be defined to perform a specific task based on a particular event (event procedures).

There are three types of procedures in Visual Basic for Applications:

  • Sub
  • Function
  • Property

Sub Procedures

A Sub procedure can accept arguments, perform a series of statements and change the value of its arguments. These are used most often when automating tasks and performing commands. A Sub procedure is defined using the keyword Sub followed by the name of the procedure:

Sub PrintReport()

' Procedure code goes here

End Sub

Sub procedures are the most common procedure type and will be used in code examples which introduce the rest of the topics discussed in this Module.

Auto_Open and Auto_Close

Only two type of auto-execute macros are supported in Project 4.0: Auto_Close and Auto_Open.

Any sub procedure named Auto_Open will execute automatically when the project file is first opened. Holding down the Shift key while opening the file will prevent the macro from executing. Note that if the Open Last File on Startup option is selected, an Auto_Open macro in the last saved file will be executed every time Project is booted.

Any sub procedure named Auto_Close will execute automatically when the project file is closed. Holding down the Shift key while closing the file will prevent the macro from executing. Note that if a number of files are closed at once (File Close All, or File Exit), all Auto_Close procedures will be executed for these files, if they exist.

If procedures with the same name appear in both the local project file and the global file, the local procedures will be executed.

Sub Auto_Open

{Code to execute when the workbook is opened}

End Sub

Sub Auto_Close

{Code to execute when the workbook is closed}

End Sub

Function Procedures

A Function procedure, sometimes referred to as a user-defined function, can also accept arguments, execute a series of statements and change the value of its arguments. Unlike a Sub procedure, however, a Function procedure may also return a value. They most often are used to perform some sort of calculation. Function procedures are defined using the keyword Function:

Function SalesFactor(MarkUp, Region)

' Function procedure code goes here

End Function

Function procedures will be discussed in more detail in Lesson 4.

Defining and Running a Procedure

When a procedure is created using the Sub, Function or Property statement (followed by the corresponding End statement), the procedure is available for use. Depending on the type of procedure, the procedure can be run from the Tools Macro command, while debugging or from another procedure, without any special "defining" process. A quick way to run a procedure is from within the module editor. Click within the procedure, and press the Run button on the Visual Basic toolbar.

To run a procedure from within another procedure, simply type the name of the procedure:

PrintReport

or, if the procedure resides on another module sheet, you can proceed the name with the module sheet name (although this isn’t absolutely necessary):

Module1.PrintReport

Procedures are, by default, available to all other procedures within the same library. To limit accessibility to a procedure, place the word Private before the Sub or Function statement and the procedure can only be called from within the current module:

Private Sub PrintReport()

General Declarations Section

All modules contain an area at the top of a module which falls before the first procedure in that module. This section is called the general declarations section. This area is used to define options and declare data that apply to the entire module sheet.

Using Comments and Line Labels to Document Code

Line labels can be used to separate the code within a procedure and can then be used by certain commands to indicate branching locations. A line label can contain any combination of characters but must begin with a letter and end with a colon:

Sub PrintReport()

PrintMySelection:

'Procedure code goes here

End Sub

Comments can be added to code placing either an apostrophe (') or the Rem statement at the beginning of the comment. Comments can appear on their own lines or at the end of code strings:

Sub PrintReport()

Selection.PrintOut 'Prints all pages of the selection

End Sub

Making Code Easier to Read

At times, code in a procedure can become so long that it extends past the edge of the screen. This can make reading the code difficult. The line-continuation character or the underscore (_) is used to extend a single line of code to more than one physical lines. There are two rules to using the line continuation character. It must immediately follow a space and it cannot appear within a text string.

Declaring and Storing Data

An essential element in many programs is storing data for later use. In VB, values are stored as variables or constants. This form of data is flexible because the type of data stored and the accessibility of the data from other procedures can be controlled.

Terminology and Concepts

Variables vs. Constants

The decision to create a variable or a constant depends on how that data will be used. A variable stores values that will change at some point in the application. For example, if the application stores a value that increments each time a particular task is completed, a variable should be used. A constant is used to store a value that does not change.

Data Types

In Visual Basic, the programmer has a great deal of control over how information is stored. The different data types available include:

Data Type | Storage Size | Range | Short cut
Boolean | 2 bytes | True or False. | n/a
Integer | 2 bytes | -32,768 to 32,767. | %
Long (long integer) | 4 bytes | -2,147,483,648 to 2,147,483,647. | &
Single (single-precision floating-point) | 4 bytes | -3.402823E38 to -1.401298E-45 for negative values; 1.401298E-45 to 3.402823E38 for positive values. | !
Double (double-precision floating-point) | 8 bytes | -1.79769313486232E308 to -4.94065645841247E-324 for negative values; 4.94065645841247E-324 to 1.79769313486232E308 for positive values. | #
Currency (scaled integer) | 8 bytes | -922,337,203,685,477.5808 to 922,337,203,685,477.5807. | @
Date | 8 bytes | January 1, 100 to December 31, 9999. | n/a
Object | 4 bytes | Any Object reference. | n/a
String | 1 byte per character | 0 to approximately 2 billion (approximately 65,535 for Microsoft Windows version 3.1 and earlier). | $
Variant | 16 bytes + 1 byte for each character | Any numeric value up to the range of a Double or any character text. | n/a
User-defined (using Type) | Number required by elements | The range of each element is the same as the range of its fundamental data type, listed above. | n/a

Besides providing (in some cases) built-in error checking, assigning the correct data type to a variable or constant also saves memory. The storage size listed above is important because it demonstrates how the programmer can save memory by assigning the most appropriate data type to a variable or constant. For example, if a declared variable is assigned the Double data type (8 bytes) but will only actually store integer values (2 bytes), the programmer wastes 6 bytes of storage space. This may not be significant when there are only a few variables but can greatly decrease performance if many variables are involved.

A variable or constant that is not assigned a particular data type defaults to the variant data type. The variant data type, while useful because it can store virtually any type of data, can also compound the problem described above by requiring 16 bytes of storage space plus 1 byte for each character (when a string is stored).

Data Accessibility and Lifetime

The accessibility or the scope of a variable or constant defines how that variable is used by procedures in the application. There are three levels of scope in Visual Basic for Applications:

Public - Data declared as public in scope is directly available to all procedures within the same library.

Module - Data declared as module in scope is directly available only to procedures within the current module.

Local - Locally declared data is available only within the procedure where it is declared.

The lifetime or the length of time that a variable or constant maintains its value, is determined by the scope of the data. By default, data that is declared with Public or Module level scope maintains its value as long as Visual Basic is running. These variables will be reset when the library is closed and reopened. They are also reset if the changes are made to the library. You can manually reset them by choosing Reset from the default Run menu. Locally declared data maintain their values while the host procedure is running.

Declaring Data

Data declarations in Visual Basic can be either implicit or explicit. An implicit declaration can also be referred to as an "on-the-fly" declaration because the programmer declares the variable simply by assigning to it a value. For example, the following code creates a variable called "X" and assigns to it the value 100:

X = 100

While this method is quick and requires little prior thought or planning on the part of the programmer, there are some reasons why this type of declaration is not the preferred method:

Implicitly declared data always uses the variant data type so regardless of the type of data stored there, 16+ bytes of memory are always allocated.

Implicit variables are always local in scope and cannot be made available to other procedures.

Explicitly declared data is defined at design time using one of the following statements: Dim, Public, Private, Static or Const. The statement used is determined by the desired scope of the variable or constant.

To force Visual Basic to always require explicitly declared variables, use the "Require Variable Declaration" option in the Module General panel of the Tools Options dialog. This places the statement Option Explicit in the general declarations section of each new module. With this option enabled, VB will always perform a pre-runtime validity check each time the name is used in the procedure, decreasing the chance that the programmer will type the name incorrectly.

Declaring Data that is Public

To define a variable that is available to all procedures within the current library, use the Public statement and place the declaration in the General Declarations section of a module sheet:

Public VariableName {as Type}

It is not possible to set the value of a variable in the same line that it is declared. Also, the value of a variable cannot be defined in the General Declarations section. It must be established within a procedure.

To define a public constant, use the Public and Const statements in the General Declaration section:

Public Const ConstantName {As type} = expression

Since the value of a constant never changes, the value of the constant is part of the declaration statement.

Declaring Data that is Module in Scope

Variables that are module in scope are available to all procedures that reside in the module where the variable is declared. These are declared in the General Declarations section using the Dim or Private statements. Again, values must be assigned within a procedure:

Dim VariableName {as type}

or

Private VariableName {as type}

Module level constants use the Private statement and are located in the General Declarations section:

Private Const ConstantName {As type} = expression

Declaring Local Data

Variables that are local in scope are recognized only within the procedure where they appear and are defined within the procedure using either the Dim statement or a Static statements:

Dim VariableName {as type}

or

Static VariableName {as type}

The Static statement causes a local variable, which normally loses its value after the procedure finishes executing, to have a "permanent" lifetime like that of a public or module variable. The value of the local variable will be maintained until the library is closed.

A constant may also be defined locally, using the Const statement:

Const ConstName {as type} = expression

Using Declared Data

The following code shows how the various data declarations might appear:

' General Declarations Section

Option Explicit

Public Counter as Integer ' Public variable

Dim State as String ' Private variable

Public Const Workdays as Integer = 4 ' Public constant

Private Const City as String = "Seattle" ' Private constant

Sub MySub()

Dim Birthday as Date ' Local variable

Const StartDate as Date = #01/01/94# ' Local constant

Counter = 1

State = "Washington"

Birthday = #02/27/64#

End Sub

Try This: Using Declared Data

  1. Assuming that MySub (code above) is located in Module1, what happens if the following procedure is executed from Module2? What willcorrect the problem?

    2. The error "Variable Not Defined" appears - to correct the problem, change State to a public variable using Public in place of the Dim statement.

    Sub MySub2()

    Module1.MySub ' Runs the procedure MySub

    MsgBox State ' Displays

    End Sub

  2. When a public or module level variable exists and a local variable with the same name is declared, which takes precedence? Run the code below for the:

    3. Local takes precedence

    Sub MySub3()

    MySub ' Runs the procedure MySub

    Dim Counter As Integer ' Declares local variable Counter

    MsgBox "MySub3 Counter = " & Str(Counter)

    ' Shows value of Counter in MySub3

    MySub4 ' Runs MySub4 (code on next page)

    End Sub

    Sub MySub4()

    ' Shows value of Counter in MySub4

    MsgBox "MySub4 Counter = " & Str(Counter)

    End Sub

Arrays

Arrays are another type of declared data, but instead of storing a single value, arrays can store many values. By declaring data as an array, it is possible to refer to a series of variables by the same name and use an index to distinguish each one. To define an array, follow the variable or constant name with a set of parenthesis and the element range. The following declaration creates a 5 by 100 array of integers:

Dim MyArray(1 to 5, 1 to 100) as Integer

Once declared, indexing can be used to refer to individual elements within the array:

Temp = MyArray(1, Counter) ' Assign the indexed value to the variable Temp

or,

MyArray(1, Counter) = (SomeVariable*15)/.05 ' Assign a value to an element

' in an array

Arrays in Visual Basic use a zero base, by default, if a lower boundary is not specified (e.g., "100", instead of "1 to 100"):

Dim MyArray(100) as Integer

The array will actually contain 101 elements, with indexing starting with 0. VB can be instructed to use a one base by placing the line Option Base 1 in the general declarations section of the module. This may be prone to errors, however, if the code from the procedure is copied to a module which does not use the Base 1 option.

Arrays and Memory

Assigning the proper data type to an array is even more important than with regular variables and constants because the number of bytes used is multiplied by the number of elements. The first example above reserves 1,000 bytes of storage space (5 * 100 * 2), whereas the same array declared as a variant:

Dim MyArray(1 to 5, 1 to 100)

requires at least 8,000 bytes (5 * 100 * 16).

The maximum size of an array varies, based on the operating system used and how much memory is available. Encountering this limit is unlikely, but using arrays that exceed the amount of random-access memory available on the system are slower because the data must be read from and written to disk.

Assigning Many Values to an Array

The Array function is useful when assigning many values to an array. Instead of using the following command to declare a 10 element array and assign the letters "A" to "J",

Dim MyArray (1 to 10) as String

MyArray(1) = "A"

MyArray(2) = "B"

MyArray(3) = "C"

...

MyArray(10) = "J"

declare the array as a variant and then use the Array function to assign the letters.

Dim MyArray

MyArray = Array("A", "B", "C", "D", "E", "F", "G", "H", "I", "J")

The downside to this method is that there is no way to control the data type for the array as it must use the variant data type. For very large arrays this may pose memory problems. Also, unless the Option Base 1 statement is used, the array uses a zero base by default. The Array function has other uses, which will be discussed later in the course.

Expressions

An expression is a combination of keywords, operators, variables, and constants that yield a string, number, date or object. Expressions can perform a calculation, manipulate characters, or test data to return the desired data type. A variety of functions and other tools are available to use with expressions.

Operators

Operators are used in VB to perform calculations and comparisons within expressions. Below are definitions for some of the operators used in VB. Other operators not listed include: And, Or, -, *, and &

\ | Divides 2 numbers and returns an integer as the result ("/" returns a floating point number).
+ | Adds 2 numbers or used like the ampersand (&) to concatenate text strings.
Is | Compares two object reference variables. If they are the same, returns the value True.
Like | Compares two strings and returns True if they are the same. Performs pattern matching when wildcard characters are used.
Eqv | Compares two expressions. If both are True or both are False, returns the value True.
Imp | Performs a logical implication on two expressions. ("It is true that if Exp1 is true, then Exp2 is also true").
Xor | Compares two expressions and returns True if one and only one expression is True. When both are True or both are False, it returns False.

Converting Data Types

It is sometimes necessary to change the data type of an expression before assigning it to a variable or using it to set an argument. For example, the following variable X is defined as a string. However, when the value 10000 is assigned to the variable, the error "Type Mismatch" appears:

Dim X as String

X = 10000

The problem can be corrected by converting the value 10000 to a text string using one of the conversion functions:

X = Str(10000)

or

X = CStr(10000)

Other conversion functions include:

Int(numericexpression) | Converts numeric expression to Integer
Chr(code) | Converts the ASCII code arguments to a one-character string. Often used to add a carriage return and line feed.
Val(stringexpression) | Returns the value of expression (converts strings to number format)
Str(numericexpression) | Returns a string representation of the numeric expression.
Format(expression[ ,fmt]) | Converts a number to a string and formats it according to fmt.
CBool | Converts expression to Boolean
CCur | Converts expression to Currency
CDate | Converts expression to Date
CDbl | Converts expression to Double
CInt | Converts expression to Integer
CLng | Converts expression to Long
CSng | Converts expression to Single
CStr | Converts expression to String
CVar | Converts expression to Variant

Dim x as Integer : x=30000

x = x * 2

Will generate an error since the Integer data type has an upper limit of 32,767.

Using Functions

Visual Basic has a host of functions available for a variety of uses:

  • Text string manipulation
  • Date and time
  • File system
  • Interaction
  • Math

Try This: Working with Expressions and Functions

  • Choose the View Object Browser command (with a module sheet active). Select "VBA" under Libraries/Workbooks. Write down the names of 3 functions within each of these categories:
  • File System
  • Information
  • Strings

Working with Arguments

When working with functions (and methods, discussed in Module 2), there are several different ways to enter arguments.

The first way is very similar to using functions in Excel, where arguments are entered with a comma separating each one. Assuming the InputBox function:

InputBox prompt[,title][,default][,xpos][,ypos][,helpfile,context]

Some arguments are required and others are optional (shown in square brackets). Optional arguments can be left blank with a comma serving as the place holder. For example, the InputBox function with the prompt and default arguments appear as follows:

InputBox "Enter file name",,"?.MPP"

While this method is quick, it is not always obvious what the arguments represent. Another method is to use named arguments. Every function has a set of argument names and these can be used directly within the function. The same command above using named arguments looks like this:

InputBox prompt:="Enter file name", default:="?.MPP"

Note that the argument name is followed by ":=" and, since the name identifies the argument, the extra commas are removed because the relative position of the argument is no longer important.

A quick way to enter the named arguments for a function is to find the function in the Object Browser and use the Paste button.

If the function returns a value and the value is to be used in an expression or assigned to a variable, parenthesis must be placed around the arguments. Otherwise the parenthesis may be left off. To return the result of the input box to the variable myFile, the code would be:

myFile = Application.InputBox(prompt:="Enter file name", default:="?.MPP")

Text String Manipulation

VB includes several functions for manipulating text strings. These include: Instr, Left, Ltrim, Mid, Right, Rtrim, and Trim.

Instr()

This function returns the position of the first occurrence of one string within another.

SearchString = "XXpXXpXXPXXP"

SearchChar = "P"

MyPos = Instr(4,SearchString, SearchChar,1) ‘Returns 6

Left()

This function returns the specified number of characters from the left side of a string.

AnyString = "Hello World"

MyStr = Left(AnyString,1) ‘Returns "H"

Mid()

This function returns the specified number of characters from a string.

MyString = "Mid Function Demo"

FirstWord = "Mid(MyString,1,3) Returns "Mid"

LastWord = "Mid(MyString,14,4) Returns "Demo"

MidWords = Mid(MyString,5) Returns "Function Demo"

Right()

Returns the specified number of characters from the right side of a string.

AnyString = "Hello World"

MyStr = Right(AnyString,1) Returns "d"

MyStr = Right(AnyString,6) Returns " World"

Controlling User Input

Two functions and one method are provided to control user input for VB modules Microsoft Project: the MsgBox function, the InputBox function, and the Message method.

InputBox Function

This function displays a dialog box that waits for the user to input text or choose a button and then returns the contents of the text box.

Message = "Enter a value between 1 and 3" ' Set prompt.

Title = "InputBox Demo" ' Set title.

Default = "1" ' Set default.

' Display message, title, and default value.

MyValue = InputBox(Message, Title, Default)

' Use helpfile and context. The help button is added automatically.

MyValue = InputBox(Message, Title, , , , "DEMO.HLP", 10)

' Display dialog at position 100,100

MyValue = InputBox(Message, Title, Default, 100, 100)

MsgBox Function

This function displays a message dialog box to the user and waits for the user to choose a button. It then returns a value indicating which button the user chose.

Msg = "Do you want to continue ?" ' Define message.

Style = vbYesNo + vbCritical + vbDefaultButton2 ' Define buttons.

Title = "MsgBox Demonstration" ' Define title.

Help = "DEMO.HLP" ' Define help file.

Ctxt = 1000 ' Define topic

' context.

' Display message.

Response = MsgBox(Msg, Style, Title, Help, Ctxt)

If Response = vbYES Then ' User chose Yes

' button.

MyString = "Yes" ' Perform some action.

Else ' User chose No

' button.

MyString = "No" ' Perform some action.

End If

Message Method

The message method is a hold over from the Project 3.0 macro language. It offers one significant advantage over the MsgBox function. It allows you to specify the text that appears on the yes and no buttons.

Application.Message message:="Is this OK?", type:=pjYesNo, _

yesText:="You bet", noText:="No way"

Lesson 2 Exercises

  1. You need to store an integer value for use in your application. It must be available to all the procedures in Module1 and its value is determined by some condition that occurs when a certain procedure is executed. Once the value is established, it will not change. Should you use a variable or a constant? Why? How might this appear in your module sheet?

    A variable should be used. It will be declared in the General Declarations section using either the Private or Dim statement. The value will be set in the procedure where the condition is tested. While the value does not change, it is not possible to declare a constant without assigning it a value and once it is declared, it cannot be modified.

    2. Dim VariableName as Integer

    Sub Sample()
    VariableName = expression
    End Sub

  2. I have a procedure written in Visual Basic for Applications and it runs very slowly. All it does is assign values to several public arrays. What might be the problem?

    3. The customer may not be using the appropriate data type for the arrays. For example, the values may be integers but the arrays are declared using the variant data type. This can significantly slow execution if very large arrays (or many variables) are involved.

  3. Write code which accepts a number from the user, multiplies the number by 100 and displays the result in a message box.

    4. Sub
    Sample()
MsgBox Val(InputBox("Enter number")) * 100
End Sub

  4. Create a macro that runs whenever the file is opened that displays a message box stating the current date and time.

    5. Sub Auto_Open()

    MsgBox Now()

    End Sub

  5. Input a procedure that prompts the user to enter 5 words separated by spaces, remove the last two words, clear off any extra spaces on the end and front of the string, and then display the following information on separate lines in a message box:

    6. --The first word
    --The middle word
    --The last word

    Sub StringFun()

    Dim daString As String

    Dim vFirstWord, vMiddleWord, vLastWord As String

    Dim v3rdSpace, vSpacePos1, vSpacePos2 As Integer

    daString = InputBox("Enter 5 words separated by spaces")

    'Finds position of 3rd space and deletes everything to the right

    v3rdSpace = InStr(InStr(InStr(1, daString, " ") + 1, _

    daString, " ") + 1, daString, " ")

    daString = Trim(Left(daString, v3rdSpace - 1))

    'Determines positions of the two spaces between the three words

    vSpacePos1 = InStr(1, daString, " ")

    vSpacePos2 = InStr(vSpacePos1 + 1, daString, " ")

    'Pulls out words

    vFirstWord = Left(daString, vSpacePos1 - 1)

    vLastWord = Right(daString, Len(daString) - vSpacePos2)

    vMiddleWord = Mid(daString, vSpacePos1 + 1, _

    vSpacePos2 - vSpacePos1 - 1)

    'Concatenates message with linefeeds

    MsgBox vFirstWord & Chr(10) & vMiddleWord & Chr(10) & vLastWord

    End Sub


Lesson 3: Program Control Structures

Lesson Objectives

Upon completion of this lesson, the participant will be able to:

  • Explain the difference between the GoSub and Goto statements.
  • Compare and contrast the If Then Else and Select Case conditional statements, noting the benefits and limitations of using one over the other and provide possible uses for each structure.

Some Topics to be introduced in this lesson include:

  • Conditional Statement
  • Branching
  • Looping
  • Nesting

Program Control Structures

Program control structures are used to shape the flow of code execution. There are three categories of control structures: branching (or decision), looping, and error. All structure types contain blocks of statements that perform tasks..

If...Then...Else

The If Then Else statement has two forms. The first is used when only a few statements are to execute based on whether the result is true or false. This type of If statement is commonly used when setting variables based on a condition.

Syntax 1:

If condition Then statements [Else elsestatements ]

Statements are separated by colons (:). The second form of the If statement is best used with larger statement blocks.

Syntax 2:

If condition Then

[statements]

[ElseIf condition-n Then

[elseifstatements]] . . .

[Else

[elsestatements]]

End If

The following example prompts the user for a number and if the number is less than zero, tells the user to enter a number greater than zero:

Sub IfThenElse()

Dim num as Integer

Num = Application.InputBox(prompt:="Enter a number, please", type:=1)

If num <= 0 Then

MsgBox "Please enter a number greater than zero"

Else

MsgBox num & " squared is " & num * num

End If

End Sub

The If Then Else branching structure is most effective in situations where there are conditions based on multiple variables. In situations where one variable has a large number of values, the Select Case statement is better suited.

Select Case

The Select Case statement executes a block of statements based on the value of an expression. VB examines the testexpression, and evaluates each of the expressionlists in turn, searching for a match. If it finds a match, it runs the code after the Case statement and stops when it reaches the next Case statement. If it finds no match, it will run the code after the Case Else statement. If more than one Case expression matches, VB will only evaluate the first one encountered and all others will be ignored.

Select Case testexpression

[Case expressionlist-n

[statements-n]] . . .

[Case Else

[elsestatements]]

End Select

The following example shows how the Select Case statement is used to display the name and telephone number of an employee in a message box based on the day of the week:

Sub AssignEmp()

Select Case Weekday(Now)

Case pjMonday , pjFriday

MsgBox "Bob Smith" & Chr(13) & "876-5432"

Case pjTuesday, pjThursday

MsgBox "Jane Johnson" & Chr(13) & "745-5844"

Case Else

MsgBox "Steve Simpson" & Chr(13) & "855-3846"

End Select

End Sub

For Next

The For Next loop executes a segment of code a specific number of times.

For counter = start To end [Step increment]

[statementblock]

Next [counter [,counter][,...]]

Do Loops

Do loops continue to execute a block of code until a certain condition is met. The condition can have one of two forms:

  • The code will execute While the condition is True

  • The code will execute Until the condition is True.

    • The Do loops have two different forms.

    Syntax 1:

    Do [{While | Until} condition]

    [statements]

    [Exit Do]

    [statements]

    Loop

    The first form of the Do loop checks for the condition before executing any code. It is possible that the block of code does not execute at all if the condition is not met on the first pass.

    Syntax 2:

    Do

    [statements]

    [Exit Do]

    [statements]

    Loop [{While | Until}condition]

    The second form of the Do loop always executes the code at least once because it checks for the condition at the end of the loop.

    This example shows how Do...Loop statements can be used. The inner Do...Loop statement loops 10 times, sets the value of the flag to False, and exits prematurely using the Exit Do statement (see next section). The outer loop exits immediately upon checking the value of the flag:

    Check = True: Counter = 0 ' Initialize variables.

    Do ' Outer Loop.

    Do While Counter < 20 ' Inner Loop.

    Counter = Counter + 1 ' Increment Counter.

    If Counter = 10 Then ' If condition is true.

    Check = False ' Set value of flag to False.

    Exit Do ' Exit inner loop.

    End If

    Loop

    Loop Until Check = False ' Exit outer loop immediately.

    While Wend

    The While Wend statement is equivalent to the Do While statement in VB. (It is provided for backwards compatibility with earlier versions of Basic and should not be used. The Do...Loop statement provides a more structured and flexible way to perform looping.) It executes a series of statements as long as a given condition is True.

    While condition

    [statements]

    Wend

    Exit

    The Exit statement is used to break out of a looping structure. When a Exit Do, Exit For, Exit While or Exit For Each is encountered within a loop, execution of the macro proceeds to the line following the Next, Wend or Loop statement for the current loop.

    Unconditional Branching

    Branching structures that unconditionally branch to other parts of the macro are less desirable than other structures because they make the macro difficult to read and debug. However, there are occasional needs for them (i.e., error checking) and they are listed below.

    Goto

    The Goto statement branches unconditionally to the specified line or label in the current procedure.

    GoTo line

    GoSub

    The GoSub statement branches unconditionally to the specified line in the current procedure. When the program encounters a Return statement, it returns to the line following the GoSub statement.

    GoSub line

    line:

    Return

    On Goto, On GoSub

    On Goto and On GoSub branch to a number of different labels or line numbers based on the value of the expression (a number between 1 and 255). The difference between the two is that On GoSub returns to the line following the statement when it encounters a Return statement, while On Goto does not.

    On expression Goto destination

    On expression GoSub destination

    Nesting Control Structures

    It is legal to nest control structures within other control structures. It is important to remember to close interior structures before closing external structures. It is possible to close more than one structure with the same Next statement (e.g., Next X, Y, Z). They will move from the inner most loop to the outer most.

    Lesson 3 Exercises

    1. Divide into groups of two. You may either work together to write one procedure or use each other as a resource while working independently. Write a procedure that does the following:

      2. Create a 2 by 10 array (ArrayName(1 to 2, 1 to 10)).

      Using a Do Loop, If statements and For Next loops, place unique random numbers between 1 and 10 in the first column of the array (ArrayName(1, 1-10). (The array should contain all the numbers between 1 and 10, but in a random order).

      Using a For Next and a Select Case, assign one of these three strings to the second column (ArrayName(2, 1-10)) based on the value in the first:

      If less than 5 then "Smaller"
      If equal to 5 then "Equal"
      If greater than 5 then "Bigger"

      Using a For Next loop, display in a message box the number and the corresponding string for each element where the random number is even.

      Sub GenerateArrayValues()

      Dim MyArray(1 To 2, 1 To 10)'Array declaration

      Dim Counter As Integer 'Counts the number of times a value is assigned to the array

      Dim RandNum As Integer 'Stores the random number

      Dim Used As Boolean 'Indicates if number has already been assigned to the array

      Dim i As Integer 'Used as a loop counter in various areas of the procedure

      Counter = 0

      Randomize 'Tells VB to use system timer for seed value when generating

      ' random numbers

      ' This part of the procedure generates the random numbers and assigns

      ' them to the array

      Do While Counter < 10 'Loop until all values are assigned

      Used = False

      RandNum = Int((10 - 1 + 1) * Rnd + 1) 'Generates random number between 1-10 (see Help)

      If Counter = 0 Then 'If first time, assigns number to first element

      MyArray(1, 1) = RandNum ' and increments counter

      Counter = Counter + 1

      Else 'If it's not the first time through the loop

      For i = 1 To Counter 'For every number in the array

      If RandNum = MyArray(1, i) Then 'Compare new number to numbers already assigned

      Used = True 'If found, then set the flag and exit the loop

      Exit For

      End If

      Next i

      If Used = False Then 'If the number does not exist in the array

      MyArray(1, Counter + 1) = RandNum ' then assign it to the next element

      Counter = Counter + 1 ' and increment the counter

      End If

      End If

      Loop

      ' This part of the procedure assigns the strings to the array based

      ' on the value

      For i = 1 To 10 'For each number in the array

      Select Case MyArray(1, i) ' compare the value and assign the appropriate

      Case Is < 5 ' string value

      MyArray(2, i) = "Smaller"

      Case Is = 5

      MyArray(2, i) = "Equal"

      Case Else

      MyArray(2, i) = "Bigger"

      End Select

      Next i

      ' The part of the procedure displays the values that are even

      For i = 1 To 10 'For each number array, see if the remainder

      If MyArray(1, i) Mod 2 = 0 Then ' is zero when divided by two (= even number)

      MsgBox "Number = " & MyArray(1, i) & " String = " & MyArray(2, i)

      End If

      Next i

      End Sub


Lesson 4: Function Procedures

Lesson Objectives

Upon completion of this lesson, the participant will be able to:

  • Explain why Function procedures differ from Sub procedures.
  • Define a function that accepts a variable-length argument list or has optional arguments.
  • Write a function that accepts an array of values and returns an array of values to a worksheet.

Some Topics to be introduced in this lesson include:

  • How Function procedures differ from Sub procedures
  • Returning data
  • Arrays

Function Procedures

Function procedures differ from sub procedures in that functions may return a value while subs may not. Further, function procedures must be called from a Macro, they will not appear on the Tools-Macros menu.

Function procedures are declared using the following structure:

Function Name (arguments)

{Function code}

Name = {The return value}

End Function

For example, this function macro accepts a temperature entered as Fahrenheit and returns the equivalent Celsius temperature:

Function FtoC (Temperature)

FtoC = (Temperature - 32) / 1.8

End Function

The accessibility of the functions depends on how they are declared when they are defined. By default, the functions have Public access, and can be used by any module within the library that contains the function. If the keyword Private is placed before Function, that function may only be called from within the same module.

Passing Data to a Function Procedure

When an argument is specified without a data type, VB will assume that the argument is a reference of the Variant data type. VB will perform the necessary conversion based on what is passed but will cause VB to allocate more memory than is probably needed. To explicitly specify the data type, include it in the argument list:

Function FtoC (Temperature as Integer)

Optional Arguments

Function arguments can be made optional by using the Optional keyword in front of the argument name when declared in the Function statement.

Function MyFunction(arg1, arg2, Optional arg3, Optional arg4)

All arguments that follow this argument in the list must also be optional and must be declared using the Optional keyword. Optional arguments must be of the variant data type. The IsMissing function can be used to test whether an optional argument was included in the argument list when a function is called.

The following is an example of using Option and IsMissing, which sets a default of "10" for the second number if IsMissing returns a true:

Function AddEm(Number1, Optional Number2)

If IsMissing(Number2) Then Number2 = 10

AddEm = (Number1 + Number2)

End Function

Lesson 4 Exercises

  1. Explain the difference between Sub procedures and Function procedures.

    2. Only one difference: function will return a value.

  2. How can a programmer check if an optional argument was passed to a function?

    3. He/she can use the IsMissing function within an If statement to check to see if the argument has been passed to the function. IsMissing will return True if no argument was passed and will return False if it was.

  3. Create a function that returns the square root of a number multiplied by 6.

    4. Function
    MyPoser(pNumber)
MyPower = pNumber ^ .05 * 6
End Function


Lesson 5: Debugging and Error Handling

Lesson Objectives

Upon completion of this lesson, the participant will be able to:

  • Successfully use the Visual Basic Module window interface and the Debug window to edit and debug code.
  • Apply Watch Expressions to code to view the value of a variable or property while stepping through code.
  • Execute Visual Basic code through the Immediate pane in the Debug window.
  • Use the On Error statement to check for errors in a Visual Basic application and correct the error using an error handling routine.
  • Use the Err and Error functions to test for errors in an application and perform corrective action based on the result of this test.

Some Topics to be introduced in this lesson include:

  • Debug Interface
  • Break mode
  • Stepping
  • Watch Expressions
  • Immediate Pane
  • On Error statement
  • Err and Error functions
  • Creating error conditions

Testing and Debugging Code

Types of Errors

There are three types of errors in programming:

  • Language errors - These errors result from incorrectly constructed code. VB detects these errors automatically when the programmer enters the line or moves off the line, or immediately before the code executes.

  • Run-time errors - These errors occur when a statement attempts an operation that is impossible to carry out. The code may be syntactically correct but, because of the current conditions, is not an appropriate operation

  • Logic errors - The code has neither language or runtime errors but does not perform in the manner in which it was intended.

    • VB can provide assistance with language and run-time errors by alerting the programmer with a message describing the type of error. Logic errors are more difficult to debug because no errors are detected by VB during execution.

    Debugging Interface

    VB includes several tools to assist the programmer in debugging and testing code. The first is the Debug window. Using the Debug window, the programmer can monitor the values of expressions and variables while stepping through each statement in the code.

    Also, the Visual Basic toolbar includes buttons for stepping through code and adding breakpoints and watches to code. (These features are discussed later in this lesson.)

    Break Mode

    The following tasks are available while in break mode:

  • Determine which active procedures have been called.

  • Watch the values of variables, properties, and statements.

  • Change the values of variables and properties.

  • Run Visual Basic statements immediately.

  • Manually control the line-by-line execution of the code.

    • When in break mode, the Debug window appears and the programmer has access to a variety of tools. When the following occurs, VB switches to break mode:

  • Choosing one of the Step buttons in the Tools Macro dialog to execute a procedure.

  • Execution reaches a line that contains a breakpoint. A breakpoint is set by selecting the line where the break should occur and pressing the Toggle Breakpoint button. (Or, select the Run Toggle Breakpoint command.)

  • Execution reaches a Stop statement.

  • A break expression defined in the Add Watch dialog changes or becomes true. (Discussed later in this lesson.)

  • An untrapped run-time error occurs.

  • The Debug button is selected in the dialog that appears after CTRL-BREAK or ESC is pressed.

    • Unlike Visual Basic 3.0, it is not possible to edit code in the Debug window in VB.

    Stepping Through Code

    While the Debug window is visible, the programmer may step through each line of code using the Step Into (F8) and Step Over (Shift+F8) commands (or the buttons on the VB toolbar.) The difference between the two commands is that the Step Into command steps through every command, including those in any procedures called by the current procedure. The Step Over command behaves exactly like the Step Into command until a call to a procedure is encountered. Step Over executes calls to procedures as one command (instead of stepping through each line in the called procedure) and then continues stepping.

    The Stop Statement

    When the procedure encounters a Stop statement, it presents the Debug window. The difference between the Stop statement and a breakpoint is that the statement is part of the executable code and is saved with the program. All break points are cleared when the file containing the procedure is closed.

    Watch Expressions

    A watch expression follows the value of a particular variable or expression and displays the value in the Watch pane of the Debug window.

    There are two ways to use a watch expression. The first is to select the variable name, expression or property in the code and select the Tools Add Watch command. This adds the variable to the list of expressions in the Watch pane. As the code executes, the value of the expression changes. It is also possible to set the Watch Type in this dialog. This is useful for instructing VB to break automatically when the value of the expression becomes True or when it changes.

    A second way to use a watch expression is to use the Instant Watch command. By selecting a variable or expression in the code and either pressing the Instant Watch button or selecting the command on the Tools menu, a dialog appears which shows the current value of the expression. Pressing the Add button adds it to the Watch pane.

    The Immediate Pane

    The Immediate pane displays information that results from debugging statements in the code or statements that are typed directly in the Immediate pane.

    Information is displayed in the Immediate pane from within a procedure using the Print method. For example, the following code displays "The value of x is ?" in the Immediate pane:

    Debug.Print "The value of x is " & x

    Or, the print method may be used directly in the Immediate pane by typing:

    Print x

    The question mark (?) is the equivalent of the Print command in the Immediate pane, so the following line produces the same result:

    ? x

    Pressing the Enter key causes the statement to evaluate. The Immediate pane will also accept other Visual Basic commands, even those that change the values of variables and properties or change the behavior of the code.

    Multiple lines of code can be entered on one line using the colon (:) as a separator, which is useful for loops:

    For x=1 to 5 : ? x : Next

    Procedure Call Stack

    The Calls dialog is useful when tracking the operation of code as it executes through a series of procedures. This is especially useful when tracking nested procedures. To view a list of all the nested calls, select the button to the right of the Procedure box.

    If, for example, procedure A called procedure B, which called procedure C, the Call dialog will list procedure C, then B, then A, with the most recently called procedure listed at the top.

    The procedures are added to the list when they are called and removed from the list as they are completed.

    Try This: A Visual Basic Debugging Interface Tour

    Insert a new Module. Display the Debug Window.

    The Immediate Pane

    1. Activate the Immediate pane and type the following:

      2. x = 2 <Enter>
      y = 3 <Enter>
      z = x + y <Enter>
      ? z <Enter.
      The result "5" is displayed in the Immediate pane.
    2. The previous example could have been written as follows:

      3. x = 2 : y = 3 : z = x + y : ? z <Enter>
    3. Type the following:

      4. L = len("The len function") : ? L <Enter>
      The result is 16.
    4. Type the following:

      5. MsgBox "Howdy!"
      Any command that can be entered in the code window can be entered in the Immediate Pane.

    The Watch Pane

    1. Type the following code on a new module sheet:

      2. Sub Main()
      Dim sum as Integer
      sum = Add (3, 6)
      End Sub

    2. Insert a second Module sheet and enter the following code:

      3. Function Add(x, y) as Integer
      add = x + y
      End Function
    3. Run Main. It executes, but the value is not displayed where it can be viewed. Add the following line to Main under the "sum" line:

      4. Debug.Print "Sum: " & sum
    4. Run Main again. Now, open the Debug window and view the contents of the Immediate panel.
    5. Use the Watch pane to display the value of x, y, add and sum during execution. In Module2, select "x" and then click the Instant Watch button and choose Add. Repeat with the remaining variables.

    6. Click on "Sub main()" and press the F8 key (the Step Into command equivalent) the macro in Debug mode. Select the Watch tab in the Debug window.

    7. Step through the macro and view the values returned to the Watch pane.

    Procedure Call Stack

    1. Insert 3 new module sheets.
    2. Enter the following code in Module3:

      3. Sub one()
      two
      End Sub
    3. Enter the following code in Module4:

      4. Sub two()
      three
      End Sub
    4. Enter the following code in Module5:

      5. Sub three()
      one
      End Sub
    5. Select Module3. Click on "Sub one()" and press the F8 key five times. Click on the Procedure Call button. The Calls dialog displays the chain of procedures that have been called but have not finished executing.
    6. Select "GLOBAL.Module3.Sub One()" and press the Show key. The contents of Module3 are displayed.
    Handling Run-time Errors

    As mentioned earlier, run-time errors are errors that occur while the procedure executes and are not syntax related. For example, the procedure tries to open a file that does not exist, the user enters the wrong type of data in a dialog box or the wrong type of sheet is active when the procedure executes. Procedures can be written to anticipate these types of errors and correct the condition, alert the user to the problem or gracefully exit from the procedure.

    VB provides the programmer with three tools for working with run-time errors; the On Error statement, the Err function and the Error function.

    On Error

    The On Error statement has three forms

    On Error GoTo

    The On Error GoTo statement enables an error handling routine and specifies the location of the routine within a procedure. The routine must be located within the procedure which enables the error handling routine and error checking remains active until the procedure completes execution or it is turned off (see details below). The On Error GoTo statement is usually placed at the top of the procedure and then any error which occurs during the procedure directs execution to the routine. A suggested format for the statement is:

    Sub MySub()

    SubLabel:

    On Error GoTo ErrorHandler

    . . .

    Exit Sub

    ErrorHandler:

    . . .

    Resume Next

    End Sub

    Notice that the label "ErrorHandler" appears towards the bottom of the procedure and the name is followed with a colon (:). This tells VB that this is a line label. The line number may also be used but it is not as easy to read the code when numbers are used instead of labels.

    The Exit Sub statement is placed in the line preceding the error handling routine. This prevents the routine from executing in the event that no errors are found. The Resume Next statement instructs VB to return execution to the line immediately following the line that generated the run-time error. The Resume statement could also be followed by a label to be used as a reference for where to resume. In the above example, subsitiuting Resume SubLabel: for Resume Next would cause the macro to continue running at the label’s location.

    On Error Resume Next

    This form of the On Error statement instructs VB to resume execution at the line immediately following the line which generated the error. The programmer should then write error checking into the procedure to respond accordingly.

    On Error GoTo 0

    This statement disables error checking.

    The Err Function

    The Err function returns an integer which represents the most recent error that occurred in the program. For example, when a divide by zero error occurs, the Err function returns 11 or when a file not found error occurs, the value returned to Err is 53. The Err function can be used to determine the type of error that called an error handling routine.

    For a complete list of all the error values, search for "trappable errors" in the VB on-line Help.

    The Error Function

    The Error function returns a message as text which corresponds to a error number. For example, the following line will display a message which shows the error number and the error message of the most recent error:

    MsgBox "The most recent error number is " & Err _

    & ". Its message text is: " & Error(Err)

    Lesson 5 Exercises

    1. Is it possible to add a Watch while in Step Mode? If so, how?

      2. Yes, highlight the variable to watch in the code pane of the Debug window, press the Instant Watch Tool on the Visual Basic toolbar and choose the Add button. Or choose Tools Add Watch.

    2. Write a procedure which will do the following: Prompt the user for a file name. If the file exists, open the file. If the file does not exist, display a custom error message and then ask the user if they wish to try another file or stop the program. Take action as specified.

      3. Sub GetFile()

      Dim goodFile As Boolean

      On Error GoTo errorHandler

      Do

      goodFile = True

      fileName = InputBox(prompt:="Enter a filename")

      If fileName = "" Then Exit Sub

      FileOpen fileName

      If goodFile Then Exit Sub

      Loop

      errorHandler:

      goodFile = False

      Msg = "The file, " & fileName & ", is either already open or not available."

      x = Application.Message(Message:=Msg, Type:=pjYesNo, _

      YesText:="Try Again", NoText:="Exit Procedure")

      If x = True Then Resume Next

      End Sub


Lesson 1: Application and Project Objects

Lesson Objectives

Upon completion of this lesson, the participant will be able to:

  • Navigate through the Object Hierarchy.
  • Execute Application and Project Methods.
  • Understand how to locate different Methods and Properties.
  • Understand what a collection is.
  • Understand how and where macros are stored.

Some Topics to be introduced in this lesson include:

  • Object Hierarchy
  • Navigation Differences between 3.0 and 4.0
  • Moving the active cell.
  • Comonalities between Methods and Properties
  • CurrentView, Table and Filter

Overview of Object Hierarchy

Visual Basic for Applications allows each application to extend the Visual Basic language with application specific objects. Microsoft Excel exposes Workbook, Chart, and Cell objects whereas Microsoft Project exposes Project, Task, Resource, and Calendar objects. Of course, there are places of overlap. Both Microsoft Project and Excel expose Application and Windows objects and wherever possible the shared objects have the same properties and methods.

Nesting of Objects

Objects are nested within each other to form a hierarchy. The Application contains the Projects, which contain the Tasks, which contain the Assignments. It is probably easiest to understand the hierarchy of the Microsoft Project object model through a figure.

The Object Hierarchy for Microsoft Project

Navigation

As you can see, the Application object sits at the top of the hierarchy. From the Application object you can navigate down to any other object. For example, the Duration field is contained in a Task which is contained in a Project which is contained in the Application. So to modify the Duration, you specify:

Application.Projects(1).Tasks(3).Duration = "3d"

Fortunately, there are some shortcuts that are available when referencing objects. First, the Application object is optional when accessing objects within Microsoft Project. So you can use:

Projects(1).Tasks(3).Duration = "3d"

Additionally, there are some pre-defined reference objects for commonly used objects. For example, there is an ActiveProject object which always refers to the active project. So, if Projects(1) were the active project, the same duration field can be accessed like:

ActiveProject.Tasks(3).Duration = "3d"

ActiveCell.Task.Duration = "5d"

Common Objects

There are some objects which are common to Microsoft Project and Excel. For example, both products support automatic or manual recalculation. Hence, the Application objects in both products have a Calculation property. For example, the following code has the same effect in Excel as it does in Project.

Application.Calculation = True

Differences between Microsoft Project and Excel

One difference to note between the implementation of Visual Basic for Applications in Microsoft Project and Excel is the extent of their respective object models. Microsoft Excel has taken the approach of creating objects for all of the data and user interface. In Microsoft Project, the emphasis was on exposing objects for the unique scheduling data (tasks, resources, etc...) and a hierarchy for navigating to that data. Most of the user interface elements are left to statements (such as FileOpen).

This difference can be seen in things like the way you close a file. In Microsoft Project, you use the FileClose statement:

Projects(2).Activate

FileClose

In Microsoft Excel, you can do this in one step:

Workbooks(2).Close

Another important difference is in the level of user input available in Microsoft Project and Excel. Visual Basic for Applications currently only provides the Visual Basic language. Excel has implemented a dialog editor in the form of Dialog Sheets which allow the user to obtain much of the benefit of the stand-alone Visual Basic dialog editor. In Excel, you can attach code to buttons and tie controls to worksheet cells.

Microsoft Project, on the other hand, provides forms for entering information about tasks or resources. These custom forms can include any of the fields that Microsoft Project supports. If a great level of user interaction is required beyond entering information about tasks or resources, it may be advantageous to use the stand-alone Visual Basic and control Microsoft Project through OLE Automation. This way you can leverage the great dialog tools in Visual Basic, but still access the rich scheduling data and the user interface statements.

Application Object

The Application is at the top of the Object Model hierarchy. It is through the Application object that all other objects can be accessed. The Application object contains several interesting properties and methods which are useful in macros.

User Interface Commands and Methods

The Application object contains methods which correspond to the user interface actions. These are the same as the macro commands found in Microsoft Project 3.0. For instance:

Application.FileOpen Name:="project1.mpp"

Application.EditCopyPicture

Since the Application object is always optional when writing macros within Microsoft Project, you can specify these items simply by their name:

FileOpen Name:="project1.mpp"

EditcopyPicture

For people familiar with the macro language in Microsoft Project version 3.0, there are a few differences of importance. While the names of many of the methods remained the same, the names of some of the methods changed to make them less tied to the menu structure (since the menu structure tends to change from version to version).

For example, the 3.0 command "OptionsSetPlan" was renamed to "BaselineSave". This change reflects both the change in terminology introduced in Microsoft Project 4.0 (Baseline vs. Plan) and the move away from menu-based naming.

Functionality has been added to this class of Application methods in two ways. First, some methods have improved functionality over their 3.0 counterparts. For example, the FileSaveAs method now has the ability to specify a table name when exporting to a different file format like XLS. Second, methods have been added to access functionality that was not available in the 3.0 macro language, like GanttBarStyleEdit. This particular command allows the macro writer to create or modify Gantt bar styles, such as changing the pattern and color for milestones.

Application Object Methods

Application Methods are commands that execute a Project feature. For example, the CalculateProject method is the same as hitting F9 on your keyboard. FileOpen is the same as choosing Open from the File Menu.

Most of the Application methods are used for basic Project commands. For example, the File and Edit menu methods have the same effect as choosing items from under your File and Edit menus.

FileNew, FileOpen, FileClose, FileSave, FileSaveAs, FileExit, EditCut, EditCopy, EditPaste, EditDelete, etc...

Some of the more interesting and useful application methods are ones that enable movement control of the active cell.

SelectCellDown, SelectCellRight, SelectCellLeft, SelectCellUp, SelectColumn. These allow easy movement of the active cell, similar to using your arrow keys. The following macro calculates a formula in the Number1 field and then moves down 3 tasks and repeats the formula.

For I = 1 to 10

ActiveCell.Task.Number1 = ActiveCell.Task.Duration * 5

SelectCellDown 3

Next

Almost all actions that can be performed manually in Project can be achieved by running application methods from within a macro. When you record a macro, you are using the user interface to issue commands. Hence, when a macro is recorded, these Application methods are used.

Exercise1:

Using the record macro feature of Project, record a macro that records as many commands that you can think of. After you are finished recording, edit your macro and look at the different application methods it recorded.

Exercise2: (MoveRect)

Write a macro using application methods that saves a file you created, and then moves the active cell around in a rectangle of any size 5 times. Then close the file. (Do not use the macro recorder or help file, this is an exercise to help train your mind to think in "method" mode.)

Sub MoveRect()

FileSave

For i = 1 To 5

SelectCellRight 2

SelectCellDown 2

SelectCellLeft 2

SelectCellUp 2

Next i

FileClose

End Sub

Application Object Properties

Most of the Application Object properties are used to set up and change the environment. For example, the Top property returns the position on the screen of the application window. You can set this property to a different value to reposition the window. However, not all properties are editable. For example, the Version property simply reports what version of Project your are currently working with. You cannot set the value. Version = 5.0 would fail.

Options & Leveling Properties

Another useful aspect of the Application object is the ability to set the option properties which correspond to the settings found in the Options and Leveling dialogs. Many times users need to make sure that before running their macro certain settings are always set to specific values. By setting a series of Application properties ahead of time the user can insure consistancy.

LevelOrder = 2 ‘Sets the leveling order to Priority,Standard

StartYearIn = 3 ‘Sets the fiscal year to start in March

MoveAfterReturn = True ‘Self explanitory

Most of the settings found in the Tools/Options dialog are accessible through the Application object. The exception here are the settings which are project specific, like the default Standard Rate for new resources. Since these options are project specific, they are contained in the Project object.

The Application object also holds some of the code module settings which are derived from the system, such as date and time formats, and the list separator (from the Module General tab of the Options dialog). Since these items are controlled by the operating system, they cannot be set from within Microsoft Project. These options are very useful when writing macros which will be run in different countries which use different settings. For example, in the United States, the normal date order is Month-Day-Year, but many other countries use Day-Month-Year. A macro could query this setting to know how to interpret dates.

Exercise:

Using the list of properties for the Application Object from the help file, write a macro which displays several current values of properties from the Options and Leveling dialogs.

Corresponding Application Methods

All of the options which can be accessed via either the Application or Project objects property can also be set using an Application method. There is one Application method for each tab in the Options dialog. For example:

Application.Calculation = pjManual

is the same as

OptionsCalculation Automatic := False

And,

ActiveProject.AutoAddResources = True

is the same as

OptionsGeneral AutoAddResources := True

The advantage of using the properties is that you can determine the current setting of the option, as demonstrated in the following example which saved the state of calculation before setting it to manual.

bCalcSetting = Application.Calculation

Application.Calculation = pjManual

...

Application.Calculation = bCalcSetting

The advantage in using the method is that many options can be set at once. The following example shows how you can set some of the display options for the application using both properties and a method.

Application.DisplayStatusBar = True

Application.DisplayScrollBars = True

Application.DisplayNotesIndicator = False

OptionsView DisplayStatusBar:=True, DisplayEntryBar:=True,

DisplayScrollBars:=True, DisplayNotesIndicator:=False

For the options which are project specific, the corresponding Application method provides the functionality to set the default for new projects. In the Tools/Options dialog, near some of the project specific options there is a ‘Set as Default" button which records the settings of the current project as the default settings for new projects. With those Application methods, there is an accompanying SetDefaults argument which allows those settings to be recorded. For example, to set the hours per week to 40 for new projects, you can use the OptionsCalendar method:

OptionsCalendar HoursPerWeek:=40, SetDefaults:=True

The following sample combines the two approaches to make the current project specific settings the defaults for new projects.

OptionsCalendar StartTime:=ActiveProject.DefaultStartTime,

FinishTime:=ActiveProject.DefaultFinishTime,

HoursPerDay:=ActiveProject.HoursPer,

HoursPerWeek:=defHoursPerWeek,

SetDefaults:=True

Project Object

Project objects are located within the Application object and contain all of the project-level information, such as the start of the project and the manager, as well as the details of the project, namely the tasks and resources.

Referencing Project Objects

There are several ways of referencing a project object. The easiest way is by referencing the active project. There is a property of the application object called ActiveProject which returns the object corresponding to the active project.

MsgBox ActiveProject.ProjectStart

This example displays the start date of the active project in a dialog box.

You can also use the Projects collection to refer to a particular project. Projects can either be referenced by their index or by their name.

MsgBox Projects(1).ProjectStart

MsgBox Projects("project1.mpp").ProjectStart

CurrentView, CurrentTable and CurrentFilter

Some useful properties of a Project object are those relating to the Views, Tables, and Filters. Each project contains CurrentView, CurrentTable, and CurrentFilter properties. These return the name of the current view, table, and filter respectively. Using these properties allows you to make sure that the user is in the correct view before executing a macro or lets you save the user’s state so that it can be restored after the execution of a macro.

The following example records the current state of the project, prints a PERT Chart, and then returns the user to the correct state.

Sub PrintPERTChart()

strView = ActiveProject.CurrentView

strFilter = ActiveProject.CurrentFilter

ViewApply "PERT Chart"

FilePrint

ViewApply strView

If strFilter <> "" Then

FilterApply strFilter

End If

End Sub

List Collections

Another useful object found in the project object is related to the CurrentView, CurrentTable, and CurrentFilter properties. It is the List collection. The List collection is a collection of strings or numbers. Because it is a collection, you can iterate over all of the items in the list using the For Each...Next construct discussed earlier. You can also index the items in the list directly.

In the Project object, there are several List collections which correspond to the Views, Tables and Filters available for use by the project. For example, the TaskViewList contains the names of all of the task views available for the project. Similarly the ResourceFilterList contains all of the resource filters.

This example is a function which checks the current view to see if it is a task view. It uses both the CurrentView and the TaskViewList properties. (This example would only have problems if a resource view had the same name as a task view.)

Function InTaskView() As Boolean

Dim bFound as Boolean

Dim varTemp as Variant

bFound = False

For Each varTemp in ActiveProject.TaskViewList

If ActiveProject.CurrentView = varTemp then

bFound = True

Exit For

End If

Next varTemp

InTaskView = bFound

End Function

Remember, even if a view is not in the TaskViewList, this does not necessarily mean that it is a resource view. The Module Editor view for editing Visual Basic code is neither a task nor a resource view.

Exercise: (ApplyAView)

Write a macro that prompts the user to enter the name of a task view and them applies it only if it is available. If it is not them return an error message.

Sub ApplyAView()

test = False

myView = InputBox("Enter a View to display: ")

For Each item In ActiveProject.TaskViewList

If LCase(item) = LCase(myView) Then

ViewApply Name:=myView

test = True

End If

Next item

If test = False Then MsgBox "View Does not exist"

End Sub


Lesson 2: Task, Resource and Assignment Objects

Lesson Objectives

Upon completion of this lesson, the participant will be able to:

  • Reference a tasks, resources and assignments.
  • Perform functions on tasks and resources.
  • Change values of fields for tasks, resources and assignments.

Some Topics to be introduced in this lesson include:

  • Referencing fields
  • Linking tasks
  • Outlining tasks
  • Getfield and Setfield functions.
  • Accessing Assignment information

Task Object

Of course, the main objective of the Project object is to hold the scheduling information for the project, namely tasks and resources.

Referencing a Task

As with Project objects, tasks can be referenced in several different ways. A task object can be referenced via the Tasks collection either by ID, Unique ID, or Name.

Tasks(1)

Tasks.UniqueID(4)

Tasks("Juggle the cat")

There are advantages and disadvantages to each of these methods. Referencing by ID (or row number) is the most straightforward, since these numbers are displayed to the user during the normal operation of Microsoft Project. Since inserting and deleting tasks can cause the ID of a task to change, referencing with the ID will not be reliable if the macro must always refer to the same task.

Referencing by UniqueID allows you to always refer to the same task, but is conceptually more difficult because this information is not normally viewed.

Lastly, referencing by name makes for very readable code since you are able to refer to the task by name. The drawback is that Microsoft Project supports multiple tasks with the same name, so referencing by name would only allow you to refer to the first task with a particular name.

Task Information

There are basically three different kinds of information contained in a task - Fields, Schedule Logic, and Structure. While there is some overlap between these types, it serves as a model for organizing the information contained in a task.

Fields (Properties)

Almost all of the information in a task can be found in one of the fields Microsoft Project supports and so access to fields is an important part of Visual Basic for Applications in Microsoft Project. Microsoft Project supports many different task fields. These fields are simply accessed as a property of the task object which corresponds to the field name.

For example, to change the duration of a task, you would do something like:

ActiveProject.Tasks(3).Duration = "3d"

The Duration field (or the Duration property of a Task) is a good example of the use of a field in Visual Basic for Applications. As shown in the example, the Duration property accepts a string. It will also accept a number which is interpreted as the number of minutes in the duration:

ActiveProject.Tasks(3).Duration = 1440 '3d * 8h/d * 60m/h

In the normal use of the product, there are some cases where the duration of a task is calculated and therefore cannot be modified. The most common occurrence is when the task is a summary task. Summary tasks summarize the information of the subtasks indented below them in the outline. Since Microsoft Project also supports a Summary field, it is easy to determine whether or not the a task is capable of having its duration changed:

If Not ActiveProject.Tasks(3).Summary Then

ActiveProject.Tasks(3).Duration = "3d"

End If

Additionally, there are many fields which one normally associates with a task, such as Duration and BaselineStart, which are also applicable to the project itself. For this reason, Microsoft Project supports all the task fields in the Project object as well. As with a summary task, most of these fields are calculated and cannot be changed.

MsgBox ActiveProject.Duration

This example would show the length of the project in a dialog box.

Another interesting example of task information is the resource assignments. Microsoft Project supports several task fields which can display the resources assigned to a task –Resource Names displays the names of the resources working on a task, Resource Initials displays the initials of the resources, and Resource Group displays the groups containing the resources.

As with any other field, these are all exposed as properties of a task.

MsgBox ActiveProject.Tasks(3).ResourceNames

This example would display the names of the resources working on task 3 in the same way as the Resource Names column in the Gantt Chart does.

Additionally, we have added objects which give users access to the same information:

MsgBox ActiveProject.Tasks(3).Resources(1).Name

would display the name of the first resource assigned to task 3.

Lastly, both the Task and the Resource objects contain an Assignment object which details the information about the assignment of a resource to a task. The details of the Assignment object are discussed later.

Schedule Logic

Another important body of information in a task is the schedule logic. In Microsoft Project, the logic is determined by creating predecessor and successor relationships. One method of examining the logic of a task is to refer to the fields which display this information as a string:

MsgBox ActiveProject.Tasks(3).Predecessors

This example would display something like "2FS+3d" to indicate that task 2 is a predecessor with a lag of 3 days.

As with resource assignments, Microsoft Project provides some of this information in an object form as well. PredecessorTasks and SuccessorTasks are collections of tasks which are the predecessors and successors of the task in question. So:

MsgBox ActiveProject.Tasks(3).PredecessorTasks(1).Duration

would display the duration of the first predecessor task of task 3.

Microsoft Project also supplies methods for manipulating task relationships. The LinkPredecessors and LinkSuccessors methods allow the macro writer to create either predecessor or successor relationships. Similarly, UnlinkPredecessors and UnlinkSuccessors allow the removal of relationships.

The following macro would unlink task 3 from all its successors:

Set x = ActiveProject.Tasks(3)

x.UnlinkSuccessors(x.SuccessorTasks)

Structure

The last kind of information contained in a task is the structure or organization of the tasks. In Microsoft Project, tasks are organized into an outline where summary tasks summarize the information of the subtasks indented below them. This is also known as a Work Breakdown Structure or WBS.

Again, this information can be derived from fields that are accessible in the product. OutlineLevel gives the outline level of a task with 1 being the top of the outline and 10 being the lowest outline level. OulineNumber gives the automatically generated WBS Code based on the outline. The second task under the third summary task would have an Outline Number of "3.2".

As with some of the other fields, Microsoft Project also provides this information in an object form. OutlineChildren is a collection of the subtasks of a given task. OutlineParent is the reverse - the summary task of a given task. With these two collections, it is possible to navigate the outline structure directly.

Sub Siblings()

Set objParent = ActiveCell.Task.OutlineParent

For Each objTemp In objParent.OutlineChildren

strTemp = objTemp.Name & ListSeparator & strTemp

Next objTemp

'Remove the last List Separator

strTemp = Left$(strTemp, Len(strTemp) - Len(ListSeparator))

MsgBox strTemp

End Sub

This example displays the names of all the tasks which have the same parent as the currently selected task.

To modify the outline, methods are exposed which move the task between outline levels. OutlineIndent moves a task down one level in the outline structure. OutlineOutdent does the reverse and moves the task up in the outline structure. Additional methods are available which change the appearance of the outline on screen. OutlineHideSubtasks will hide the subtasks of a summary task. OutlineShowSubtasks will show any hidden subtasks of a summary task. OutlineShowAllTasks will show all hidden subtasks of any summary task.

To link and unlink tasks together you can use the LinkPredecessors or LinkSuccessors methods. The following example prompts the user for the name of a task and then makes the task a predecessor of the selected tasks.

>Sub LinkTasksFromPredecessor()

>Dim Entry ' Task name entered by user

>Dim T ' Task object used in For Each loop

>Dim Exists ' Whether or not the resource exists

>' Prompt the user for the name of a task to turn into a predecessor.

>Entry = InputBox("Enter the name of a task:")

>Exists = False ' Assume task doesn't exist.

>' Search active project for the specified task.

>For Each T in ActiveProject.Tasks

>If T.Name = Entry Then

>Exists = True

>' Make the task a predecessor of the selected tasks.

>ActiveSelection.Tasks(1).LinkPredecessors Tasks := T

>End If

>Next T

>' If task doesn't exist, display error and quit Sub procedure.

>If Not Exists Then

>MsgBox("Task not found.")

>Exit Sub

>End If

>End Sub

Exercise1: (TaskTraverse)

Write a macro that traverses a listing of tasks. If the duration is greater than 5 days then remove 10% of the duration from that task. Also check to see if a summary task has more than 5 children. If so then collapses that outline.

>Sub TaskTraverse()

>For Each t In ActiveProject.Tasks

>If t.Duration > 5 * 480 Then t.Duration = t.Duration * 0.9

>If t.Summary Then

>If t.OutlineChildren > 5 Then t.OutlineHideSubtasks

>End If

>Next t

>End Sub

Exercise2: (TaskLink)

Write a macro that will automatically link only the first two tasks under a summary task.

>Sub TaskLink()

>For Each t In ActiveProject.Tasks

>i = 0

>If t.Summary Then

>If t.OutlineChildren > 1 Then

>idTmp1 = t.ID + 1

>idTmp2 = t.ID + 2

>ActiveProject.Tasks(idTmp2).LinkPredecessors Tasks:=ActiveProject.Tasks(idTmp1)

>End If

>End If

>Next t

>End Sub

Resource Object

The Resource object follows the same guidelines as the Task object. Access to all of the fields are available directly as properties of the object.

Referencing a Resource

As with the Task object, there are several ways of referencing a Resource object. A Resource object can be referenced via the Resources collection either by ID, Unique ID, or name.

Resources(3)

Resources.UniqueID(10)

Resources("Ken")

The same advantages and disadvantages of these methods that are seen in the Task object apply to the Resource object as well. The only difference is that you do not normally have multiple resources with the same name, so indexing by name is more reliable with Resource objects than it is with Task objects.

Resource Information Fields (Properties)

Just like with the Task object, the fields associated with a resource are accessible as properties of the Resource object:

ActiveProject.Resources("Susan").StandardRate = "$25.00/h"

ActiveProject.Resources(3).BaseCalendar = "Night Shift"

This is the easiest and most understandable way of accessing the information for a resource.

GetField and SetField Methods

Another set of methods is also available for both Task and Resource objects which allow you to access field information. These are the GetField and SetField methods.

GetField takes a field number and returns the contents of the field as a string. This is useful if you want to ensure that the value returned is a string. It is also useful if you want to programmatically access fields at run-time.

This example prompts for the name of a field and then displays the information contained in that field on a resource view:

Sub DisplayField()

strTemp = InputBox("Enter the name of the field you want to see")

strTemp = LCase(strTemp)

Select Case strTemp

Case "name"

intFieldID = pjResourceName

Case "initials"

intFieldID = pjResourceInitials

Case "standard rate"

intFieldID = pjResourceStandardRate

Case ""

End

Case Else

MsgBox "You entered a field I don’t understand"

End

End Select

MsgBox(ActiveCell.Resource.GetField(FieldID:=intFieldID))

End Sub

The SetField method is the reciprocal of GetField. It takes a field number and the string value to which you want to set the field.

ActiveCell.Resource.SetField FieldID:=pjResourceName,_

Value:="Jimbo"

Exercise1:

Write a macro that will prompt the user to enter the name of a resourse and then display the value for the Max units and ask them if they would like change the value. If yes then get the new value and make the change.

>Sub ResMaxUnits()

>RName = InputBox("Enter the name of the resource to edit")

>RMax = InputBox("The Max Units for " & RName & " is " & _ ActiveProject.Resources(RName).GetField(FieldID:=pjMaxUnits) & " Do you want to Change it? Y/N")

>If RMax = "y" Then

>ActiveProject.Resources(RName).MaxUnits = InputBox("Enter new value")

>End If

>End Sub

Assignment Object

The Assignment object holds information about how work on a task is being accomplished by a resource. The information includes the amount of work, the cost, and the start and finish dates of the work on the task. In Microsoft Project you can see this information through either the Task Form or Resource Form views.

Referencing an Assignment

Assignment objects are referenced by a Unique ID value associated with each assignment. Because these values are not necessarily sequential, it is probably easier to iterate over the Assignments collection with For Each...Next to find the particular assignment you want to work with.

Fields (Properties)

As with Task and Resource objects, Assignment objects provide access to the information contained in the assignment fields. This includes fields such as Actual Cost, Overtime Work, and Units.

This example provides a list of all the tasks a resource is working on in the resource’s Text1 field in much the same way that the Resource Names field of a task displays all the resources working on the task:

Sub TaskNamesField()

Dim Sep, strTemp As String

Dim r, a As Object

Sep = ListSeparator

For Each r In ActiveProject.Resources

strTemp = ""

For Each a In r.Assignments

strTemp = a.TaskName & Sep & strTemp

Next a

'Remove the last List Separator

strTemp = Left$(strTemp, Len(strTemp) - Len(Sep))

r.Text1 = strTemp

Next r

End Sub

Assignment Information Over Time

Because the work on a task occurs over a period of time, it is often useful to view the allocation of resources over time. While the Assignment object does not contain this information in a time-phased manner, the TimescaledData method of the Application object does allow you to access it programmatically.

The TimescaledData method takes several arguments to specify the task and resource combination you wish to examine, the date range, the type of periods (such as Week vs. Day), and the type of information (Work vs. Cost). It returns a string containing the values for each period separated by the List Separator. You can then parse the string to determine the values in each period.

This example displays a dialog box of the return timescaled data. It is the assignment of resource 1’s work broken down in hours across the entire project.

MsgBox TimescaledData(ActiveCell.Task.ID, 1, ActiveProject.ProjectStart, _

ActiveProject.ProjectFinish, pjWork, pjTimescaleHours)

Exercise1: (AssignWork1)

Write a macro that finds all assignments of an inputed resource and removes 1 hour of work from each assignment.

>Sub AssignWork1()

>RName = InputBox("Enter the name of the resourse to remove work from:")

>For Each t In ActiveProject.Tasks

>For Each r In t.Assignments

>If r.ResourceName = RName Then r.Work = r.Work - 60

>Next r

>Next t

>End Sub

Exercise2: (AssignWork2)

Write a macro that finds all assignments of all task with the name equal to the text1 field of the task and adds 20% more work than it already has.

>Sub AssignWork2()

>For Each t In ActiveProject.Tasks

>For Each r In t.Assignments

>If r.ResourceName = t.Text1 Then r.Work = r.Work + r.Work * 0.2

>Next r

>Next t

>End Sub


Lesson 3: Calendar, Selection and Window Objects

Lesson Objectives

Upon completion of this lesson, the participant will be able to:

  • Manipulate the working calendar.
  • Use Date arithmetic.
  • Reference the active cell and task.
  • Manipulate Windows inside Project.

Some Topics to be introduced in this lesson include:

  • Period Method
  • Weekday object
  • Shifts
  • Date Arithmetic.
  • ActiveCell/ActiveSelection
  • Window activating

Calendar Object

For the objects discussed so far, almost all of the information that is available via the object model was accessible through Dynamic Data Exchange (DDE) in Microsoft Project 3.0. The Calendar object presents information which was previously only accessible through the Microsoft Project Exchange (MPX) file format.

The Calendar object contains information about when work can take place during the project including the days and the times during the day that are available for work. Additionally, each resource has its own calendar which can contain information about differences, such as vacations, from the normal calendar.

Calendar Object Hierarchy

Period Method and Object

The easiest way to access information in a calendar is to use the Period method. The Period method takes a range of dates and returns a Period object. A Period object is like a collection of days except that you cannot iterate over the days in a Period. For example, to specify Independence Day in the United States as a nonworking day, one could do:

ActiveProject.BaseCalendars("Standard").Period("7/4/94") _

.Working = False

Note that if the finish date of a range is not given, as in this example, the period returned is the one day.

The following example sets July 4th and July 5th as nonworking:

With ActiveProject.BaseCalendars("Standard")

.Period("7/4/94", "7/5/94").Working = False

End With

This method is very useful when the range you want to work with cannot be easily described by the Year, Month, and Day objects.

Year, Month, Day Objects

A more object oriented way of manipulating information in a calendar is to access the Year, Month and Day objects contained in the calendar. With these objects and the collections which contain them, one can perform more powerful operations on the calendar.

For Each y in ActiveProject.BaseCalendars("Standard").Years

y.Months(7).Days(4).Working = False

Next y

By using the objects, one can make the 4th of July a nonworking day every year. To make the code a little more readable, one could instead specify the name of the month like:

For Each y in ActiveProject.Calendar.Years

y.Months("July").Days(4).Working = False

Next y

Weekday Objects

The final way of manipulating the calendar is to access the Weekday object. Microsoft Project allows the user to specify a day of the week as a working day or as a day off. This makes it easy to make a 4 day work week instead of the standard Monday through Friday.

One could make all Fridays nonworking like:

ActiveProject.BaseCalendars("Standard").Weekdays(6).Working = False

To make the code more readable, as was done with the Month object, there are two choices. One could use a defined constant:

ActiveProject.BaseCalendars("Standard").Weekdays(pjFriday) _

.Working = False

Or use the name of the day:

ActiveProject.BaseCalendars("Standard").Weekdays("Friday") _

.Working = False

Properties and Methods

The Period, Year, Month, Day, and Weekday objects share most of the same properties and methods.

The Working property that was used in the above examples sets whether or not work can occur on the range of the calendar specified by the object.

The Shift1, Shift2, and Shift3 properties return a Shift object which allows you to specify the Start and Finish time for a shift

The Default method applies to resource calendars. It returns the object to the state of its associated Base Calendar.

An example which uses more of these properties would be one to make Fridays a half-day of work:

With ActiveProject.BaseCalendars("Standard").Weekdays("Fri")

.Working = True

.Shift1.Start = "8:00"

.Shift1.Finish = "12:00"

.Shift2.Clear

.Shift3.Clear

End With

Scheduling Methods

One of the most interesting set of methods exposed by Microsoft Project are those which give the macro writer access to scheduling capabilities. Microsoft Project provides methods to add and subtract dates as well as display dates and durations in different formats.

Date Arithmetic

By exposing date arithmetic methods in Microsoft Project, a realm of different macros are possible. It also makes it possible to include Microsoft Project as a part of an integrated scheduling solution. With these methods, a Solution Provider could use Microsoft Project as a scheduling engine by either entering the information into Microsoft Project, or by just using the date arithmetic methods directly.

DateAdd

The DateAdd method accepts a start date and a duration and returns the finish date. Optionally, you can specify a calendar to be used in the calculation. If a calendar is not specified, then the project calendar is used.

x = DateAdd("7/11/94 8:00am", "3d")

In this example, x would be 7/13/94 at 5:00pm, since a 3d activity beginning on July 11th at 8:00am would end at the end of July 13th.

DateSubtract

The DateSubtract method is the reciprocal of the DateAdd method. It accepts a finish date and a duration and returns the start date. As with the DateAdd method, you can optionally specify a calendar.

x = DateSubtract("7/13/94 5:00pm", "3d")

Being the complement of DateAdd, this example would return 7/11/94 at 8:00am.

DateDifference

The DateDifference method is related to both DateAdd and DateSubtract method. It takes two dates and returns the duration between them. Again, a calendar can be optionally specified.

x = DateDifference("7/11/94 8:00am", "7/13/94 5:00pm")

Here, DateDifference would return 1440 minutes which is 3 days.

Date Arithmetic Example

Using these methods, you can create a fairly simple macro which will adjust all of the dates in a project when your project start date slips:

Sub AdjustDates()

nCurDateFormat = Application.DefaultDateFormat

Application.DefaultDateFormat = pjDate_mm_dd_yy_hh_mmAM

sStartDate = ActiveProject.ProjectStart

sNewStartDate = InputBox(Prompt:="Enter New Start Date", Default:=sStartDate)

If sNewStartDate = "" Then End 'Canceled the InputBox

nDelta = DateDifference(sStartDate, sNewStartDate)

If nDelta = 0 Then

MsgBox "New start date must be greater than current start date."

End

End If

For Each t In ActiveProject.Tasks

If t.ConstraintDate <> "" Then

Select Case t.ConstraintType

Case pjMFO, pjFNLT, pjFNET

‘Finish Constraints are fine

t.ConstraintDate = DateAdd(t.ConstraintDate, nDelta)

Case Else

'Start Constraints are problematic.

'8:00am + 1d gives 5:00pm. Since we want 8:00am the

'next day, we add 1d+1m and then subtract the 1m

t.ConstraintDate = DateAdd(t.ConstraintDate,nDelta + 1)

t.ConstraintDate = DateSubtract(t.ConstraintDate, 1)

End Select

End If

Next t

ActiveProject.ProjectStart = sNewStartDate

Application.DefaultDateFormat = intCurDateFormat

End Sub

Date & Duration Formatting

Related to the Date Arithmetic methods are some methods which allow you to display dates and durations in different formats.

DateFormat

DateFormat takes a date and a constant specifying the format in which you want the date to appear. The available formats are the same as the default formats for displaying information in Microsoft Project.

MsgBox DateFormat("12/31/94", pjDate_mmmm_dd_yyyy)

This example would display ‘December 31, 1994’ in a dialog box.

DurationFormat

Similar to the DateFormat method, DurationFormat takes a duration and a constant specifying the units in which you want the duration to appear. The available units are minutes, hours, days, and weeks.

MsgBox DurationFormat("3d", pjWeeks)

This example would display ‘.6w’ in a dialog box.

DurationValue

Although the DurationValue method does not affect the formatting of a duration, it is closely related to the DurationFormat method. DurationValue take a string and returns the value of that string as a duration. Microsoft Project expresses durations in minutes, so 1 day = 8 hours = 480 minutes.

x = DurationValue("2d")

Here, x would be set to 960 which is the number of minutes in 2 days.

Because durations are expressed in minutes, you can add durations using normal arithmetic. For example, the following code would add the entered duration to the selected task.

x = DurationValue(InputBox("Enter amount by which to increase _ duration"))

ActiveCell.Task.Duration = ActiveCell.Task.Duration + x

strTemp = "The new duration in weeks is "

strTemp = strTemp & DurationFormat(ActiveCell.Task.Duration, pjWeeks)

MsgBox strTemp

Exercise1: (CalRangeSet)

Write a macro that schedules a Christmas break. First propmt the user for a date range, and set those days in that range to nonworking on the base calendar.

Sub CalRangeSet()

DRangeStart = InputBox("Enter the Start date of the break")

DRangeFinish = InputBox("Enter the Finish date of the break")

ActiveProject.BaseCalendars("Standard").Period(DRangeStart, DRangeFinish).Working = False

End Sub

Exercise2: (CalTaskMove)

Write a macro that prompts the user for an amount of time ("3d") and then creates a new task that starts that many days after the previous task.

Sub CalTaskMove()

Dim newTime As String

newTime = InputBox("Enter the a duration")

x = ActiveProject.Tasks(ActiveCell.Task.ID - 1).Start

ActiveCell.Task.Start = DateAdd(x, newTime)

End Sub

Selection Objects

Even though Microsoft Project does not supply objects for all of the user interface elements in the product, selection of information is provided so that macro writers can manipulate information based on the users selection.

Theory

Microsoft Project supports two variations of the active selection: a Cell object accessible from the ActiveCell property of the Application, and a Selection object available through the ActiveSelection property of the Application.

Since Microsoft Project can be thought of more as a database with records and fields than a spreadsheet with rows and columns, both the Cell and Selection object provide information about the selected records (tasks or resources) and the selected fields.

Cell Object

The Cell object allows access to the active record and field in the selection. This is sometimes a subset of the selection, if the selection contains more than one cell.

To determine the record, the Cell object contains a Task and a Resource object. This allows the macro writer to access all of the fields of the selected record. For example:

MsgBox "You have task " & ActiveCell.Task.Name & " selected."

will display the name of the task regardless of the field selected.

There are occasions where a task will not be selected, for instance in a resource view. In this case, ActiveCell.Task will return Nothing. So a more robust version of this example would be:

If Not (ActiveCell.Task Is Nothing) Then

MsgBox "You have task " & ActiveCell.Task.Name & " selected."

End If

To determine the field selected, the Cell object provides two properties. The FieldName property contains the name of the field as a string. So we could do:

If Not (ActiveCell.Task is Nothing) Then

strTemp = "You have the "

strTemp = strTemp & ActiveCell.FieldName

strTemp = strTemp & " field of "

strTemp = strTemp & ActiveCell.Task.Name

strTemp = strTemp & " selected."

MsgBox strTemp

End If

The FieldID property returns the ID number of the field which can be used with either the GetField or the SetField methods discussed earlier.

If Not (ActiveCell.Task is Nothing) Then

strTemp = InputBox("Enter value to be placed in the Active Cell")

ActiveCell.Task.SetField(FieldID:=ActiveCell.FieldID, Value:=strTemp)

End If

Selection Object

The Selection object is an extension of the Cell object. Instead of the Task and Resource objects contained in the Cell object, the Selection object contains Tasks and Resources collections. Similarly, in place of the FieldName and FieldID properties are FieldNameList and FieldIDList List collections.

With the Selection object one could implement a version of the Fill Down command found in Microsoft Project and Excel.

If Not (ActiveCell.Task is Nothing) Then

strTemp = InputBox("Enter value to be placed in all the cells in the same column as the active cell")

For Each t in ActiveSelection.Tasks

t.SetField(FieldID:=ActiveCell.FieldID, Value:=strTemp)

Next t

End If

Exercise

Write a macro that will increment a counter in a cell. For example, if you type a 1 in a cell and select it plus cells below and then run the macro, you would end up with these cells being filled with 1, 2, 3, 4, 5. See if you can also get it to work with text. Ex. Phase1, Phase2, Phase3, etc.

Window & Pane Objects

The Window and Pane objects offer a limited set of properties, but are useful when you want to manipulate some of the visual properties of your project windows.

A Window object provides a Close method, allowing you to close a window. This is useful when you have multiple windows open for the same project. This example closes the active window:

ActiveWindow.Close

To change the height of a window:

ActiveWindow.Height = 400

To change the state of the current window, use the WindowState property. There are three states to choose from, pjMaximized, pjMinimized, and pjNormal. To maximize the window use:

ActiveWindow.WindowState = pjMaximized

Project also allows control over each individual pane within the active window through the pane object. To determine which pane is active in a window:

ActiveWindow.ActivePane

This returns 1 for the top pane, and 2 for the bottom pane.

You can manipulate the panes in a window as objects directly:

ActiveWindow.TopPane.Activate

This activates the top pane. You could also use the Application object property PaneNext which Activates the lower pane if the upper pane is active or activates the upper pane if the lower pane is active.

ActiveWindow.BottomPane.Close

This closes the bottom pane.

Another way to close the bottom pane is to use the Application objects PaneClose method. This is the same as choosing remove split from the window menu. If you want to split the screen, then use PaneCreate.


Lesson 4: View, Table and Filter Methods

Lesson Objectives

Upon completion of this lesson, the participant will be able to:

  • Apply Views, Tables and Filters.
  • Create and edit Views, Tables and Filters.
  • Access lists of Tables, Views and Filters.

Some Topics to be introduced in this lesson include:

  • ViewApply and ViewEdit
  • TableApply and TableEdit
  • FilterApply and FilterEdit
  • ViewList, TableList, FilterList

Views Methods

Project gives you full control over views by using Application Object methods. Here is a listing of the possible view methods.

ViewApply Sets the view in the active window. The same as choosing View More Views and then applying a view from the list. To set the Module Editor View use the following.

ViewApply name:="Module Editor", singlePane:=True

ViewEditCombination and ViewEditSingle Methods allows the user to create or edit a single or combination view. The benefit is that the user does not have to see any dialog box displayed.

ViewEditCombination name := "Kris' View", create := True,_ topView := "Resource Sheet",_ bottomView := "Resource Graph"

ViewEditSingle name := "Kris' Task Schedule", create := True, _ filter:="In Progress Tasks", table := "Schedule"

The ViewList method is used to return a view name or a list of all view names defined in the project. TaskViewList only returns those that are task views.

For Each t In ActiveProject.ViewList

MsgBox t

Next t

There are 15 ViewShowXXXX methods, which allows you to format the task and resourse forms. The equivalent would be going to your format menu choosing details and then picking one type from the list. The 15 types are: Availability, Cost, CumulativeCost, CumulativeWork, Notes, Objects, Overallocation, PeakUnits, PercentAllocation, PredecessorsSuccessors, ResourcesPredecessors, ResourcesSuccessors, Schedule, SelectedTasks, and Work

ViewShowSchedule

Exercise

Write a macro that creates and applies a split screen view with a Task Sheet on top and a Task Form on the bottom formated to show Resource Cost. (**Do not use the macro recorder)

Tables Methods

The Tables method is another Application Object method. It is used for setting the active pane in the active window. If you executed the Tables method it would simply bring up the More Table dialog box.

In order to give the user more control, Project supplies the TableApply method. When used, the user must supply a valid name of a table. In return, no dialog box will be displayed.

TableApply "Tracking"

If you would like to create a new or edit an existing table, you should use the TableEdit method. This method allows full customization of 15 options in a table. The following macro command will create a new table called Flags containing task information and does not appear in the menu.

TableEdit name := "Flags", taskTable := True, create := True, _

fieldName := "Priority", showInMenu := False

The TaskTableList and ResourceTableList methods are used to return a task or resource table name or a list of all task or resource tables currently defined in the project.

For Each t In ActiveProject.TaskTableList

MsgBox t

Next t

Exercise1

Using the list of customizable options for a table, listed in online help, write a macro that creates a new table containing fields: ID, Name, Actual Start, and Actual Finish. Do not use the macro recorder. (Hint: A new TableEdit line is necessary for each field you add)

Filter Methods

The Filters method is another Application Object method. It is used for setting the filter of the active pane in the active window. If you made a call to the Filters method it would simply bring up the More Filters dialog box.

In order to give the user more control, Project supplies the FilterApply method. When used, the user must supply a valid name of a filter. In return, no dialog box will be displayed.

FilterApply "Milestones"

If you would like to create a new or edit an existing Filter, you should use the FilterEdit method. This method allows full customization of 12 options in a filter. The following example creates a filter for tasks with the highest priority (if one doesn't exist), and then applies the filter.

Sub CreateAndApplyHighestPriorityFilter()

Dim TaskName ' Index for For Each loop

Dim Found ' Whether or not the filter exists.

Found = False ' Assume the filter doesn't exist.

For Each TaskName In ActiveProject.TaskFilterList

If TaskName = "Highest Priority" Then

Found = True

Exit For

End If

Next TaskName

' If filter doesn't exist, create it.

If Not Found Then FilterEdit Name:="Highest Priority", _

create:=True, taskFilter:=True,_

FieldName:="Priority", _

test:="equals", value:="Highest"

' Apply the filter.

FilterApply "Highest Priority"

End Sub

The TaskFilterList and ResourceFilterList methods are used to return a task or resource filter name or a list of all task or resource filters currently defined in the project.

For Each t In ActiveProject.FilterTableList

MsgBox t

Next t

Exercise1

Using the list of customizable options for a filter, listed in online help, write a macro that creates a new interactive filter that will prompt the user to enter a beginning ID and an Ending ID, then displays only milestones in that range. Do not use the macro recorder. (Hint: A new FilterEdit line is necessary for each row you add)


Lesson 5: Sorting and Multiple Projects

Lesson Objectives

Upon completion of this lesson, the participant will be able to:

  • Sort
  • Consolidate Projects
  • Share Resources

Some Topics to be introduced in this lesson include:

  • Sorting
  • Consolidation
  • Resource Sharing

Sort Method

The Sort Method allows the user to sort the tasks or resources in the active pane. The user supplies the keys and direction, either ascending or decending

Sort Key1:="Priority", ascending1:=True, Key2:="Start",

ascending2:=False, renumber:=false, outline:=False

Multiple Projects

Consolidation

The ConsolidateProjects Method allows the user to consolidate many projects together into one. The syntax is:

ConsolidateProjects filenames, newWindow, attachToSources,_

poolResources, hideSubtasks

filenames is a listing of the different files you want to consolidate.

newWindow specifies whether to create a new window for the projects you specify with the filenames argument.

attachToSources specifies whether changes in the consolidated project affect source projects.

poolResources specifies whether to pool the resources of the projects you specify with the filenames argument

hideSubtasks specifies whether to hide the subtasks of the projects you specify with the filenames argument.

The following example creates a consolidated project, prints a report, and closes the consolidated project without saving it.

Sub ConsolidatedReport()

ConsolidateProjects Filenames := "project1.mpp,project2.mpp"

ReportPrint Name:="Critical Tasks"

FileClose save := pjDoNotSave

End Sub

Resource Sharing

The ResourceSharing Method allows Control over resource sharing. It takes three arguments.

object.ResourceSharing share, name, pool

share specifies whether to share resources.

name specifies the filename of the resource pool.

pool specifies whether resources in the pool take precedence over resources in the local project.

The following line of code sets the active project to use resources from a file called "Pool.mpp"

ResourceSharing share:=True, name:="Pool.mpp"

The ResourceSharingPoolAction Method Performs specific actions on a resource pool.

ResourceSharingPoolAction action, fileName, readOnly

By setting the action parameter it will do 1 of 5 actions: Causes the resource pool to take precedence over the sharers. Causes the sharers to take precedence over the resource pool. Opens the sharer (the file specified with the fileName argument). Opens all sharers into a consolidated project or Unlinks the sharer from the resource pool. (The sharer is specified with the fileName argument.)

A property that can be useful is the resourcePoolName property. It simply Returns the filename of the resource pool used by a project. If it is not using a resource pool it returns the name of the project.

msgbox resourcePoolName


Lesson 1: Starting, Activating, and Closing Applications

Lesson Objectives

Upon completion of this lesson, the participant will be able to:

  • Describe and demonstrate how to activate an application via a macro.
  • Describe and demonstrate how to maximize or minimize an application via a macro.
  • Describe and demonstrate how to start an application via a macro.
  • Describe and demonstrate how to close an application via a macro.
  • Describe and demonstrate how to tell if an application is running via a macro.

Some Topics to be introduced in this lesson include:

  • Activating Applications
  • Maximizing and Minimizing Applications
  • Starting Applications
  • Closing Applications
  • How To Tell If An Application Is Running

Activating Applications

Switching to another application means the same thing as "giving it focus" or "activating" it. There are a variety of ways a macro in a source application can make a target application active. Most of them require that the target application is running and is in the Windows Task List. An "invisible" application is one that is running in memory, but is not physically visible and does not show up in the Windows Task List. Throughout Module 3, unless specified otherwise, the phrase "visible application" or "running visibly" means the application is in the Windows Task List, not that it's physically visible. This concept is covered in detail in Lesson 3.

If invisible applications aren't strange enough, an application can have no windows at all, so there is nothing to activate. Such an application can still show up in the Windows Task List, for example a VB3 program that has a Main procedure but no Forms. The rest of Module 3 assumes all running applications have a window and are in the Windows Task List unless specified otherwise.

Here's some items related to activating an application:

  • AppActivate
  • AppMaximize, AppMinimize, AppRestore (MSProject window only)
  • Visible Property
  • Shell
  • AppExecute

AppActivate

The most common way to activate an application The application to be activated has to be in the Windows Task List. AppActivate is discussed in detail later.

AppMaximize, AppMinimize, AppRestore (MSProject window only)

Another application can use DDE or OLE Automation to tell MSProject to execute one of these. MSProject must be in the Windows Task List. The MSProject window is activated as well as changed in the specified manner. See MSProject Online Help for more information about these methods.

Visible Property

Many applications that support OLE Automation have a Visible property. If an application is running but not in the Windows Task List, then setting its Visible property to True will add it to the Windows Task List and activate it. If it's already in the Windows Task List, then setting Visible to True does nothing. OLE Automation and the Visible property are covered in detail in Lesson 3.

Shell

The Shell command is normally used to start an instance of an application, but can also be used to switch to a currently running application that supports only one instance. For example, using the Shell command in an Excel macro to start MSProject will simply switch to MSProject if it's already running. The Shell command is discussed in detail later in this lesson.

AppExecute

MSProject also has the AppExecute method which can be used to start or switch to a target application. The AppExecute method is discussed in detail later in this lesson.

The table below provides some comments and sample code illustrating some of the ways to activate an application.

AppActivate | Target Application must be in the Windows Task List. You specify the window title that you want to activate. In VB for Applications, you don't have to specify the name of maximized documents. | MSProject macro that switches to an instance of Excel that is in the Windows Task List. Sub Sub1() AppActivate "Microsoft Excel" End Sub
AppMaximize AppMinimize AppRestore | MSProject methods. Another application can use DDE or OLE Automation to tell MSProject to execute one of these. MSProject must be in the Windows Task List. | Excel macro that switches to MSProject and maximizes it - MSProject must be in the Windows Task List. Sub Sub2() Dim x As Object Set x = GetObject(,"MSProject.Application") x.AppMaximize End Sub
Visible | A property common to many applications that support OLE Automation. If an application is running but not in the Windows Task List, setting its Visible property to True will add it to the Windows Task List and activate it. If it's already in the Windows Task List, setting Visible to True does nothing. It's usually used in combination with AppActivate. | Excel macro that activates MSProject. MSProject must be running but doesn't have to be in the Windows Task List. Setting Visible to True covers that possibility. Sub Sub3() Dim x As Object Set x = GetObject(,"MSProject.Application") x.Visible = True AppActivate "Microsoft Project" End Sub
Shell | If the target application is already running (in the Windows Task List or not), and supports only one instance, then Shell activates it rather than starting it. | Excel macro that switches to MSProject if it is already running, otherwise it starts MSProject. Sub Sub4() Shell "C:\Winproj\Winproj.exe", 3 End Sub
AppExecute | Specific to MSProject. MSProject can use this to activate an application in the Windows Task List or to start another application. Requires an exact window title in order to switch to another application. | MSProject macro to switch to Excel if "Microsoft Excel - Book1" is in the Windows Task List. Sub Sub5() AppExecute Window:="Microsoft Excel - Book1" End Sub

AppActivate title [ , wait ]

Used to switch to any application listed in the Windows Task List.

title

In VB3 this must be set to the title bar text of the window to be activated - including the hyphen and document name if there is an open maximized document. In applications that support Visual Basic for Applications, like Excel and MSProject, the title only needs to include the application name part of the title bar, but if you do include the hyphen part, it must match exactly. The title argument is not case sensitive.

If there is more than one window that matches the specified title, then the most recently used instance (the highest one in the Windows Task List) is activated. Windows that are not on the Windows Task List can't be activated.

AppActivate cannot activate an application that is running invisibly - i.e. one that is running but doesn't show in the Windows Task List.

wait

This argument is only available in applications that support Visual Basic for Applications. VB3 doesn't use this argument. Set this argument to True if the source macro trying to execute the AppActivate command must wait until the source application has focus before it is allowed to activate the specified target. The default is False.

Example

Suppose there are three instances of NotePad listed in the Windows Task List in the order shown:

NotePad - Test2.txt

NotePad - Test1.txt

NotePad - (Untitled)

The table below shows what would result from various uses of AppActivate:

Command | Result
AppActivate "NotePad" | Activates the first one in the Windows Task List.
AppActivate "NotePad - wow" | Error
AppActivate "NotePad - Test1.txt" | Activates the specified instance only.

Example

Suppose the title bar in MSProject says: Microsoft Project - P1.MPP

Then an Excel macro could switch focus to MSProject with any of the following commands:

AppActivate "Microsoft Project"

AppActivate "Microsoft Project"

AppActivate "Microsoft Project - P1.MPP"

A VB3 procedure could only use the last statement above.

If a source application establishes an OLE conversation with MSProject, then it can use AppActivate with the Caption property of the target application. The Caption property represents the exact title bar text. The following example could be a VB3 procedure or an Excel macro that activates MSProject regardless of what's on the title bar:

Sub Sub1()

Dim x As Object

Set x = GetObject(,"MSProject.Application")

AppActivate x.Caption

End Sub

Maximizing and Minimizing Another Application

Depending on the applications, a source application might be able to maximize, minimize, resize, or move a target application. You can manipulate the MSProject window using the MSProject methods AppMaximize, AppMinimize, AppRestore, AppMove, and AppSize (there are similar methods to manipulate the document windows). The above methods are specific to MSProject. Many applications have a WindowState property that can be used to maximize, minimize, or restore their application window. Some commands, like Shell, that are used to start applications include options to control how the target application window comes up - Shell is covered later in this lesson.

Example

The following Excel macro assumes that MSProject is already running. It makes MSProject visible (in case it was running invisibly), switches to MSProject and maximizes it.

Sub Sub5()

Dim x As Object

Set x = GetObject(, "MSProject.Application")

x.Visible = True

x.AppMaximize

End Sub

Example

The following MSProject macro assumes that an instance of Excel is already running. It makes that instance visible and maximizes it.

Note that the predefined MSProject constant pjMaximized has the same value as the predefined Excel constant xlMaximized. The MSProject macro used pjMaximized instead of xlMaximized because the Excel constants are not recognized in MSProject macros automatically without establishing a reference to the Excel 5.0 Object Library. This is covered in detail in lesson 3. Of course, you can use the actual value instead of the constant.

Sub b2()

Dim x As Object

Set x = GetObject(, "Excel.Application")

x.Visible = True

x.WindowState = pjMaximized

End Sub

Starting Other Applications

There are a variety of ways a macro in a source application can start a target application. Many applications support a command like Shell. If both the source and target applications support OLE Automation, then the source can use CreateObject or GetObject to start the target application. MSProject also has the AppExecute method which can switch to, or start up, a target application.

See Online Help for a complete discussion of related commands.

Shell pathname [ , windowstyle ]

Starts the specified application with the optional specified window style. To insure that the target application is completely started before the source macro continues, follow the Shell command with the DoEvents command if it has one.

pathname

Name of executable file including optional path. It can include optional command line arguments. It can not be the name of a document (although Online Help says it can).

windowstyle

Pass one of the following optional values to control the state of the target window when it starts (default is 2).

1, 5, 9 Normal with focus.

2 Minimized with focus.

3 Maximized with focus.

4,8 Normal without focus.

6,7 Minimized without focus.

As soon as the target application responds that it has finished the initial part of its startup process, the calling macro will proceed to the next line of code after the Shell command. It will not wait for the other application to close before continuing. Shell can be used as a function. It returns an id number (called a module handle) that identifies the instance of the executable that it started. You can pass this id to some API procedures to get information about that instance, including whether it's still running. If you don't want your macro to continue until the target executable has quit, the GetModuleUsage API function is useful. API calls are covered in lesson 8. The GetModuleUsage function is used in an example later in this lesson. If you don't want to use the value returned by Shell, then don't use ( ) around the arguments.

If the target application supports multiple instances (like Excel) then Shell always starts a new instance. For applications like MSProject that support only a single instance, Shell activates the existing instance.

When Shell looks for the specified executable, if a directory is supplied with the filename, it only looks there. If no directory is specified, it looks at the following, in the order given, until it finds the executable or gives an error: current directory, windows directory, system directory, and path statement. It doesn't look in Win.ini or Reg.dat (OLE registry information).

If you include command line arguments (like a document filename) with the executable name, Shell will wait only until the target application releases control back to the operating system; it doesn't necessarily wait for the document to open.

Shell is not aware of "working directories". If it's important, try using the Chdrive and Chdir commands to switch to the working directory before using the Shell command - that way the target application might find startup files it needs (for example MSProject's Global.mpt).

Example

Assume MSProject is not running, that winproj.exe is in c:\winproj and Global.mpt is in c:\winproj\workdir and that the current directory is c:\stuff. Then this Excel macro will start MSProject maximized with focus, but will create a new default Global.mpt without warning messages.

Sub StartMSProject()

Shell "c:\winproj\winproj.exe", 3

End Sub

With the same assumptions as above, the following Excel macro will start MSProject with the Global.mpt from the working directory:

Sub StartMSProject()

ChDrive "c"

ChDir "c:\winproj\workdir"

Shell "c:\winproj\winproj.exe", 3

End Sub

Example

Assume Excel is not running. This MSProject macro starts Excel maximized with focus and tells it to load the specified workbook. As soon as Excel finishes its startup screen, it lets the MSProject macro continue as it loads test.xls in the background.

Sub Sub1()

Shell "c:\Excel\Excel.exe c:\Excel\data\test.xls", 3

AppActivate "Microsoft Project"

End Sub

Note that if you replace the above Shell statement with

Shell "c:\Excel\data\test.xls", 3

it gives an error, although Online Help says it should work.

AppExecute window, command, minimize, activate

MSProject method only. It can be used to activate or start a target application or both. You must provide the window or command argument or both.

window

Set to the title bar text of the window to be activated, including the hyphen and document name if there is a maximized document. It's not case sensitive.

command

The command used to start the target application. Similar to the pathname argument in the Shell command.

minimize

Set this to True to minimize the target window. Default is False.

activate

Set this to True if you want to give focus to the target application. Default is True.

AppExecute looks at the window argument first if provided. If it finds the window, then it ignores the command argument. If the window argument is not given or has a bad value, then it looks to the command argument. In the case where it has to depend on the command argument, it may look for an exiting instance first or it may not, depending on the target application. For example, it always starts a new copy of NotePad. In Windows 3.1 it uses an existing instance of Excel, but in Windows 95 it always starts a new instance.

In cases where AppExecute is switching to an existing instance, the minimize and activate arguments are ignored, and AppExecute switches to the most recently used instance of the target application (the highest one in the Windows Task List). It cannot be used to activate an application that is not in the Windows Task List.

If AppExecute does have to start a new instance, it looks at the following to locate the executable: If a pathname is supplied in the command argument, it looks no further, otherwise it checks Reg.dat, and then in the current directory, windows directory, system directory, and the path statement. This is different from Shell which always starts a new instance, and never checks Reg.dat.

You can specify a document file along with the executable file in the command argument, but then Reg.dat is not checked. You cannot specify just a document file for the command argument.

Example

Suppose there are two copies of Excel running and two copies of NotePad running, and they are in the following order in the Windows Task List:

NotePad - Test2.txt

Microsoft Excel - Book1

NotePad - Test1.txt

Microsoft Excel - Book2

The table below shows the result of various commands, each starting with the above assumptions.

Command | Result
AppExecute window:="Notepad" | Error
AppExecute window:="Notepad - Test1.txt" | Activates that one
AppExecute command:="Notepad" | Starts a new copy of NotePad
AppExecute command:="Notepad - Test1.txt" | Error
AppExecute command:="Excel" | Activates the first Excel in the Windows Task List
AppExecute window:="Excel - Book2" | Activates that one

Example

Note: The following command should start Excel minimized with focus, but gives an error if Excel is not already running. Get rid of the Minimize argument or set it to False, and it works OK.

AppExecute Command:="c:\Excel\Excel.exe", Minimize:=True

Example

Assuming Excel is not running and that Excel.exe is in c:\Excel and that Excel is properly registered, then any of the following alone should start Excel and give it focus.

AppExecute command:="c:\Excel\Excel.exe"

AppExecute command:="Excel.exe"

AppExecute command:="Excel"

AppExecute window:="ha ha", command:="Excel"

Example

Assume the same as the above, but also that c:\Excel is not in the Path statement, and that Test.xls is in c:\Excel. Then

AppExecute command:="c:\Excel\Excel.exe test.xls"

works, but

AppExecute command:="Excel.exe test.xls"

fails because it can't find Excel.exe and won't check the registry.

AppExecute command:="c:\Excel\test.xls"

fails too, because it doesn't do associations.

Example

Assume Excel is already running, and that the title bar is "Excel - Book1.xls". Then the following both work:

AppExecute Window:="Excel - Book1.xls"

AppExecute Window:="Excel - Book1.xls", Command:="ha ha"

Closing Applications

There are a couple of ways that a macro can close an application: Using OLE Automation to apply the Quit method of the target application (if it has one) or DDE to send the Quit command of the target application (if it has one), or, in the worse case, activating the target application and using a SendKeys command to choose File Exit or to send the Alt-F4 key combination. SendKeys, OLE Automation, and DDE are covered in later lessons.

Applications that are started as a result of an OLE reference may close automatically when the OLE reference is destroyed. Reference-dependence is covered in detail in Lesson 3.

When a macro tells a target application to quit, it should take into account the possibility that the target application might display "alerts", warning messages, or error messages. An alert is usually a message that offers you a choice of actions. For example, when told to quit, MSProject might give the message "Save changes to 'Project1'?", or "Some other application is using Microsoft Project. Do you want to exit Microsoft Project?". The conservative approach to handling potential messages is to activate the target application before telling it to close. Some applications have commands that turn off "alerts". The default response for an alert is automatically chosen without showing the message. Both MSProject and Excel have the DisplayAlerts property. MSProject also has the Alerts method. The following lines have the same effect in MSProject:

Alerts False

DisplayAlerts = False

With alerts turned off, MSProject automatically saves changes to projects that have been saved at least once in the past, and automatically brings up the Save As dialog for new projects that have changed.

MSProject has its DisplayAlerts property equal to True by default. If a macro wants to be sure MSProject will display alerts, it should put DisplayAlerts equal to True, just in case some other macro had previously put DisplayAlerts equal to False.

Try This

The following Excel macro saves any projects in MSProject that need to be saved, without giving alert messages. Then the macro closes MSProject.

1. Create two new projects in MSProject. Save one but not the other, then enter a task in each one.

2. Enter and run the following Excel macro. When it brings up the Save As dialog, see what happens if you choose cancel.

Sub Sub1()

Dim x As Object

Set x = GetObject(,"MSProject.Application")

x.DisplayAlerts = False

AppActivate "Microsoft Project"

x.Quit

End Sub

3. Change the macro so it assigns True to DisplayAlerts instead of False. Create two more projects as in step (1) and run the macro again.

Note: The DisplayAlerts line could have been replaced by: x.Alerts False

MSProject was activated before closing it so any unanticipated error messages could be seen.

Example

Suppose several copies of NotePad are running and one has the title bar "NotePad - Test1.txt". The following MSProject macro closes that specific instance of NotePad:

Sub Sub1()

AppActivate "NotePad - Test1.txt"

SendKeys "%{F4}", True

End Sub

If you leave off the " - Test1.txt" in the AppActivate statement, it would close one of the instances of NotePad, but maybe not the one you wanted.

How To Tell If An Application Is Running

Here's a couple of ways to tell if another application is currently running.

Try to activate another application and trap the error if it fails. If it fails, you know the application's not in the Windows Task List, although it might be running "invisibly".

Try to establish an OLE or DDE conversation with an application and trap the error if it fails (although it might fail because the other application is running but not responding). This method can tell if an application is running even if it's not in the Windows Task List. Using GetObject when the target application is displaying a message might cause the calling macro to lock up. OLE Automation and DDE are covered in detail in Lessons 3 and 4.

API calls: These are covered in detail in Lesson 8. The FindWindow function is perhaps the cleanest way to tell if an application is running (in the Windows Task List or not). To use it, you must know the classname of the application. For example, the classname of MSProject 4.0 is "JWinproj-WhimperMainClass", and the classname of Excel 5.0 is "XLMAIN". The GetModuleUsage function is often used with the Shell command to test if the application instance started with Shell is still running.

Try This

The following MSProject macro tells you whether NotePad is in the Windows Task List or not.

1. Make sure NotePad is not running.

2. Enter and run the following MSProject macro.

Sub IsNotePadRunning()

Dim MyErr As Integer

On Error Resume Next

AppActivate "NotePad"

MyErr = Err

On Error GoTo 0

If MyErr > 0 Then

MsgBox "NotePad is not running."

Else

AppActivate "Microsoft Project"

MsgBox "NotePad is running"

End If

End Sub

3. Start NotePad and run the above macro again.

Try This

The following Excel macro tells you whether MSProject is responding or not to GetObject.

1. Make sure MSProject is not running.

2. Enter and run the following Excel macro.

Sub IsMSProjectRunning()

Dim x As Object, MyErr As Integer

On Error Resume Next

Set x = GetObject(, "MSProject.Application")

MyErr = Err

On Error GoTo 0

If MyErr > 0 Then

MsgBox "MSProject is not responding."

Else

MsgBox "MSProject is responding"

End If

End Sub

3. Start MSProject. Don't have any dialogs or messages open in MSProject. Run the above Excel macro again.

4. Make sure you don't have anything important open in any application. Open the Tools Macros dialog in MSProject, switch back to Excel, and run the above macro again.

Try This

The following Excel macro tells you whether MSProject is running or not. It uses the FindWindow API call with the classname of MSProject. The GetClassname API function in Lesson 8 can be used to find classnames.

1. Make sure MSProject is not running.

2. Enter and run the following Excel macro.

'PLACE THE DECLARE LINE IN THE DECLARATION AREA OF AN EXCEL MODULE

Declare Function FindWindow Lib "USER" _

(ByVal lpClassName As Any, ByVal lpWindowName As Any) As Integer

Sub IsMSProjectRunning()

If FindWindow("JWinproj-WhimperMainClass", 0&) = 0 Then

MsgBox "MSProject is not running"

Else

MsgBox "MSProject is running"

End If

End Sub

3. Start MSProject and run the above Excel macro again.

Try This

The following Excel macro starts MSProject and establishes an OLE conversation. Then it waits in a DoEvents loop until it is no longer able to use the reference to MSProject to read the MSProject caption.

1. Make sure MSProject is not running.

2. Enter and run the following Excel macro. It should start and activate MSProject. Adjust the path to MSProject if necessary.

Sub Sub5()

Dim x As Object, s As String

Shell "c:\winproj\winproj.exe", 3

On Error Resume Next

Set x = GetObject(, "MSProject.Application")

Do

DoEvents

s = x.Caption

Loop Until Err > 0

MsgBox "MSProject is busy or not running."

End Sub

3. Exit MSProject. The MsgBox line in the above macro should execute.

Try This

The following MSProject macro uses the Shell statement to start a new instance of Excel and waits in a DoEvents loop until that instance of Excel quits. The value returned by the Shell statement is stored in the variable moduleHandle which identifies the instance of Excel. The API function GetModuleUsage is passed the value of moduleHandle and returns a nonzero result as long as the instance of Excel is still running.

1. Make sure Excel is not running.

2. Enter and run the following MSProject macro. It should start and activate Excel.

'PUT THIS IN THE DECLARATION AREA:

Declare Function GetModuleUsage _

Lib "KERNEL" (ByVal hModule As Integer) As Integer

Sub a1()

Dim moduleHandle As Integer

moduleHandle = Shell("c:\Excel\Excel.exe", 3)

Do

DoEvents

Loop Until GetModuleUsage(moduleHandle) = 0

MsgBox "The instance of Excel is no longer running."

End Sub

3. Exit MSProject. The MsgBox line in the above macro should execute.

Lesson 1 Exercises

Assume in these exercises that there are no "invisible" applications, i.e. that any applications running are listed in the Windows Task List. Also assume that there are no "busy" applications. Try to do these without API calls. They all can be done using AppActivate, SendKeys, and On Error Resume Next.

  1. Write an Excel macro that tries to activate (not start) MSProject. If it fails, then the macro gives the following message:

    2. Make sure Microsoft Project is running before using this macro.

    The message box should just have an OK button. Then the macro ends.

  2. Write an MSProject macro that tries to activate (not start) Excel. If it fails, then the macro gives the following message:

    3. Excel is not running. Do you want to start it?

    The message box should have a Yes and No button. If the user selects Yes, then the macro starts a new instance of Excel, and ends. If the user selects No, then the macro just ends.

  3. Write an MSProject macro that tests if Excel is running. If Excel is not running, then the macro starts Excel and ends. If Excel is running, then the macro activates MSProject and displays the following message:

    4. Excel is already running. You can switch to it,

    or start a new instance.

    The message box should have 3 buttons labeled: Current, New, and Cancel. If the user chooses the Current button then the macro activates Excel and then ends. If the user chooses the New button, then the macro starts a new instance of Excel, makes it active, and ends. If the user chooses Cancel then the macro just ends.

    Use the "Message" method so you can change the Yes button caption to Current, and the No button caption to New. For help, look up "Message" in the MSProject Online Help, in the VB section.

  4. Write an MSProject macro that closes one instance of Excel. Make sure that any Excel alerts like "Save changes in 'Book1'?" are shown before it closes. Test the macro by entering some data in a new Excel workbook, and then switching to MSProject and running the macro.


Lesson 2: SendKeys

Lesson Objectives

Upon completion of this lesson, the participant will be able to:

  • Describe and demonstrate how to use SendKeys to send key strokes to another application.

Some Topics to be introduced in this lesson include:

· Sending key strokes to another application with SendKeys

SendKeys

The macro languages in many applications support a SendKeys statement that can be used to send key strokes to the active object in the active application. Here's the form of SendKeys in MSProject, Excel, Word, and VB3:

SendKeys string,[wait]

string

String that contains the keys you want to send. This includes text as well as special keys like {HOME}, {ESC}, and {ENTER}. See Online Help for the rest of the special keys. The shift, control and alt keys are represented by the single characters +, ^, and %. The following eight characters must be enclosed in braces to send them as literals without interpretation:

+ ^ % { } [ ] ~

The ~ is shorthand for {ENTER}, although it's not listed in Online Help. It's easier to read a macro that doesn't use this shortcut.

To repeat a key several times, put the key followed by a space and the number of repetitions inside braces.

SendKeys can't send the PRINT SCREEN (PRTSC) key.

wait

Optional argument that can be set to True to force the calling macro to wait until the target application has finished processing the key strokes. The default is False which allows the calling macro to continue immediately.

If the target application has its own SendKeys command and supports DDE, then the source application could use DDEExecute to tell the target application to use the SendKeys command in the target application, for example:

DDEExecute "SendKeys ""hello"""

However it's better to use the source application's SendKeys command directly:

SendKeys "hello"

In both cases, the target application must be made active first, for example by using AppActivate.

To improve code readability you can use several SendKeys statements instead of one long one.

Example

The MSProject macro below starts a new copy of NotePad maximized, enters the name, start, and finish of the active project along with some text, saves the file, and closes the instance of NotePad. The "Y" is sent to choose Yes to the overwrite warning in case the file already exists,

Sub SK3()

Shell "NotePad", 3

SendKeys "Project Summary Information:{Enter 2}", True

SendKeys "Name: " & ActiveProject.Name & "{Enter}", True

SendKeys "Start: " & ActiveProject.Start & "{Enter}", True

SendKeys "Finish: " & ActiveProject.Finish & "{Enter}", True

SendKeys "%FS"

SendKeys "C:\TEST2.TXT{ENTER}"

SendKeys "Y" 'in case get overwrite message

SendKeys "%{F4}"

End Sub

Example

The following MSProject macro sends keys to itself. It should be attached to a button on a toolbar and used only when in the module editor. When run, it creates a Sub/End Sub template with top and bottom comment borders, and positions the cursor one space to the right of the first word Sub.

Sub NewSub()

SendKeys "'{= 20}{Enter}"

SendKeys "Sub{Enter 5}"

SendKeys "End Sub{ENTER}"

SendKeys "'{= 20}"

SendKeys "{Up 6}{END}"

SendKeys " "

End Sub

Here's what the key strokes do:

' Apostrophe for a comment line for the top border

{= 20} Top border: ====================

{Enter} Next line

Sub String for the start of the sub

{Enter 5} 5 blank lines

End Sub String for the end of the sub

{Enter} Next line

' Apostrophe for a comment line for the bottom border

{= 20} Bottom border: ====================

{UP 6}{END} Position cursor after the first word Sub

Note: There is a space at the end of the string s so that the cursor moves one space to the right of the first word Sub.

Example

The following MSProject macro sends keys to itself. It assumes there are at least three objects in the Gantt drawing layer of the active project. It applies the Gantt Chart full screen and enters some text in the THIRD drawing layer object which is assumed to be a text box.

Sub SendKeysToTextBox()

ViewApply Name:="&Gantt Chart", SinglePane:=True

SendKeys "{F6}{TAB 2}{F2}"

SendKeys "{HOME}+{END}Hello{ENTER}Goodbye {! 10}{F6}"

End Sub

Here's what the key strokes do:

{F6} Put focus on the first drawing layer object

{TAB 2} Put focus on the third object - a text box

{F2} Put the text box in edit mode (flashing cursor)

{HOME}+{END} Select all the text currently in the text box.

Hello Enter some text

{Enter} New line

Goodbye Enter some text

{! 10} Enter 10 exclamation points.

{F6} Switch focus back to Gantt Chart table

In general, the {F6} key cycles focus from the top pane, to the drawing layer (if the top pane is a Gantt Chart) to the bottom pane (the bottom pane has no drawing layer). Once the drawing layer has focus, the {TAB} key cycles focus though the objects in the order they were created.

Lesson 2 Exercises

  1. Write an MSProject macro that lets the user enter some text in an input box and assigns it to a string variable. Then the macro starts a new instance of NotePad maximized with focus, and uses SendKeys to put the string variable contents into the new NotePad file. Note that if S is a string variable, then you can send it with SendKeys without quotes.

  2. Write an MSProject macro that selects and copies the task name column from the active project, starts a new maximized instance of NotePad with focus, and uses SendKeys to paste the task names into NotePad. If you have to, use the macro recorder to find out how to apply the Gantt view, select the name column, and do Edit Copy. Test it when the active project has tasks and when it doesn't.

  3. Write an MSProject macro that does the same thing as the above exercise without using copy/paste. After the macro starts NotePad, it uses a For Each loop - for each task T in the active project, it uses SendKeys to send the task name as key strokes and then sends the {Enter} key to get to the next row. Note that T.Name is a string and can be sent using SendKeys without quotes around it.

  4. Write an MSProject macro, to be run from a toolbar button, that enters the following text when you are in the Module Editor:

    5. If Then

    End If

    It should put 2 spaces between "If" and "Then" and 1 blank row before the "End If" line, and the cursor should end up on space to the right of the first "If". The indentation of the two lines should be determined by the position of the cursor when the macro was run.


Lesson 3: OLE Automation

Lesson Objectives

Upon completion of this lesson, the participant will be able to:

  • Describe the degree of OLE Automation support provided in Excel, Project, Word, and VB3.
  • Describe the general forms of GetObject and CreateObject possible with Excel, Project, and Word objects.
  • Describe and demonstrate how to use GetObject(,class) where class is "Excel.Application" or "MSProject.Application".
  • Describe and demonstrate how to use CreateObject(class) where class is "Excel.Application", "MSProject.Application", or "Word.Basic".
  • Describe how Application Object Libraries can be used and what application currently have them.
  • Define Invisible and Reference-Dependence Applications and Documents.
  • Describe the Visible property and ways that an application can run invisibly

Some Topics to be introduced in this lesson include:

  • CreateObject
  • GetObject
  • Application Object Libraries
  • Invisible Applications and Documents
  • Reference-Dependent Applications and Documents

OLE Automation

OLE Automation is the process by which a source application uses object variables or references to control a target application, or documents or other objects supported by the target application. You start by setting an object variable to the target application or some object that the target application supports, using CreateObject, GetObject, or you establish a reference to the target application's Application Object Library (if it has one). Then the object variable in the source macro can use the methods and properties of the corresponding object in the target application.

An application can also use CreateObject and GetObject to refer to itself or one of its subordinate objects. For example the following is both a legal Excel macro and a legal MSProject macro:

Sub Macro1( )

Dim s As Object

Set s = CreateObject("Excel.Sheet")

s.Cells(1, 3).Value = "abc"

s.SaveAs "d:\excel5\class\create2.xls"

End Sub

Note that an application cannot initiate a DDE conversation with itself - see the section on DDE. For example, the following statement is illegal in an MSProject macro:

DDEInitiate "Winproj", "System"

OLE Automation Support

Here's the degree to which Excel, MSProject, Word, and VB3 support OLE Automation:

Excel and MSProject

Excel 5.0 and MSProject 4.0 macros can use all three techniques: CreateObject, GetObject, or establishing a reference to another application's Application Object Library.

Word

Word 6.0 macros cannot use OLE Automation to control other applications, but other applications can use OLE Automation to control it. When other applications use an object variable to control Word, they cannot use the Word named arguments. Word commands can be used by listing the values of arguments without argument names, but you can't skip arguments with consecutive commas (or whatever the list separator is). For example, here's the syntax for the Word Basic command FileOpen, with the first three arguments:

FileOpen .Name = text [,.ConfirmConversions = number] [,.ReadOnly = number]

Both of the following Word lines open the specified file as read only:

FileOpen .Name = "c:\word6\t1.doc", .ReadOnly = 1

FileOpen "c:\word6\test1.doc", 0, 1

The second line above has a dummy 0 for the value of the ConfirmConversions argument - you can't skip it when you don't use the argument names.

The MSProject macro below tells Word Basic to do the same thing as the above. Word does not have to open when the macro runs. If Word is not open before the MSProject macro runs, then Word will automatically close when the MSProject macro ends, because w is a local variable.

Sub Sub1()

Dim w As Object

Set w = CreateObject("Word.Basic")

w.FileOpen "c:\word6\t1.doc", 0, 1

End Sub

DDE actually shines here - you can use the argument names if you use DDEExecute. Word must be open before the MSProject macro below runs.

Sub Sub1()

DDEInitiate "WinWord", "system"

DDEExecute "[FileOpen .Name = ""c:\word6\t1.doc"", .ReadOnly = 1]"

DDETerminate

End Sub

One last warning about using Word Basic commands without argument names - there are a few problems with some commands. For example, the EditFind command requires a bogus dummy string argument between its first and second argument if you don't use argument names:

EditFind .Find = "wow", .Direction = 0 'OK

EditFind "wow", 0 'Doesn't work, but should

EditFind "wow", " ", 0 'Does work, but shouldn't

Visual Basic

Visual Basic 3.0 procedures can use OLE Automation to control other applications, but another application cannot use OLE Automation to control VB3 objects. For example an MSProject macro can't set an object variable to manipulate a text box in a VB3 form. VB3 has some other limitations:

VB3 cannot make references to Application Object Libraries.

VB3 procedures can't use some of the block structures available in Visual Basic for Applications, such as the "For Each" loop and the "With" block.

VB3 procedures cannot used named argument, but must instead list the argument values in order. MSProject behaves inconsistently regarding skipping arguments by using consecutive commas (assuming the list separator is a comma). Skipping arguments by using consecutive commas causes an "Argument value not valid" error for some methods/functions in MSProject macros. Even in cases where it's OK in an MSProject macro, the same statement may cause the error when run from a VB3 procedure.

The following table of syntax examples assumes the object variable x refers to MSProject:

Statement | MSProject | VB3
x.FileOpen Name:="P1.mpp" | Yes |
x.FileOpen "P1.mpp" | Yes | Yes
x.SelectCell 3, , False | Yes |
x.SelectCell 3, 4, False | Yes | Yes
x.FilePageSetupFooter "task sheet", _ "left footer", , "right footer" |  |
x.FilePageSetupFooter "task sheet", _ "left footer", "", "right footer" | Yes | Yes

Some Terminology

Here's some terminology that will be used in the OLE Automation examples. These terms will become clearer in the examples, and are discussed in greater detail in the "Invisible Objects and Object Lifetime" topic.

Invisible Application: An application that is running but doesn't show in the Windows Task List. An application can be made visible by setting its Visible property to True if it has one. In this context, "visible" means "in the Windows Task List", not necessarily physically visible.

Invisible Document: A document in an invisible application, or a document in a visible application, but the document can't be seen and doesn't appear in the list of open windows. An invisible document can be "more hidden" than a "hidden" document. As you'll see later, an MSProject invisible project might not show up in the Window Unhide list, but will show in the Window New Window list.

Reference-Dependent Object: An open object that exists only as long as it or one of its subordinate objects is being referenced.

As you'll see later, some objects can be toggled between invisible and visible. Also, some actions can cause a reference-dependent object to become reference-independent.

Here's some things that can cause an object variable to stop pointing to an object:

The object variable was set to some other object

The object variable was set to Nothing, for example Set x = Nothing

The object variable was a local variable and the macro has ended

The END macro command was executed (not by choosing the menu command Run End)

The menu command Run, Reset was used

Note: The last two items apply to clearing the value of any variable.

As you experiment with CreateObject and GetObject, you may end up running invisible copies of applications. The following macros can be used to make MSProject and Excel visible. The way GetObject is used in these macros requires that MSProject and Excel already be running (visible or not). The On Error Resume Next statements prevent error messages if they are not running. The GetObject function is discussed in detail later in this lesson. There are also API calls that can be used to make applications visible - see Lesson 8.

Try This

(A) The Excel macro below makes MSProject visible and active if it is running (and not busy).

1. Get into Excel and create an new module called OLE (From the Insert menu, choose Macro, and then Module).

2. Enter the following macro:

Sub ShowMSProject()

Dim oMSP As Object

On Error Resume Next

Set oMSP = GetObject(, "MSProject.Application")

If Err > 0 Then

MsgBox "MSProject is busy or not running."

Else

oMSP.Visible = True

AppActivate "Microsoft Project"

End If

End Sub

3. Save the workbook.

4. Start MSProject, switch to Excel and run the ShowMSProject macro. MSProject should become active. As you'll see later, this macro can make MSProject active even if it were originally invisible.

(B) The MSProject macro below makes the youngest instance of Excel visible and active if it is already running (and not busy).

1. Get into MSProject and create an new module called OLE.

2. Enter the following macro:

Sub ShowExcel()

Dim oXL As Object

On Error Resume Next

Set oXL = GetObject(, "Excel.Application")

If Err > 0 Then

MsgBox "Excel is busy or not running."

Else

oXL.Visible = True

AppActivate "Microsoft Excel"

End If

End Sub

3. Start a new instance of Excel, switch to MSProject and run the ShowExcel macro. The instance of Excel should become active. As you'll see later, this macro can make the youngest instance of Excel active even if it were originally invisible.

CreateObject (class)

Returns a reference to an object determined by the class argument. Depending on class, the reference may be to an existing object or to a newly created object. The object reference returned by CreateObject is usually assigned to an object variable.

Class

A string of the form "appName.objectType". Here are some of the values available for MSProject, Excel, and Word:

  • appName objectType
  • MSProject Application (Online Help left this out.)
  • MSProject Project
  • Excel Application
  • Excel Sheet
  • Excel Chart
  • Word Basic

Note that Word doesn't have a Word.Application object. However, the Word.Basic object is like an application object. If Word is started as a result of CreateObject or GetObject then when the object variable ceases to exist, Word automatically closes all documents and the Word application without warnings.

Many of the following examples use x as the object variable, but any legal object variable name could be used.

Using CreateObject With MSProject Objects

Set x = CreateObject("MSProject.Application")

Refers to an existing instance if MSProject is running, otherwise it starts an invisible reference-dependent instance with no open projects. Does not activate MSProject. The x refers to MSProject.Application.

Note that a reference-dependent instance of MSProject becomes reference-independent if you open any projects with methods like FileNew or FileOpen.

Global.mpt Concerns: Project looks in the current directory and in the winproj.exe directory for Global.mpt, not in the working directory. If can't find, it creates one in the executable directory without warning.

Try This

(A) The Excel macro below starts MSProject, and makes it visible:

1. Make sure MSProject is not running.

2. Enter the following macro in Excel and run it.

Dim x As Object 'In the declaration area.

Sub Sub1a()

Set x = CreateObject("MSProject.Application")

x.Visible = True

End Sub

3. Switch to MSProject. You should see no open projects.

4. Switch back to the Excel macro and from the Run menu, choose Reset.

5. Check the Windows Task List. MSProject should not be listed. Is it running invisibly or just not running at all? Did the macro start a reference-dependent or reference-independent instance of MSProject.

(B) The Excel macro below starts MSProject invisibly, creates a new project, and adds a new task to it.

1. Make sure MSProject is not running.

2. Enter the following macro in Excel and run it.

Sub Sub1b()

Dim x As Object

Set x = CreateObject("MSProject.Application")

x.FileNew

x.ActiveProject.Tasks.Add Name:="wow"

End Sub

3. Check the Windows Task List. Microsoft Project should not be in the list.

4. Start MSProject manually in Program Manager. The new project and task created by the macro should be there. Is this instance of MSProject reference-dependent?

5. Close MSProject and don't save changes to the new project.

6. Change the macro so that x is declared as a module-level variable, i.e. move the Dim statement to the declaration area of the Excel module. Also, add the line x.Visible=True before the line x.FileNew.

7. Run the macro again.

8. Try to close MSProject - you should get a warning that MSProject is being used by another application. Cancel the message. Why didn't this message come up the first time you ran the macro?

9. Switch back to the Excel macro and from the Run menu, choose Reset.

10. Switch to MSProject and close it. Why no message this time?

Set x = CreateObject("MSProject.Project")

Starts an invisible reference-dependent instance of MSProject, if it's not running. It then creates a new invisible project. The x refers to the new project, and x.Parent refers to MSProject.Application. The new project is reference-dependent, unless the command executed as an MSProject command.

If MSProject is running visibly, then the name of the invisible project isn't listed in the Window menu's open project list or in the Window Unhide list, but is listed in the Window New Window list. You can use Window New Window to make the invisible project become visible.

Try This

The MSProject macro below creates two new invisible projects and displays the names of all the "open" projects.

1. Enter the following macro in MSProject and run it.

Sub Sub2a()

Dim p As Object, p1 As Object, p2 As Object

Set p1 = CreateObject("MSProject.Project")

Set p2 = CreateObject("MSProject.Project")

For Each p In Projects

MsgBox p.Name

Next

End Sub

2. After the macro ends, check the MSProject Window menu, and you can see that the two new projects are not listed as open or hidden. Use Window New Window to make the projects visible, and then close them. Were these two new projects reference-dependent?

3. Paste the above macro into an Excel module. Replace the word "Projects" in the "For Each ..." line to "p1.Parent.Projects" (without the quotes). Note that p1.Parent refers to MSProject.

4. Run the macro. Switch to MSProject. Verify that the two new projects are not in the Window New Window list. Do you think the two projects are invisible or just not open at all? Were the two created projects reference-dependent?

Using CreateObject With Excel Objects

Set x = CreateObject("Excel.Application")

Always starts a new invisible reference-independent instance of Excel. The x refers to the Excel.Application object of the new instance.

Set x = CreateObject("Excel.Sheet")

Starts an invisible reference-dependent instance of Excel if it's not running, otherwise it uses the *youngest instance. It creates a new worksheet "Sheet1" in a new reference-dependent workbook called "Object" (or "Object 2" etc.). The x refers to Sheet1, x.Parent to the workbook, and x.Parent.Parent to Excel.Application. If Excel is visible, then the new workbook is visible, and Excel is reference-independent.

*If there are existing instances, youngest means the one that was started last.

Try This

The MSProject macro below creates two new workbooks, and puts the time in cell A1 of Sheet1 of each workbook.

1. Make sure Excel is not running.

2. Enter the following macro in MSProject and run it.

Dim s1 As Object, s2 As Object 'In the declarations area.

Sub Macro1()

Set s1 = CreateObject("Excel.Sheet")

Set s2 = CreateObject("Excel.Sheet")

s1.Cells(1, 1).Value = Format(Now, "mm:ss")

s2.Cells(1, 1).Value = Format(Now, "mm:ss")

s1.Parent.Parent.Visible = True

End Sub

3. Check the names of the workbooks and the times in cell Sheet1!A1 of each workbook. Close the workbooks "Object" and "Object 2". What does s1.Parent.Parent.Visible refer to?

4. Manually use File New to create another workbook in Excel and type "hey" in Sheet1!A1.

5. Leave Excel running. Switch back to MSProject and run the macro again. Note that it did not activate the Excel window this time - setting the Visible property to True only activates Excel if it is not in the Windows Task List.

6. Switch to Excel. Check the workbook names again. Did the macro create a new instance of Excel the second time it was run?

7. Leave Excel running. Switch back to MSProject and from the Run menu choose Reset. Switch to Excel. Are the workbooks created by the macro still there? Did the macro create reference-dependent workbooks?

If s1 and s2 had been declared locally, would you have seen the workbooks created by the macro after the macro ended?

Set x = CreateObject("Excel.Chart")

Starts an invisible reference-dependent instance of Excel if it's not running, otherwise it uses the youngest instance. It creates a new worksheet "Sheet1" and chart sheet "Chart1" in a new reference-dependent workbook called "Object (or "Object 2" etc.). Chart1 is based on Sheet1 which Excel populates with sample data. The x refers to Chart1, x.Parent to the workbook, and x.Parent.Parent to Excel.Application. If Excel is visible, then the new workbook is visible, and Excel is reference-independent.

Question: How can you use x to refer to Sheet1?

Try This

The MSProject macro below creates a new workbook with one worksheet and one chart sheet.

1. Enter the following macro in MSProject and run it.

Dim oChart As Object 'In the declarations area.

Sub Macro1()

Set oChart = CreateObject("Excel.Chart")

oChart.Parent.Parent.Visible = True

End Sub

2. Switch to Excel. Where is the chart getting its data from? How can you find out whether the workbook created is reference-dependent?

Using CreateObject With Word Objects

Set x = CreateObject("Word.Basic")

If Word is not running, then a visible reference-dependent instance of Word is started with focus and with no open documents, otherwise x references the youngest existing instance of Word without activating it. The x refers to Word.Basic.

Try This

The MSProject macro below creates a new Word document, enters some text, and saves the document.

1. Make sure Word is not running.

2. Enter the following macro in MSProject and run it.

Sub w1()

Dim w as object

Set w = CreateObject("Word.Basic")

w.FileNew

w.Insert "hello"

w.FileSaveAs "c:\temp.doc"

End Sub

3. Is Word still running after the macro ends? Was the instance of Word created reference-dependent? If w had been declared as a module-level variable, would Word remain open after the macro ends? Open c:\temp.doc to see if it was created and saved correctly. Close temp.doc. Create a new doc and enter some text.

4. Leave Word running. Switch to MSProject and change "hello" to "wow" in the macro and run it again. Is Word still running? Did it overwrite c:\temp.doc? Any overwrite warning? Did it use the existing instance of Word or start a new instance?

GetObject ([pathname][,class])

Returns a reference to an object determined by the arguments. Depending on the arguments, the reference may be to an existing object or to a newly created object. The object reference returned by CreateObject is usually assigned to an object variable.

pathname

The path and file name of a document file.

class

Has the same meaning as in CreateObject.

You must provide one or the other or both of the arguments.

You don't need to use the class argument if you give a document name. If you provide a document pathname but not a class, then it finds the correct application if the system associations are correctly setup, and then uses the default class for the application.

If you use an empty string for pathname then GetObject("", class) behaves like CreateObject(class).

If you leave out pathname, then GetObject(, class) usually requires class to be an application object and the application to be running.

If you provide both a document pathname and a class, then the specified document must support that class. For example, the first statement below is legal and the second is not:

Set x = GetObject("c:\winproj\p1.mpp", "MSProject.Project") 'OK

Set x = GetObject("c:\winproj\p1.mpp", "MSProject.Application") 'Not OK

Using GetObject With MSProject Objects

Set x = GetObject(, "MSProject.Application")

MSProject must be running, otherwise an OLE Automation error occurs. The x refers to MSProject Application.

Set x = GetObject("", "MSProject.Application")

Behaves like: Set x = CreateObject("MSProject.Application").

Set x = GetObject("", "MSProject.Project")

Behaves like: Set x = CreateObject("MSProject.Project")

Set x = GetObject("c:\wprj4dat\p1.mpp")

Set x = GetObject("c:\wprj4dat\p1.mpp", "MSProject.Project")

Each of these starts an invisible reference-dependent instance of MSProject, if it's not running. If the specified MPP file is not open, then it is opened invisibly, and is reference-dependent unless the command was executed as an MSProject command. The x refers to the project, and x.Parent refers to MSProject.Application.

These are ILLEGAL :

Set x = GetObject(, "MSProject.Project")

Set x = GetObject("c:\wprj4dat\p1.mpp", "MSProject.Application")

Using GetObject With Excel Objects

Set x = GetObject(,"Excel.Application")

Excel must be running, otherwise an OLE Automation error occurs. The x refers to

Excel.Application for the youngest instance of Excel.

Set x = GetObject("","Excel.Application")

Behaves like: Set x = CreateObject("Excel.Application").

Set x = GetObject("","Excel.Sheet")

Behaves like: Set x = CreateObject("Excel.Sheet")

Set x = GetObject("c:\Excel\test.xls")

Set x = GetObject("c:\Excel\test.xls", "Excel.Sheet")

Each of these starts an invisible reference-independent instance of Excel, if it's not running, otherwise it uses the youngest existing instance. If the specified XLS file is not open, then it is opened as a hidden workbook, and is reference-dependent unless the command was executed as an Excel command. The x refers to the activesheet in the specified file.

Set s = GetObject("","Excel.Chart")

Behaves like: Set s = CreateObject("Excel.Chart")

Set s = GetObject("c:\Excel\test.xls", "Excel.Chart")

Behaves like: GetObject("c:\Excel\test.xls") except that the workbook must contain at least one chart sheet.

These are ILLEGAL :

Set s = GetObject(,"Excel.Sheet")

Set s = GetObject("c:\Excel\test.xls", "Excel.Application")

Using GetObject With Word Objects

Set w = GetObject("", "Word.Basic")

Behaves like w = CreateObject("Word.Basic")

Set d = GetObject("d:\word6\test.doc")

Doesn't give an error message, but you can't use it for anything.

These are ILLEGAL:

Set w = GetObject(, "Word.Basic")

Set w = GetObject("d:\word6\test.doc", "Word.Basic")

CreateObject and GetObject - Review

There are many exotic ways to use CreateObject and GetObject, but only a few variations are commonly used. First of all, the application you want to control is usually already running visibly, and there usually is just one instance. Also, you usually set the object variable to refer to the application, not to a subordinate object in the application, like a sheet or chart. To work with other subordinate objects in the application, you work your way down the object ladder.

The table on the next page summarizes the syntax variations of CreateObject and GetObject. The most commonly used forms are highlighted.

Set x = | Result
CreateObject("MSProject.Application") GetObject("","MSProject.Application") | Refers to an existing instance if MSProject is running, otherwise it starts an invisible reference-dependent instance with no projects open. The x refers to MSProject.Application.
CreateObject("MSProject.Project") GetObject("","MSProject.Project") | Starts an invisible reference-dependent instance of MSProject, if it's not running. It then creates a new invisible project. The x refers to the new project, and x.Parent refers to MSProject.Application. The new project is reference-dependent, unless the command executed as an MSProject command.
CreateObject("Excel.Application") GetObject("","Excel.Application") | Always starts a new invisible reference-independent instance of Excel. The x refers to the Excel.Application object of the new instance.
CreateObject("Excel.Sheet") GetObject("","Excel.Sheet") | Starts an invisible reference-dependent instance of Excel if it's not running, otherwise it uses the youngest instance. It creates a new worksheet "Sheet1" in a new reference-dependent workbook called "Object" (or "Object 2" etc.). The x refers to Sheet1, x.Parent to the workbook, and x.Parent.Parent to Excel.Application. If Excel is visible, then the new workbook is visible and Excel is reference-independent.
CreateObject("Excel.Chart") GetObject("","Excel.Chart") | Starts an invisible reference-dependent instance of Excel if it's not running, otherwise it uses the youngest instance. It creates a new worksheet "Sheet1" and chart sheet "Chart1" in a new reference-dependent workbook called "Object (or "Object 2" etc.). Chart1 is based on Sheet1 which Excel populates with sample data. The x refers to Chart1, x.Parent to the workbook, and x.Parent.Parent to Excel.Application. If Excel is visible, then the new workbook is visible and Excel is reference-independent.
CreateObject("Word.Basic") GetObject("", "Word.Basic") | If Word is not running, then a visible reference-dependent instance of Word is started with focus and with no open documents, otherwise it activates the youngest existing instance. The x refers to Word.Basic.
GetObject(,"MSProject.Application") | MSProject must be running, otherwise an OLE Automation error occurs. The x refers to MSProject Application.
GetObject("c:\data\p1.mpp") GetObject("c:\data\p1.mpp", _ MSProject.Project") | Starts an invisible reference-dependent instance of MSProject, if it's not running. If the specified MPP file is not open, then it is opened invisibly, and is reference-dependent unless the command was executed as an MSProject command. The x refers to the project, and x.Parent refers to MSProject.Application.
GetObject(,"Excel.Application") | Excel must be running, otherwise an OLE Automation error occurs. The x refers to Excel.Application for the youngest instance of Excel.
GetObject("c:\data\test.xls") GetObject("c:\data\test.xls", _ "Excel.Sheet") | Each of these starts an invisible reference-independent instance of Excel, if it's not running, otherwise it uses the youngest existing instance. If the specified XLS file is not open, then it is opened as a hidden workbook, and is reference-dependent unless the command was executed as an Excel command. The x refers to the activesheet in the specified file.
GetObject("c:\data\test.xls", _ "Excel.Chart") | Behaves like GetObject("c:\data\test.xls") except that the workbook must contain at least one chart sheet in the workbook.

USING APPLICATION OBJECT LIBRARIES

Excel and MSProject have their own Application Object Libraries. Other applications may have their own libraries in the future.

Advantages of using object libraries:

You don't need to set an object variable with either CreateObject or GetObject. Your macro can use the predefined object names that refer to the target application, for example, Excel and MSProject (although in some cases you must use Excel.Application and MSProject.Application).

Macros in the source application can use the named constants from the target Application Object Library. For example, if Excel has a reference to the Microsoft Project 4.0 Object Library, then Excel macros would automatically understand constants like pjDuration.

Disadvantages of using object libraries:

Once a macro in a source application references a target application library, the target application might continue to run invisibly after the source macro ends, and even after the source application closes.

If you close the target application after if has been referenced by a source macro, then the source application may have trouble referencing the library again until you do one of the following in the source application.

Choose the menu command Run Reset.

Execute the End command in the Debug window or in a macro.

Uncheck the reference to the Object Library, close the dialog, get back into it, and recheck the reference.

Exit and restart the source application.

Microsoft Project 4.0 Object Library

To use the Microsoft Project 4.0 Object Library from Excel, get into an Excel module and choose Tools, References, and check: Microsoft Project 4.0 Object Library. Then you don't need CreateObject or GetObject to refer to MSProject. You can just use the name MSProject or MSProject.Application to refer to MSProject. You could also introduce another object variable with a shorter name, for example:

Set x = MSProject.Application

When an Excel macro references MSProject, it refers to an existing instance if MSProject is already running, otherwise it starts a new invisible instance with no open projects. In the latter case, MSProject continues to run until you do one of the following:

Choose the Excel menu command Run Reset.

Execute the End command in the Debug window or in an Excel macro.

Uncheck the reference to the Microsoft Project 4.0 Object Library in Excel, close the dialog, get back into it, and recheck the reference.

Exit Excel and restart it.

Manually close MSProject or tell it to Quit via a macro.

Also, if you close MSProject after an Excel macro has referenced it, then Excel macros can't reference MSProject again until one of the above actions is taken.

Try This

The Excel macro below starts MSProject if not already running, makes it visible and active, and creates a new visible project.

1. Enter the following Excel macro and run it.

Sub Sub4()

MSProject.Application.Visible = True

AppActivate "Microsoft Project"

MSProject.FileNew

End Sub

2. Close MSProject (choose Yes to any warning message).

3. Run the macro again. Did you get an error message? From the Run menu, choose Reset, and run the macro again.

Excel 5.0 Object Library from MSProject

To Use the Excel 5.0 Object Library from MSProject, get into the module editor and choose Tools, References, and check Excel 5.0 Object Library. Then you don't need CreateObject or GetObject to refer to Excel. You can just use the name Excel or Excel.Application. You could also use another object variable with a shorter name, for example:

Set x = Excel.Application.

The first time an MSProject macro references Excel, a new invisible instance is run, and all later references use that same instance. That instance continues running until you manually close it or use a macro to tell it to Quit. Note that there isn't a way to reference an existing instance of Excel using this library technique. If you need to reference an existing instance, then use GetObject.

Also, if you close Excel after an MSProject macro has referenced it, then MSProject macros can't reference Excel again (via the library reference) until one of the following actions is taken in MSProject:

Uncheck the reference to the Excel 5.0 Object Library, close the dialog, get back into it, and recheck the reference.

Execute the End command in the Debug window or in an MSProject macro.

Choose the menu command Run Reset.

Exit MSProject and restart it.

Note: Unlike MSProject, when you close Excel, it does not give a warning that another application is using Excel.

Invisible Objects and Object Lifetime - Review

This section reviews and formalized the concepts of reference-dependent objects and opening applications and documents invisibly.

Invisible Application:

An application that is running but doesn't show in the Windows Task List. This is not the same as being minimized or hidden under other windows. If a macro creates an invisible instance of an application, the macro may need to close the application or make it visible before the macro ends, to avoid having invisible instances eating up resources.

If x refers to MSProject.Application, then MSProject can be made visible by using x.Visible=True, x.AppMaximize, x.AppMinimize, or x.AppRestore. The last three statements always activate MSProject, but x.Visible=True makes MSProject active only if MSProject isn't already visible. The statement x.Visible=False has no effect on MSProject.

If x refers to Excel.Application, then x.Visible=True makes Excel visible, and x.Visible=False makes it invisible. Using x.Visible=True when Excel is already visible does not activate Excel.

Microsoft Word can't be made invisible using OLE Automation.

Invisible Document:

A document that is in an invisible application, or a document in a visible application, but the document can't be seen and doesn't appear on the list of open files at the bottom of the application's Window menu. If the application is visible, the document might be invisible because of the method used to open it, or because it was made hidden by some command after it was opened.

If you use CreateObject or GetObject to create/open a project in MSProject, then the project is invisible.

If you use CreateObject or GetObject to create/open a sheet or chart in a new invisible instance of Excel, then the associated workbook is invisible. If Excel is then made visible, the workbook is still a hidden workbook.

There are no invisible documents in Word.

Try This

These Excel macros illustrates when an invisible project can or cannot be the active project.

1. Make a test project with two tasks named T1 and T2 and save it as "c:\p1.mpp".

2. Close MSProject.

3. Enter the following Excel macro and run it.

Sub Macro1( )

Dim x As Object, p As Object

Set x = CreateObject("MSProject.Application") 'Starts invisible

x.FileOpen "c:\p1.mpp" 'Open p1.mpp

Set p = x.ActiveProject 'Set object variable

p.Tasks(2).Name = "zawa" 'Change task2 name

x.Alerts False 'Save without asking

x.Quit 'Close MSProject

End Sub

4. Check that the name of task 2 has changed to zawa.

5. The following Excel macro won't work. Enter and run it. Choose OK to the MSProject error message, switch back to Excel, and choose Goto in the Excel error message. What's wrong with this macro?

Sub Macro2()

Dim x As Object, p As Object

Set p = GetObject("c:\p1.mpp")

Set x = p.Parent

x.Visible = True

p.Tasks(2).Name = "zawa"

x.FileSave

x.Quit

End Sub

6. Here' a quick fix for the above macro. Add the following three lines before the x.FileSave line, and run the macro again. Which application's messages is the "On Error" line supposed to prevent? Which application's messages is the "x.Alert" line supposed to prevent?

On Error Resume Next

x.Alerts False

x.FileOpen "c:\p1.mpp"

Reference-dependent Object:

An open object that exists only as long as it or one of its subordinate objects is being referenced. The object could be an application or a subordinate object that the application supports, like a project in MSProject, or a worksheet in Excel, or Word Basic in Word.

If you run an MSProject macro that starts Word as a result of

x=CreateObject("Word.Basic")

then that instance of Word.Basic is reference-dependent, because if the value of x changes or x ceases to exist, then Word will automatically close without warning, and without saving changes to documents.

The next two definitions are specific cases:

Reference-dependent document:

An open document that exists only as long as it or one of its subordinate objects is being referenced. When a reference-dependent document closes automatically, it typically does not automatically save changes or ask if you want to save changes.

For example, if you run an EXCEL macro that opens a project using

Set p=GetObject("c:\winproj\p1.mpp")

then p1.mpp is reference-dependent, because if the value of p changes or p ceases to exist, then p1.mpp automatically closes without warning and without saving changes.

NOTE: If you run the above command in an MSProject macro instead of an Excel macro, then p1.mpp is not reference-dependent. I.e. even after p ceases to exist, p1.mpp is still open - it's invisible, but can be seen on the Window New Window list.

Similarly, if you run an MSProject macro that opens a worksheet using

Set s = GetObject("c:\Excel\test.xls")

then test.xls is reference-dependent, because if the value of s changes or s ceases to exist, then test.xls automatically closes. Note that test.xls opens as a hidden workbook and will become reference independent if unhidden manually or by executing

s.Parent.Parent.Windows("test.xls").Visible = True

Reference-dependent projects are created/opened as a result of CreateObject or GetObject run from another application like Excel, and are invisible at first. They can be made visible through the Window New Window menu command if it's available. Invisible reference-dependent projects can never be the active project.

Reference-independent projects are most recently created/opened with methods other than CreateObject or GetObject, i.e. like FileNew and FileOpen.

Technically there are no reference-dependent Word documents because Word doesn't have a Word.Document object. However, the Word.Basic object can be reference-dependent and if the Word.Basic object closes, it closes the application and all open documents without warning.

Reference-dependent Application Instance:

An instance of an application that exists only as long as it or one of its subordinate objects is being referenced.

MSProject can be reference-dependent only if there are no open reference-independent projects, and if MSProject was started as a result of CreateObject/GetObject or a reference via the Microsoft Project 4.0 Object Library.

For example, if MSProject is not running, then starting it with

Set x=CreateObject("MSProject.Application")

creates a reference-dependent instance of MSProject, because if the value of x changes or x ceases to exist, then MSProject closes automatically.

If MSProject is started as the result of CreateObject or GetObject, then if starts out dependent on the object variable used in the CreateObject or GetObject command. After that, it can become reference-independent by restarting it manually, or by opening reference-independent projects.

There are no visible reference-dependent instances of Excel. Once an instance of Excel shows up in the Windows Task List, it remains running until you manually close it or use some command like the Quit method. Invisible instances may or may not be reference dependent. CreateObject("Excel.Application") starts reference-independent instances. CreateObject("Excel.Sheet") and CreateObject(Excel.Chart") create reference-dependent instances if Excel was not already running.

Technically Word can't be a reference-dependent application because there is no

Word.Application object, but the Word.Basic object can be reference-dependent and behaves like an application object.

Using VB3 Forms With MSProject

Because Visual Basic for Applications in MSProject does not include rich event driven graphical interface objects such as text boxes, dropdown lists, etc., some developers will choose to create custom applications using VB3 and MSProject. Two possible design philosophies are listed below

Design it strictly as a VB3 program that controls MSProject. No MSProject macro code is used at all. Advantage: Simplicity.

Write most of the code in MSProject macros. Any "fancy" input/output dialogs are designed in small VB3 programs that are called from the MSProject macros. Advantage: Speed.

The second approach requires some way for the VB3 program to return user input to the calling MSProject macro. The are several ways to pass data between VB3 and MSProject macros, including: OLE Automation, DDE, and API calls (for example, passing data via a global memory block).

Try This

This example illustrates a VB3 program returning input to MSProject via OLE Automation, using the Text9 and Text10 fields of the project summary task of the active project. The purpose of the example is for illustration only - the function it performs could be done without VB3. Here's a short description of the logic:

The MSProject macro warns the user that the Text9 and Text10 fields of the project summary task will be modified and allows the user to cancel the macro.

If the user chooses to continue, the MSProject macro sets the project summary Text10 field to blank.

The MSProject macro uses Shell to start the VB3 program AddTask.exe.

The MSProject macro waits in a DoEvents loop until the project summary Text10 field is no longer blank. During this time, in the VB3 form, the user can enter the name for a new task in a textbox and then choose OK or Cancel. The VB3 program returns "ok" or cancel" in the project summary Text10 field, and, if OK was chosen, returns the new task name in the project summary Text9 field.

The MSProject macro assigns the returned values (the project summary Text9 and Text10 fields) to variables sTextEntered and sButtonChosen. If sButtonChosen = "ok", then a new task is added to the active project with the new name that the user entered.

Here are the detailed steps:

1. Start VB3 (Microsoft Visual Basic 3.0). If the toolbox isn't showing, then from the Window menu choose Toolbox. Resize Form1 as shown in the picture. Press F4 and change the Caption property to "Add Task".

2. Create the textbox shown in the picture (use the [image] tool). Change its Name property to txtTextBox and change its Text property to blank (so it's empty).

3. Create the OK command button as shown in the picture (use the [image] tool). Change its Name property to cmdOK, and change its Caption property to "OK". Double click the button and enter the body of the cmdOK_Click procedure shown below:

Sub cmdOK_Click ()

Dim oMSP As object

Set oMSP = GetObject(, "MSProject.Application")

oMSP.ActiveProject.Text9 = txtTextBox.Text

oMSP.ActiveProject.Text10 = "ok"

End

End Sub

4. Create the command button that says "Cancel" as shown in the picture. Change its Name property to cmdCancel, and change its Caption property to "Cancel". Double click the button and enter the body of the cmdCancel_Click procedure shown below:

Sub cmdCancel_Click ()

Dim oMSP As object

Set oMSP = GetObject(, "MSProject.Application")

oMSP.ActiveProject.Text10 = "cancel"

End

End Sub

5. In MSProject, create a test project, turn on the option to view the project summary task (in the Tools Options View dialog).

6. In VB3, press F5 to test run the program. If the form pops up successfully, enter a new task name in the textbox. Test both the OK and Cancel buttons. After each test, switch to MSProject and verify that Text9 and Text10 of the project summary task have been assigned the appropriate values. It won't change Text9 if Cancel is chosen. If you get runtime errors, use the Run menu End command, and fix the errors.

7. Switch to File Manager and create the directory C:\AddTask. Switch back to VB3. From the File menu, choose "Make Exe File ..." and save it as C:\AddTask\AddTask.exe. Next, from the File menu choose "Save Project", and save everything to the C:\AddTask directory, accepting the default file names. Finally, exit VB3.

8. Enter and test run the MSProject macro below:

Sub AddTask()

Dim sTextEntered As String

Dim sButtonChosen As String

Dim nAnswer As Integer

nAnswer = MsgBox("This macro uses Text9 and Text10 of the " & _

"active project summary task. Continue?", vbOKCancel)

If nAnswer = vbCancel Then End

ActiveProject.Text10 = ""

Shell "C:\AddTask\AddTask.exe", 1 'start as normal window

Do

DoEvents

Loop Until ActiveProject.Text10 <> ""

sTextEntered = ActiveProject.Text9

sButtonChosen = ActiveProject.Text10

If sButtonChosen = "ok" Then

ActiveProject.Tasks.Add Name:=sTextEntered

End If

End Sub

Lesson 3 Exercises

  1. The VB3 program described below displays the name and duration of one task at a time from the active project in a VB3 form, and has an option to update the duration. It also has buttons to move to the previous or next task id. Some error checking is added in Step (13). Follow the steps below.

    1. Start VB3 (Microsoft Visual Basic 3.0). If the toolbox isn't showing, then from the Window menu choose Toolbox. Resize Form1 as shown in the picture.

    2. Create the label that says "# of Tasks" as shown in the picture (click [image] on the tool bar and draw a rectangle on Form1). With the label selected, press F4 and change the Caption property to "# of Tasks". Likewise create the labels that say "Id", "Name", and "Duration".

    3. Create the label to the right of "# of Tasks". Change its Caption property to a blank and change its Name property to lblNumOfTasks. Similarly, create the labels to the right of "Id" and "Name", with Name properties lblTaskID and lblTaskName.

    4. Create a text box to the right of "Duration" as shown on the picture (use the [image] tool). Change its Name property to txtDuration and its Text property to blank.

    5. Create the command button that says "Close" as shown in the picture (use the [image] tool). Change its Name property to cmdClose, and Caption property to "Close". Similarly, create the "Previous", "Next", and "Update" buttons with Name properties cmdPrevious, cmdNext, and cmdUpdate, and Caption properties "Previous", "Next", and "Update".

    6. Double click on any part of Form1. Press F2. From the Procedures list, double click on "(declarations)". Use the Dim command to dimension object variables oMSP and oTask, and integer variables nTaskID and nNumOfTasks.

    7. Double click on an empty part of the form to get to the Form_Load event procedure. Enter the following event procedure (the Sub and End Sub are already there). When Form1 is loaded, this will display the # of tasks, and the id, name and duration of the task with Id = 1 (assuming it's not blank).

      8. Sub Form_Load ()
      Set oMSP = GetObject(, "MSProject.Application")
      nNumOfTasks = oMSP.ActiveProject.Tasks.Count
      lblNumOfTasks = nNumOfTasks
      nTaskID = 1
      lblTaskID = nTaskID
      Set oTask = oMSP.ActiveProject.Tasks(nTaskID)
      lblTaskName = oTask.Name
      txtDuration = oTask.Duration
      End Sub

    8. Double click each of the buttons on the form, one at a time, to get to each button click event procedure and enter the code shown below.

      9. 'This will update the task duration with the text from the txtDuration text box.

      Sub cmdUpdate_Click ()
      oTask.Duration = txtDuration
      End Sub

      'This will close the VB3 program.

      Sub cmdClose_Click ()
      End
      End Sub

      'This will move to the previous task id unless it is already at 1.

      Sub cmdPrevious_Click ()
      If nTaskID > 1 Then nTaskID = nTaskID - 1

      lblTaskID = nTaskID
      Set oTask = oMSP.ActiveProject.Tasks(nTaskID)
      lblTaskName = oTask.Name
      txtDuration = oTask.Duration
      End Sub

      'This will move to the next task id unless is at the largest id in the project.

      Sub cmdNext_Click ()
      If nTaskID < nNumOfTasks Then nTaskID = nTaskID + 1

      lblTaskID = nTaskID
      Set oTask = oMSP.ActiveProject.Tasks(nTaskID)
      lblTaskName = oTask.Name
      txtDuration = oTask.Duration
      End Sub

    9. Switch to MSProject and set the default duration units to "days" (Tools Options Schedule tab, Show Duration In). Create a test project with tasks T1, T2, and T3 each with duration 1d.

    10. Switch to VB3 and move Form1 if necessary so you can see the name and duration fields in the background. Press F5 to run the VB3 program. When Form1 loads, T1 data should be displayed in the form. Test the Previous and Next buttons, but not the Update button yet.

      11. IMPORTANT: If you get runtime error messages, then choose End from the Run menu, check your work, and make corrections.

    11. Display T1 again in the form. The duration is 480 in the textbox (the 480 is the duration in minutes). Enter 960 in the duration text box and choose Update. The duration of T1 in the project changes to 960d. Why? Enter 2d in the duration text box and choose Update. The duration of T1 should become 2d. Why? Close Form1 and change the duration of T1 back to 1d.

      12. Here's a review of the rules used when setting the duration property of a task to a value:

      • If the value has the string data type, then it behaves as if you had entered the characters in the duration field manually. A string of digits with no duration unit uses the default duration unit. A string that includes a duration unit uses that unit. Note that the value of a text box has the string data type.

      • If the value has a numeric data type (integer, long, etc.) then it is treated as minutes.

      • The above VB3 program is awkward because the duration is displayed in the text box as minutes with no unit, but a unit must be added manually before choosing Update, otherwise you end up with the default duration unit. One way to make it more consistent would be to replace txtDuration by CLng(txtDuration) in the cmdUpdate_Click procedure, so the updated duration would be interpreted as a pure number representing whole minutes. However, the step below shows a better way: It uses GetField to get the duration as a string (just as it looks in the project task table) instead of a pure integer representing minutes.

    12. In the Form_Load, cmdPrevious_Click, and cmdNext_Click procedures, replace:

      13. txtDuration = oTask.Duration
      with:
      txtDuration = oTask.GetField(29)
      The easiest way to do this is to double click on an empty part of the form and then use the menu command Edit Replace. The 29 is from the pjTaskDuration constant listed in the help topic on the GetField method. Test the VB3 program again.

    13. Add error trapping code if necessary so that the VB3 program sets lblTaskName and txtDuration to the empty string "" if the row at nTaskId is blank, i.e. if oTask is Nothing. Also, if oTask is Nothing, the Update_Click procedure will display the message "Task is blank" and then put "" in the txtDuration textbox. Don't bother trapping bad values entered in the txtDuration textbox.

    14. Add another command button labeled GoTo that lets the user enter a task id in an input box, and then displays the id, name, and duration for that task. Start with On Error Resume Next to trap bad id numbers. Assign the value returned by the InputBox to a local integer variable N and then use Set oTask = oMSP.ActiveProject.Tasks(N). If an error occurred (Err > 0) then give a message saying "Bad Id" and then exit the sub. Otherwise, Assign N to nTaskId and update lblTaskID, lblTaskName, and txtDuration as in the other procedures (checking for blank rows).

  2. Write an MSProject macro that creates a new invisible project, adds three tasks to it called "a", "b", and "c", and link the tasks in order with FS relationships. The project is invisible the whole time.

    3. Note: You can't activate the invisible project or apply a view or select any tasks in a table or use the link tool button. Use CreateObject to create the project. If P is the object variable that refers to the new invisible project, then you can use the Add method several times to add the three tasks, for example, P.Tasks.Add Name:="a". Then you can put the appropriate values in the Predecessors field for tasks 2 and 3, for example, P.Tasks(2).Predecessors=1.

    After you run the macro, look on the Window menu to see what projects are open. Is the Unhide item available on the Window menu? Choose New Window from the Window menu and make the invisible project show up in a new window. Are the tasks and predecessors correct?

  3. Write an Excel macro that uses the data on Sheet1 of the active Excel workbook to create a new project. Columns A, B, and C on Sheet1 contain a list of task names, starting dates, and durations, for example Sheet1 might contain the following in cells A1:C4

    4. T1 11/7/94 5d
    T2 11/3/94 2w
    T3 11/14/94 16h
    T4 11/9/94 3d

    The macro can assume that the data starts in cell A1 and that there are no blank rows, but has to calculate how many rows there are. The macro should do the following steps:

    Start MSProject if it's not running: Use CreateObject and assign the returned value to an object variable called oMSP (so oMSP refers to MSProject).

    Make MSProject visible and active.

    Create a new visible project (use MSProject's FileNew method). Later, the new project can be referenced as oMSP.ActiveProject.

    Assign the number of tasks on Sheet1 to a variable, for example

    N = Sheets("Sheet1").Cells(1, 1).CurrentRegion.Rows.Count

    For R = 1 to the number of tasks on Sheet1: Use the Add method (with parenthesis around the Name argument) to add another task to the project - use the appropriate cell value for the Name argument, and assign the return value from the Add method to an object variable T (so T refers to the new task). Then use T to assign the appropriate sheet values to the start and duration of the new task.

    Use OLE Automation where possible, and avoid copy/paste techniques.

    Notes:

    In Excel, to access the content of a cell at row R column C of Sheet1, use can use the expression: Sheets("Sheet1").Cells(R,C).Value.

    In the For loop, R will be the loop variable, and C will be 1, 2, or 3, depending on whether you want the name, start, or duration.

    To add a new task at row R in the new project and have the object variable T refer to the new task, use: Set T = oMSP.ActiveProject.Tasks.Add (Name:= value)

    where the Name argument comes from row R column 1 of Sheet1.

    You can use ActiveSheet in the macro instead of Sheets("Sheet1"). If you use ActiveSheet, then some worksheet (not necessarily Sheet1) must be active before you run the macro. The advantage of using notation like Sheets("Sheet1") is that Sheet1 doesn't have to be active - you can run the macro from the Excel module editor.

    Test run the macro once when MSProject is open and once when it's not. You should see the new project and tasks being added.

  4. Create a VB3 program that displays the task ids and names in a list box (use the [image] tool). All the code is in the Form_Load procedure, except for a Close button that just has the End command. The list is initialized in the Form_Load procedure. Use an object variable oMSP to refer to MSProject and an object variable oTasks to refer to all the tasks in the active project. For n=1 to oTasks.Count, oTasks(n) represents a single task, so if oTasks(n) is not blank, then add an item to the list box where the item is the concatenation of the task Id and name separated by a space. In general, a string can be added to a list box List1 as follows:

    5. List1.AddItem string

    Note: To check if a task oTasks(n) is not blank, use the If/EndIf block that starts with:

    If Not oTasks(n) Is Nothing Then

    Open or create a test project with some nonblank tasks and some blank tasks, and run the VB3 program. Only the nonblank tasks should show in the list.

    The following limitations are from the VB3 Programmer's Guide, Appendix D: List boxes can

    hold 5440 items, each item has a maximum of 1K characters, and the total of all characters in the list box cannot exceed 64K.

  5. Create a VB3 program that, for the selected task, lists the names of all the resources assigned to that task in a list box. Form1 will have a list box and a Close button. Don't do any error checking. To test it, switch to MSProject and select a task that has some resources assigned to it; then switch back to VB3 and run the program. You should see the resource names assigned to the selected task show up in the VB3 listbox on Form1.

  6. Write an MSProject macro that starts a new invisible instance of Excel and creates a new workbook. For each nonblank task in the active project, the task names and durations are written to the first two columns of Sheet1 in the new workbook. Then the Excel Save As dialog comes up so you can enter a filename to save the new workbook. After that Excel quits. The only part of Excel you see is the Save As dialog and any overwrite warning. You don't get the "Save changes?" message. Write the macro so that the durations show up as text in the workbook just like they look in the task table. No blank rows are written to the worksheet. Test run the macro on a project that has several tasks including some blank rows, then open up the workbook it saved and see if it has the correct data.

  7. Write an MSProject macro that switches to Excel if it's running, otherwise starts a new visible instance and switches to it. The macro maximizes the Excel window and adds a new workbook. The task names and durations in the active project are written to the first two columns of Sheet1. The durations are written as pure numbers representing working days relative to ActiveProject.HoursPerDay. Then a chart sheet is added and the ChartWizard method is used to specify the source range for the chart to be the data in Sheet1. Assuming that x refers to Excel.Application, and that s refers to x.Sheets("Sheet1"), then the chart can be added with the following lines in the MSProject macro:

    8. x.Charts.Add

    x.ActiveChart.ChartWizard _

    Source:=s.Cells(1, 1).CurrentRegion, _

    PlotBy:=2, _

    CategoryLabels:=1


Lesson 4: DDE vs. OLE Automation

Lesson Objectives

Upon completion of this lesson, the participant will be able to:

  • List some of the DDE keywords found in Excel, Project, Word, and VB3.
  • Describe the purpose of DDEInitiate, DDETerminate, DDEExecute, DDEPoke and DDERequest.
  • Describe the error messages that can occur if a target application does not respond quickly enough to DDE or OLE Automation commands.
  • Describe how a macro in another application can run an Excel or Project macro and pass arguments.
  • Describe how a macro in another application can assign values to a global variable in Project.

Some Topics to be introduced in this lesson include:

  • DDE Commands Used in Excel, Project, Word, and VB3
  • DDE and OLE Automation Timeouts
  • Macros Running Another Application's Macros and Passing Arguments
  • Macros Assigning Values to Another Application's Global Variables

DDE Macro Languages - Quick Review of a DDE Conversion

A source application has macro commands that allow it to initiate a conversation with a target application. It can choose to talk to the target application as a "whole" (the System topic) or with a specific open document. The source application can then use a DDE command to read (request) specific data from the target application or document, or to change (poke) the values of specific data in the target application or document. What request/poke items the target will respond to depends on the specific target application, and whether the source is talking to the system topic or to a specific document. The request/poke items the target will respond to are "hard coded" in the target application, and usually cannot be executed in the target's own macros. In addition to request/poke, the source application can also use DDE to tell the target to execute one of the target's own menu or macro commands - it usually doesn't matter whether the conversation is with the system topic or with a specific document.

The exact syntax and degree of DDE support depends on the application. Some applications allow simultaneous conversations with multiple target applications, keeping the conversations separate by assigning each one a channel number (Excel and Word) or identifying each one with a different object in the application like a text box (VB3). MSProject only allows one conversation at a time.

MSProject, Excel, and Word have common keywords, but the actual syntax and usage varies. VB3 has different keywords for properties and methods that serve a similar purpose, and also has a robust set of event procedures. The table below shows the DDE-related keywords in these applications. See the Online Help or manuals of each application for syntax details and examples:

MSProject | EXCEL | WORD | *VB3
DDEInitiate | DDEInitiate | DDEInitiate | LinkTopic, LinkMode props
DDEExecute | DDEExecute | DDEExecute | LinkExecute method
DDETerminate | DDETerminate | DDETerminate | LinkMode prop
 | DDERequest | DDERequest | LinkItem prop, LinkRequest method
 | DDEPoke | DDEPoke | LinkItem prop, LinkPoke method
 |  | DDETerminateAll |

*VB3 also includes a LinkTimeout property, as well as the following event procedures: LinkClose, LinkError, LinkExecute, LinkNotify, and LinkOpen.

The rest of this section uses the Excel keywords to represent the generic commands.

Note:

If the target application is not running when the source macro uses DDEInitiate, then you get a message asking if you want to start the target. For example, if Excel is not running when an MSProject executes DDEInitiate "Excel","System", then you get the message: Linked data not accessible. Start application 'EXCEL.EXE' ?

A DDE conversation can be initiated with a target application even if it the target application is running invisibly (not in the Windows Task List).

An application can't initiate a DDE conversation with itself.

Try This

This example has an MSProject macro that uses DDEExecute to send a string to a VB3 program, which displays the string in a text box. The VB3 program is compiled as an executable.

1. Create a new directory in File Manager called C:\VB3TEST

2. In a new VB3 project, set the LinkMode property of Form1 to 1-Source.

3. Create a text box and a command button on Form1. Set the Caption property of the command button to Close, and put the End command in its click procedure.

4. Double click any empty part of Form1, and from the Proc dropdown list, choose LinkExecute. Add the code below to the Form_LinkExecute procedure.

Sub Form_LinkExecute (cmdstr As String, cancel As Integer)

cancel = False

Text1.Text = cmdstr

End Sub

5. From the File menu, choose "Make Exe File ..." and save it as C:\VB3TEST\VB3PROG.EXE

6. From the File menu choose "Save Project" and save everything to the C:\VB3TEST directory accepting the default file names.

7. Exit VB3.

8. Enter and run the following MSProject macro.

Sub Sub1()

Shell "C:\VB3TEST\VB3PROG.EXE", 1

DDEInitiate "vb3Prog", "Form1"

s = InputBox("enter some text")

DDEExecute s

DDETerminate

End Sub

Time Out

Some applications include a DDEExecute timeout argument or a DDE timeout option setting. For example, MSProject has a timeout argument with its DDEExecute command, and VB3 has the LinkTimeout property. Excel's DDEExecute does not have a timeout argument. Setting a timeout allows you to control how long the source application should wait for the target application to finish. If you know the target is going to be taking a long time to finish the command, and if you want your calling application to continue to the next line after the DDEExecute statement without waiting, then you may want to set the timeout to the smallest legal value and trap the timeout error. Of course the source and target applications can only "share" time in a cooperative multitasking environment if they release control occasionally, for example, while waiting for input/output operations or by using commands like DoEvents.

Example

The following MSProject macro tells Excel to open a "really large" workbook. The macro waits the minimum 1 second for Excel to finish and then continues.

Sub DDEProjectMacro()

DDEInitiate "Excel", "System"

On Error Resume Next

DDEExecute "[Open(""d:\excel5\class\big.xls"")]", 1

On Error Goto 0

DDETerminate

'More code can go here if it doesn't

'depend on Big.xls being open

End Sub

Example

This example shows an MSProject macro, DDEProjMacro1, that runs an Excel macro, ExcelMacro1. The MSProject macro quickly continues after the DDEExecute command, even though Excel is in the background waiting for input to its own message. To test this, enter the MSProject macro in MSProject and enter the Excel macro in Excel. Then run the MSProject macro and OK its message. Then switch to Excel and OK its message.

Sub DDEProjMacro1() 'MSProject macro

DDEInitiate "Excel", "system"

On Error Resume Next

DDEExecute "[Run(""ExcelMacro1"")]", 1

On Error Goto 0

DDETerminate

MsgBox "DDEProjMacro1 is done."

End Sub

Sub ExcelMacro1() 'Excel macro run by the above MSProject macro

MsgBox "ExcelMacro1 Message"

End Sub

There is no timeout option when using OLE Automation. There is not a consistent way that all applications handle OLE timeouts. If GetObject or CreateObject fail because the target application is not running, then you usually get an OLE Automation error quickly. If the target application is running, but busy, then the amount of time that the source application waits before giving a message, and the text of that message, depend on the source application. In some cases, GetObject or CreateObject can succeed in establishing an OLE reference, but when you try to use the reference to access the methods/properties of the target application, it might not respond at all, or respond by saying it's busy.

The next two tables illustrate how MSProject and Excel macros deal with OLE timeout problems. The delay times given were derived from tests on a specific machine.

The following table shows some examples of MSProject macros that use OLE Automation to control Excel, and some of the timeout problems that can occur. The bolded macro lines (in the second column) are executing when the messages occur.

State of Excel before the MSProject macro runs. | The MSProject macro. | Result in MSProject after the MSProject macro is run.
Excel is not running. | Sub ProjMacro1() Dim x As Object Set x = GetObject(,"Excel.Application") End Sub | OLE Automation error.
The Excel title bar says "Microsoft Project - Book1". A dialog, like File Page Setup, or a message box is open in Excel. | Sub ProjMacro2() Dim x As Object Set x = GetObject(,"Excel.Application") x.Workbooks.Add End Sub | The following warning dialog comes up after about five seconds, with options to "Switch To", "Retry", or "Cancel" This action cannot be completed because the EXCEL application (Microsoft Excel - Book1) is busy. Choose "Switch To" to activate EXCEL and correct the problem.
The Excel title bar says "Microsoft Project - Book1". Excel is "Ready". The following Excel macro will be called from MSProject: Sub ExcelMacro1() MsgBox "wow" End Sub | Sub ProjMacro3() Dim x As Object Set x = GetObject(, "Excel.Application") x.Run "ExcelMacro1" MsgBox "ProjMacro3 message" End Sub | The following warning dialog comes up after a minimum of about five seconds if you provide any input to MSProject, like clicking the mouse or pressing a key. Your options are to "Switch To" or "Retry". You can't choose Cancel. This action cannot be completed because the EXCEL application (Microsoft Excel - Book1) is not responding. Choose "Switch To" to activate EXCEL and correct the problem.

The following table shows some examples of Excel macros that use OLE Automation to control MSProject, and some of the timeout problems that can occur. The bolded macro lines (in the second column) are executing when the messages occur.

State of MSProject before the Excel macro runs. | The Excel macro. | Result in Excel after the Excel macro is run.
MSProject is not running. | Sub ExcelMacro1() Dim x As Object Set x = GetObject(,"MSProject.Application") End Sub | OLE Automation error.
A dialog, like File Page Setup, or a message box is open in MSProject. | Sub ExcelMacro2() Dim x As Object Set x = GetObject(,"MSProject.Application") End Sub | The following message comes up after about 45 seconds, with OK, Cancel, and Help buttons: The object is not responding. Continue waiting? If you choose Cancel, you get an OLE Automation error. If you choose OK then you get the following message with OK and Help buttons. Microsoft Excel is waiting for another application to complete an OLE action. It takes you back to the first message when you choose OK.
MSProject is "Ready". The following MSProject macro will be called from Excel: Sub ProjMacro1() MsgBox "wow" End Sub | Sub ExcelMacro3() Dim x As Object Set x = GetObject(, "MSProject.Application") x.Macro "ProjMacro1" MsgBox "ExcelMacro1 message" End Sub | The following message comes up after about 60 seconds, with OK and Help buttons: Microsoft Excel is waiting for another application to complete an OLE action. The message repeats each time you choose OK.

Try This

The MSProject macro below attempts to add a new workbook in Excel, but fails if an Excel dialog or message is open.

1. Run Excel and from the File menu choose Page Setup.

2. Leave the Excel Page Setup dialog open, and switch to MSProject.

3. Enter and run the following MSProject macro.

Sub ProjMacro2()

Dim x As Object

Set x = GetObject(,"Excel.Application")

x.Workbooks.Add

End Sub

Using DDE to Control MSProject From Another Application

The file DDEINFO.WRI that shipped with Project 3.0 is not included with Project 4.0, however the information in that file applies to using DDE to control Project 4.0 as well, except where features have been changed or added.

Macros in other applications might use DDE or OLE Automation or both to control MSProject. Both OLE Automation and DDE can do some things, like getting/setting task, resource, and assignment information, but it is usually easier to use OLE Automation. Some things can be directly done only by DDE, like passing arguments to an MSProject sub procedure or assigning a value to an MSProject global variable. Some things can be directly done only by OLE Automation, like getting the list of base calendars, tables, views, and filters.

Other applications can use DDEExecute to make MSProject execute many of its own macro statements. For example, if gVar is declared as a global variable in an MSProject module, then the following Excel macro assigns the value "wow" to gVar:

Sub aaa()

Dim chn As Integer

chn = DDEInitiate("winproj", "system")

DDEExecute chn, "gVar = ""wow"""

DDETerminate chn

End Sub

The DDEExecute line above causes MSProject to execute the statement

gVar = "wow"

which assigns the value "wow" to the global variable gVar. After the above Excel macro runs, you could go to the Debug Window in MSProject and enter the following to check the value of gVar: ? gVar

Using Poke and Request.

Unique Ids

One drawback to using DDERequest and DDEPoke is that you must specify tasks, resources, or assignments by Unique Ids, not ids or names.

Data Size Limitations

One of the advantages DDERequest and DDEPoke do have when talking to MSProject is the use of the asterisk wildcard character - but this can also be a nightmare depending on how much data is returned and how much data the calling application can deal with. MSProject itself doesn't want to return more than 64K at a time. A VB3 Text Box can only receive 32K at a time (that's the formal spec).

Syntax Variations

MSProject returns requested data (DDERequest) to other applications and receives poked data (DDEPoke) from other applications in a format that uses tabs to delimit fields and newline (chr(13) & chr(10)) characters to separate records. When requesting task or resource records from MSProject, blank rows are skipped. The exact syntax and approach used with DDERequest and DDEPoke depends on the source application. Excel Visual Basic macros convert requested data into a variant "array" that's pretty tricky to work with. VB3 on the other hand retrieves the same requested data as a straight forward string that can be parsed for the tab and newline characters. Of course, you wouldn't normally use DDE at all in an Excel macro or VB3 program to talk to MSProject, because they both support OLE Automation. Applications that don't support OLE Automation are stuck with DDE (if they support it).

The following statements in Excel shows how the names, durations, and start dates of all tasks in P1.mpp can be requested and stored in a variant array variable called DataRequested (assuming P1.mpp is open):

Dim DataRequested As Variant

Dim channel As Integer

channel = DDEInitiate ("Winproj", "P1.mpp")

DataRequested = DDERequest(channel, "T(*,(name,duration,start))")

If only one record is returned (one task in the project) then one index is used and it specifies which of the requested fields you want (by position in the list):

This... Accesses this ...

DataRequested(1) name (of the single task)

DataRequested(2) duration (of the single task)

DataRequested(3) start (of the single task)

But if 2 or more records are returned then two indices are used - the first to specify the task record and the second to specify which of the requested fields you want. For example, to get the fields for the 56th task record:

This... Accesses this ...

DataRequested(56,1) name (of the task in the 56th record)

DataRequested(56,2) duration (of the task in the 56th record)

DataRequested(56,3) start (of the task in the 56th record)

UBound(DataRequested) is the number of (nonblank) records returned, provided at least 2 (nonblank) records are returned, but is the number of requested fields if only one record is returned.

Several of the following Excel macro examples compare how to accomplish a task using DDE versus OLE Automation.

Example

Each of these Excel macros opens the project c:\wprj4dat\P1.mpp.

Sub DDE_12()

Dim SystemChannel

SystemChannel = DDEInitiate("winproj", "system")

DDEExecute SystemChannel, "FileOpen ""c:\wprj4dat\p1.mpp"""

DDETerminate SystemChannel

End Sub

Sub ole_12()

Dim oMSP As Object

Set oMSP = GetObject(, "MSProject.Application")

oMSP.FileOpen "c:\wprj4dat\p1.mpp"

End Sub

Example

Each of these Excel macros displays the name of the active project.

Sub DDE_1()

Dim SystemChannel As Integer

Dim RequestedData As Variant

Dim ActiveProjectName As String

SystemChannel = DDEInitiate("winproj", "system")

RequestedData = DDERequest(SystemChannel, "ActiveProject")

ActiveProjectName = RequestedData(1)

MsgBox ActiveProjectName

End Sub

Sub OLE_1()

Dim oMSP As Object

Set oMSP = GetObject(, "MSProject.Application")

MsgBox oMSP.ActiveProject.Name

End Sub

Example

Each of these Excel macros displays the name of the active project calendar.

Sub DDE_3()

Dim SystemChannel As Integer

Dim ActiveProjectName As String

Dim DocumentChannel As Integer

Dim RequestedData As Variant

Dim CalendarName As String

SystemChannel = DDEInitiate("winproj", "system")

RequestedData = DDERequest(SystemChannel, "ActiveProject")

ActiveProjectName = RequestedData(1)

DocumentChannel = DDEInitiate("winproj", ActiveProjectName)

RequestedData = DDERequest(DocumentChannel, "P(4)")

CalendarName = RequestedData(1)

MsgBox CalendarName

DDETerminate SystemChannel

DDETerminate DocumentChannel

End Sub

Sub ole_3()

Dim oMSP As Object

Set oMSP = GetObject(, "MSProject.Application")

MsgBox oMSP.ActiveProject.Calendar

End Sub

Example

Each of these Excel macros sets the calendar of the active project to "Company Calendar". To test these, make a new base calendar called "Company Calendar", and in Summary Info, choose Standard for the calendar. Then run the Excel macro.

Sub DDE_2()

Dim SystemChannel As Integer

Dim DocumentChannel As Integer

Dim ActiveProjectName As String

Dim RequestedData As Variant

Dim CalendarName As String

SystemChannel = DDEInitiate("winproj", "system")

RequestedData = DDERequest(SystemChannel, "ActiveProject")

ActiveProjectName = RequestedData(1)

DocumentChannel = DDEInitiate("winproj", ActiveProjectName)

'You must put "Company Calendar" in a cell on an Excel sheet

'first; you can't hard code "Company Calendar" into the

'DDEPoke statement

Sheets("Sheet1").Range("A1") = "Company Calendar"

DDEPoke DocumentChannel, "P(4)", Sheets("Sheet1").Range("a1")

DDETerminate SystemChannel

DDETerminate DocumentChannel

End Sub

Sub OLE_2()

Dim oMSP As Object

Set oMSP = GetObject(, "MSProject.Application")

oMSP.ProjectSummaryInfo calendar:="Company Calendar"

End Sub

Example

This MSProject macro displays the list of available task tables. That includes all task tables in Global.mpt and all task tables in the active project. There is no direct way to do this using DDE.

Sub ole7()

Dim oMSP As Object

Dim n As Integer

Set oMSP = GetObject(, "MSProject.Application")

For n = 1 To oMSP.ActiveProject.TaskTableList.Count

MsgBox oMSP.ActiveProject.TaskTableList(n)

Next n

End Sub

RUNNING ANOTHER APPLICATION'S MACROS

MSProject Macros Running Excel Macros

MSProject macros can use DDE and OLE Automation to run Excel macros that take no arguments. It's also possible for an MSProject macro to pass arguments to an Excel procedure and even to get the result back from an Excel function procedure, but only using OLE Automation.

In these examples, it is assumed the Excel macros being called are in the active workbook, and that the macro names are unique.

Example

Each of these MSProject macros runs the Excel macro ExcelSubNoArgs that takes no arguments. The Excel macro ExcelSubNoArgs is shown after the MSProject macros.

Sub DDE_1()

DDEInitiate "Excel", "System"

AppActivate "Microsoft Excel"

DDEExecute "[Run(""ExcelSubNoArgs"")]", 60

DDETerminate

AppActivate "Microsoft Project"

MsgBox "MSProject macro is continuing."

End Sub

Sub OLE_1()

Dim x As Object

Set x = GetObject(, "Excel.Application")

AppActivate "Microsoft Excel"

x.Run "ExcelSubNoArgs"

AppActivate "Microsoft Project"

MsgBox "MSProject macro is continuing."

End Sub

Here's the Excel macro that is called by the above MSProject macros:

Sub ExcelSubNoArgs()

MsgBox "ExcelSubNoArgs message"

End Sub

Try This

This illustrates an MSProject macro using OLE Automation to pass arguments to an Excel sub procedure.

1. Enter the following Excel procedure. This will be called from the MSProject macro in step 2.

Sub ExcelSubWithArgs(dur As Long, start As Date)

MsgBox dur & ", " & start

End Sub

2. Enter the following MSProject macro and run it. It passes a duration in minutes and a start date to the above Excel macro.

Sub MSProjectMacro1()

Dim x As Object

Set x = GetObject(, "Excel.Application")

AppActivate "Microsoft Excel"

x.Run "ExcelSubWithArgs", 480, #1/1/95 10:00:00 AM#

AppActivate "Microsoft Project"

MsgBox "MSProject macro is continuing."

End Sub

NOTE: MSProject can't use DDEExecute to pass arguments to an Excel macro. The DDEExecute statement in the MSProject macro below attempts to execute the ExcelSubWithArgs macro above. The MSProject macro below causes the Excel error: Cannot find macro 'ExcelSubWithArgs 480, #1/1/95 10:00:00 AM#'.

Sub DDE_2()

DDEInitiate "Excel", "system"

AppActivate "Microsoft Excel"

DDEExecute _

"[Run(""ExcelSubWithArgs 480, #1/1/95 10:00:00 AM#"")]"

DDETerminate

End Sub

Try This

This illustrates an MSProject macro that uses OLE Automation to pass arguments to an Excel function procedure and assigns the returned value to an MSProject variable.

1. Enter the following Excel function procedure. This will be called from the MSProject macro in step 2. The Excel function procedure returns the largest of the three numbers passed to it.

Function ExcelFnWithArgs(a As Double, b As Double, c As Double)

Dim maxnum As Double

maxnum = a

If b > maxnum Then

maxnum = b

End If

If c > maxnum Then

maxnum = c

End If

ExcelFnWithArgs = maxnum

End Function

2. Enter the following MSProject macro and run it. It should display a 10 which is the largest of the three numbers passed to the Excel function above.

Sub MSProjectMacro1()

Dim x As Object, result As Double

Set x = GetObject(, "Excel.Application")

result = x.Run("ExcelFnWithArgs", 10, 5, 3)

MsgBox "result is: " & result

End Sub

Excel Macros Running MSProject Macros

Excel macros can use DDE and OLE Automation to run MSProject macros that take no arguments. It's also possible for an Excel macro to pass arguments to an MSProject procedure, but only using DDEExecute. It's not possible for an Excel macro to directly read values returned by calling an MSProject function procedure.

In these examples, it is assumed the MSProject macros are either in the Global.mpt or in the active project, and that the macro names are unique.

Example

Each of these Excel macros runs the MSProject macro "ProjectMacro1" shown after the Excel macros. Assume there is only one MSProject macro with that name.

Sub dde9()

Dim SystemChannel As Integer

SystemChannel = DDEInitiate("winproj", "system")

AppActivate "Microsoft Project"

DDEExecute SystemChannel, "ProjectMacro1"

DDETerminate SystemChannel

AppActivate "Microsoft Excel"

End Sub

Sub ole9()

Dim oMSP As Object

Set oMSP = GetObject(, "MSProject.Application")

oMSP.Macro "ProjectMacro1"

End Sub

Here's the MSProject macro that was called by the above Excel macros:

Sub ProjectMacro1()

MsgBox "ProjectMacro1 is running"

End Sub

Try This

The Excel macro below uses DDE to pass arguments to an MSProject sub procedure.

1. Enter the following MSProject procedure. This will be called from the Excel macro in step 2.

Sub MSProjectMacro1(s As String, n As Integer)

AppActivate "Microsoft Project"

MsgBox "MSProjectMacro1 is running." & Chr(10) & Chr(10) _

& "String value passed: " & s & Chr(10) _ & "Integer value passed: " & n

AppActivate "Microsoft Excel"

End Sub

2. Enter the following Excel macro and run it. It passes a string and an integer to the MSProject sub procedure above.

Sub ExcelDDE1()

Dim SystemChannel As Integer, command As String

SystemChannel = DDEInitiate("winproj", "system")

command = "MSProjectMacro1 ""hello"", 10"

MsgBox "This is the DDEExecute command that will " _

& "be sent to MSProject: " & Chr(10) & Chr(10) _

& command

DDEExecute SystemChannel, command

DDETerminate SystemChannel

End Sub

Note: If you want to pass the values of Excel variables s and n, instead of literals "hello" and 10, it might be clearer to declare QUOTE and COMMA constants and use them to build the DDEExecute command string. For example:

Const QUOTE = """"

Const COMMA = ","

command = " MSProjectMacro1 " & QUOTE & s & QUOTE & COMMA & n

NOTE: You can't use OLE Automation to pass arguments to MSProject macros. The following Excel macro attempts to use OLE Automation to pass arguments to MSProjectMacro1 from the previous "Try This" example. The Excel macro below causes the MSProject error: Cannot find macro 'ProjectMacro1 "hello", 10'.

Sub ole10()

Dim oMSP As Object

Set oMSP = GetObject(, "MSProject.Application")

'The next line causes the error:

'Cannot find macro 'ProjectMacro1 ""hello"", 10'.

oMSP.Macro "ProjectMacro1 ""hello"", 10"

End Sub

Assigning Values to Another Application's Global Variables

An Excel macro can use DDEExecute to directly assign a value to an MSProject global variable.

An MSProject macro can NOT directly assign a value to an EXCEL global variable, although it can pass an argument to an Excel macro that assigns the passed value to an Excel global variable.

Try This

The Excel macro below assigns values to some global variables declared in an MSProject module.

1. In an MSProject module, declare the global string variable gProjStrVar and the global integer variable gProjIntVar.

2. Enter and run the following Excel macro.

Sub ExcelDDE1()

Dim SystemChannel As Integer

SystemChannel = DDEInitiate("winproj", "system")

DDEExecute SystemChannel, "gProjStrVar = ""wow"""

DDEExecute SystemChannel, "gProjIntVar = 100"

DDETerminate SystemChannel

End Sub

3. Switch to MSProject and get into the Debug Window (from the View menu in the Module Editor). In the Immediate pane of the Debug Window, examine the values of the global variables gProjStrVar and gProjIntVar. They should be wow and 100 respectively.

Review of Advantages and Disadvantages of Controlling MSProject by DDE

Here's a review of some of the advantages and disadvantages of using DDE to talk to MSProject from another application:

Advantages

  • Faster.
  • Easy to get the coordinates of the selected cell.
  • Asterisk wild card to access "all" of something.
  • Can pass arguments to MSProject macros.
  • Can assign values to MSProject global vars.

Disadvantages

  • Have to use Unique Ids to access task/resource/assignment data.
  • Cryptic syntax.
  • Asterisk wild card (overflow problems).
  • Can't get list of tables, views, filters, base calendars.
  • MSProject must already be running.

Lesson 4 Exercises

  1. Write an MSProject macro called AllOneDay (with no arguments) that sets the durations of all tasks in the active project to 1d. Write it so it skips blank rows. Then write an Excel macro that runs the AllOneDay macro. Try writing the Excel macro two ways: once using DDEExecute, and once using OLE Automation. Test each on a project that has some tasks that have a duration different from 1d.

  2. Write an MSProject sub procedure called IncreaseCost that takes an integer argument, TaskId, and a currency argument, CostChange. The procedure adds the value of CostChange onto the FixedCost field of the task specified by TaskId. For example, if the current FixedCost of task 2 is $50.00, then the following call will increase it to $80.25:

    3. IncreaseCost 2, 30.25

    Write an Excel macro that passes the values 1 and 10.50 to the MSProject sub procedure IncreaseCost. Test it. It should add $10.50 to the FixedCost of task 1 each time you run it.


Lesson 5: Copy and Paste

Lesson Objectives

Upon completion of this lesson, the participant will be able to:

  • Describe what paste formats Project provides to other applications depending on what was copied and how it was copied.
  • Describe the difference between EditCopy and EditCopyPicture.
  • Describe what formats can be pasted into Project depending on the target view and the copy source.
  • Describe the difference between EditPaste and EditPasteSpecial.
  • Describe the difference between DDEPasteLink and choosing the Paste Link option with EditPasteSpecial.
  • Demonstrate the use of the above commands in macros.

Some Topics to be introduced in this lesson include:

  • EditCopy
  • EditCopyPicture
  • EditPaste
  • EditPasteSpecial
  • DDEPasteLink

Copy, Paste, and Related Commands

This section discusses the use of copy/paste related macro commands to exchange data with other applications. Data can be exchanged in several basic formats - text, picture, and object - with options to link to the source. The available options depend on both the source and target applications.

OUTPUT

The following MSProject macro commands can be used to copy data from the active selection in the active project:

EditCopy

EditCopyPicture

EditCopy fromDate, toDate, includeTable, includeTimescale

Used to copy data from the active project.

The optional arguments are only used when copying data from the Resource Usage view. If the Resource Usage view is active and EditCopy is used without any arguments, then the Copy Resource Usage dialog is opened. When the fromDate and toDate arguments are specified, then it copies timescale data from the minimum number of periods that include the specified dates. If no dates are specified, then it defaults to roughly the periods visible on screen. If an application supports OLE Automation, it can also get Resource Usage data from MSProject by using MSProject's TimescaledData method and summing over all the tasks that a resource is assigned to.

Depending on the active selection in the active project, EditCopy can provide the data in the form of text, a picture, or an object, with the option to link to the source project. Here are some of the Paste Special formats that might be available in Word when data is copied from Project 4.0:

Unformatted text

Picture

Microsoft Project 4.0 Project Object

The rest of this lesson refers to the formats generically as text, picture, and object. Note that the object format without linking creates an embedded object, whereas a linked object is the same as a linked picture.

Here are some of the formats EditCopy can provide to other applications, depending on the application and the active selection in MSProject:

 | Text | Picture1 | Object1 | Paste Link
Task/Resource Sheet | X | X | X | X
Gantt Chart | X | X | X | X
Resource Usage | X | X | X | X2
Resource Graph |  | X | X | X
Pert Chart |  | X | X | X
Calendar view |  | X | X |
Task/Resource Form Selected text in field | X |  |  | X
Task/Resource Form Details Notes | X |  |  | X
Task/Resource Form Details Objects | X |  |  | X

1 The picture and object formats are available in the target application only if the source project file is still open.

2 Resource Usage can include text from a table and/or timescale data - you can't paste link Resource Usage text into another application if the copy includes timescale data. Also, column titles and timescale labels are included only if Tools Options "Copy Resource Usage Header" is checked.

When text is copied, fields are tab separated, and rows are separated by newline strings (chr(13) & chr(10)). Text from a locked first column in a table cannot be copied.

NOTE: If you select a whole row in a table, the Edit menu changes Copy(Cell) to Copy(Task/Resource). This only makes a difference if you paste text back into Project, not if you paste text into another application. If you paste into Project, Copy(Tasks/Resource) copies all fields, even those not in the active table. You can also see the difference if you look in the clipboard at View, Display Text, for example, copying cells might show Display Text as "Copy 2Rx4C", but copying whole tasks might show as "2 tasks".

EditCopyPicture object, forPrinter

Used to copy the active selection in the active project as a picture or an object, but not as text. This works with all non-form task/resource views.

The arguments are optional.

object

If this is False, then only the picture format is provided to other applications. If True, then both the picture and object formats are provided. Paste Link is provided only if this argument is True. The default is False.

forPrinter

If True, then the copied image is formatted for the screen, otherwise for the printer. If not specified, then the Copy Picture dialog is opened.

The camera button on the default standard toolbar does the same thing as using the EditCopyPicture command with object:=False. It prompts for the forPrinter argument.

Here are some of the formats EditCopyPicture can provide depending on the object argument (see exceptions below the table):

object argument | Picture | Object | Paste Link
True | X | X | X
False | X |  |

Exceptions:

Gantt Chart: If ForPrinter:=True, then the Object format is not provided.

Calendar view: No paste link format is provided.

Try This

The following MSProject pastes a picture of rows 3 and 4 of the active Gantt Chart into the start of the active Word document.

1. Open or create a test document in Word.

2. Leave Word open and switch to MSProject. Open/create a test project that has tasks in at least the first four rows.

3. Enter the following MSProject macro and run it. After it finishes, you should see that Gantt picture at the top of the Word document.

Sub copaste2()

Dim w As Object

ViewApply "Gantt chart"

SelectRow Row:=3, Height:=1, RowRelative:=False

EditCopyPicture

Set w = CreateObject("Word.Basic")

w.StartOfDocument

w.EditPaste

AppActivate "Microsoft Word"

End Sub

INPUT

The following MSProject macro commands can be used to paste data into the active project:

EditPasteSpecial

EditPaste

DDEPasteLink

EditPasteSpecial link, type, displayAsIcon

Note: Online Help only shows the Link argument, but Object Browser shows all three arguments.

The arguments are optional.

link

If True, then creates an OLE paste link.

type

Determines the paste format. Possible values are:

0 Object

1 Picture

2 Text

displayAsIcon

Determines whether an object should show as an icon. Use this argument only when pasting an object.

Whether or not the EditPasteSpecial command opens the Paste Special dialog depends on what arguments are included and their values:

These always bring up the Paste Special dialog:

EditPasteSpecial Link:=False, Type:=0, DisplayAsIcon:=True

EditPasteSpecial Link:=False, Type:=0

EditPasteSpecial Link:=False, Type:=1

These don't bring up the Paste Special dialog:

EditPasteSpecial Link:=False, Type:=0, DisplayAsIcon:=False

EditPasteSpecial Link:=False, Type:=1, DisplayAsIcon:=False

EditPasteSpecial Link:=False, Type:=2

Here are some of the formats available to EditPasteSpecial when a range of cells is copied from Excel, depending on the active selection in the active project:

 | Text | Picture | Object | Paste Link
Task/Resource Sheet | X |  |  | X
Gantt Chart | X | X | X | X
Text Box on Gantt Chart | X* |  |  |
Resource Usage | X |  |  | X
Resource Graph |  |  |  |
Pert Chart |  |  |  |
Calendar view |  |  |  |
Task/Resource Form Selected text in field | X* |  |  |
Task/Resource Form Details Notes | X* |  |  |
Task/Resource Form Details Objects |  | X | X | X

* Text Box on Gantt and selected text and notes in task/resource forms can use EditPaste to paste text, but can't use EditPasteSpecial at all.

Note: The following MSProject macro command can be used to activate the source, if an OLE object is selected in MSProject (it's like double clicking on the currently selected object):

ObjectVerb verb:=0

Try This

This macro selects and copies the range A1:B2 from the active Excel worksheet and pastes it as a picture onto the Gantt Chart of the active project.

1. Create a test worksheet in Excel with something in the range A1:B2.

2. Leave Excel open. Switch to MSProject and create a test project.

3. Enter and run the following MSProject macro. When it's done you should see a picture of the Excel cells on the Gantt chart.

Sub copaste3()

Dim x As Object

Set x = GetObject(, "Excel.Application")

x.Range("A1:B2").Select

x.Selection.Copy

ViewApply Name:="Gantt Chart"

EditPasteSpecial Link:=False, Type:=1, DisplayAsIcon:=False

End Sub

Is there any way to have the MSProject macro resize the picture?

EditPaste

This never paste links. Whether it pastes as text, picture, or object depends on the active selection in MSProject and what was copied by the source application.

DDEPasteLink

Used to paste link data into MSProject using the older DDE paste link format, instead of the newer OLE 2.0 format. For OLE 2.0 compliant applications, OLE links are used by default when paste link is selected. The DDE links may perform faster and be less stressful on resources than OLE links, however, they may lack some of the newer OLE functionality. For example, when you double click a cell in an MSProject task table that contains an OLE link, the source application will be activated, whereas, if it contains a DDE link, then the task information dialog opens.

Try This

The following MSProject macro copies the contents of the active cell in Excel and DDEPastelinks it into the start field of the task in row 2.

1. Select a cell in an Excel worksheet that contains something.

2. Switch to MSProject and enter the following MSProject macro.

Sub copaste3()

Dim x As Object

Set x = GetObject(, "Excel.Application")

x.ActiveCell.Copy

ViewApply "Task Sheet"

SelectTaskField Row:=2, Column:="Start", RowRelative:=False

DDEPasteLink

End Sub

3. Test the macro in the following cases:

If there is a task with id=2 and the table is sorted on id.

If there is no task in row 2 before running the macro.

If there is a task in row 2, but no task with id=2 because of the of the way the table is sorted.

Lesson 5 Exercises

  1. Select a cell in the Calendar view in MSProject and choose Edit Copy. Switch to Word and see what formats are available in its Edit Paste Special dialog. Is Paste Link available?

  2. Write an MSProject macro that uses OLE Automation to copy the range A1:D3 from the active Excel worksheet. The macro then pastes it into the object area of the Task Form formatted for Objects, for task 3. Assume there are at least 3 tasks in the active project, and that there is a workbook open in Excel.

    3. There is a "Try This" example in this lesson that shows how an MSProject macro can use OLE Automation to copy an Excel range. To find out how to paste it correctly into MSProject, create a test project with at least 3 tasks and then record an MSProject macro that applies the Task Form view, uses the Edit Goto menu command to go to task 3, formats the Details for Objects, and then uses the Edit Paste menu command.

    To test the completed MSProject macro, create a test Excel worksheet with some test data in A1:D3, then switch back to MSProject and run the macro. You should see the Excel range in the Object area of the Task Form for task 3.

  3. Write an MSProject macro that copies the Gantt chart of the active project and then uses OLE Automation to paste it into the active Word document as an object. The Word command, EditPaste, uses the object format by default to paste the Gantt as an embedded object. Assume that there is at least one task in the active project, and that there is a document open in Word.

    4. Walk through this manually first. Does the camera tool or Edit Copy in MSProject allow you to paste as an object into Word? Does it matter what tasks are selected in the Gantt chart? What happens if you select a blank task and choose Edit Copy and then do Edit Paste in Word?

    Test run the MSProject macro and switch to Word. You should see the embedded Gantt object.


Lesson 6: File Input/Output

Lesson Objectives

Upon completion of this lesson, the participant will be able to:

  • List the most commands used to read and write text files.
  • Describe formatting problems that can occur using the Write# command.
  • Demonstrate in a macro how to use FreeFile, Open, Input#, Write#, EOF, and Close.

Some Topics to be introduced in this lesson include:

  • Macro Commands Used To Read and Write Text Files
  • Formatting Data For Output To Text Files

FILE INPUT/OUTPUT

This section is a light introduction to file input/output, and emphasizes sequential processing of CSV files.

Visual Basic for Applications has a rich set of file input/output commands. You can read/write data from any offset within a file, or read/write data sequentially. You can easily read/write comma separated files or read/write a byte at a time, a line at a time, or fixed length records.

Sequential processing means that you read from a file or write to a file sequentially, starting from the beginning of the file. Random processing means that you can read data from a file or write data to a file, starting at any position within the file.

Here's a couple of possible uses for file input/output in MSProject macros:

Create custom reports that write to CSV files.

Create (write) or process (read) custom mpx files.

Use a temporary file to "dynamically" exchange data between MSProject and another application or a VB3 program.

The following commands can handle most sequential file input/output needs:

Command | Common Usage
FreeFile | Get a free file handle (needed by other commands)
Open | Open the file
Input # | Read in fields and assign them to variables
Write # | Write out data - automatically comma separated
Print # | Write out data - not automatically comma separated
EOF | Used to check if all records have been read
LOF | Length of file - file must have been opened by Open
FileLen | Length of file - must not be open - you specify the filename
Close | Close a file opened by Open

NOTE: If you leave out the Close command at the end of your macros, or if you get a runtime error before the macro executes the Close command, you may get a message telling you the file is already open when you run the macro again. If this happens, use the menu command Run Reset.

If you need random access, then you'll want to look at some of these commands:

Put | Write data starting at a specified position within the file
Get | Read data starting at a specified position within the file
Seek | Specify the position for the next read/write
Loc | Returns the position for the next read/write

See Online Help for the detailed syntax and options available with the above commands.

Formatting Concerns

When reading/writing CSV files, you need to deal with the formatting that the CSV file contains. Different applications format different kinds of data in different ways when creating CSV files. About the only thing that is consistent is that the fields are separated by commas. The table below shows how the same MSProject fields would be written out using the Write# command compared to using FileSaveAs with the CSV format. It shows how the Id, Name, Duration, Start, and Flag1 task properties are written out for a single task, with no additional formatting. The task has Id=1. It starts on 1/2/95 8:00 AM, but the current MSProject Date Format shows the date in a task table as 1/2/95. It is assumed that Activeproject.HoursPerDay is 8.

Screen 1 | MsgBox 2 | Write# 3 | FileSaveAs 4
1 | 1 | 1 | 1
task1 | task1 | "task1" | task1
1d | 480 | 480 | 1d
1/2/95 | 1/2/95 8:00:00 AM | #1995-01-02 8:00:00# | 1/2/95
Yes | True | #TRUE# | No

1 The Screen column shows how the data appears in the task table on screen.

2 The MsgBox column was discovered by examining the output from:

Set t = ActiveProject.Tasks(1)

MsgBox t.ID

MsgBox t.Name

MsgBox t.Duration

MsgBox t.Start

MsgBox t.Flag1

3 The Write# column was discovered by writing to a text file and then examining the text file in NotePad. The code looked like:

Dim fnum As Integer, t As Object

fnum = FreeFile

Open "c:\test.csv" For Output As fnum

Set t = ActiveProject.Tasks(1)

Write #fnum, t.ID, t.Name, t.Duration, t.Start, t.Flag1

4 The FileSaveAs column was created manually by choosing File, Save As, and using the CSV format.

Formatting woes: The # signs in the Write# column aren't recognized as date and boolean (true/false, yes/no) qualifiers when the CSV file created by Write# is manually read back in by MSProject or Excel using File Open (error messages result in MSProject). Also, if the pure number 480 is read back into MSProject using File Open, it doesn't interpret it as minutes, and instead would tack on the default duration units, so you could end up with a duration of 480d.

The table below shows some ways to get around these formatting problems. It assumes the same data as in the previous table.

Screen | Command | Writes this
1d | Write# fnum, t.Duration | 480
1d | 1 Write# fnum, t.Duration / 60 / 8 & "d" | "1d"
1d | 2 Write# fnum, t.GetField(pjTaskDuration) | "1d"
1/2/95 | Write# fnum, t.Start | #1995-01-02 8:00:00#
1/2/95 | 2 Write# fnum, CStr(t.Start) | "1/2/95 8:00:00 AM"
1/2/95 | Write# fnum, t.GetField(pjTaskStart) | "1/2/95"
Yes | Write# fnum, t.Flag1 | #TRUE#
Yes | Write# fnum, CStr(t.Flag1) | "True"
Yes | Write# fnum, Format(t.Flag1,"yes/no") | "Yes"
Yes | 2 Write# fnum, t.GetField(pjTaskFlag1) | "Yes"

1 In general, the expression: T.Duration / 60 / 8

should be replaced by: T.Duration / 60 / Activeproject.HoursPerDay

2 Commonly used methods.

Try This

This MSProject macro writes Id, Name, Duration, Start, and Flag1 values for all tasks in the active project to a CSV file.

1. Open/Create a test file with some tasks.

2. Enter and run the following MSProject macro:

Sub write3()

Dim fnum As Integer

Dim oTask As Object

fnum = FreeFile()

Open "c:\test.csv" For Output As fnum

For Each oTask In ActiveProject.Tasks

Write #fnum, _

oTask.ID, _

oTask.Name, _

oTask.GetField(pjTaskDuration), _

CStr(oTask.Start), _

oTask.GetField(pjTaskFlag1)

Next

Close fnum

End Sub

3. After the macro finishes, open up c:\test.csv in NotePad and examine how the data is formatted. Close NotePad.

4. Open c:\test.csv in Excel and examine how the data is formatted. Close Excel.

5. Use the MSProject menu command File Open to open c:\test.csv. Any problems?

Did a task sheet view have to be active for this macro to work? Did there have to exist a table that begins with fields Id, Name, Duration, Start, and Flag1?

Try This

This MSProject reads in task Text1, Name, and Duration fields from a text file and searches for a task in the active project whose Text1 and Name fields match those read in - the search is case sensitive for Text1, but not for Name. If it finds a match, it sets the duration of that task to the duration read in. If doesn't find a match then if adds a new task with the Text1, Name, and Durations read in.

1. Enter the text below in NotePad. Save it as c:\match.txt and then exit NotePad.

"012","task x","10d"

"005","task y","20d"

"007","task w","30d"

2. Create a project with the following task data:

Id Name Duration Text1

1 task a 1d 009

2 task x 1d 011

3 task w 1d 007

4 task x 1d 012

3. Enter the following MSProject sub procedure, but don't run it yet.

Sub MergeFile()

Dim fnum As Integer, otask As Object

Dim Text1Input$, NameInput$, DurationInput$

Dim matchingID As Integer

fnum = FreeFile()

Open "c:\match.txt" For Input As fnum

Do Until EOF(fnum)

Input #fnum, Text1Input, NameInput, DurationInput

matchingID = GetIdOfMatch(Text1Input, NameInput)

If matchingID = 0 Then

Set otask = ActiveProject.Tasks.Add

Else

Set otask = ActiveProject.Tasks(matchingID)

End If

otask.Text1 = Text1Input

otask.Name = NameInput

otask.Duration = DurationInput

Loop

Close fnum

End Sub

4. Enter the following MSProject function. It is passed the Text1 and Name read in, and it returns the ID of the first matching task it finds. If there is no match, it returns a 0.

Function GetIdOfMatch(TextInput$, NameInput$) As Integer

Dim otask As Object

For Each otask In ActiveProject.Tasks

If Not otask Is Nothing Then

If otask.Text1 = TextInput _

And UCase(otask.Name) = UCase(NameInput) Then

GetIdOfMatch = otask.ID

Exit Function

End If

End If

Next

GetIdOfMatch = 0

End Function

5. Run the MergeFile macro and then check a task table to see if it updated the tasks correctly. It should look like this:

Id Name Duration Text1

1 task a 1d 009

2 task x 1d 011

3 task w 30d 007

4 task x 10d 012

5 task y 20d 005

Binary Examples

Example

This MSProject macro plugs the word "hello" into an existing file Test1, starting at the 3rd byte, without changing the rest of the file.

Sub Bin1()

Dim fnum As Integer

Dim s As String

fnum = FreeFile()

Open "c:\Test1" For Binary As fnum

s = "hello"

Put fnum, 3, s

Close fnum

End Sub

Example

This MSProject macro reads 5 characters, one character at a time, from the file Test1, starting with the 3rd byte in the file. The Ascii code for each byte read is displayed in a MsgBox, along with the character, if it's printable, or a message if it's not.

Sub Bin2()

Dim fnum As Integer

Dim n as integer

Dim c As String * 1 'String can hold 1 char only

Dim s As String

fnum = FreeFile()

Open "c:\Test1" For Binary As fnum

For n = 3 To 5

Get fnum, n, c

If Asc(c) >= 32 Then

s = c

Else

s = "Can't display"

End If

MsgBox "n = " & n & Chr(10) & _

"Ascii code = " & Asc(c) & Chr(10) & _

"Character: " & s

Next

End Sub

Lesson 6 Exercises

  1. Write an MSProject macro that lets the user enter a path and filename in an InputBox, and then saves the comma separated Task UniqueId and Start fields to that file, where the UniqueId's are saved without quotes, and the Start dates are saved with quotes. For example if a task with UniqueId 7 has a start of 10/1/94 then the record written to the CSV file looks like:

    2. 7,"10/1/94 8:00:00 AM"

    Don't write out records for blank tasks. Assume there's at least one nonblank task in the active project. Don't bother with a custom error handler to handle bad filenames etc. Test this on a project with a couple of tasks and examine the file it creates (open it in NotePad).

  2. Create and save a text file in NotePad that contains the Unique Id and duration fields shown below:

    3. 3,"5d"

    1,"2d"

    7,"3d"

    Save the file as "C:\M3L6E2.TXT".

    Write a macro that reads in this file and assigns the durations to the appropriate tasks (matching the Unique Ids). You can hard code the filename "C:\M3L6E2.TXT", but make no assumptions as to the number of records it contains (i.e. use the Do Until EOF(fnum) loop).

    Details: Declare a long variable Uid and a string variable Dur. For each record, the Input# command reads the record into the Uid and Dur variables; then the duration of the task with Unique Id = Uid is set equal to the value of Dur. If there is no task with Unique Id = Uid, then display the message "There is no task with Unique Id = ", followed by the value of the variable Uid. Then continue on to the next record.

    This is much easier than it looks - no searching required. For example, if a task has Unique Id = 5, and you wanted to set its duration to 100d, you could use the Unique Id directly:

    ActiveProject.Tasks.UniqueId(5).Duration ="100d"

    If there is no task with Unique Id = 5, then the above statement would cause a trappable error (On Error Resume Next etc.). Of course, you're working with variables Uid and Dur instead of literals 5 and "100d".

    Test the macro: Create a project with at least 7 tasks. Display the Unique Id column. Run the macro. Check that the durations of the tasks with unique ids 1, 3, and 7 have changed correctly. Then try deleting the task with unique id = 3 and run the macro again. It should give the error message about unique id = 3.


Lesson 7: Workgroup Features

Lesson Objectives

Upon completion of this lesson, the participant will be able to:

  • List the Project mail-related macro commands.
  • Describe the purpose of the four messagetype values for the MailSendProjectMail command.
  • Demonstrate the use of MailSend, MailRoutingSlip, and MailSendProjectMail in a macro.

Some Topics to be introduced in this lesson include:

  • Project Mail-Related Macro Commands

Programming Workgroup Features

This section includes a discussion of the macro commands related to the mail features in MSProject. See Online Help for full documentation. Here's the macro commands as they are used in the default standard menu (right click the menu bar and choose customize, then edit the Standard menu bar):

Menu item | Macro command
File |
Send | MailSend
[Add/Edit Routing Slip] | MailRoutingSlip
Tools, Multiple Project |
Open from Database | Macro "OpenFromDatabase"
Save to Database | Macro "SaveToDatabase"
Tools, Workgroup |
Send Task Request | MailSendProjectMail
Send Task Update | MailSendProjectMail MessageType:="TaskUpdates"
Request Task Update | MailSendProjectMail MessageType:="UpdateRequest"
Set Reminder | SchedulePlusReminderSet
Send Schedule Note | MailSendScheduleNote

The available mail related macro commands are listed and discussed below:

  • MailLogOff
  • MailLogOn
  • MailRoutingSlip
  • MailSend
  • MailSendProjectMail
  • MailSendScheduleNote
  • MailSession
  • MailSystem
  • MailUpdateProject
  • SchedulePlusReminderSet

Note the difference between establishing a session and running the Mail application itself. None of the MSProject mail commands start the Mail application directly, although you'll get a system message asking if you want to log on to mail.

Email Address

Some of the mail commands can automatically send mail to resources (commands without a "To" argument). If the Email Address field for a resource is nonblank, then it must contain a valid email name. If the Email Address field is blank, then the resource name field is used instead.

MailSend to, cc, subject, body, enclosures, includeDocument, returnReceipt

What it sends: Normal piece of mail with options for attachments (enclosures), and an option to attach a copy of the active project.

Who it goes to: Recipients specified by the to argument.

Some of the arguments are discussed below. See Online Help for complete documentation.

enclosures

Can be a string containing a list of filenames to attach to the mail.

includeDocument

Set True to attach a copy of the active project.

body

Can be multiline text (e.g. s="line1" & chr(10) & "line2")

to

Online Help says the "to" argument can be a list of names separated by semicolons. However, MailSend actually treats them as a single name. For example,

MailSend To:="Jim; Mary"

causes an error message saying it can't find "Jim; Mary".

Leave out the To: argument to get a dialog box.

MailRoutingSlip to, subject, body, allAtOnce, returnWhenDone, trackStatus,

clear, sendNow

What it sends: Normal piece of mail with an attached copy of the active project.

Who it goes to: Recipients specified by the to argument.

Some of the arguments are discussed below. See Online Help for complete documentation.

to

Same as in the MailSend method.

clear

After a routing slip is sent, the File menu changes "Add Routing Slip" to "Edit Routing Slip"; if you send the slip again, you get the message:

You have routed this project before. Do you want to route it again?

To reset it, use:

MailRoutingSlip Clear:=True

sendNow

Prevents the mail from being sent if set to False.

MailSendProjectMail messageType, subject, body, fields, updateAsOf, showDialog, installationMessage

What it sends: Depends on the messageType argument. See below.

Who it goes to: Sends mail to resources assigned to the tasks - each resource only receives mail about the tasks it is assigned to.

The arguments subject and body replace default expressions.

The Project must be saved - otherwise it tells you it must be saved and asks if you want to save it.

A task table must be active. Depending on the value of the messageType argument, it will look at all tasks, selected tasks, or it will prompt you. If messageType is "Custom" , then it looks only at selected tasks, and you get an error if no tasks are selected. The other choices for messageType behave as follows: It looks at selected tasks if more than one task is selected. If only one task is selected, then it prompts you to choose all tasks or selected tasks. If no task is selected, then it looks at all tasks.

Some of the arguments are discussed below. See Online Help for complete documentation.

messageType

This is the most important argument. It can be one of the following strings:

"Custom"

"TaskRequest" (default)

"TaskUpdates"

"UpdateRequest"

messageType:="Custom" - Sends specified field information to resources assigned to selected tasks. You must specify the fields argument otherwise you get a fields dialog to select from. When a resource opens the mail, the fields cannot be edited. The resource can send a response, but the original sender can't use the response to update fields in the project.

messageType:="TaskRequest" - Asks resources to accept task assignments. When a resource opens the mail, the fields automatically included are:

Accept?

Task Name

Work

Start

Finish

Comments

If the fields argument is used, then additional read only fields show up to the right of the automatic ones. Only "Accept?" and "Comments" can be edited when a resource opens the mail. When the resource replies and confirms the task, it automatically tries to make a task in the resource's Schedule+.

messageType:="TaskUpdates" - Tells resources of changes in assigned task dates. It only includes tasks with Yes in the "Update Needed" task field, which only happens if at least one resource confirmed a request, and the dates have since changed. The task "Confirmed" field is Yes if no resources are assigned to a task. If a task has resources, then "Confirmed" is No until all resources assigned to the task have confirmed task requests.

BUG: If R confirms T, and then R is unassigned and reassigned to T, then TaskUpdates asks if you want to send mail to R to tell it that it's no longer assigned to T.

When a resource opens the mail, the fields automatically included are:

Task Name

Work

Start

Finish

Comments

If the fields argument is used, then additional read only fields show up to the right of the automatic ones. None of the fields can be edited. If a resource opens the mail and chooses the "Update Schedule+" button, then a new task is added to the resource's Schedule+ with the updated dates - it doesn't remove the old task from Schedule+.

messageType:="UpdateRequest" Requests status from resources on the selected tasks.

The updateAsOf argument is only used if the messageType is "UpdateRequest". It causes the following phrase to show up in the mail:

Enter status as of : ...

It will send update requests to a resource even if the resource has never confirmed a TaskRequest.

When a resource opens the mail, the fields automatically included are:

Task Name

Start

Work

Completed

Remaining Work

Comments

If the fields argument is used, then additional read only fields show up to the right of the automatic ones. The task Name field and any extra fields cannot be edited or updated. If a resource opens the mail and double clicks any field or selects the Reply button, the Reply button changes to a Send button, and a question mark character is placed by the following field names: Start, Work Completed, and Remaining Work. At that point, the resource can edit the fields with the question marks.

NOTE: If a resource opens the mail and changes the start date, then the task in Schedule+ does not get updated.

fields

Specifies the (only) task fields used if messageType:="Custom", or additional fields used with other message types. Titles can be put in square brackets after field name, e.g. Fields:="Duration,Name[Event],Start". Some fields like Name use the default title like Task Name unless you specify a title in []. The titles used in the project tables don't matter.

Note: When a resource opens the mail, they cannot edit any of the extra fields specified by the fields argument. The extra fields appear to the right of the automatic fields.

installationMessage

Optional message that replaces the default error message that occurs if the message handler is not properly installed.

MailSendScheduleNote manager, taskContacts, resources, selection, includeDocument, includePicture, body, subject

What it sends: Normal piece of mail with options for attaching a copy and/or picture of the active project.

Who it goes to: All resources or selected resources or resources assigned to selected tasks, depending on the active view and the value of the selection argument. There are also options to include the manager and contacts in the mailing list.

It works in any view. The selection argument can be true if a task or resource table is active.

The arguments subject and body replace default expressions.

MailUpdateProject dataFile

The dataFile argument must be the fullname of the kind of file invisibly attached to a mail reply to a TaskRequest or a mail reply to an UpdateRequest. To get this filename, you need to use MAPI calls in MAPI.dll and/or VBAMAPI.dll, or write a VB application using the MAPI Session and MAPI Messages custom controls (In VB, choose File, Add File, and select MSMAPI.VBX - it's probably in the system directory). Note that you can't use File, Save Attachment in mail to save this special kind of attachment.

If it's the right kind of data file, then MSProject reads it and updates the appropriate project.

SchedulePlusReminderSet start, leadTime

For each selected task and each resource assigned, it creates an appointment with a reminder for the resource in Schedule+. A task table must be active.

Note: SchedulePlusReminderSet creates appointments in Schedule+, whereas MailSendProjectMail (with messagetype:= "TaskRequest" or "TaskUpdates" or "UpdateRequest") creates tasks in Schedule+.

MailLogoff

Do this after other MSProject mail commands, otherwise you can't exit and sign out of the mail application while project is still running - you can exit Mail, but you can't exit and sign out. MailLogoff notifies the mail spooler that it is done using it.

MailLogon name, password, downloadNewMail

Allows you to start a session without the sign on dialog box - if you know the user name and password - and control whether new mail is downloaded. The name argument is the name of the user who will be sending mail.

MailSession

You can check if this property is Null to see if another mail command failed, for example:

On Error Resume Next

MailLogon

If IsNull(MailSession) then ...

MailSystem

You can use this property to find out what type of mail system is available:

0 pjNoMailSystem Unrecognized or none

1 pjMAPI Microsoft Mail

3 pjMAPICompatible MAPI compatible

Lesson 7 Exercises

  1. Assume the resource EmailAddress field in the active project contains valid email names. Write a macro that loops through all the nonblank resource records and uses MailSend to send mail to each resource listing their standard and overtime rate on separate lines in the body of the mail, for example,

    2. Standard Rate: $20.00/h

    Overtime Rate: $30.00/h

    The mail subject line is: Rates

    Use the To, Subject, Body, and IncludeDocument arguments of the MailSend method. You need to set the IncludeDocument argument to False to prevent it from attaching a copy of the active project to the mail (IncludeDocument defaults to True).

    Test it out on a project that has some valid email names entered in the resource EmailAddress field. Open the mail and see if it worked.

  2. Assume the EmailAddress resource field in the active project contains valid email names. Write a macro that sends mail to each resource, where the body of the mail to a resource is its multiline notes (from the Resource Form). The subject of the mail is "Multiline Notes". This is similar to exercise 1. Use GetField to get the multiline notes.

  3. Write a macro that sends a Task Request to all the resources that are assigned to tasks. The subject of the mail should say "Assignments", the body should say "Respond ASAP", and the "Resources Names" field should be included with the usual Task Request fields. Don't show any dialog boxes.


Lesson 8: API's and DLL's

Lesson Objectives

Upon completion of this lesson, the participant will be able to:

  • Define API and DLL.
  • Describe how to declare an API function.
  • Describe how to use API functions to hide a window, show a window, make a window "always on top", and how to tell if an application is running and whether it is visible or not.

Some Topics to be introduced in this lesson include:

  • Where To Find Information About Specific API Functions
  • How To Get API Declarations and Global Constants Into a Macro
  • API functions To Manipulate and Get Information About Application Windows
  • API functions To Pass Data Between Applications Using Global Memory and the ClipBoard.

API's and DLL's

A DLL (Dynamic-link library) is a set of procedures that can be called from windows applications. There are plenty of standard DLL's available. The Windows API includes the User, GDI, and Kernel libraries. Other examples of API's are MAPI (messaging API) and TAPI (telephony API). Documentation about what procedures are in various API libraries is usually found in the appropriate SDK (software development kit). VB3 Professional Edition includes Win31wh.hlp, a help file that ships with the Windows SDK. It's in the WinAPI subdirectory of VB3, and documents Windows API procedures. Win31wh.hlp uses C language syntax, but you need not be a C programmer to get the gist of what a procedure is for. To call a DLL procedure from a macro, you first declare it in the declarations area at the top of a module. Declarations are technical statements telling your macro where to find the DLL procedure, how to pass data to it (if it takes arguments), and what data the procedure will return, if any. Instead of entering declarations manually, you usually copy them from some documentation text or help file. VB3 also includes Win31API.hlp, which has declarations that you can copy and paste into the declarations area of one of your modules. VB3 and applications that support Visual Basic for Applications can call DLL procedures.

API DECLARATIONS

Before you can use a procedure from a DLL, you must declare it. The declarations are entered or pasted into the declaration area in a module. A Declaration must be on one line, unless the macro editor in the application has a continuation character. For example, in Visual Basic for Applications you can use the underscore character to continue a logical line to the next physical line. You can't do that in VB3.

Most declarations include arguments. When you call the procedure in your macro, you replace the arguments just like you would when calling a macro procedure. Some of the API procedures have flag arguments that must be set to one of a few predefined values. The same documentation that contains the declaration statements also contains a list of global constants that you can copy and paste into the declaration area of a module. You can then use the named constants when you call the procedure. In some cases, you are allowed to pass the sum of two constants for a flag to combined two actions, for example:

SWP_NOMOVE + SWP_NOSIZE

Most of the API declarations are function procedures instead of sub procedures. Often they return only a success/failure flag. You can ignore the return value if you have no use for it, by not assigning a variable when you call the function, and not using ( )'s around the argument list. For example, both of the following are legal:

nPreviousState = ShowWindow(handle, SW_SHOWMAXIMIZED)

ShowWindow handle, SW_SHOWMAXIMIZED

In the declaration examples below, return values that are usually ignored are not discussed. See the API documentation for information on these return values.

There are some examples of API declarations below, along with some comments about what the procedures do. There are also some examples of MSProject and Excel procedures that use them. Most of these examples could be run from any application that supports Visual Basic for Applications (like Excel and MSProject) or from VB3, except where indicated otherwise. These examples require that the API procedures used be declared in the declaration area of a module.

Some Window-Related Procedures

The first set of API procedures manipulate or get information about windows:

  • GetActiveWindow
  • SetWindowPos
  • ShowWindow
  • GetClassname
  • FindWindow
  • IsWindowVisible

GetActiveWindow

Declare Function GetActiveWindow Lib "USER" () As Integer

GetActiveWindow returns the handle to the active window. A window handle is an integer that identifies a window. It's not of much use by itself, but the window handle is usually passed to other procedures when talking actions or requesting data about a specific window. You normally assign it to an integer variable, for example,

handle = GetActiveWindow()

SetWindowPos

Declare Sub SetWindowPos Lib "USER" _

(ByVal hWnd As Integer, _

ByVal hWndInsertAfter As Integer, _

ByVal x As Integer, ByVal y As Integer, _

ByVal cx As Integer, ByVal cy As Integer, _

ByVal wFlags As Integer)

SetWindowPos can be used to move or resize a window, and change the position (zorder) of the specified window within the stack of windows. Below is a description of its arguments:

hWnd

Handle to the window you want to effect.

hWndInsertAfter

A value that specifies the desired zorder. You can either declare and pass one of the constants below, or pass the actual number. If you use the named constants, you must put them in the declaration area of a module:

Global Const HWND_TOP = 0

Global Const HWND_BOTTOM = 1

Global Const HWND_TOPMOST = -1

Global Const HWND_NOTOPMOST = -2

wFlags

A flag that helps describe what you want to do with the window. Here's a few of the possible constants it can be:

Global Const SWP_NOSIZE = &h1

Global Const SWP_NOMOVE = &h2

Global Const SWP_SHOWWINDOW = &h40

Global Const SWP_HIDEWINDOW = &h80

x,y

Cordinates where you want the upper left corner of the window. Ignored if you include SWP_NOSIZE in wFlags.

cx,cy

Width and height you want for the window. Ignored if you include SWP_NOMOVE in wFlags.

ShowWindow

Declare Function ShowWindow Lib "USER" _

(ByVal hWnd As Integer, ByVal nCmdShow As Integer) As Integer

The ShowWindow procedure can make the specified window visible or invisible, as well as maximize, minimize, or normalize it. If you use ShowWindow to hide an application window, then that application will no longer be in the Windows Task List. The return value tells what state the window was in before you called the procedure. You normally won't use the returned value. Below is a description of its arguments:

hWnd

Handle to the window you want to effect.

nCmdShow

A flag that helps describe what you want to do with the window. Here's a few of the possible constants it can be:

Global Const SW_HIDE = 0

Global Const SW_SHOWNORMAL = 1

Global Const SW_SHOWMINIMIZED = 2

Global Const SW_SHOWMAXIMIZED = 3

GetClassname

Declare Function GetClassname Lib "USER" _

(ByVal hWnd As Integer, _

ByVal lpClassname As String, _

ByVal nMaxCount As Integer) As Integer

Each window has a Classname associated with it that can be used in other procedures to get information about the window. The API GetClassname function returns the Classname of the window that you specify. For example, by using this function, you would discover that the Classname of the MSProject application window is "JWinproj-WhimperMainClass".

hWnd

Handle to the window you want to effect.

lpClassname

Memory address or string variable name where you want the Classname placed. You usually pass it the name of a fixed length string variable. When the procedure is done, it will have assigned the Classname to your variable. When you declare the fixed length string variable, give it a length equal to the maximum number of characters you want it to return (in case the Classname is really long). Here's an example of a variable declaration that reserves room for 10 characters:

Dim s As String * 10

After the procedure is done, you could see the Classname with the command:

MsgBox s

nMaxCount

Maximum number of characters you want it to place in lpClassname.

FindWindow

Declare Function FindWindow Lib "USER" _

(ByVal lpClassname As Any, ByVal lpWindowName As Any) As Integer

FindWindow can tell if a specific application is running, even if the application is running invisibly (not in the Windows Task List). You need to provide a Classname or window title bar caption (see GetClassname for a method for discovering application Classnames). The return value is a handle to the window, or 0 if it can't find it. You normally assign the return value to an integer variable, for example,

handle = FindWindow("JWinproj-WhimperMainClass", 0&)

lpClassname

String with the Classname, or 0& to ignore.

lpWindowName

String with the window title, or 0& to ignore

IsWindowVisible

Declare Function IsWindowVisible Lib "User" _

(ByVal hWnd As Integer) As Integer

IsWindowVisible can tell if an application window is visible (in the Windows Task List) or not.

hWnd

Handle to the window you are inquiring about.

You need to provide a handle to the window of interest. Normally the handle returned by FindWindow is used. IsWindowVisible returns True if the window is visible or False if it is not, so IsWindowVisible is normally used in an IF statement.

Examples of Window-Related Procedures

The examples below assume the appropriate declarations and global constants, as described above, have be placed in the declaration area of a module.

Example

This Excel macro gives a message that tells if MSProject is running, and if it is, it tells whether it is in the Windows Task List (running visibly) or not.

Sub WhatAboutMSProject()

Dim handle As Integer

handle = FindWindow("JWinproj-WhimperMainClass", 0&)

If handle = 0 Then

MsgBox "MSProject is not running"

ElseIf IsWindowVisible(handle) then

MsgBox "MSProject is in the Windows Task List"

Else

MsgBox "MSProject is running, but is not " & _

"in the Windows Task List"

End If

End Sub

Example

This macro makes the active window topmost, i.e. "always on top". The coordinates for moving and sizing are ignored, so it passes zeroes for those arguments.

Sub MakeActiveWindowTopMost()

SetWindowPos GetActiveWindow(), _

HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE + SWP_NOSIZE

End Sub

Example

This macro makes the active window not topmost, i.e. "not always on top". The coordinates for moving and sizing are ignored, so it passes zeroes for those arguments.

Sub MakeActiveWindowNotTopMost()

SetWindowPos GetActiveWindow(), _

HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOMOVE + SWP_NOSIZE

End Sub

Example

This MSProject macro allows you to discover the Classname of any window. When it runs, it minimizes MSProject to a topmost icon and the caption under the icon will say "Microsoft Project - " followed by the Classname of whatever window is active, for example you would see the following caption under it if Excel were active:

Microsoft Project - XLMAIN

It works by going into a DoEvents loop which uses the API procedures GetActiveWindow and GetClassname, and displays the returned Classname in the MSProject window caption. The fixed length string sClassname is used to hold the returned Classname (maximum 30 characters), and the string sOldClassname is used to tell when the Classname has changed.

Sub ShowClassnames()

'DECLARE A STRING VARIABLE WITH ROOM FOR 30 CHARACTERS

Dim sClassname As String * 30

Dim sOldClassname As String

MsgBox "This MSProject macro displays Classnames " & _

"of the active window under a minimized " & _

"MSProject icon, after the hyphen. " & _

"To end the macro, maximize MSProject."

MakeActiveWindowTopMost

sOldClassname = ""

AppMinimize

Do

DoEvents

GetClassname GetActiveWindow(), sClassname, 30

If sClassname <> sOldClassname Then

ActiveWindow.Caption = sClassname

sOldClassname = sClassname

End If

Loop While WindowState = pjMinimized

ActiveWindow.Caption = ActiveProject.Name

MakeActiveWindowNotTopMost

End Sub

Example

This MSProject macro checks if Excel is running, and if it is, it makes it invisible (removes it from the Windows Task List). If more than one instance of Excel is running, it only effects one instance.

Sub HideExcel()

Dim handle As Integer

handle = FindWindow("XLMAIN", 0&)

If handle = 0 Then

MsgBox "Excel is not running"

Else

ShowWindow handle, SW_HIDE

End If

End Sub

Example

This MSProject macro checks if Excel is running, and if it is, it makes it visible (puts it in the Windows Task List) and maximizes it. If more than one instance of Excel is running, it only effects one instance.

Sub ShowExcel()

Dim handle As Integer

handle = FindWindow("XLMAIN", 0&)

If handle = 0 Then

MsgBox "Excel is not running"

Else

ShowWindow handle, SW_SHOWMAXIMIZED

End If

End Sub

Some Memory Allocation and Clipboard Procedures

These procedures are used for passing data between applications.

  • GlobalAlloc
  • GlobalLock
  • GlobalUnlock
  • GlobalFree
  • lstrcpy
  • lstrcpyn
  • lstrlen
  • OpenClipboard
  • EmptyClipboard
  • SetClipboard
  • GetClipboardData
  • CloseClipboard

GlobalAlloc

Declare Function GlobalAlloc Lib "KERNEL" _

(ByVal wFlags As Integer, ByVal dwBytes As Long) As Integer

Allocates global memory of the specified kind and amount and returns a memory block id.

In Windows, global blocks of memory that can be shared by applications are identified in two ways: By a block id number, and by a memory address. There are also different kinds of memory blocks, for example, moveable blocks that windows is allowed to move around in memory to optimize system performance, fixed blocks that it can't move, and blocks with other characteristics. You tell the GloballAlloc function what kind of memory you want and how much. It returns 0 if there isn't enough available, otherwise it returns the id number for the block. You normally assign it to an integer variable, for example:

MemoryBlockId = GlobalAlloc(GMEM_DDESHARE, 100&)

If MemoryBlockId = 0 Then

MsgBox "Not enough free memory"

End

End If

dwBytes

Long integer that tells how many bytes to allocate.

wFlags

Determines what "kind" of memory. The safest kind to use is DDE share memory, because windows will automatically free this memory when the application that allocated it quits. The corresponding constant for this type of memory is shown below. See the API documentation for other possible kinds of memory.

Global Const GMEM_DDESHARE = &h2000

GlobalLock

Declare Function GlobalLock Lib "KERNEL" _

(ByVal hMem As Integer) As Long

Locks the specified memory block and returns an address. You must lock it before you can use it. When locked, Windows will insure that no other applications will mess with the contents of that memory block. It's analogous to record locking. In addition, GlobalAlloc is used to convert memory block id numbers into memory block addresses. Some procedures must be passed ids, while others require addresses. You normally assign it to a long integer variable, for example:

MemoryBlockAddress = GlobalLock(MemoryBlockId)

where MemoryBlockId might have been the result of a GlobalAlloc call.

hMem

Id of the memory block you want to lock.

GlobalUnlock

Declare Function GlobalUnlock Lib "KERNEL" _

(ByVal hMem As Integer) As Integer

hMem

Id of the memory block you want to unlock. You must unlock a global memory block before you can free it.

GlobalFree

Declare Function GlobalFree Lib "KERNEL" _

(ByVal hMem As Integer) As Integer

hMem

Id of the memory block you want to free.

lstrcpy

Declare Function lstrcpy Lib "KERNEL" _

(ByVal lpString1 As Any, ByVal lpString2 As Any) As Long

This function is used to copy data from one string (or memory block) to another. The content of lpString2 is copied to into the string lpString1; lpString1 must have enough room to hold lpString2. The character 0 marks the end of a string or the data to be copied from a memory block, up to a maximum of 64K characters (bytes).

When you pass a string variable or constant to this function, you are actually passing a memory block address. The terms "string" and "memory block address" are interchangeable in this context.

lpString1

Target memory address or string.

lpString2

Source memory address or string.

lstrcpyn

Declare Function lstrcpyn Lib "KERNEL" _

(ByVal lpString1 As Any, ByVal lpString2 As Any, _

ByVal nChars As Integer) As Long

Like lstrcpy, but it allows you to specify a maximum number of characters to copy. Much safer.

lpString1

Target memory address or string. You must reserve at least as much room (minus 1) as you specify by the nChars argument.

lpString2

Source memory address or string.

nChars

The maximum number of characters you want to copy. You actually have to specify one more than the number of characters you want, because it counts the 0 character. For example, if lpString2 is the string "Happy" and you specify nChars=3, then lpString1 becomes "Ha".

lstrlen

Declare Function lstrlen Lib "Kernel" _

(ByVal lpString As Any) As Integer

This function is used to get the length of a string .The character 0 marks the end the string. The length returned does not count the 0.

lpString

Memory address or string you want to measure.

OpenClipboard

Declare Function OpenClipboard Lib "USER" _

(ByVal hWnd As Integer) As Integer

Opens the Clipboard so it can be accessed.

hWnd

Handle of the window accessing the Clipboard; you usually pass the result returned from GetActiveWindow().

EmptyClipboard

Declare Function EmptyClipboard Lib "USER" () As Integer

Used to clear the Clipboard.

SetClipboardData

Declare Function SetClipboardData Lib "USER" _

(ByVal wFormat As Integer, ByVal hMem As Integer) As Integer

Used to put data on the Clipboard. You tell it the format of the data and where it's at (pass a memory block id).

wFormat

Constant that determines the kind of data you are copying to the Clipboard, i.e. the Clipboard format. See the API documentation for the possible choices. For text, use:

Global Const CF_TEXT = 1

hMem

Id of the memory block you want "copied to the Clipboard"

GetClipboardData

Declare Function GetClipboardData Lib "USER" _

(ByVal wFormat As Integer) As Integer

Used to get data from the Clipboard. You tell it what kind (format) of data you want. It returns a memory block id for the memory where the Clipboard data is located. You normally assign it to an integer variable, for example:

MemoryBlockId = GetClipboardData(CF_TEXT)

You normally use GlobalLock to convert the id to an address and then use lstrcpy to copy the data into a string variable.

wFormat

Same as in SetClipboardData

CloseClipboard

Declare Function CloseClipboard Lib "USER" () As Integer

You must close the Clipboard so other applications can use it. You can place this before any OpenClipboard call to insure that the Clipboard isn't already open.

Examples of Memory Allocation and Clipboard Procedures

The examples below assume the appropriate declarations and global constants, as described above, have be placed in the declaration area of a module.

Example

This macro allows you to enter text in an InputBox and assign it to a string variable. The contents of the string variable is then placed on the Clipboard, (without placing it in any cell and without using EditCopy). The string variable value is copied to a global memory block, and then the Clipboard is told to point there. Note that you don't use GlobalFree to free up this memory block - the Clipboard is responsible for the memory after you use the SetClipboardData procedure.

Sub PutTextOnClipboard()

Dim MemoryBlockId As Integer

Dim MemoryBlockAddress As Long

Dim s As String

s = InputBox("Enter text to put on Clipboard")

OpenClipboard GetActiveWindow()

EmptyClipboard

'ALLOCATE A GLOBAL MEMORY BLOCK

MemoryBlockId = GlobalAlloc(GMEM_DDESHARE, Len(s))

'CONVERT THE MEMORY BLOCK ID INTO AN ADDRESS

MemoryBlockAddress = GlobalLock(MemoryBlockId)

'COPY THE STRING VARIABLE S INTO THE MEMORY BLOCK

lstrcpy MemoryBlockAddress, s

'TELL THE CLIPBOARD WHERE TO GET ITS DATA FROM

SetClipboardData CF_TEXT, MemoryBlockId

CloseClipboard

MsgBox "Open up the Clipboard. Your string should be there."

End Sub

Example

This macro copies a maximum of 100 characters from the Clipboard directly into a string variable (without placing it in any cell and without using EditPaste). Then the macro shows the contents of the string variable.

Sub GetTextFromClipboard()

Dim MemoryBlockId As Integer

Dim MemoryBlockAddress As Long

Dim s As String * 100 'Must reserve room in the string

OpenClipboard GetActiveWindow()

MemoryBlockId = GetClipboardData(CF_TEXT)

MemoryBlockAddress = GlobalLock(MemoryBlockId)

lstrcpyn s, MemoryBlockAddress, 101 'Plus 1 for the 0 character

GlobalUnlock MemoryBlockId

CloseClipboard

MsgBox "The text on the Clipboard is: " & s

End Sub

Lesson 8 Exercises

  1. Write an MSProject macro that starts a new instance of the Calculator application that comes with Windows (Calc.exe) and makes it a top most window.

  2. Write an MSProject macro that clears the Clipboard and then waits in a DoEvents loop until it sees the word "hello" on the Clipboard. At that point, it activates the Microsoft Project window and displays a message "goodbye". Use the appropriate API calls to do this - see the GetTextFromClipBoard example. Use lstrcpyn where nchars=6 (1 + length of "hello").


Answers To Selected Exercises

Module 1 - Lesson 1 Exercises Page 1-9

3. | No, make the macro non-interactive and then use a combination of FilterEdit and FilterApply or use the SendKeys statement before the FilterApply method.
4. | No, remove the Copies:= from the statement to make it read >> FilePrint 1. Also, changing any default settings will fix it, i.e. add the parameter Color:=True

Module 1 - Lesson 2

"Try This: Using Declared Data" Page 1-17

1. The error "Variable Not Defined" appears - to correct the problem, change State to a public variable using Public in place of the Dim statement.

2. Local takes precedence

Module 1 - Lesson 2 Exercises Page 1-23

1. A variable should be used. It will be declared in the General Declarations section using either the Private or Dim statement. The value will be set in the procedure where the condition is tested. While the value does not change, it is not possible to declare a constant without assigning it a value and once it is declared, it cannot be modified.

Dim VariableName as Integer

Sub Sample()

VariableName = expression

End Sub

2. The customer may not be using the appropriate data type for the arrays. For example, the values may be integers but the arrays are declared using the variant data type. This can significantly slow execution if very large arrays (or many variables) are involved.

3.

Sub Sample()
MsgBox Val(InputBox("Enter number")) * 100
End Sub

4.

Sub Auto_Open()

MsgBox Now()

End Sub

Module 1 - Lesson 2 Exercises (continued)

5.

Sub StringFun()

Dim daString As String

Dim vFirstWord, vMiddleWord, vLastWord As String

Dim v3rdSpace, vSpacePos1, vSpacePos2 As Integer

daString = InputBox("Enter 5 words separated by spaces")

'Finds position of 3rd space and deletes everything to the right

v3rdSpace = InStr(InStr(InStr(1, daString, " ") + 1, _

daString, " ") + 1, daString, " ")

daString = Trim(Left(daString, v3rdSpace - 1))

'Determines positions of the two spaces between the three words

vSpacePos1 = InStr(1, daString, " ")

vSpacePos2 = InStr(vSpacePos1 + 1, daString, " ")

'Pulls out words

vFirstWord = Left(daString, vSpacePos1 - 1)

vLastWord = Right(daString, Len(daString) - vSpacePos2)

vMiddleWord = Mid(daString, vSpacePos1 + 1, _

vSpacePos2 - vSpacePos1 - 1)

'Concatenates message with linefeeds

MsgBox vFirstWord & Chr(10) & vMiddleWord & Chr(10) & vLastWord

End Sub

Module 1 - Lesson 3 Exercises Page 1-30

1.

Sub GenerateArrayValues()

Dim MyArray(1 To 2, 1 To 10) 'Array declaration

Dim Counter As Integer 'Counts the number of times a value is assigned to the array

Dim RandNum As Integer 'Stores the random number

Dim Used As Boolean 'Indicates if number has already been assigned to the array

Dim i As Integer 'Used as a loop counter in various areas of the procedure

Counter = 0

Randomize 'Tells VB to use system timer for seed value when generating

' random numbers

' This part of the procedure generates the random numbers and assigns

' them to the array

Do While Counter < 10 'Loop until all values are assigned

Used = False

RandNum = Int((10 - 1 + 1) * Rnd + 1) 'Generates random number between 1-10 (see Help)

If Counter = 0 Then 'If first time, assigns number to first element

MyArray(1, 1) = RandNum ' and increments counter

Counter = Counter + 1

Else 'If it's not the first time through the loop

For i = 1 To Counter 'For every number in the array

If RandNum = MyArray(1, i) Then 'Compare new number to numbers already assigned

Used = True 'If found, then set the flag and exit the loop

Exit For

End If

Next i

If Used = False Then 'If the number does not exist in the array

MyArray(1, Counter + 1) = RandNum ' then assign it to the next element

Counter = Counter + 1 ' and increment the counter

End If

End If

Loop

' This part of the procedure assigns the strings to the array based

' on the value

For i = 1 To 10 'For each number in the array

Select Case MyArray(1, i) ' compare the value and assign the appropriate

Case Is < 5 ' string value

MyArray(2, i) = "Smaller"

Case Is = 5

MyArray(2, i) = "Equal"

Case Else

MyArray(2, i) = "Bigger"

End Select

Next i

' The part of the procedure displays the values that are even

For i = 1 To 10 'For each number array, see if the remainder

If MyArray(1, i) Mod 2 = 0 Then ' is zero when divided by two (= even number)

MsgBox "Number = " & MyArray(1, i) & " String = " & MyArray(2, i)

End If

Next i

End Sub

Module 1 - Lesson 4 Exercises Page 1-34

1. Only one difference: function will return a value.

2. He/she can use the IsMissing function within an If statement to check to see if the argument has been passed to the function. IsMissing will return True if no argument was passed and will return False if it was.

3.

Function MyPoser(pNumber)
MyPower = pNumber ^ .05 * 6
End Function

Module 1 - Lesson 5 Exercises Page 1-43

1. Yes, highlight the variable to watch in the code pane of the Debug window, press the Instant Watch Tool on the Visual Basic toolbar and choose the Add button. Or choose Tools Add Watch.

2.

Sub GetFile()

Dim goodFile As Boolean

On Error GoTo errorHandler

Do

goodFile = True

fileName = InputBox(prompt:="Enter a filename")

if fileName = "" Then Exit Sub

FileOpen fileName

If goodFile Then Exit Sub

Loop

errorHandler:

goodFile = False

Msg = "The file, " & fileName & ", is either already open or not available."

x = Application.Message(Message:=Msg, Type:=pjYesNo, _

YesText:="Try Again", NoText:="Exit Procedure")

If x = True Then Resume Next

End Sub

Module 2 - Lesson 1

Exercise2: (MoveRect) Page 2-6

Sub MoveRect()

FileSave

For i = 1 To 5

SelectCellRight 2

SelectCellDown 2

SelectCellLeft 2

SelectCellUp 2

Next i

FileClose

End Sub

Exercise: (ApplyAView) Page 2-10

Sub ApplyAView()

test = False

myView = InputBox("Enter a View to display: ")

For Each item In ActiveProject.TaskViewList

If LCase(item) = LCase(myView) Then

ViewApply Name:=myView

test = True

End If

Next item

If test = False Then MsgBox "View Does not exist"

End Sub

Module 2 - Lesson 2

Exercise1: (TaskTraverse) Page 2-16

Sub TaskTraverse()

For Each t In ActiveProject.Tasks

If t.Duration > 5 * 480 Then t.Duration = t.Duration * 0.9

If t.Summary Then

If t.OutlineChildren > 5 Then t.OutlineHideSubtasks

End If

Next t

End Sub

Module 2 - Lesson 2 (continued)

Exercise2: (TaskLink) Page 2-16

Sub TaskLink()

For Each t In ActiveProject.Tasks

i = 0

If t.Summary Then

If t.OutlineChildren > 1 Then

idTmp1 = t.ID + 1

idTmp2 = t.ID + 2

ActiveProject.Tasks(idTmp2).LinkPredecessors _

Tasks:=ActiveProject.Tasks(idTmp1)

End If

End If

Next t

End Sub

Exercise1: Page 2-18

Sub ResMaxUnits()

RName = InputBox("Enter the name of the resource to edit")

RMax = InputBox("The Max Units for " & RName & " is " & _

ActiveProject.Resources(RName).GetField(FieldID:=pjMaxUnits) _

& " Do you want to Change it? Y/N")

If RMax = "y" Then

ActiveProject.Resources(RName).MaxUnits = _

InputBox("Enter new value")

End If

End Sub

Exercise1: (AssignWork1) Page 2-20

Sub AssignWork1()

RName = InputBox("Enter the name of the resourse to remove work from:")

For Each t In ActiveProject.Tasks

For Each r In t.Assignments

If r.ResourceName = RName Then r.Work = r.Work - 60

Next r

Next t

End Sub

Module 2 - Lesson 2 (continued)

Exercise2: (AssignWork2) Page 2-20

Sub AssignWork2()

For Each t In ActiveProject.Tasks

For Each r In t.Assignments

If r.ResourceName = t.Text1 Then r.Work = r.Work + r.Work * 0.2

Next r

Next t

End Sub

Module 2 - Lesson 3

Exercise1: (CalRangeSet) Page 2-26

Sub CalRangeSet()

DRangeStart = InputBox("Enter the Start date of the break")

DRangeFinish = InputBox("Enter the Finish date of the break")

ActiveProject.BaseCalendars("Standard") _

.Period(DRangeStart, DRangeFinish).Working = False

End Sub

Exercise2: (CalTaskMove) Page 2-26

Sub CalTaskMove()

Dim newTime As String

newTime = InputBox("Enter the a duration")

x = ActiveProject.Tasks(ActiveCell.Task.ID - 1).Start

ActiveCell.Task.Start = DateAdd(x, newTime)

End Sub

Module 3 - Lesson 1 Exercises Page 3-18

1.

Sub M3L1E1()

Dim MyErr As Integer, msg As String

On Error Resume Next

AppActivate "Microsoft Project"

MyErr = Err

On Error GoTo 0

If MyErr > 0 Then

msg = "Make sure Microsoft Project is running " & _

"before using this macro."

MsgBox msg

End If

End Sub

2.

Sub M3L1E2()

Dim MyErr As Integer, response As Integer

On Error Resume Next

AppActivate "Microsoft Excel"

MyErr = Err

On Error GoTo 0

If MyErr > 0 Then

msg = "Excel is not running. Do you want to start it?"

response = MsgBox(msg, vbYesNo)

If response = vbYes Then

AppExecute command:="Excel" 'or use Shell with full path

Else

End 'don't need this; macro ends anyway

End If

End If

End Sub

Module 3 - Lesson 1 Exercises (continued)

3.

Sub M3L1E3()

Dim msg As String, response As String, MyErr As Integer

On Error Resume Next

AppActivate "Microsoft Excel"

MyErr = Err

On Error GoTo 0

If MyErr > 0 Then

AppExecute command:="Excel" 'or use Shell with full path

Else

AppActivate "Microsoft Project" 'so next msg can be seen

msg = "Excel is already running. You can switch to it, " & _

"or start a new instance."

response = Message(msg, pjYesNoCancel, "Current", "New")

If response = True Then 'Current (Yes) button

AppActivate "Microsoft Excel"

ElseIf response = False Then 'New (No) button

Shell "D:\Excel5\Excel.exe", 3 'Shell new instance

Else 'Cancel button

End 'don't need this; macro ends anyway

End If

End If

End Sub

4.

Sub M3L1E4()

Dim MyErr As Integer

On Error Resume Next

AppActivate "Microsoft Excel"

MyErr = Err

On Error GoTo 0

If MyErr = 0 Then

SendKeys "%{F4}" 'Send Alt-F4 to close it

End If

End Sub

Module 3 - Lesson 2 Exercises Page 3-23

1.

Sub M3L2E1()

Dim s As String

s = InputBox("Enter some text.")

Shell "Notepad.exe", 3

SendKeys s

End Sub

2.

Sub M3L2E2()

ViewApply Name:="&Gantt Chart"

SelectTaskColumn Column:="Name"

EditCopy

Shell "NotePad.exe", 3

SendKeys "%EP"

End Sub

3.

Sub M3L2E3()

Dim T As Object

Shell "NotePad.exe", 3

For Each T In ActiveProject.Tasks

SendKeys T.Name

SendKeys "{Enter}"

Next

End Sub

4.

Sub M3L2E4()

SendKeys "If Then"

SendKeys "{Enter 2}"

SendKeys "End If"

SendKeys "{Up 2}"

SendKeys "{Left 3}"

End Sub

Module 3 - Lesson 3 Exercises Page 3-49

1.

Step (13): In the Form_Load, cmdPrevious_Click, and cmdNext_Click procedures, replace the two lines

lblTaskName = oTask.Name

txtDuration = oTask.GetField(29)

with the following lines:

If oTask Is Nothing Then

lblTaskName = ""

txtDuration = ""

Else

lblTaskName = oTask.Name

txtDuration = oTask.GetField(29)

End If

And the new cmdUpdate_Click procedure is:

Sub cmdUpdate_Click ()

If oTask Is Nothing Then

MsgBox "Task is blank"

txtDuration = ""

Else

oTask.Duration = txtDuration

End If

End Sub

Step (14): A command button was created, labeled "GoTo", and its Name property was changed to cmdGoto. The click procedure is shown below:

Sub cmdGoto_Click ()

Dim N As Integer

On Error Resume Next

N = InputBox("Enter task id")

Set oTask = oMSP.activeproject.tasks(N)

If Err > 0 Then

MsgBox "Bad ID"

Exit Sub

End If

nTaskID = N

lblTaskID = nTaskID

If oTask Is Nothing Then

lblTaskName = ""

txtDuration = ""

Else

lblTaskName = oTask.Name

txtDuration = oTask.GetField(29)

End If

End Sub

Module 3 - Lesson 3 Exercises (continued)

2.

Sub m3l3e2()

Dim P As Object

Set P = CreateObject("MSProject.Project")

P.Tasks.Add Name:="a"

P.Tasks.Add Name:="b"

P.Tasks.Add Name:="c"

P.Tasks(2).Predecessors = 1

P.Tasks(3).Predecessors = 2

End Sub

3.

Sub M3L3E3()

Dim oMSP As Object, T As Object

Dim N As Integer, R As Integer

Set oMSP = CreateObject("MSProject.Application")

oMSP.Visible = True

AppActivate "Microsoft Project"

oMSP.FileNew

N = Sheets("Sheet1").Cells(1, 1).CurrentRegion.Rows.Count

For R = 1 To N

Set T = oMSP.ActiveProject.Tasks _

.Add(Name:=Sheets("sheet1").Cells(R, 1).Value)

T.Start = Sheets("sheet1").Cells(R, 2).Value

T.Duration = Sheets("sheet1").Cells(R, 3).Value

Next

End Sub

4. A command button named cmdClose and a listbox named List1 was created on Form1 in VB3. The code is shown below:

Sub Form_Load ()

Dim oMSP As object, oTasks As object

Dim n As Integer

Set oMSP = GetObject(, "msproject.application")

Set oTasks = oMSP.ActiveProject.Tasks

For n = 1 To oTasks.Count

If Not oTasks(n) Is Nothing Then

List1.AddItem oTasks(n).Id & " " & oTasks(n).Name

End If

Next

End Sub

Sub cmdClose_Click ()

End

End Sub

Module 3 - Lesson 3 Exercises (continued)

5. A command button named cmdClose and a listbox named List1 was created on Form1 in VB3. The code is shown below:

Sub Form_Load ()

Dim oMSP As object, oResources As object

Dim n As Integer

Set oMSP = GetObject(, "msproject.application")

Set oResources = oMSP.ActiveCell.Task.Resources

For n = 1 To oResources.Count

List1.AddItem oResources(n).Name

Next

End Sub

Sub cmdClose_Click ()

End

End Sub

6.

Sub M3L3E6()

Dim x As Object, T As Object, R As Integer

Set x = CreateObject("Excel.Application")

x.Workbooks.Add

R = 1

For Each T In ActiveProject.Tasks

If Not T Is Nothing Then

x.ActiveSheet.Cells(R, 1).Value = T.Name

x.ActiveSheet.Cells(R, 2).Value = T.GetField(29)

R = R + 1

End If

Next

x.ActiveWorkbook.Close SaveChanges:=True

x.Quit

End Sub

Module 3 - Lesson 3 Exercises (continued)

7.

Sub M3L3E7()

Dim x As Object, T As Object, s As Object

Dim R As Integer, MyErr As Integer

On Error Resume Next

AppActivate "microsoft excel"

MyErr = Err

On Error GoTo 0

If MyErr > 0 Then

AppExecute command:="Excel.exe"

AppActivate "Microsoft Excel"

End If

Set x = GetObject(, "Excel.Application")

x.WindowState = pjMaximized

x.Workbooks.Add

Set s = x.ActiveSheet

R = 1

For Each T In ActiveProject.Tasks

If Not T Is Nothing Then

s.Cells(R, 1).Value = T.Name

s.Cells(R, 2).Value = _

T.Duration / 60 / ActiveProject.HoursPerDay

R = R + 1

End If

Next

x.Charts.Add

x.ActiveChart.ChartWizard _

Source:=s.Cells(1, 1).CurrentRegion, _

PlotBy:=2, _

CategoryLabels:=1

End Sub

Module 3 - Lesson 4 Exercises Page 3-73

1. The MSProject macro:

Sub AllOneDay()

Dim T As Object

For Each T In ActiveProject.Tasks

If Not T Is Nothing Then

T.Duration = "1d"

End If

Next

End Sub

The Excel DDE macro:

Sub M3L4E1a()

Dim SystemChannel As Integer

SystemChannel = DDEInitiate("winproj", "system")

DDEExecute SystemChannel, "AllOneDay"

DDETerminate SystemChannel

End Sub

The Excel OLE macro:

Sub M3L4E1b()

Dim oMSP As Object

Set oMSP = CreateObject("MSProject.Application")

oMSP.Macro "AllOneDay"

End Sub

2. The MSProject macro:

Sub IncreaseCost(TaskID As Integer, CostChange As Currency)

Dim T As Object

Set T = ActiveProject.Tasks(TaskID)

T.FixedCost = T.FixedCost + CostChange

End Sub

The Excel macro:

Sub M3L4E2()

Dim SystemChannel As Integer

SystemChannel = DDEInitiate("winproj", "system")

DDEExecute SystemChannel, "IncreaseCost 1, 10.5"

DDETerminate SystemChannel

End Sub

Module 3 - Lesson 5 Exercises Page 3-83

1. "Microsoft Project 4.0 Project Object" and "Picture". Paste Link is not available.

2.

Sub M3L5E2()

Dim x As Object

Set x = GetObject(, "Excel.Application")

x.Range("A1:D3").Select

x.Selection.Copy

ViewApply Name:="Task Form"

EditGoTo ID:=3

ViewShowObjects

EditPaste

End Sub

3.

Sub M3L5E3()

Dim x As Object

ViewApply "Gantt Chart"

SelectAll

EditCopy

Set x = CreateObject("Word.Basic")

x.EditPaste

End Sub

Module 3 - Lesson 6 Exercises Page 3-92

1.

Sub M3L6E1()

Dim fnum As Integer

Dim otask As Object

Dim sFileName

sFileName = InputBox("Enter a path and filename")

fnum = FreeFile()

Open sFileName For Output As fnum

For Each otask In ActiveProject.Tasks

If Not otask Is Nothing Then

Write #fnum, otask.UniqueID, CStr(otask.Start)

End If

Next

Close fnum

End Sub

2.

Sub M3L6E2()

Dim fnum As Integer, otask As Object

Dim Uid As Long, Dur As String, MyErr As Integer

fnum = FreeFile()

Open "C:\M3L6E2.txt" For Input As fnum

Do Until EOF(fnum)

Input #fnum, Uid, Dur

On Error Resume Next

ActiveProject.Tasks.UniqueID(Uid).Duration = Dur

MyErr = Err

On Error GoTo 0

If MyErr > 0 Then

MsgBox "There is no task with unique id = " & Uid

End If

Loop

Close fnum

End Sub

Module 3 - Lesson 7 Exercises Page 3-100

1.

Sub M3L7E1()

Dim r As Object

For Each r In ActiveProject.Resources

If Not r Is Nothing Then

MailSend To:=r.EMailAddress, _

Subject:="Rates", _

Body:=" Standard Rate: " & r.StandardRate & Chr(10) _

& " Overtime Rate: " & r.OvertimeRate, _

IncludeDocument:=False

End If

Next

End Sub

2.

Sub M3L7E2()

Dim r As Object

For Each r In ActiveProject.Resources

If Not r Is Nothing Then

MailSend To:=r.EMailAddress, _

Subject:="Multiline Notes", _

Body:=r.GetField(pjResourceNotes), _

IncludeDocument:=False

End If

Next

End Sub

3.

Sub M3L7E3()

ViewApply "Gantt Chart"

SelectAll

MailSendProjectMail MessageType:="TaskRequest", _

Subject:="Assignments", _

Body:="Respond ASAP", _

Fields:="Resource Names", _

ShowDialog:=False

End Sub

Module 3 - Lesson 8 Exercises Page 3-115

1.

'********************************************************

'Put in the declarations section

Declare Function GetActiveWindow Lib "USER" () As Integer

Declare Sub SetWindowPos Lib "USER" _

(ByVal hWnd As Integer, _

ByVal hWndInsertAfter As Integer, _

ByVal x As Integer, ByVal Y As Integer, _

ByVal cx As Integer, ByVal cy As Integer, _

ByVal wFlags As Integer)

Global Const HWND_TOPMOST = -1

Global Const SWP_NOSIZE = &h1

Global Const SWP_NOMOVE = &h2

'********************************************************

Sub M3L8E1()

Shell "Calc.exe", 1

DoEvents 'Precaution- Give it a chance to open.

AppActivate "Calculator" 'Precaution- Make sure it's active

SetWindowPos GetActiveWindow(), _

HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE + SWP_NOSIZE

End Sub

Module 3 - Lesson 8 Exercises (continued)

2.

'********************************************************

'Put in the declarations section

Declare Function GetActiveWindow Lib "USER" () As Integer

Declare Function OpenClipboard Lib "USER" _

(ByVal hWnd As Integer) As Integer

Declare Function EmptyClipboard Lib "USER" () As Integer

Declare Function GetClipboardData Lib "USER" _

(ByVal wFormat As Integer) As Integer

Global Const CF_TEXT = 1

Declare Function CloseClipboard Lib "USER" () As Integer

Declare Function GlobalLock Lib "KERNEL" _

(ByVal hMem As Integer) As Long

Declare Function GlobalUnlock Lib "KERNEL" _

(ByVal hMem As Integer) As Integer

Declare Function lstrcpyn Lib "KERNEL" _

(ByVal lpString1 As Any, ByVal lpString2 As Any, _

ByVal nChars As Integer) As Long

'********************************************************

Sub M3L8E2()

Dim MemoryBlockId As Integer

Dim MemoryBlockAddress As Long

Dim s As String * 5 'Reserve room for "hello"

OpenClipboard GetActiveWindow()

EmptyClipboard

CloseClipboard

Do

DoEvents

OpenClipboard GetActiveWindow()

MemoryBlockId = GetClipboardData(CF_TEXT)

MemoryBlockAddress = GlobalLock(MemoryBlockId)

lstrcpyn s, MemoryBlockAddress, 6 'must specify one higher

GlobalUnlock MemoryBlockId

CloseClipboard

Loop Until s = "hello"

MsgBox "goodbye"

End Sub


About This Book

The Microsoft Word Developer's Kit includes introductory and advanced material about programming macros in WordBasic and complete reference information about the WordBasic language in Microsoft® Word version 6.0 and 7.0. Additional information about WordBasic extensions and the Word application programming interface (Word API) is included in the appendixes.

The Microsoft Word Developer's Kit disk provided in this book includes files
for use with WordBasic, the function libraries of extensions to WordBasic described in the appendixes, and the C programming tools required to program custom function libraries with the Word API. For information about installing files from the Microsoft Word Developer's Kit disk, see the following:

  • For information about installing templates of WordBasic examples, as well as text files with more WordBasic information, see Chapter 1, "Introduction," in Part 1, "Learning WordBasic."
  • For information about installing the workgroup extensions, see Appendix A, "Workgroup Extensions for Microsoft Word," in Part 3, "Appendixes."
  • For information about installing the ODBC extensions, see Appendix B, "ODBC Extensions for Microsoft Word," in Part 3, "Appendixes."
  • For information about installing the Word API programming tools and the
    files for a sample WLL, see Appendix C, "Microsoft Word Application Programming Interface," in Part 3, "Appendixes."

All WordBasic macro examples in Part 2, "WordBasic Reference," are available directly from the online Help available with the Microsoft Word package. For information about copying and using these examples, see Chapter 2, "Getting Started with Macros," in Part 1, "Learning WordBasic."

Note

Setup does not install WordBasic Help in the Typical installation. If you selected the Typical installation during Setup, you must rerun Setup to add WordBasic Help to your existing installation.


Organization

The book is divided into three parts:

  • Part 1, "Learning WordBasic," gets you started programming in WordBasic
    or learning the details of WordBasic if you already know another Basic programming language.
  • Part 2, "WordBasic Reference," documents all the statements and functions in the WordBasic language.
  • Part 3, "Appendixes," provides information about advanced topics such as workgroup and ODBC extensions, the Word API, and AppleScript™.

Part 1, "Learning WordBasic"

This part includes the following:

  • Chapter 1, "Introduction," presents a brief overview of WordBasic as well as suggestions on learning how to program.
  • Chapter 2, "Getting Started with Macros," presents step-by-step procedures
    to get you started recording macros.
  • Chapter 3, "WordBasic Fundamentals," gives an overview of the primary elements of WordBasic.
  • Chapter 4, "Advanced WordBasic," completes the discussion of the language.
  • Chapter 5, "Working with Custom Dialog Boxes," gives tips on designing dialog boxes with the Dialog Editor and shows you how to use dialog functions in your macros to create dynamic dialog boxes.
  • Chapter 6, "Debugging," explains techniques for testing and troubleshooting your macros.
  • Chapter 7, "The Well-Behaved Macro," shows you how to make your macros robust and stable.
  • Chapter 8, "Communicating with Other Applications," shows you how to integrate applications using dynamic data exchange (DDE) and OLE Automation.
  • Chapter 9, "More WordBasic Techniques," illustrates ways to develop powerful macros and custom wizards using WordBasic.

Part 2, "WordBasic Reference"

This part includes the following:

  • "Language Differences Across Versions of Word" identifies WordBasic statements and functions that operate differently or are not available in one or more versions of Word.
  • "Language Summary" presents the WordBasic language in lists of related statements and functions.
  • "Statements and Functions" is an alphabetic reference for WordBasic, with thorough examples.
  • "Operators and Predefined Bookmarks" describes all the available mathematical operators and built-in bookmarks.
  • "Error Messages" is a comprehensive list of the Word and WordBasic error messages and their associated numbers, which you can use to handle errors
    in your macros.

Part 3, "Appendixes"

This part includes the following:

  • Appendix A, "Workgroup Extensions for Microsoft Word," describes the MAPI functions provided in WBMAPI.DLL (a library of functions included on the Microsoft Word Developer's Kit disk), which you can use to integrate WordBasic macros with electronic mail programs such as Microsoft Mail on any Windows® platform.
  • Appendix B, "ODBC Extensions for Microsoft Word," presents the ODBC functions available in the WBODBC.WLL add-in library (provided on the Microsoft Word Developer's Kit disk) for adding enhanced database functionality to WordBasic macros on any Windows platform.
  • Appendix C, "Microsoft Word Application Programming Interface," is a guide to using the Word API, the tools provided on the Microsoft Word Developer's Kit disk, and a programming language such as Microsoft Visual C++™ to create your own Word add-in libraries of custom functions, which you can access directly from Word or a WordBasic macro.
  • Appendix D, "AppleScript," describes the unique AppleScript scripting commands available for controlling Word with scripts on the Apple® Macintosh®.
  • Appendix E, "Operating Limits," documents Word and WordBasic operating limits.


Typographic Conventions

In general, this book uses the following typographic conventions. For details on syntax and notation conventions for the WordBasic reference, see "Statements and Functions" in Part 2, "WordBasic Reference."

Example of convention | Explanation
If, Then, ChDir, FileName$(), .Path = | In syntax, characters in bold indicate keywords and symbols that must be typed in macro instructions.
 | In descriptive text, all WordBasic statement and function names appear in bold.
Message$, Save, text, number | In syntax, words in italic indicate placeholders for variable information you supply.
 | In descriptive text, words in italic either refer to placeholders in syntax or introduce new terms.
[Else], [Save], [, .Password = text], [Filename$] | In syntax, bold and italic items inside square brackets are optional.
If count = 13 Then MsgBox "Count reached 13." count = 1 End If | In WordBasic examples, text in this monospace font indicates literal macro instructions. Characters in this monospace font within descriptive text refer to the same characters in the example under discussion.
NORMAL.DOT, MACRO EXAMPLES | Words in all capital letters indicate filenames.
ENTER, ALT, CTRL+F9, COMMAND | Words in small capital letters indicate literal key names; a plus sign between two key names indicates that the keys must be pressed in combination.
rich-text format (RTF), dynamic data exchange (DDE) | Abbreviations are spelled out the first time they are used.

A Note About Versions

The Microsoft Word Developer's Kit documents WordBasic as it is supported by the following versions of Microsoft Word:

Microsoft Word version 7.0, which runs in Windows 95 and Windows NT™ version 3.51 or later.

Microsoft Word version 6.0 for Windows, which runs in the Microsoft Windows family of operating systems: Windows version 3.1 or later, Windows for Workgroups version 3.1 or later, Windows 95, and Windows NT version 3.1 or later.

Microsoft Word version 6.0 for the Macintosh, which runs in Apple Macintosh System 7 or later on any Apple Macintosh computer with at least a 68020 processor, or in System 7.5 or later on any Apple Power Macintosh™.

Microsoft Word version 6.0 for Windows NT, which runs in Windows NT version 3.5 or later and Windows 95.

This book uses the phrases "in Windows" and "on the Macintosh" to describe behavior that differs across those platforms. The phrase "in Windows" refers to Word version 7.0, Word version 6.0 for Windows, and Word version 6.0 for Windows NT.

In a few cases, the phrase "in Windows 95" is used to describe behavior specific to Word version 7.0. Also, the phrase "in Windows NT" is used to describe behavior specific to Word version 6.0 for Windows NT. Behavior described with the phrase "in Windows 95" or "in Windows NT" does not occur in Word version 6.0 for Windows, even when it is running in Windows 95 or Windows NT.


Chapter 1 Introduction

Welcome to "Learning WordBasic." This part of the Microsoft Word Developer's Kit introduces the tools Word provides for writing and testing macros, the elements of the WordBasic language itself, and techniques useful for various tasks. This chapter provides a brief overview of the WordBasic macro language, some tips on how to approach learning WordBasic, a description of the sample files provided on the Microsoft Word Developer's Kit disk with instructions for loading them, and references to resources for additional information.


Features of WordBasic

WordBasic is a structured programming language originally modeled on the Microsoft QuickBasic™ language. It combines a subset of the instructions available in standard Basic languages with statements and functions based on the Word user interface. You can use WordBasic to modify any Word command or to write your own. You can assign your macros to menus, toolbars, and shortcut keys so that they look and function like regular Word commands.

WordBasic includes the following features for developing macros.

Macro-editing environment

The macro-editing environment includes tools for testing and debugging macros. For example, buttons on the Macro toolbar can step and trace through macros, show current variable values in a paused macro, and "comment out" instructions (Chapter 2, "Getting Started with Macros," and Chapter 6, "Debugging").

Control structures

WordBasic supports most of the standard Basic control structures, including If ¼ Then ¼ Else, For ¼ Next, While ¼ Wend, and Select Case (Chapter 3, "WordBasic Fundamentals," and Chapter 4, "Advanced WordBasic").

Subroutines and user-defined functions

By writing subroutines and defining functions, you can create modular code that is easy to test. You can also store libraries of subroutines and functions that can be used in more than one macro (Chapter 4, "Advanced WordBasic").

Dialog Editor

You can use the Dialog Editor included with Word to design custom dialog boxes that support most of the standard dialog box controls in the Microsoft Windows family of operating systems and the Apple Macintosh System 7 operating system. The Dialog Editor automatically creates the WordBasic instructions that define your custom dialog box (Chapter 5, "Working with Custom Dialog Boxes").

DDE and OLE Automation

To communicate with other applications, Word supports dynamic data exchange (DDE) and provides partial support for OLE Automation (Chapter 8, "Communicating with Other Applications").

Extensibility

In Windows, you can extend WordBasic's capabilities by calling functions stored in dynamic-link libraries (DLLs) and Word add-in libraries (WLLs), as well as functions available through the Windows application programming interface (API). On the Macintosh, you can call functions stored in Word add-in libraries, and you can run AppleScript scripts from within WordBasic (Chapter 9, "More WordBasic Techniques").


Tips on How to Learn WordBasic

Here are some suggestions for getting the most from the time you spend learning WordBasic.

Learn Word first

The more you know about Word, the better prepared you will be to venture into WordBasic. Most macros perform a sequence of actions in Word, and most instructions in a macro are equivalent to commands or actions in Word. So working with WordBasic is a little like working with Word without a user interface; instead of commands and dialog boxes, you use WordBasic instructions. The statements and functions you use to write instructions are much easier to understand if you're familiar with the features of Word they represent.

Also, if you know Word well, you can better answer the question you're likely to ask when writing a macro: "What's the best way to do this?" People have been known to write long macros for tasks that could be handled by a single Word command.

Learn what you need

Learn what you need for the task at hand. WordBasic can seem overwhelming
at first, particularly if you haven't had experience with a macro programming language. A great way to learn the language is to investigate how to implement a particular macro idea you have. As you gain experience writing different types of macros, you'll cover a lot of ground.

Use the macro recorder

The macro recorder can record the WordBasic instruction for virtually every action you take in Word. You can use the macro recorder to see how actions in Word translate into WordBasic instructions, and vice versa. Also, you'll find recording part of a macro is often faster and easier than writing out the instructions.

Use Help

Help is a powerful tool for learning WordBasic. In a macro-editing window,
you can type a WordBasic instruction and press F1 (Windows), or HELP or COMMAND+/ (Macintosh), to immediately display the Help topic for that statement or function. The Help topic for most statements and functions includes an example you can copy and paste into your macro.

Read the first four chapters

After reading the first four chapters of "Learning WordBasic," you'll have a
solid base from which to launch your macro explorations. The other chapters in "Learning WordBasic" provide information about WordBasic capabilities or techniques you may need for a particular application.


Sample Files

The Microsoft Word Developer's Kit disk includes several files that are referred to in "Learning WordBasic."

File | Description
EXAMPLES.DOT (MACRO EXAMPLES on the Macintosh disk) | A template containing the sample macros described in "Learning WordBasic."
INVOICE2.DOT (INVOICE FORM on the Macintosh disk) | The invoice form template described in Chapter 9, "More WordBasic Techniques."

File | Description
NWIND.XLS (NORTHWIND DATABASE on the Macintosh disk) | A Microsoft Excel workbook used by the invoice form described in Chapter 9, "More WordBasic Techniques."
POSITION.TXT (not available on the Macintosh disk) | A text file that lists the order of arguments for WordBasic statements and functions. This file is useful if you are using a Visual Basic® version 3.0 application to send WordBasic instructions through OLE Automation. For more information about using OLE Automation with Word, see "Using OLE Automation" in Chapter 8, "Communicating with Other Applications."
STARTER.WIZ (STARTER WIZARD on the Macintosh disk) | A blank wizard that contains the routines shared by all Word wizards, as described in Chapter 9, "More WordBasic Techniques."
MKWIZARD.WIZ (WIZARD MAKER WIZARD on the Macintosh disk) | A wizard that makes a wizard according to your specifications.
WIN16API.TXT and WIN32API.TXT (not available on the Macintosh disk) | A text file containing prewritten Declare instructions for calling Windows application programming interface (API) functions from WordBasic; for more information about using Windows API functions, see "Calling Routines in DLLs" in Chapter 9, "More WordBasic Techniques."

Loading the Sample Files

The sample files referred to in "Learning WordBasic" are located in the WRDBASIC folder on the Windows disk and the WORDBASIC folder on the Macintosh disk. To use them, you need to copy the files to your hard disk.

Windows

  • Copy the templates (EXAMPLES.DOT and INVOICE2.DOT) and wizards (STARTER.WIZ and MKWIZARD.WIZ) into your template folder, which is the path specified for User Templates on the File Locations tab in the Options dialog box (Tools menu).
  • Copy the database file NWIND.XLS into your Microsoft Excel program folder. If you have not installed Microsoft Excel, you cannot use this file.
  • Copy POSITION.TXT, WIN16API.TXT, and WIN32API.TXT into your document folder.

Macintosh

  • Copy the templates (MACRO EXAMPLES and INVOICE FORM) and wizards (STARTER WIZARD and WIZARD MAKER WIZARD) into your template folder, which is the folder specified for User Templates on the File Locations tab in the Options dialog box (Tools menu).
  • Copy the database file NORTHWIND DATABASE into your Microsoft Excel program folder. If you have not installed Microsoft Excel, you cannot use this file.

Accessing the Macro Examples

To run the macros in the EXAMPLES.DOT template (Windows) or MACRO EXAMPLES template (Macintosh), you can use the Templates command (File menu) to load the template as a global template. When the template is loaded as a global template, you can use the Macro command (Tools menu) to run the macros. You can also use the Organizer dialog box (Macro command, Tools menu) to copy the macros to another template. To view or edit the macros, you can open the template directly or copy the macros to another open template, and then use the Macro command (Tools menu) to open a macro in a macro-editing window.


Other Resources

The resources described in this section provide additional information about Word macros and programming with WordBasic.

Microsoft Product Support Services

Microsoft offers a variety of support options to help you get the most from your Microsoft product. For more information about Microsoft Product Support Services, see "Technical Support" in Help.

If you have questions concerning programming techniques and solutions, refer to the following electronic services. These services are available 24 hours a day, 7 days a week, including holidays.

The Microsoft Network

In Word version 7.0, you can use The Microsoft Network™ to interact with other users or access the Microsoft Knowledge Base to get product information. From the Help menu, choose The Microsoft Network. Select where you want to go, and then choose Connect.

CompuServe, America Online, and GEnie

The Microsoft Knowledge Base (KB) and Microsoft Software Library (MSL) are available on the CompuServe®, America Online®, and GEnie™ information services. CompuServe also hosts Microsoft forums where you can interact with other users and Microsoft support personnel.

Service | Access
CompuServe | To access the Microsoft Knowledge Base, type go mskb at any ! prompt. To access the Microsoft Software Library, type go msl at any ! prompt. To access Microsoft forums, type go microsoft at any ! prompt.
America Online | To access the Microsoft Knowledge Base, click Keyword on the Go To menu, type microsoft in the Enter Word(s) box, and then click Go. In the Microsoft Resource Center, click Knowledge Base.
GEnie | To access the Microsoft Knowledge Base, type m505 at the GEnie system prompt.

Internet

Access the Microsoft Software Library (MSL) and the Microsoft Knowledge Base (KB) at any of the following Internet sites:

  • Microsoft World Wide Web site, located at www.microsoft.com
  • Microsoft Gopher site, located at gopher.microsoft.com
  • Microsoft FTP site (which supports anonymous logon), located at ftp.microsoft.com

The KB at the World Wide Web and Gopher sites provides full-text searches and automatic links to files on the MSL so you can download files directly from KB articles.

Microsoft Download Service

(206) 936-6735 via modem. Access the Driver Library and the most current technical notes (1200, 2400, 9600, or 14,400 baud; no parity; 8 data bits; 1 stop bit).

Product Training and Consultation

Microsoft Solution Providers are independent organizations that provide consulting, integration, customization, development, technical support and training, and other services for Microsoft products. These companies are called Solution Providers because they apply technology and provide services to help solve real-world problems.

To find out more about Microsoft Solution Providers:

  • In the United States and Canada, call 1-800-SOL-PROV between
    6:30 A.M. and 5:30 P.M. Pacific time, Monday through Friday, excluding holidays.
  • Outside North America, contact your local Microsoft office.

Books

Learn Basic Now, Michael Halvorson and David Rygmyr (Microsoft Press®, 1989) and Learn Basic for the Apple Macintosh Now, Michael Halvorson and David Rygmyr (Microsoft Press, 1990). If you have little or no experience with a programming language, these books may be a helpful starting point. They use the Microsoft QuickBasic programming language, on which WordBasic was modeled. ISBN 155615240X and ISBN 1556153147

Hacker's Guide to Word for Windows (2nd ed.), Woody Leonhard, Vincent Chen, and Scott Krueger (Addison-Wesley Publishing Company, 1994). An insider's guide to Word and WordBasic. ISBN 0201407639


Chapter 2 Getting Started with Macros

This chapter introduces the tools you need to create macros: the macro recorder and the macro-editing window. The macro recorder provides an easy way to record simple, "playback" macros and to start building more complex ones. The macro-editing window is a window with special capabilities for writing, editing, and testing macros in the Word macro language, WordBasic. This chapter includes a series of practices in which you record and then edit a very simple macro that applies bold and italic formatting.

The chapter goes on to discuss the relationship between macros and templates and how to store macros. Finally, the last two sections discuss modifying Word commands and creating "auto" macros that run automatically in response to such actions as creating a new document.

In this chapter:

  • Recording a macro
  • Running a macro
  • Editing a macro
  • Macros and templates
  • Saving a macro
  • Macro housekeeping
  • Modifying a Word command
  • Auto macros


Recording a Macro

You can create a macro by recording it with the macro recorder, writing it in WordBasic, or both. For many macros, even complex ones, a good technique is to start by recording as much of the macro as possible and then finish by writing the parts of the macro that can't be recorded.

Starting the Recording

To begin recording a macro, choose the Macro command from the Tools menu and then choose the Record button in the Macro dialog box, or simply double-click "REC" on the status bar. Word displays the Record Macro dialog box, in which you can name, describe, and assign the macro you are about to record.

Word provides two ways to identify macros: the macro name and its description text. Although you may be tempted to accept the macro name that Word proposes, and get on with recording your macro, it's a good idea to get into the habit of giving meaningful names to macros right away. A macro with a descriptive name is easy to identify. Macro names cannot include spaces, commas, or periods. If you want to include two or more words together in a macro name, you can begin each word with a capital letter to make the name easy to read. For example, "TransposeCharacters" or "OpenSalesReport" are readable macro names. If you assign a macro to a toolbar button, the macro name is displayed in a ToolTip when the mouse pointer is positioned over the toolbar button. When a macro name is displayed in a ToolTip, a space is placed before capital letters; for example, the ToolTip for a macro named "OpenSalesReport" would be "Open Sales Report."

It's also worth taking the time to write a short description in the Description box. As you accumulate macros over time, you may find it difficult to remember what each one does. A macro description provides a helpful reminder. If you assign a macro to a menu or to a toolbar button, its description appears in the status bar when you select the menu item or position the mouse pointer over the toolbar button. A macro description can be up to 255 characters long, although only about 100 characters appear on most status bars (the length of the status bar depends on screen resolution).

By default, macros you record are stored in the Normal template. If a different template is attached to the active document, you can also store a macro in that template. For more information on storing macros in different templates, see "Macros and Templates" later in this chapter.

Û To start recording the BoldItalic macro

The BoldItalic macro, a macro that applies bold and italic formatting to a selection, is the practice macro you will create in this chapter. Of course, you can easily apply bold and italic separately by pressing Ctrl+B and Ctrl+I (Windows) or command+B and command+I (Macintosh). But if you often format text as bold italic, it's convenient to have a quick way to apply both formats at once.

1. Do one of the following:

  • From the Tools menu, choose Macro, and then choose the Record button.
  • Double-click "REC" on the status bar.

2. In the Record Macro Name box, type BoldItalic.

3. In the Description box, type Applies bold and italic formatting to selected text.

The next step is to assign the BoldItalic macro to a shortcut key. This procedure is described in the next section.

Assigning the Macro

Even before you begin to record your macro, you can assign it to a menu, toolbar, or shortcut key. You could wait until after you've recorded it, but if you assign the macro right away, you can try it out after you've finished recording. Also, fewer steps are needed to assign it at this point. If the macro you're recording doesn't work out, you can easily delete it; any assignments you've made for it are removed also.

There are advantages and disadvantages to each kind of assignment. A menu item provides the highest visibility, but menus have limited space. A toolbar button is slightly more accessible than a menu item, but its purpose is less obvious. A shortcut key is hidden, but provides the quickest access.

Û To assign the BoldItalic macro to a shortcut key

Because the BoldItalic macro is a short macro that must run quickly to be worth running at all, it makes sense to assign it to a shortcut key for quick access.

1. In the Record Macro dialog box, choose the Keyboard button.

Word displays the Customize dialog box with the BoldItalic macro name selected.

2. Position the insertion point in the Press New Shortcut Key box, and do one of the following:

  • In Windows, press Ctrl+Shift+B.
  • On the Macintosh, press command+Shift+B.

3. Choose the Assign button.

By default, this duplicate shortcut key was assigned to the Bold command. When you choose the Assign button, the shortcut key is assigned to the BoldItalic macro. Later, if you remove this assignment, the shortcut key will be reassigned to the Bold command.

4. Choose the Close button.

Now you're ready to take the actions you want the macro recorder to record. This procedure is described in the next section.

Recording the Macro Actions

When you've named your macro and assigned it, you're ready to begin recording. After you close the Record Macro dialog box, the macro recorder records every action you take in Word until you turn the recorder off.

When the macro recorder is on, the Macro Record toolbar is displayed. It contains the Stop and Pause buttons, which you can use to stop and pause the macro recorder. If you click the Pause button to pause the recorder — perhaps to arrange something for your macro that you didn't set up in advance — the button remains in the down position. You can click it again to resume recording.

When the macro recorder is on, a recorder graphic attaches to the mouse pointer when it is positioned over a document window. In addition, the abbreviation "REC" (for "record") is highlighted in the status bar. You can double-click it to stop recording. (When the macro recorder is not on, you can double-click "REC" to start recording.)

When you stop recording, the Macro Record toolbar disappears automatically.

Here are a few things to be aware of when you're recording macros:

  • You can use the mouse to choose commands or click the scroll bar, but you can't use the mouse to move the insertion point or select text in your document. The macro recorder does not record mouse movements in a document window.
  • If you choose the Cancel button to dismiss a dialog box, Word does not record the command.
  • If you use the BACKSPACE key (Windows) or the DELETE key (Macintosh) when you're typing, Word does not record the characters you delete or the backspacing action. In other words, it's as if you had never typed those characters.
  • Word cannot record the following: printer setup options specific to a particular printer, document statistics, and any actions taken from the Find File dialog box (File menu) after the first search.

Û To record the actions of the BoldItalic macro

1. From the Format menu, choose Font. In the Font dialog box, select Bold Italic in the Font Style list, and then choose OK.

2. Click the Stop button on the Macro Record toolbar.


Running a Macro

You can run macros using the Macro dialog box (Tools menu), or you can run them using menu, toolbar, and shortcut key assignments. To use the Macro dialog box to run a macro, select the one you want to run, and then choose the Run button.

The list of macros displayed depends on the setting in the Macros Available In box. By default, the list shows all available macros, which includes the macros stored in the Normal template and any other open templates. If you choose, you can list just the macros stored in a particular template. You can also list all the built-in Word commands. If you have removed a macro or Word command from its menu, toolbar, or shortcut key assignment, you can still run it using the Macro dialog box.

Because you've already assigned the BoldItalic macro to a key combination, there's no need to use the Macro dialog box; you can run the macro directly from your document.

Û To run the BoldItalic macro

1. Select some text in a document.

2. Press Ctrl+Shift+B (Windows) or command+Shift+B (Macintosh).

The bold and italic formats are applied.

Now try an experiment. With the text still selected, choose Undo from the Edit menu. Apply a different font to the selection, and then press the shortcut keys assigned to the BoldItalic macro (Ctrl+Shift+B in Windows; command+Shift+B on the Macintosh).

Notice that the font changes back to whichever font the text had when you recorded the macro. This happens because the macro recorder records all the settings in a dialog box when it records a command. In this case, it recorded the current font when you recorded the macro, so now when you run the macro, it applies that font to the selected text.

What you want the macro to do is just apply bold and italic formatting and ignore any other character formatting. To achieve this result, you need to edit the macro. This process is described in the next section, "Editing a Macro."

Other Ways to Run Macros

You can run macros in several other ways, most of them in response to specific events that can trigger macros.

The command line. In Windows, you can add the name of a macro to the Word command line so that the macro will run when Word starts. You can modify the Word command line by selecting the Word icon in Program Manager (Windows 3.x and Windows NT) or the Word shortcut icon in the Programs subfolder in the Start Menu folder (Windows 95) and choosing the Properties command from the File menu. Here is the syntax for starting a macro using the command line:

winword /m MacroName

MacroName is the name of the macro that runs when Word starts. Each icon in Program Manager or shortcut icon on the Start Menu can have a different command line, so you can create different Word icons that launch different macros when Word starts.

The Macintosh does not provide a command line, but you can use the Word Settings (6) file to designate a macro to run when Word starts. You can access this file through the ToolsAdvancedSettings command. (To run the command, select ToolsAdvancedSettings from the list of Word commands in the Macro dialog box (Tools menu), and then choose the Run button.) In the Advanced Settings dialog box, select Microsoft Word from the Categories list, and then type WordSwitches in the Option box; in the Setting box, type /m MacroName where MacroName is the name of the macro to run when Word starts. Then choose the Set button.

Auto macros. Auto macros are macros that run automatically when you create a new document, open an existing document, and so on. For more information, see "Auto Macros" later in this chapter.

MACROBUTTON fields. These fields launch macros when they are double-clicked, and can be inserted anywhere in a document.

Form fields. A form field can trigger a macro when the field is selected ("on entry") and after it has been modified ("on exit"). For information on running macros from form fields, see "Automating Forms" in Chapter 9, "More WordBasic Techniques."


Editing a Macro

You can edit an existing macro or write a new macro from scratch using a macro-editing window. Macro-editing windows have several special properties:

  • The Macro toolbar is displayed whenever you open a macro-editing window. This toolbar provides quick access to several commands for running and testing macros.
  • When you run a macro in the macro-editing window, Word highlights any line containing certain kinds of errors.
  • You can position the insertion point on a line containing a WordBasic instruction and get Help for that instruction by pressing F1 (Windows), or HELP or COMMAND+/ (Macintosh).
  • Formatting is controlled by the Macro Text style. You can use this style to set character and paragraph formatting for text in all macro-editing windows.

To begin writing a new macro, choose Macro from the Tools menu, type a name for the macro in the Macro Name box, and then choose the Create button.

When the macro-editing window appears, the instructions Sub MAIN and End Sub (between which all the other instructions must appear) are already on the screen with the insertion point positioned between them.

To open and edit an existing macro, select the one you want to edit from the list of macros in the Macro dialog box, and then choose the Edit button (the Create button becomes the Edit button when an existing macro is selected).

Û To open the BoldItalic macro for editing

· From the Tools menu, choose the Macro command. Then select the BoldItalic macro and choose the Edit button.

Examining the Macro

The Word macro recorder does not record keystrokes, as some macro recorders do; it records actions, which are translated into the Word macro language, WordBasic. So when you open a recorded macro in the macro-editing window, the window displays a series of WordBasic instructions.

Consider the text of the BoldItalic macro, beginning with Sub MAIN and ending with End Sub. These two statements begin and end every WordBasic macro. "Sub" stands for subroutine, which is a subsection of a larger program. The larger program in this case is Word itself. From the perspective of WordBasic, a macro is a small task within a larger task — the task of running Word. "MAIN" indicates that this is the main subroutine of the macro. In the case of the BoldItalic macro, it's also the only subroutine in the macro.

Now consider the lines sandwiched between Sub MAIN and End Sub:

FormatFont .Points = "12", .Underline = 0, .Color = 0, .Strikethrough = 0, .Superscript = 0, .Subscript = 0, .Hidden = 0, .SmallCaps = 0, .AllCaps = 0, .Spacing = "0 pt", .Position = "0 pt", .Kerning = 0, .KerningMin = "", .Tab = "0", .Font = "Times New Roman", .Bold = 1, .Italic = 1

These lines form a single statement, the FormatFont statement. A statement is a WordBasic instruction that tells the macro to do something. The FormatFont statement corresponds to the Font dialog box (Format menu). Each word in the statement that begins with a period corresponds to an option in the dialog box. These words, such as .Points, .Strikethrough, and .Hidden, are called arguments — they qualify the statement. (Note that if you recorded your macro on the Macintosh, the FormatFont statement includes two additional arguments—.Outline and .Shadow—that are valid only on the Macintosh.)

Every argument in a statement has a value, which corresponds to the setting of the option in the dialog box. For example, the Font dialog box contains several check boxes which can be either selected or cleared. Likewise, the WordBasic arguments that correspond to those check boxes can have one of two values. If the Strikethrough check box is selected, for example, the WordBasic argument would read .Strikethrough = 1. If the check box were not selected, the argument would read .Strikethrough = 0.

Editing the BoldItalic Macro

The BoldItalic macro you recorded earlier in this chapter didn't work properly as it was recorded. The only thing you wanted the macro to do was apply bold and italic formatting. Unfortunately, it also applied other character formats such as font and font size. With the macro open in a macro-editing window, you can correct that problem by removing the irrelevant arguments from the FormatFont statement.

Û To edit the FormatFont statement

· With the macro open in a macro-editing window, select and delete every argument except .Bold and .Italic.

The edited BoldItalic macro should look like this:

Sub MAIN
FormatFont .Bold = 1, .Italic = 1
End Sub

Getting Help on WordBasic

In a macro-editing window, you can immediately get reference information about any WordBasic instruction by positioning the insertion point on the same line as the instruction and pressing F1 (Windows), or HELP or COMMAND+/ (Macintosh).

Û To get Help for the FormatFont statement

· Position the insertion point anywhere in the FormatFont statement, and then press F1 (Windows), or HELP or COMMAND+/ (Macintosh).

For many WordBasic instructions, Help provides examples you can copy. You can click Example in the Help topic to display the examples. You can choose the Copy button (Word version 6.0) or choose Copy from the shortcut menu (Word version 7.0) in the example window to copy the text of the code example onto the Clipboard. You can then paste the example into your own macro or document.

You can also use the Help menu in Word to access Help topics about WordBasic. Help provides a language summary that groups WordBasic statements and functions by category, as well as information on predefined bookmarks and error messages. All the reference information contained in Part 2, "WordBasic Reference," is available in Help.

The Macro Toolbar

Whenever you open a macro-editing window, the Macro toolbar is displayed, if it isn't displayed already.

Many of the buttons on the toolbar are used for testing, but several of the buttons can be used for running and recording macros:

Active Macro

This box lists the macros open in macro-editing windows. If more than one macro is open, you can use the Active Macro box to select which macro runs when you click the Start button.

Record

Displays the Record Macro dialog box, so that you can begin recording a macro.

Record Next Command

Records a single command or action in Word and inserts the resulting WordBasic instruction in the active macro-editing window (or the most recently active one, if a document window is active). For more information, see "The Record Next Command Button" later in this section.

Start

Runs the macro selected in the Active Macro box. By default, this is the macro in the active macro-editing window (or the most recently active one, if a document window is active).

Macro

Displays the Macro dialog box. Clicking this button is a shortcut for choosing the Macro command from the Tools menu.

For information on the Trace, Continue, Stop, Step, Step Subs, Show Variables, and Add/Remove REM buttons, see Chapter 6, "Debugging." For information on the Dialog Editor button, see Chapter 5, "Working with Custom Dialog Boxes."

Running the Macro from the Macro-Editing Window

You can use the Start button on the Macro toolbar to run the macro in the active macro-editing window. Some macros, however, will not run unless a document window is active. For example, if you run the BoldItalic macro when its macro-editing window is active, an error occurs, because the Font command (Format menu) is not available when a macro-editing window is active.

If you browse through the menus when a macro-editing window is active, you can see that many commands are unavailable — they are commands for tasks that aren't useful for editing macros.

If you have a document window open in addition to a macro-editing window, you can choose the Arrange All command from the Window menu to display both the document window and the macro-editing window. To run the BoldItalic macro now, you can just click in the document window to make it active, and then click the Start button on the Macro toolbar.

Error Checking in the Macro-Editing Window

Whenever you run a macro, Word automatically checks the syntax of each WordBasic command. In programming, syntax refers to the rules governing the spelling of arguments, the number of arguments, and so on. Word also checks to make sure the arguments have appropriate values. If a macro-editing window is open and Word discovers an instruction with a problem, it highlights the instruction and presents an error message.

To see how Word identifies syntax errors, you can alter the syntax of the BoldItalic macro. Try deleting the comma between the .Bold and .Italic arguments so that the FormatFont statement looks like the following:

FormatFont .Bold = 1 .Italic = 1

Now try running the macro.

Another common error is to type an argument without the period in front of it. It's easy to make these errors, but by highlighting the line containing the error, the macro-editing window helps you find them.

The Macro Text Style

The Macro Text style determines the formatting of text in macro-editing windows. You can't apply direct formatting to text in a macro-editing window, but you can modify the Macro Text style. The Macro Text style is a special style that is stored in the Normal template. It affects every macro-editing window, regardless of whether the macro displayed in a macro-editing window is stored in the Normal template or in another template.

You use the Style command (Format menu) to modify the Macro Text style. A document window must be active when you choose the Style command; you cannot choose the Style command when a macro window is active.

Note

When you modify the Macro Text style, Word updates the style definition displayed in the Style dialog box (Format menu) only for the document that is active and for the Normal template. This means that when other documents and documents based on other templates are active, the Macro Text style definition displayed in the Style dialog box may not be current.

To find out the current, correct style definition of Macro Text, create a document based on the Normal template. Choose Style from the Format menu, and then select the Macro Text style in the Styles list (if necessary, select All Styles in the List box to see the Macro Text style in the Styles list); the Description box will show the current style definition.

View Options for Macro-Editing Windows

You can use the View tab in the Options dialog box to set view options for macro-editing windows. View options you set for macro-editing windows do not affect view options for document windows. For example, you can hide the status bar in macro-editing windows but not in document windows.

The Record Next Command Button

Sometimes, you want to record one or two commands to insert into an existing macro you're working on, but you don't want to record a new macro. The Record Next Command button on the Macro toolbar provides this capability. When you have a macro-editing window open, you can use the Record Next Command button to record the next Word command you choose or action you take (such as scrolling through a document). Word inserts the equivalent WordBasic instruction at the insertion point in the macro-editing window.

If a macro window is active and you want to record a command that isn't available in macro-editing windows, switch to a document window before clicking the Record Next Command button. If you click the Record Next Command button and then switch to a document window, Word will record your switching windows rather than the command you want to record.

Stopping or Pausing a Macro

When a macro is running, you can stop or pause it by pressing the ESC key. Word displays a message stating that the macro was interrupted. If the macro is open in a macro-editing window, you can click the Continue button on the Macro toolbar to continue running the macro, or you can press the ESC key again or click the Stop button on the Macro toolbar to stop the macro. If the macro is not open in a macro-editing window when you press the ESC key, Word simply stops the macro.


Macros and Templates

Word stores macros in templates, just as it does styles and AutoText entries. When you create a new macro, it is stored by default in the Normal template and is available "globally" — that is, you can always run or edit the macro, even if the active document is based on a different template. When you store a macro in a template other than the Normal template, you can run or edit it only when the template itself or a document based on the template is the active document.

Whether or not a macro stored in a template other than Normal is available depends on which document is active. For example, if you choose the Macro command when a document attached to a template other than Normal is active, any macros stored in that template, as well macros stored in the Normal template, are available in the list of macros. But if you switch to a document attached to the Normal template and choose the Macro command again, the macros stored in the other template are not listed.

The same holds true for new macros that you create. To store a new macro in a given template, either the template itself or a document attached to the template must be active when you create the macro:

  • If you are creating a new macro using the Macro dialog box, you select the appropriate template name in the Macros Available In box and then choose the Create button to open a new macro-editing window.
  • If you are recording a new macro, you select the appropriate template name in the Make Macro Available To box in the Macro Record dialog box.

Neither the Normal template nor a document based on the Normal template needs to be active to store new macros globally. You can store new macros in the Normal template even if no documents attached to the Normal template are open.

Note that you choose which template to store a macro in when you create it, rather than when you first save it. Once you've stored a macro in a particular template, you can use the Organizer dialog box to move or copy it to another template. For more information, see "Macro Housekeeping" later in this chapter.

When you open a macro, notice that the title of the macro-editing window includes either the name of the template in which the macro is stored or "Global" if the macro is stored in the Normal template.

Why Store Macros in Different Templates?

Since macros stored in the Normal template are always available and macros stored in other templates are less widely available, you might wonder about the advantages of storing macros in other templates.

One advantage is that macros designed to work with a particular type of document can be stored in the template used to produce that document. Another reason to store macros in different templates is that the Normal template can get crowded. The more macro instructions you store in Normal, the longer it takes to save the template. You won't notice a difference if you have ten or twenty macros stored in Normal, but as you add macros, Normal will gradually take longer to save.

Together, macros and templates can be used to create a Word "application" — a highly customized version of Word designed to accomplish a particular task or set of tasks. For example, a group of macros and templates could be designed to automate the creation of forms and other documents a company uses. Because the macros used in the application are stored within one or more custom templates, the application is relatively simple to distribute; it's just a matter of copying the templates. If the application's macros were stored in the Normal template, it would be much more complicated to install the application on another machine, which already has its own Normal template.

Making Templates Global

Sometimes it's useful to make a macro or set of macros available temporarily. For example, you may create a set of macros for a task you perform only occasionally. Rather than storing them in the Normal template, you can store them in another template and load that template as a global template when you want to run them.

You use the Templates command (File menu) to load templates as global templates. You can also store a template in the Startup folder (specified on the File Locations tab in the Options dialog box (Tools menu)) to load it automatically as a global template each time you start Word. When a template is loaded globally, its macros become available in the same way macros stored in the Normal template are available. A document based on a loaded global template doesn't need to be active for you to run the macros stored there.

One important difference between loaded global templates and the Normal template, however, is that you cannot edit macros or add new ones to a global template. In effect, a global template is available on a read-only basis.

Priority Among Templates

In the case of a naming conflict (that is, when you select a macro to run when more than one macro with the same name is stored in the available templates), macros stored in the template attached to the active document have priority over other macros. Next in priority are macros stored in the Normal template. Lowest in priority are the macros stored in other global templates (assuming global templates are loaded); priority among other global templates is determined by the alphabetical order of the template names.

Naming conflicts occur most often with "auto" macros, specially named macros that run automatically (for example, when a document is created or opened). For more information on auto macros, see "Auto Macros" later in this chapter.

Naming conflicts may also arise if you modify Word commands. For more information, see "Modifying a Word Command" later in this chapter.


Saving a Macro

When a macro-editing window is active, the Save and Save As commands on the File menu change to the Save Template and Save Copy As commands.

Using the Save Template Command

You can think of the Save Template command as the "save macros" command — that's what the command is designed to do and why it's available only when a macro-editing window is active. The command is called Save Template because it saves the templates the macros are stored in along with all the other items stored in there, such as autotext entries and styles. Use the Save Template command to save macros as you edit them, just as you use the Save command to save documents as you're writing or revising them, rather than waiting until your work is completed.

Using the Save Copy As Command

The Save Copy As command is designed to make it easy to save a macro as a text file, which is useful if you want to store macros apart from the template. When you choose the Save Copy As command, Word displays the Save As dialog box. In Windows, Word proposes the macro name with a .TXT extension as the filename. On the Macintosh, Word proposes the macro name alone as the filename. In either case, you can change the name Word proposes and even select a different file format if you want to.


Macro Housekeeping

Macro housekeeping includes renaming, copying, moving, and deleting macros. You can use the Organizer dialog box for all these tasks. To display the Organizer dialog box, choose Macro from the Tools menu, and then choose the Organizer button. If the templates you want to work with are not open, you can use the Open File buttons to open them.

You can select more than one macro to copy or delete in the Organizer dialog box. To select a series of macros, hold down SHIFT and click the first and last items in the series. To select individual macros, hold down CTRL (Windows) or COMMAND (Macintosh) and click each item.


Modifying a Word Command

You can modify most Word commands by turning them into macros. For example, you can modify the Open command on the File menu so that instead of displaying a list of Word document files (in Windows, files ending with the .DOC filename extension), Word displays every file in the current folder.

To display the list of built-in Word commands in the Macro dialog box, you select Word Commands in the Macros Available In box. Every menu command and every command available on a toolbar or through shortcut keys is listed. Menu commands begin with the menu name associated with the command. For example, the Save command on the File menu is listed as FileSave. This is the same convention used by WordBasic statements. The WordBasic statement equivalent to the Save command, for example, is FileSave.

You can run any one of these commands by selecting it and choosing the Run button in the Macro dialog box. For example, if you select the FileSave command and choose the Run button, Word saves the current document, just as if you had chosen Save from the File menu.

Note, however, that the Create button is disabled when Word Commands is selected in the Macros Available In box. You cannot edit the commands themselves, but by giving a macro the same name as a Word command, you can replace the Word command with a macro. Then, whenever you choose the Word command using a menu, toolbar, or shortcut keys, Word runs the replacement macro instead. For example, if you create a macro called FileSave, Word runs this macro when you choose the Save command from the File menu, click the Save button on the Standard toolbar, or press Ctrl+S (Windows) or COMMAND+S (Macintosh).

To replace a Word command, you can either type its name in the Macro Name box or select it from the list of Word commands. You then select the template in which you would like to store the macro that replaces the command — either the Normal template or the one attached to the active document — and choose the Create button. Word displays a macro-editing window for the new macro.

An Example

This example takes you through the steps needed to modify the Close command on the File menu. In this example, you'll store the macro that replaces the FileClose command in the Normal template, so that the command will be modified globally — that is, for every document.

Û To modify the FileClose command

1. From the Tools menu, choose Macro.

2. In the Macros Available In box, select Word Commands.

3. In the Macro Name box, select FileClose.

4. In the Macros Available In box, select either Normal.dot (Global Template) in Windows or Normal (Global Template) on the Macintosh.

5. Choose the Create button.

The FileClose macro now appears in a macro-editing window.

As the previous illustration shows, Word automatically inserts the instruction FileClose in the new macro. Any macro with the same name as a Word command initially contains one or more lines that run the Word command the macro replaces. (The macro also inherits the Word command's description, which appears in the Description box in the Macro dialog box.)

You can edit the new macro in many ways. For example, you could add a FileSave instruction:

Sub MAIN
    FileSave
    FileClose
End Sub

To test the new command, open an existing document, change it in some way, and then close it (using the Close command on the File menu). The original Word command would prompt you to save your document if it contained any unsaved changes. The new macro avoids that prompt by saving changes automatically.

Note that you could remove the FileClose instruction from the macro if you wanted to:

Sub MAIN
    MsgBox "Sorry, the Close command is disabled."
End Sub

Now, when you choose the Close command, Word does not close the document window, but displays the following message box.

In fact, you could remove every instruction from the macro, so that only Sub MAIN and End Sub remain:

Sub MAIN
End Sub

Now, when you choose the Close command, nothing happens at all. In this way, you can not only modify Word commands but disable them. Disabling commands can be useful if you are creating an environment for a particular kind of document and don't want the user to be able to run certain commands. (Note that you can also disable a Word command by removing it from its menu, toolbar, and shortcut key assignments.)

If you want to run a modified command in another macro, you use a ToolsMacro instruction to run the macro that replaces the original command. For example, to run the FileClose macro, you would use the following instruction:

ToolsMacro .Name = "FileClose", .Run

Note that you could not include this instruction inside the FileClose macro, because Word does not allow a macro to run itself.

Modifying Commands that Display Dialog Boxes

To modify commands that display dialog boxes (the Open command on the File menu, for example), it's helpful to understand how to work with dialog records. For information on dialog records and modifying commands that display dialog boxes, see "Working with Dialog Records" in Chapter 4, "Advanced WordBasic."

Restoring a Modified Command

Since modifying a Word command involves creating a macro with the same name as the command you want to modify, globally restoring an original Word command is simply a matter of deleting or renaming the macro that replaced it in the active or Normal template.

In other cases, you might want to modify a command globally, but restore the original command for a particular template. For example, you could modify the Open command on the File menu (FileOpen) so that it lists every file in a folder instead of just the Word document files. But perhaps a particular template only uses Word document files. It would make sense to restore the original Open command for that template.

To restore an original Word command only for a particular template, you create a second replacement macro that overrides the replacement macro stored in the Normal template. This second replacement macro just runs the original Word command. To create this replacement macro, you follow the same steps used to create the first replacement macro: specify the command you want to restore from the list of Word commands, select the template name in the Macros Available In box, and then choose the Create button to create the new macro.

The trick to this procedure is that even though you don't want to modify the command, you must still make some change to the second replacement macro. Otherwise, Word will not save it when you close it. You can simply add a space to the command and delete the space. This action "dirties" the macro so that Word will save it when you choose the Save Template command or close the macro-editing window. The requirement that you change the macro in some way is a safeguard to prevent you from opening a macro and replacing a Word command without intending to.


Auto Macros

Word recognizes the following five macro names that run automatically.

Macro name | When it runs
AutoExec | When you start Word
AutoNew | Each time you create a new document
AutoOpen | Each time you open an existing document
AutoClose | Each time you close a document
AutoExit | When you quit Word

You create an auto macro just as you do a regular macro. The only difference is that you must give the macro one of the special auto macro names that Word recognizes. Just like other macros, auto macros can be defined either globally or for a particular template. The only exception is the AutoExec macro, which must be stored either in the Normal template or in a template in the Startup folder (the Startup folder is specified on the File Locations tab in the Options dialog box (Tools menu)).

In the case of a naming conflict, Word always runs the auto macro stored in the template attached to the active document. For example, if you define an AutoNew macro as a global macro stored in the Normal template, Word runs that macro whenever you create a new document, unless the new document is attached to a template that contains an AutoNew macro; in that case, Word runs the AutoNew macro stored in the attached template.

Auto Macro Examples

The following examples are intended to demonstrate some of the ways auto macros can be used. Don't worry if you don't understand the WordBasic instructions at this point. Chapters 3 and 4 describe the WordBasic language elements used in these examples.

AutoExec

By default, Word creates a new document based on the Normal template whenever you start Word. The following AutoExec macro replaces the new document based on the Normal template with one based on the LETTER template.

Sub MAIN
    FileNew .Template = "LETTER"
End Sub

AutoOpen

When you open a document, the following AutoOpen macro displays a prompt to ask if you would like to turn on revision marks; if you choose the Yes button, the macro turns on revision marks. You could modify this macro to test for different conditions. For example, you might want to turn on revision marks only if you aren't the author of the document you are opening. The macro could test for this condition and display or not display the prompt accordingly. For information on testing for conditions, see Chapter 3, "WordBasic Fundamentals."

Sub MAIN
    answer = MsgBox("Do you want to turn on revision marks?", 36)
    If answer = - 1 Then
        ToolsRevisions .MarkRevisions = 1
    End If
End Sub

AutoNew

The following AutoNew macro displays the Save As dialog box when you create a new document based on the template in which the AutoNew macro is stored. The comments (preceded by apostrophes) describe the purpose of each instruction; they have no effect when the macro runs.

Sub MAIN
    Dim FSArec as FileSaveAs            'Create the dialog record "FSArec"
    GetCurValues FSArec                'Place current values into FSArec
    choice = Dialog(FSArec)            'Display FileSaveAs dialog box
    If choice = -1 Then FileSaveAs FSArec    'If user chose OK, run FSA
End Sub

AutoClose

When a document is closed, the following AutoClose macro makes a backup copy by copying the document to a file server. On the Macintosh, the path "E:\DOCS\BACKUP" would change to a Macintosh path, such as "BACKUP SERVER:DOCUMENTS:BACKUP."

Sub MAIN
    file$ = FileName$()                        'Store filename in "file$"
    FileClose 1                                'Close and save the file
    CopyFile .FileName = file$, .Directory = "E:\DOCS\BACKUP"    'Backup
End Sub

AutoExit

You probably have certain view options you prefer; for example, you may generally like to work with the Standard and Formatting toolbars displayed. The following AutoExit macro resets those settings, so that when you start Word again you have the environment you want, regardless of what was displayed or hidden when you last quit Word. This particular example displays the Standard and Formatting toolbars, but of course you could edit the macro to specify any settings you wanted.

Sub MAIN
    ViewToolbars .Toolbar = "Standard", .Show
    ViewToolbars .Toolbar = "Formatting", .Show
End Sub


Chapter 3 WordBasic Fundamentals

This chapter introduces the fundamental elements of WordBasic that you need to write macros or add to macros you record. The building blocks WordBasic provides are simple, but you can use them to produce macros that perform almost any word-processing task.

In this chapter:

  • A simple macro
  • Statements and functions
  • Strings and numbers
  • Variables
  • Expressions
  • Conditionals and loops
  • Displaying messages and requesting information
  • Common WordBasic techniques
  • Some sample macros


A Simple Macro

A good way to get started with WordBasic is to look at a simple macro. This one transposes characters (for example, to change "teh" to "the"). The following table illustrates the actions that the macro takes and the corresponding WordBasic instructions.

What happens on the screen | WordBasic instruction | Explanation
 |  | Before the macro begins, the insertion point is positioned after the letters to be switched.
 | CharLeft 1, 1 | First, the macro moves the insertion point to the left by one character and selects that character.
 | EditCut | Then it cuts the selected letter.
 | CharLeft 1 | Then it moves the insertion point to the left by one character.
 | EditPaste | Next, it pastes the character that was cut.
 | CharRight 1 | Finally, it moves the insertion point to the right by one character — back to where it was before the macro began.

You can easily record this macro by starting the macro recorder and performing the actions described in the table. (Remember, while recording a macro, you need to use the keyboard to move the insertion point and select text.) If you do so and then choose the Macro command (Tools menu) to open the macro in a macro-editing window, you'll see the following instructions:

Sub MAIN
CharLeft 1, 1
EditCut
CharLeft 1
EditPaste
CharRight 1
End Sub

As explained in the previous chapter, Sub MAIN and End Sub begin and end every macro. Notice that each instruction within the macro is on a separate line. You can place more than one instruction on the same line, but only if you separate each instruction with a colon (:). Generally, macros are easier to read if each instruction is on a separate line.

Also, notice the pattern of capitalization. When Word saves a macro, it gives the proper capitalization to every word that it recognizes as part of the WordBasic "vocabulary." You do not have to worry about typing instructions with the correct capitalization because WordBasic is not case-sensitive — it recognizes instructions typed in any combination of uppercase and lowercase letters.

Two of the instructions, CharLeft and CharRight, move the insertion point and optionally select text. The other two instructions, EditCut and EditPaste, correspond to the Cut and Paste commands on the Edit menu. In Word, virtually every action you can take has an equivalent WordBasic instruction.

Comments

Comments explain a macro to others and remind you of the purpose of the macro or of particular instructions. Word ignores comments when it runs the macro.

You can use the REM statement to insert a comment in a macro. For example:

REM This is a comment

Or you can use an apostrophe:

'This is also a comment

Both ways of commenting have advantages. The REM statement helps to make comments visible. But REM and the comment that follows it must be on their own line. You can use an apostrophe to place a comment on the same line as an instruction. Word interprets any text after the apostrophe until the end of the line as a comment. For example, you could add comments to these instructions from the macro that transposes characters described earlier in this chapter:

CharLeft 1, 1 'Select character to the left

EditCut 'Cut selected character

You can use the Add/Remove REM button on the Macro toolbar to easily add or remove REM statements. For more information about using the Add/Remove REM button, see Chapter 6, "Debugging."


Statements and Functions

WordBasic instructions are composed of statements and functions, which are defined as follows:

  • A statement carries out an action. For example, opening a file, selecting text, and scrolling through a document are all actions. Virtually every action you can perform in Word has an equivalent WordBasic statement.
  • A function retrieves information. A function sometimes also performs an action, but the primary purpose of a function is to return information to the macro. A function can determine the character formatting of selected text, whether a document is in outline view, whether a toolbar is displayed, and many other things.

When you begin working with WordBasic, it's very helpful to get a sense of the different statements and functions available to you. A good way to do this is to browse through "Language Summary" in Part 2, "WordBasic Reference," which classifies WordBasic statements and functions according to the tasks they accomplish.

Statements

Most WordBasic statements are equivalent to Word commands. For example, the following instruction, which uses the EditFind statement, is equivalent to choosing the Find command from the Edit menu and searching for "Yours truly":

EditFind .Find = "Yours truly", .Direction = 0, \
        .MatchCase = 0, .WholeWord = 0, .PatternMatch = 0,\
        .SoundsLike = 0, .FindAllWordForms = 0, .Format = 0, .Wrap = 1

Each option in the Find dialog box has a corresponding argument in the EditFind statement. For example, the Match Case check box is represented by the .MatchCase argument. Arguments that correspond to dialog box options begin with a period (.) and are separated by commas (,). Each argument has a value associated with it, which may be a number or text enclosed by quotation marks. For example, .MatchCase takes a numeric value, while .Find takes a text value.

The syntax for each statement in Part 2, "WordBasic Reference," indicates the values that arguments require. You can see the same entry in Help by positioning the insertion point in the EditFind statement in the macro-editing window and pressing F1 (Windows) or HELP or COMMAND+/ (Macintosh). In the entry for EditFind, the syntax line shows all the available arguments for the statement with the values they require:

EditFind [.Find = text] [, .Replace = text] [, .Direction = number] [, .WholeWord = number] [, .MatchCase = number] [, .PatternMatch = number] [, .SoundsLike = number] [, .FindAllWordForms = number] [, .Format = number] [, .Wrap = number]

The syntax also indicates which arguments are necessary and which are optional; brackets ([ ]) enclose optional arguments. For complete information on how to interpret syntax lines, see the introduction to "Statements and Functions" in Part 2, "WordBasic Reference."

Controlling Where Lines Break in Long Instructions

In a WordBasic macro, every instruction ends with a paragraph mark. Most instructions are less than a line long, but some WordBasic statements have many arguments and can't fit on a single line. When you record one of these instructions, Word wraps it onto a second or third line as needed. For example, if you record changing information on the User Info tab in the Options dialog box (Tools menu), Word inserts an instruction like the following one in the macro you're recording:

ToolsOptionsUserInfo .Name = "Lucie Caselli", .Initials = "LC", .Address = "Aperture Film"

You can make multiple-line instructions such as this one more readable by adding line breaks. To do so, place the insertion point at the location where you want to break the line, type the backslash ( \) character to indicate to Word that the instruction continues into the next paragraph, and then press ENTER. For example, here's how you could rearrange the preceding ToolsOptionsUserInfo instruction by inserting a line break and some tab characters:

ToolsOptionsUserInfo .Name = "Lucie Caselli", .Initials = "LC", \

.Address = "Aperture Film"

Functions

WordBasic functions do not correspond to Word commands as neatly as statements do, but they provide many types of information about documents and the current state of Word. For example, the Font$() function returns the name of the font where the insertion point is located. Often, the information that a function returns is placed in a variable, which is a kind of storage container. Variables are described in the "Variables" section later in this chapter.

A function is easily distinguished from a statement because it ends with parentheses. Here are some examples:

Font$()
Selection$()
CharColor()
CountStyles()
ViewOutline()
BookMarkName$()

Note that some functions include a dollar sign ($) character just before the ending parentheses. These functions return information in the form of text, or strings. The other functions return numbers. Strings and numbers are described in the following section.


Strings and Numbers

In addition to statements and functions, a macro contains data, or information. For example, if a macro includes a FileOpen statement to open a file, it also needs to know the name of the file to open. The filename is considered to be a piece of information. In WordBasic, information must be in the form of either a string or a number.

  • A string is a series of characters treated as a single piece of information. A string can include letters, numbers, spaces, and punctuation marks — any characters. A double quotation mark is used to indicate the beginning and end of a string. A string can be as long as 65,280 characters, unless there isn't enough memory available to hold it.
  • A number can include a decimal value and can accommodate as many as 14 digits (not including an exponent value if one is included).

Here are some examples of strings and numbers.

Strings | Numbers
"Please type your name" |  | 52.6
"Lucida Sans Type" |  | .12345678901234
"3,500" |  | 3500
"10" |  | 10

Note that you can include numbers in a string, but WordBasic does not interpret them as numeric values. For example, the string "42" simply represents the characters "4" and "2," not the value 42.

Numbers in WordBasic can include a period as a decimal separator, but not other separators. For example, the number 3,500 generates an error. Note that in WordBasic the decimal separator must be a period, regardless of the decimal separator specified with the International option in Control Panel (Windows) or the keyboard layout specified with the Keyboard control panel (Macintosh).

Note

Large numbers can be expressed as mmm E eee, in which mmm is the mantissa and eee is the exponent (a power of 10). The highest positive number allowed is 1.7976931348623E+308, which represents 1.7976931348623 x 10308. (Technically, WordBasic numbers are double-precision floating-point numbers and occupy 8 bytes of memory.)

Including Quotation Marks and Special Characters in Strings

You can include any character in a string, but double quotation marks and special characters must be handled in a special way. A double quotation mark (") is used to mark the beginning and end of a string, so if you want to include one within a string, you must indicate that it is not intended to end or begin the string. To do so, you use the Chr$() function, which returns a character corresponding to the character code you specify. The code for a double quotation mark is 34. For example, the following instruction assigns the string "The word "cool" appears twice." to the variable result$:

result$ = "The word " + Chr$(34) + "cool" + Chr$(34) + \

" appears twice."

Word provides a shortcut for typing instructions that include quotation marks within strings. If you type two double quotation marks in a row ("") where a double quotation mark should appear within a string, Word splits the string at those places and inserts + Chr$(34) + between each segment when you first run the instruction or save the macro. For example, consider the following line typed in a macro-editing window:

result$ = "The word ""cool"" appears twice."

When you run or save the macro for the first time, Word automatically converts the instruction so it looks like the previous example with Chr$().

You also use Chr$() to include a nonprinting character such as a tab or newline character. For more information, see Chr$() in Part 2, "WordBasic Reference."


Variables

A variable is a storage container for a string or a number. A macro can change the contents of a variable as it is running. In other words, the value of a variable — the string or number it contains — can vary, which is why a variable is so named.

Variables provide the means for flexible and powerful macros. For example, to avoid overusing the word "cool," you could write a macro to calculate how many times the word appears in your document or in a paragraph. This macro may be useful, but it is not very flexible because it counts only the word "cool." Using a variable, you can modify the macro to calculate how frequently any word that you specify appears in a document. For a discussion of this macro, see "Some Sample Macros" at the end of this chapter.

WordBasic supports string variables and numeric variables to store strings and numbers. A string variable is identified by a dollar sign ($) ending character. A numeric variable does not end with a dollar sign character. Here are some examples of possible string and numeric variable names.

Examples of string variable names | Examples of numeric variable names
MyName$ | Total
SearchText$ | count
answer$ | size

When creating a variable name, keep the following rules in mind:

  • It must begin with a letter.
  • It can contain only letters, numbers, and underscore ( _ ) characters; punctuation marks and spaces are not allowed.
  • It cannot be longer than 40 characters.
  • It cannot be a reserved word. A reserved word is a word that already has a defined meaning in WordBasic. These words include statements, functions, arguments, and operators (such as AND and MOD).

Assigning Values to Variables

A variable has no value until you assign it one. In effect, it is an empty container waiting to be filled by a string or numeric value.

In some programming languages, you have to "declare" variables before you can assign values to them. In other words, before you write the body of your program, you must specify all the words that are going to be used as variable names. You do not have to declare variables in WordBasic, so often a variable appears in your macro for the first time when you assign it a value. But for complex macros that use many variables, you can make the macro more readable by declaring all the variables at the beginning of the macro. You use the Dim statement to declare a variable. For information, see Dim in Part 2, "WordBasic Reference."

To assign a value to a variable, you use an equal sign (=), placing the variable name on the left side and the value you are assigning it on the right side. The following example assigns the string "Willie" to the variable MyName$:

MyName$ = "Willie"

Don't try to place the value you are assigning on the left side of the equal sign — this doesn't work. The following example produces a syntax error:

"Willie" = MyName$            'Produces a syntax error

Once you have assigned a value to a variable, you can use that variable just as you would use a string or number. If the variable is numeric, you can use it in mathematical expressions. The first line of the following example assigns to counter a value of 6. The second line assigns to counter the result of the expression counter + 1, or 7:

counter = 6
counter = counter + 1

You cannot assign numeric values to string variables or string values to numeric variables. The following statements are not acceptable (either statement would prevent a macro from running and cause Word to display the message "Type mismatch"):

strg$ = 3.14159                'Produces an error
number = "hi, there"            'Produces an error

Variables often act as containers for information returned by a function. For example:

firstdoc$ = FileName$()

In this example, firstdoc$ stores the filename of the current document.

Changing Strings to Numbers and Numbers to Strings

Sometimes you need to change a string value to a numeric value, or vice versa. You use the Val() function to convert a string to a number and the Str$() function to convert a number to a string. For example, the following input box asks the user to type the number of files the macro should open.

The InputBox$() function, which displays the input box, returns a string value. So the Val() function is used to convert the string value to the NumFiles numeric value:

NumFilesString$ = InputBox$("How many files do you want to list?")
NumFiles = Val(NumFilesString$)

On the other hand, the MsgBox statement accepts only string values. So if you want to use MsgBox to display a numeric value, you must first convert it into a string with the Str$() function. For example:

NumFiles$ = Str$(NumFiles)
MsgBox "You have chosen to list" + NumFiles$ + " files."

These instructions display the following message box.

The Str$() function adds a space before positive numbers. The space accommodates the minus sign (–) for negative numbers. You can use the LTrim$() function to remove the space. For an example, see LTrim$() in Part 2, "WordBasic Reference." For more information on InputBox$() and MsgBox, see "Displaying Messages and Requesting Information" later in this chapter.


Expressions

An expression is a formula that can include either strings or numbers. A numeric expression consists of numbers or numeric variables linked together by operators to perform a mathematical calculation. For example, 2+2 is an expression.

WordBasic supports the following standard mathematical operators.

Operator | Function
+ | Addition
– | Subtraction
* | Multiplication
/ | Division
MOD | Modular division

The MOD operator performs a special type of division in which the whole-number part of the division result is discarded and the remainder is returned. For example, the result of 7 MOD 3 is 1 (1 is the remainder when you divide 7 by 3).

You can use just one mathematical operator — the plus sign (+) — in string expressions because, while it doesn't make sense to multiply, divide, or subtract strings, it's often useful to "add" or combine them. For example:

Word$ + " was found" + Str$(count) + " times in your document."

For more examples of combining strings, see "Some Sample Macros" at the end of this chapter. For detailed information on WordBasic operators, see "Operators and Predefined Bookmarks" in Part 2, "WordBasic Reference."


Conditionals and Loops

Conditionals and loops are key elements for building powerful and flexible macros. They are defined as follows:

  • A conditional statement tells the macro to run a group of instructions only if a specified condition is met. The logic of a conditional statement is simple and familiar. "If it's raining, I'll put on my raincoat" is an example of a conditional statement.
  • A loop statement tells the macro to repeat a group of statements either a specified number of times or until a condition is met. The equivalent in everyday life might be "Beat the egg whites until they are fluffy." In Word, a loop might be "Format every paragraph until you reach the end of the document."

Conditional and loop statements are often referred to as control structures because they control when and how other statements are run. Generally, a control structure is composed of a beginning instruction and an ending one, with the instructions being controlled in the middle.

WordBasic offers more than one conditional statement and more than one way to create a loop. This chapter covers the If conditional and the While ¼ Wend loop; the next chapter covers the Select Case conditional and the For ¼ Next loop.

What Is a Condition?

A condition is an expression that is either true or false. WordBasic uses conditions to determine whether or not to run the statements in an If conditional or a While ¼ Wend loop.

Consider the statement "Today is Monday." This statement is either true or false: either today is Monday or it isn't. The statement becomes a condition when it is put into a conditional sentence: "If today is Monday, I'll go to work." This conditional says that if the condition ("today is Monday") is true, the second part of the sentence will occur ("I'll go to work").

In WordBasic and other programming languages, you express a condition by comparing values. For example, if you say "Today is Monday," you are comparing today to Monday and saying that Monday and today are the same. In WordBasic, you compare values by using relational operators — symbols that state how values stand in relation to each other (they're equal, one is greater than the other, and so on). The symbols in the following table are probably familiar to you from math, although some might look a little different (for example, > = rather than >).

Relational operator | Meaning
= | Equal to
<> | Not equal to
> | Greater than
< | Less than
>= | Greater than or equal to
<= | Less than or equal to

Word evaluates conditions — expressions that use relational operators — as either true or false. Here are some examples.

Condition | Evaluation
7 = 35 | False
7 <> 6 | True
7 <= 7 | True

You can also compare strings.

Condition | Evaluation
"Bob" = "Bob" | True
"Bob" = "bob" | False
"Bob" <> "Jerry" | True
"Blue" < "Green" | True
"love" > "life" | True

Most often, string comparisons are used to determine whether two strings match. For example, a macro might contain a condition such as StyleName$() = "Heading 2" which tests whether the current style name is "Heading 2." As the condition "Bob" = "bob" (which evaluates as false) reveals, the case of letters is significant in string comparisons; an uppercase "B" does not match a lowercase "b." You can use the WordBasic functions LCase$() and UCase$(), which return strings in lowercase and uppercase characters, to equalize case when doing string comparisons where case should be ignored.

How Word Evaluates String Comparisons

You can use the > or < operator to compare whether one string is "greater than" or "less than" another. This sort of comparison is rare, but if you do use it, you need to know a little more about how string comparisons are evaluated. Word evaluates string comparisons character by character until it finds characters that don't match; the alphabetic or character code values for each character are then compared.

If the characters are letters in the alphabet, Word evaluates them according to which letter is first in the alphabet. For example, "B" follows "A" in the alphabet, so "B" is evaluated as greater than "A." Likewise, an uppercase "B" follows a lowercase "a" in alphabetic order, so "B" is evaluated as greater than "a," even though the character code for "B" (66) is less than the character code for "a" (97). (The character codes for all lowercase letters are higher than the character codes for all uppercase letters; for that reason "b" is evaluated as greater than "B.") If the characters are nonalphabetic, Word evaluates them according to their character code value. For example, a period (.) is greater than a comma (,) because 46, the code for a period, is greater than 44, the code for a comma.

Thus, "Blue" < "Green" is true because "B" comes before "G" in the alphabet. In the condition "love" > "life", both strings begin with "l," so Word evaluates the second characters in the strings; "o" comes after "i" in the alphabet, so the first string is evaluated as greater than the second one.

Note

You can use numbers to represent "true" and "false". In a conditional, false can be represented as 0 (zero), and true can be represented as –1. Therefore, if the result of a conditional expression is 0 (zero), it is evaluated as false. If the result is any nonzero number (not just –1), it is evaluated as true. See "The While¼Wend Loop" later in this chapter for an example of a macro that uses this capability.

An Example

You can create a macro that is the WordBasic equivalent of the sentence "If today is Monday, I'll go to work."

To start with, create a series of numeric variables corresponding to the days of the week:

Sunday = 1
Monday = 2
Tuesday = 3
Wednesday = 4
Thursday = 5
Friday = 6
Saturday = 7

Next, add this instruction:

ThisDay = WeekDay(Today())

The numeric variable ThisDay holds the value returned by the WordBasic functions Today() and WeekDay(). Today() returns a serial number that represents the current date; WeekDay() converts that serial number into a number from 1 to 7, where 2 represents Monday, just like the variables you've set up. Now the macro is ready for the following conditional statement:

If ThisDay = Monday Then MsgBox "Time to go to work!"

The MsgBox statement displays a message box, so if the day happens to be Monday and you run the macro, you'll get this message box on your screen.

The If Conditional

You can write the If conditional in several different ways, depending on how complex your control structure needs to be. The previous example used the shortest form, or syntax, as shown here:

If condition Then instruction

This syntax says that if the condition is true, the instruction will run. Generally, this form is used just for a single instruction because every instruction that is part of this form of the If conditional must be on the same line. In the following example, if the text is bold, bold formatting is removed:

If Bold() = 1 Then Bold 0

You could add instructions on the same line, separating each one with a colon (:). In the following example, if the text is bold, bold formatting is removed and italic applied:

If Bold() = 1 Then Bold 0 : Italic 1

But if you want to include more than one instruction within the If control structure, you generally use the following syntax:

If condition Then
 Series of instructions
End If

All the instructions between If and End If are dependent on the condition. In the following example, If evaluates, or "tests," the condition to determine whether selected text is formatted as bold. If it is, the instructions remove the bold formatting and apply italic and underline formatting:

If Bold() = 1 Then                'If the selected text is bold, then
    Bold 0                        'remove bold formatting
    Italic 1                        'apply italic formatting
    Underline 1                    'apply underline formatting
End If

If control structures can include an Else instruction. Instructions subject to Else run if the condition is not true:

If condition Then
 Series of instructions to run if condition is true
Else
 Series of instructions to run if condition is false
End If

The following example toggles bold formatting. That is, if the selected text is formatted as bold, the first Bold instruction removes bold formatting; if the text is not bold, the second Bold instruction applies bold formatting (this is how the Bold button on the Formatting toolbar works):

If Bold() = 1 Then                'If the selected text is bold, then
    Bold 0                        'remove bold formatting
Else                                'otherwise
    Bold 1                        'apply bold formatting
End If

An abbreviated, one-line version of the If ¼ Then ¼ Else syntax is available without the ending End If:

If condition Then instruction Else instruction

Again, this one-line structure works well for conditionals where only one or two instructions are involved. For example:

If Bold() = 1 Then Bold 0  Else Bold 1

For cases where multiple instructions are involved, the full syntax with End If works better.

The most complex form of the If conditional includes the ElseIf instruction:

If condition1 Then
Series of instructions to run if condition1 is true
ElseIf condition2 Then
Series of instructions to run if condition2 is true
Else
Series of instructions to run if no condition is true
End If

ElseIf is a second If conditional contained within a single If control structure. You could add an ElseIf instruction to the "days of the week" example presented earlier. In English, the conditional could be expressed as "If today is Saturday or Sunday, I'll stay at home; otherwise, I'll go to work." In WordBasic, the conditional might look like the following:

If ThisDay = Saturday Then
    MsgBox "Stay at home!"
ElseIf ThisDay = Sunday Then
    MsgBox "Stay at home!"
Else
    MsgBox "Go to work!"
End If

You can add as many ElseIf instructions to an If conditional as you need. For example, you could use ElseIf to test a condition for every day of the week (although this wouldn't be a very efficient technique).

The While¼Wend Loop

You can think of a While ¼ Wend loop as a conditional that can run the statements it controls more than once. Here's the syntax for the While ¼ Wend loop:

While condition
 Series of instructions to run if condition is true
Wend

As with the If conditional, the instructions within a While ¼ Wend loop will not run unless condition is true. If condition is true, the instructions repeat until the condition is no longer true. If the condition never changes, an "endless loop" occurs — the instructions within the loop repeat endlessly until someone interrupts the macro by pressing ESC or clicking the Stop button on the toolbar. This is not usually an effect you want to achieve, so when you create a While ¼ Wend loop, you must build into it a means of changing the condition that starts the loop from true to false. This may sound difficult, but in practice it usually isn't. Consider the following example:

Sub MAIN
StartOfDocument
TRUE = - 1
EditFind .Find = "cool", .Direction = 0, .MatchCase = 0, \
    .WholeWord = 0, .PatternMatch = 0, .SoundsLike = 0, \
    .FindAllWordForms = 0, .Format = 0, .Wrap = 0
count = 0
While EditFindFound() = TRUE
    count = count + 1
    RepeatFind
Wend
MsgBox "Cool was found" + Str$(count) + " times."
End Sub

This macro moves the insertion point to the start of the document and then searches for the word "cool." It uses a While ¼ Wend loop to continue searching for "cool" until every instance of the word has been found. The macro then reports how many times it found the word in the document.

The condition EditFindFound() = TRUE controls the While...Wend loop. The EditFindFound() function returns a value of –1 if the result of the most recent search using EditFind was successful. If the search wasn't successful, EditFindFound() returns 0 (zero). In a condition, a result of 0 (zero) corresponds to "false," and –1 corresponds to "true." So if the search is not successful, EditFindFound() returns 0 (zero) and the condition is no longer true. Note that the variable TRUE, defined earlier as –1, is used instead of –1 to make the condition easier to read.

Compound Expressions in Conditional Statements

You can link two or more conditions together into a compound expression that is evaluated as a single condition. To link conditions together, you use the logical operators AND and OR, described as follows:

  • When two conditions are linked by AND, both conditions must be true in order for the compound expression to be true.
  • When two conditions are linked by OR, the compound expression is true if either condition is true.

The following table provides some examples of compound expressions.

Compound expression | Evaluation
10 > 5 And 100 < 200 | True
3 < 6 And 7 > 10 | False
8 < 7 Or 90 > 80 | True
2 < 1 Or 3 > 60 | False
"Y" > "N" And "yes" <> "no" | True
"Y" < "N" Or 4 <> 4 | False

Earlier in this section, the ElseIf instruction was used in an If control structure to express the conditional "If today is Saturday or Sunday, I'll stay at home; otherwise, I'll go to work." The following example uses a compound expression instead:

If ThisDay = Saturday Or ThisDay = Sunday Then
    MsgBox "Stay home today!"
Else
    MsgBox "Time to go to work!"
End If

The compound expression is more efficient in this case than using ElseIf — fewer instructions are needed to accomplish the same task and the instructions are also easier to understand, since they're closer to the way you would express the condition in English.

Note that the following instruction would not work properly:

If ThisDay = Saturday OR Sunday        'Produces the wrong result

Although this instruction reads like English, and you might therefore expect it to work, it does not. The expression ThisDay = Saturday is one condition and, on the other side of OR, Sunday is the other condition. WordBasic reads the compound expression as something like "If today is Saturday or if Sunday is Sunday." Because Sunday is always Sunday, the compound expression is always evaluated as true, no matter what day it is.

When WordBasic evaluates compound expressions, it proceeds from left to right; all conditions are evaluated first, then all compound expressions with AND, then all compound expressions with OR. You can use parentheses to control the order of evaluation, as in mathematical expressions.

Note

The AND and OR operators can be tricky. It is easy in some cases to use an OR operator when you need to use an AND. If you have any uncertainty over which one to use, test your macro.

The NOT Operator

A third logical operator available in WordBasic is NOT. The NOT operator negates the expression that follows it. The following table shows some examples.

Expression | Evaluation
Not (5 > 10) | True
Not (8 < 7 Or 90 > 80) | False
Not (0) | True

The logic of the last example may not be immediately obvious. Because 0 (zero) is evaluated as false, Not (0) means "not (false)," or true.

The NOT operator is useful as a way to make a condition easier to read. For example, compare the following two instructions:

If ViewOutline() = 0 Then ViewOutline
If Not ViewOutline() Then ViewOutline

The instructions have the same effect, but the second one is closer to the way the conditional would be expressed in English: "If the document is not in outline view, then switch to outline view."

Note

The NOT operator works well with functions such as ViewOutline() that return –1 (true) or 0 (false); it can reverse either value the function returns. It is usually not appropriate to use NOT with functions that can return other values. For more detailed information on NOT, see "Operators and Predefined Bookmarks" in Part 2, "WordBasic Reference."


Common WordBasic Techniques

So far, this chapter has presented the building blocks needed to construct macros with WordBasic. This section describes a few widely used WordBasic techniques that employ some of those building blocks.

Inserting Text into a Document

To insert text, special characters, and even nonprinting characters like tab characters, you use the Insert statement. The Insert statement is the macro equivalent of typing at the keyboard; anything you can type, a macro can insert with Insert. For example, the following instruction inserts the phrase "Sincerely yours" into a document:

Insert "Sincerely yours"

Notice that the statement doesn't specify where "Sincerely yours" is to be inserted. Just as when you type, the phrase is inserted into the active document wherever the insertion point is currently located. If there is a selection, Insert will replace it (assuming the Typing Replaces Selection check box on the Edit tab in the Options dialog box (Tools menu) is selected).

The Insert statement inserts plain text into a document. The text you insert takes on the formatting of the text that precedes it. If you want to insert text with a different format, you place instructions to apply that formatting before the Insert instruction, just as you would turn on formatting before typing text. The following example turns on italic formatting just before inserting text and turns it off just afterward:

Italic 1                                'Turn on italic
Insert "Love's Labour's Lost,"        'Insert text
Italic 0                                'Turn off italic
Insert " by William Shakespeare"        'Insert more text

You can insert many special characters and nonprinting characters with Insert by typing them and enclosing them in quotation marks, as you would other text. For example, the following instruction inserts a tab character:

Insert "        "                        'Insert a tab character

Just looking at this instruction, though, it's difficult to tell whether you intend to insert a tab character or several spaces. In general, it's a better practice to use the Chr$() function with Insert to insert nonprinting characters:

Insert Chr$(9)                        'Insert a tab character

To insert paragraph marks, use InsertPara.

If you want to insert text into a document that isn't active, you include statements in your macro to open the document or switch to it. The following example activates the document associated with the variable LetterDoc$ and moves the insertion point to a bookmark called "Closing" before inserting text:

Activate LetterDoc$                'Switch to the LetterDoc$ window
EditGoTo "Closing"                'Move the insertion point to a bookmark
Insert "Sincerely yours"            'Insert text

Working on Part of a Document

Quite often, you want a macro to operate on only part of a document. For example, a macro that creates a table and inserts information into the table should operate just within the table. Or a macro may be designed to perform a series of formatting and editing operations on a particular paragraph.

The most useful tool Word provides for identifying discrete parts of documents is bookmarks. A simple use for bookmarks is just to mark a selection or location in a document. The following instruction marks the current selection (or the current location of the insertion point if there is no selection) with the bookmark "temp":

EditBookmark .Name = "temp", .Add

You can also use bookmarks to select text between two arbitrary locations in a document, as shown in the following example. It marks the current location with the bookmark "temp" and then pastes text from the Clipboard into the next paragraph. The ExtendSelection instruction activates extend mode, and the EditGoto instruction returns to the "temp" bookmark, selecting all the text between the end of the inserted text and "temp" as it does so.

EditBookmark .Name = "temp", .Add        'Insert bookmark "temp"
ParaDown                                    'Move to next paragraph
EditPaste                                'Paste from Clipboard
ExtendSelection                            'Activate extend selection
EditGoto "temp"                            'Return to "temp"; select text

Word provides a set of predefined bookmarks for macros. These bookmarks do not appear in the list of bookmarks that appears in the Bookmark and Go To dialog boxes (Edit menu), but a macro can use them in the same way it can use other bookmarks. Here is the list of predefined bookmarks.

Bookmark | Description
\ Sel | Current selection or the insertion point
\ PrevSel1 | Most recent location where editing occurred
\ PrevSel2 | Second most recent location where editing occurred
\ StartOfSel | Start of the current selection
\ EndOfSel | End of the current selection
\ Line | Current line or the first line of the current selection
\ Char | Current character or the character following the insertion point if there is no selection
\ Para | Current paragraph or the first paragraph of the selection
\ Section | Current section or the first section in the selection
\ Doc | Entire contents of the active document

Bookmark | Description
\ Page | Current page or the first page of the selection
\ StartOfDoc | Beginning of the document
\ EndOfDoc | End of the document
\ Cell | Current cell or the first cell in the selection
\ Table | Current table or the entire first table of the selection
\ HeadingLevel | The heading that contains the insertion point or selection, plus any subordinate headings and text

For a more detailed description of the predefined bookmarks, see "Operators and Predefined Bookmarks" in Part 2, "WordBasic Reference."

The following example places a tab character in front of every paragraph in a table cell. The first instruction uses the predefined bookmark " \ Cell" to select the current cell (assuming the insertion point is already within a cell). The EditReplace instruction then replaces every paragraph mark with a paragraph mark and a tab character. After the replace operation, each paragraph except the first paragraph (since it isn't preceded by a paragraph mark) begins with a tab character. The CharLeft instruction then moves the insertion point to the start of the cell and inserts a tab character in front of the first paragraph.

EditGoTo "\Cell"
EditReplace .Find = "^p", .Replace = "^p^t", .Direction = 0, \
            .ReplaceAll, .Format = 0, .Wrap = 0
CharLeft
Insert Chr$(9)

You can use the SelInfo() function to test whether the insertion point is within a table. The following example uses SelInfo() to control a While loop that moves through a table and inserts information into each cell. When the macro reaches the last cell of the table, it stops.

EditGoTo .Destination = "t"                'Go to next table
While SelInfo(12) = - 1
    'Series of instructions to run while in the table
Wend

For more information, see SelInfo() in Part 2, "WordBasic Reference."

Reading Text from a Document

Frequently, a macro needs to "read" text from a document. For example, if a macro is moving through a document, it may need to check its location by checking the contents of a selection.

You use the Selection$() function to return the contents of the current selection. If no text is selected, Selection$() returns the character following the insertion point. The following example determines whether or not a paragraph contains text or just consists of a paragraph mark. If the selection is just a paragraph mark (Chr$(13) is equivalent to a paragraph mark), the message "This paragraph is empty" is displayed.

EditGoto "\Para"                            'Select paragraph
If Selection$() = Chr$(13) Then            'Test selection
    MsgBox "This paragraph is empty."
Else
    MsgBox "This paragraph contains text."
End If

You can also use the GetBookmark$() function to return text marked by a bookmark. For more information, see Selection$() and GetBookmark$() in Part 2, "WordBasic Reference."

Testing for the End of a Document

You often need macros to perform a series of operations on every instance of a particular element in a document. For example, you might want a macro to change the capitalization of every heading formatted with the Heading 5 style. A common way to set up this sort of macro is to have the macro start at the beginning of the document and stop when it reaches the end of the document.

Word provides several ways to test for the end of the document. The most straightforward is the AtEndOfDocument() function, which returns a true value,
–1, when the insertion point is at the end of the document. The following loop operates until the insertion point reaches the end of the document:

While AtEndOfDocument() <> -1
    'Series of instructions to run until the end of the document
Wend

The LineDown() and ParaDown() functions return a false value, 0 (zero), when they are unable to move the insertion point, which occurs only when they are at the end of a document. The following loop moves through the document a paragraph at a time until the insertion point reaches the end of the document:

While ParaDown()
    'Series of instructions to run until the end of the document
Wend

The end of a document is defined as the location just in front of the final paragraph mark in the document. The functions AtEndOfDocument(), LineDown(), and ParaDown() will not return a value indicating the end of a document unless the insertion point is at that location. It is not enough for the insertion point to be somewhere on the last line or somewhere in the last paragraph of a document.

You can also use CmpBookmarks() to test for the end of of the document, as shown in the following example:

While CmpBookmarks("\Sel", "\EndOfDoc")
    'Series of instructions to run until the end of the document
Wend

The EditFind and EditReplace instructions do not directly test for the end of a document, but you can use them to perform a task for as long as something is found. The following example changes the capitalization of each Heading 5 paragraph in a document. After the first search for a heading, the While ¼ Wend loop repeats the search until no more headings formatted with the Heading 5 style are found:

StartOfDocument
EditFindClearFormatting
EditFindStyle .Style = "Heading 5"
EditFind .Find = "", .Direction = 0, .Format = 1, .Wrap = 0
While EditFindFound() = - 1
    ChangeCase 2                'Capitalize first letter of each word
    RepeatFind
Wend


Displaying Messages and Requesting Information

WordBasic includes several statements and functions you can use to communicate with the user. This section explains the Print, MsgBox, MsgBox(), InputBox$(), and Input statements and functions, each of which provides a different way to display a message or to request information. Here's a brief overview of the capabilities of each one:

  • Print displays a message in the status bar. It is useful for displaying status messages while the macro is running. It doesn't require any response from the user.
  • The MsgBox statement displays a message box that the user must acknowledge before the macro can continue. The MsgBox() function displays a message box and also returns a value. You can use MsgBox() to ask the user a question that requires a "yes" or "no" answer.
  • InputBox$() displays a dialog box in which the user can type a response to a prompt.
  • Input displays a prompt in the status bar where the user can type a response.

You can also create your own dialog boxes with check boxes, list boxes, and other features. For more information, see Chapter 5, "Working with Custom Dialog Boxes."

Note

Print and Input can also be used to insert information into or read information from text files. For information on using Print and Input in this way, see "Using Sequential File Access" in Chapter 9, "More WordBasic Techniques."

Print

The Print statement displays a message in the status bar. Its most common use is to display a message describing the status of the macro. For example, if a macro needs time to perform a task, you might use the Print statement to display the message "Working…" in the status bar so the user understands that something is indeed happening.

The instruction Print "Working..." displays the following message in the status bar.

The Print statement accepts strings, string variables, numbers, and numeric variables, and allows you to mix them together. Here are some examples of valid Print instructions:

Print "Hello"
Print Name$
Print 365.25
Print Total

The Print statement can also display multiple items separated by commas or semicolons. When you use commas as delimiters, Word inserts a predefined tab space between the items. When you use semicolons as delimiters, the next item starts immediately after the previous one. For example:

Print "Hello, "; Name$, "The total is "; Total

MsgBox and MsgBox()

The MsgBox statement displays a message in a message box that the user must acknowledge before the macro can continue. You can provide a title for the message box and specify a symbol that identifies the type of message you want to display. For example:

MsgBox "The macro is finished.", "Sample Macro", 64

This instruction displays the following message box.

In the previous MsgBox instruction, "Sample Macro" is the message box title and 64 is a number that controls which symbol and buttons are displayed. For more information on using these arguments, see MsgBox in Part 2, "WordBasic Reference."

The MsgBox() function is just like the MsgBox statement, except that you can use it to give the user a choice or to ask the user a question. For example:

answer = MsgBox("OK to reformat?", "Two Column Macro", 292)

This instruction displays the following message box.

If the user chooses the Yes button, MsgBox() returns one value; if the user chooses the No button, MsgBox() returns a different value. The values are placed in the variable answer. The numeric argument 292 specifies the symbol and buttons displayed.

InputBox$()

InputBox$() displays an input box in which the user can type a response to a prompt. You can provide a title for the input box, a prompt, and a default response. For example:

DocName$ = InputBox$("Name of the file to open?", "Open Macro", \
        "Latest memo")

This instruction displays the following input box.

The user can replace the default response or accept it. The response is placed in the variable DocName$. Note that the user can type more than one line in an input box and can type enter to begin a new line. If the user presses enter to begin a new line, either Chr$(11) + Chr$(10) (Windows) or just Chr$(11) (Macintosh) is included in the string InputBox$() returns. In Windows, the Chr$(11) + Chr$(10) combination is interpreted as two paragraph marks when inserted into a document; in effect, an extra paragraph mark is inserted. You can use the CleanString$() function to remove the extra paragraph mark, as shown in the following example:

Address$ = InputBox$("Please type an address:", "Letter Macro")
Insert CleanString$(Address$)

Input

The Input statement uses the status bar to prompt the user for information. Because it's easy to overlook a prompt in the status bar, InputBox$() is generally preferred over Input. However, Input is a little more flexible than InputBox$(). Input can assign the user's response to numeric or string variables, whereas InputBox$() only returns strings. For example:

Input "What point size for the headline", Size

This instruction displays the following prompt. Notice that Input adds a question mark to the prompt.

The user's response is placed in the numeric variable Size.

You can prompt for a list of variables by separating each one with a comma. For example:

Input ItemNumber, Quantity
Input UserName$, ID

The user must respond with appropriate values separated by commas. The following are examples of acceptable responses:

1234,3
Mark Kyle, 6823

Input always attempts to divide the user's response at a comma. If you want to allow responses that contain commas, use a Line Input instruction. Line Input works like Input, but with one important difference: You can specify only a single string variable. For example:

Line Input Address$

If Word encounters a comma in the response, it returns the comma as part of the string that is assigned to Address$.


Some Sample Macros

This section provides some macro ideas and demonstrates ways you can use some of the WordBasic elements introduced in this chapter.

The macros described in this section are available on the Microsoft Word Developer's Kit disk in EXAMPLES.DOT (Windows) or MACRO EXAMPLES (Macintosh). For information about installing the files on the disk, see Chapter 1, "Introduction."

Delete to the Beginning of a Sentence

Here's a simple macro to delete the text between the insertion point, positioned within a sentence, and the beginning of the sentence. The macro capitalizes the first letter of the remaining text:

Sub MAIN
    SentLeft 1, 1            'Move to start of sentence; select text
    EditCut                    'Cut selected text
    ChangeCase 4                'Capitalize first letter of remaining text
End Sub

Remove Excess Paragraph Marks

When you're typing in Word and you reach the end of a line, Word automatically moves the insertion point to the next line. You press Enter only when you reach the end of a paragraph. But many other sources of text include a paragraph mark at the end of every line. This text is difficult to work with in Word because Word treats each line as a separate paragraph and does not wrap the text. The solution is to remove the excess paragraph marks, leaving only the ones that end each paragraph. You can do this by hand, using the Replace command (Edit menu), but it is faster to record the process and run a macro such as the following:

Sub MAIN
StartOfDocument
EditReplace .Find = "^p^p", .Replace = "@#$#", \
        .Direction = 0, .ReplaceAll, .Format = 0, .Wrap = 0
FileSave
EditReplace .Find = "^p", .Replace = " ", .ReplaceAll, \
        .Format = 0, .Wrap = 0
FileSave
EditReplace .Find = "@#$#", .Replace = "^p^p", .ReplaceAll, \
         .Format = 0, .Wrap = 0
End Sub

This macro assumes that two consecutive paragraph marks signify the end of a paragraph. When you remove paragraph marks from text, you usually want to preserve separate paragraphs. For that reason, this macro replaces two consecutive paragraph marks with the placeholder "@#$#". It then replaces each remaining paragraph mark with a space. Finally, it replaces the "@#$#" placeholder with two paragraph marks.

Determine How Many Days Until a Future Date

The following macro uses two WordBasic time and date functions, DateValue() and Today(), to count the number of days between today and a future date that you specify. An InputBox$() instruction prompts you to specify a future date; a MsgBox instruction displays a message box that indicates the number of days between the current date and the specified date. For a complete listing of time and date functions, see "Language Summary" in Part 2, "WordBasic Reference."

Sub MAIN
    enddate$ = InputBox$("Please enter future date:")
    serialenddate = DateValue(enddate$)
    numdays = serialenddate - Today()
    MsgBox "The number of days between now and " + enddate$ + \
        " is" + Str$(numdays) + "."
End Sub

Count How Many Times a Word Appears

The first version of this macro (see "The While¼Wend Loop" earlier in this chapter) counted the number of times the word "cool" appeared in a document. You can modify this macro so that it counts the number of times any word appears in a document:

Sub MAIN
TRUE = - 1
searchtext$ = InputBox$("Please type a word to search for:")
StartOfDocument
EditFind .Find = searchtext$, .Direction = 0, .MatchCase = 0, \
    .WholeWord = 0, .PatternMatch = 0, .SoundsLike = 0, \
    .FindAllWordForms = 0, .Format = 0, .Wrap = 0
count = 0
While EditFindFound() = TRUE
        count = count + 1
        RepeatFind
Wend
MsgBox searchtext$ + " was found" + Str$(count) + " times."
End Sub

The first line of the macro uses the InputBox$() function to prompt the user for the text to search for. The user's response is placed in the variable searchtext$.

When the macro is finished, it displays a message box indicating how many times searchtext$ was found.

You could further improve this macro by presenting different messages according to whether the text was not found, found just once, or found more than once. To do so, you can replace the MsgBox instruction in the example with the following If conditional:

If count = 0 Then
    MsgBox searchtext$ + " was not found."
ElseIf count = 1 Then
    MsgBox searchtext$ + " was found once."
Else
    MsgBox searchtext$ + " was found" + Str$(count) + " times."
End If

This conditional tests for two specific conditions: count = 0 (the text was not found) and count = 1 (the text was found only once). All other cases (the text was found more than once) are handled by Else. If count = 0, the macro will display a message box similar to the following one.

You can make one more refinement to this macro by changing the MsgBox instructions so that when the word being counted is displayed, it is enclosed by quotation marks. Because quotation marks cannot be used inside a string, you need to use the Chr$() function: Chr$(34) produces a double quotation mark. In the following example, quote$ is assigned the result of Chr$(34). In the MsgBox instruction, quote$ is used in strings wherever a double quotation mark should appear:

quote$ = Chr$(34)
If count = 0 Then
    MsgBox quote$ + searchtext$ + quote$ + " was not found."
ElseIf count = 1 Then
    MsgBox quote$ + searchtext$ + quote$ + " was found once."
Else
    MsgBox quote$ + searchtext$ + quote$ + " was found" + \
    Str$(count) + " times."
End If

This example displays a message box similar to the following one.

For more information on the Chr$() function, see Chr$() in Part 2, "WordBasic Reference."


Chapter 4 Advanced WordBasic

This chapter introduces the advanced elements of the WordBasic language, which you can use to create complex, powerful macros.

In this chapter:

  • More conditionals and loops
  • Array variables
  • Subroutines and user-defined functions
  • Working with dialog records


More Conditionals and Loops

The previous chapter introduced the If conditional and the While…Wend loop. This chapter introduces the following control structures, which are typically useful in more complex macros:

  • The For…Next loop
  • The Select Case conditional
  • The Goto statement

The For…Next Loop

You use the For…Next loop when you want to carry out a group of instructions a specific number of times. Here is the syntax (the arguments in brackets are optional):

For CounterVariable = Start To End [Step Increment]
Series of instructions
Next [CounterVariable]

Word carries out the instructions between For and Next as many times as it takes for the CounterVariable to increment from the Start value to the End value. The CounterVariable is incremented each time Word runs the Next instruction following the instructions. The Increment indicates how much to increment the counter; if this is omitted, as is often the case, the counter is incremented by 1.

Examples

The following example displays in the status bar the numbers from 1 to 12, one at a time:

For dozen = 1 To 12            'Loop 12 times
    Print dozen                'Display the value in the status bar
Next dozen                    'Return to the For statement to repeat loop

The initial value of dozen is 1, as set in the For instruction. During the first iteration, the Print statement displays 1 (the value of dozen) in the status bar; during the next iteration, it displays 2; during the next, 3; and so on until month reaches 12 — the end of the loop and the last number displayed in the status bar.

The following example creates a document with a sample sentence formatted in each available font:

For count = 1 To CountFonts()        'Loop for the number of fonts
    fname$ = Font$(count)            'Place a font name in "fname$"
    Font fname$                        'Apply formatting with this font
    Insert "This is " + fname$ + "."    'Insert sentence
    InsertPara                        'Insert paragraph mark
Next count

The CountFonts() function returns the number of available fonts. Because this value is the end value of the loop, the number of times the loop will repeat is equivalent to the number of available fonts. The Font$() function returns the name of the current font from the list of available fonts. In the example, the instruction Font$(count) returns the font whose position in the list of fonts corresponds to the value of count.

Several functions begin with "Count" and work much like CountFonts() does: They return the number of macros, AutoText entries, styles, and so on. These functions are often used to control For…Next loops just as CountFonts() does in the previous example.

You can nest a For…Next loop by placing it within another For…Next loop. The following example uses a nested loop to create a simple calendar based on a 360-day year:

For months = 1 To 12             'Loop 12 times
    For days = 1 To 30            'Loop 30 times
        Insert Str$(days)         'Insert "days" as a string
    Next days                    'Return to "For days = 1..."
    InsertPara                    'Insert a paragraph mark
Next months                        'Return to "For months = 1..."

The outside loop repeats 12 times, corresponding to the months of the year. Then, for each month, the inside loop repeats for the 30 days in the month. The Insert instruction uses the Str$() function to convert the value stored in the numeric variable day into a string, then inserts it into a document (you cannot use the Insert statement to insert a numeric value).

You can set up For ¼ Next statements in many ways. The following table provides some examples of different start and end values and their possible increment values.

Example | Result
For dozens = 0 To 144 Step 12 | The variable dozens increments from 0 (zero) to 144 in steps of 12.
For countdown = 10 To 1 Step -1 | The variable countdown decrements from 10 to 1 in steps of –1.
For loop = start To finish Step size | The variable loop increments or decrements from the value of the variable start to the value of the variable finish in steps equal to the variable size.
For count = count To count + 10 | The initial value of the variable count is increased by 10 in steps of 1 (the default increment).

Note that the For…Next loop increment (the value after Step) can be a positive or negative number — positive numbers increase the counter, and negative numbers decrease it. If the end value is larger than the start value (for example, For x = 1 To 10), the increment must be positive. Likewise, if the end value is smaller (for example, For x = 10 To 1), the increment must be negative.

The Select Case Conditional

Select Case is useful when you want to test many different conditions or a range of conditions. It's similar to the If conditional, but is more efficient for testing multiple conditions. Here is the syntax (arguments in brackets are optional):

Select Case Expression
Case CaseExpression
Series of instruction(s)
[Case Else
 Series of instruction(s)]
End Select

A SelectCase conditional can contain any number of Case instructions. The result of the Expression is compared with the CaseExpression values in every given Case instruction until a match is found. If a match is found, the instructions following the appropriate Case instruction are carried out. If there is no match, the instructions following Case Else are carried out. If there is no Case Else instruction and no match is found, Word displays an error message. To be safe, you should include a Case Else instruction — even if no statements follow it and it has no effect — to ensure that Word doesn't generate an error, regardless of the value of Expression. In CaseExpression, you can use the Is keyword when you want to use logical operators to compare Expression with a value. For example, Case Is > 5. You use the To keyword to test for a range of values. For example, Case 10 To 20 (10 and 20 are included in the range).

Examples

A macro that creates a calendar needs to determine how many days are in each month. Four of the months contain 30 days, February has 28 (in non-leap years), and the remaining months have 31 days. In the following example, the Select Case instruction tests the value of the month variable and then assigns the appropriate value to the lastday variable. The month variable is a number from 1 to 12 that corresponds to a month of the year.

Select Case month                'Select the value of month
    Case 4,6,9,11                'If month is 4,6,9, or 11
        lastday = 30                'the month has 30 days
    Case 2                        'If month is 2 (February)
        lastday = 28                'the month has 28 days
    Case Else                    'Otherwise
        lastday = 31                'the month has 31 days
End Select

Note that the first Case instruction has several values, separated by commas. If month equals any one of these values, the instruction following the Case instruction (lastday = 30) is carried out.

The following example uses the StyleName$() function to return the name of the style applied to the paragraph that contains the insertion point. Each Case instruction proposes a style name to match the one returned by StyleName$(). If the style name matches the proposed style, the instruction following the Case instruction is carried out.

Select Case StyleName$()                    'Select the current stylename
    Case "ListItem1"                        'If it's "ListItem1"
        ToolsBulletsNumbers .Type = 0    'add a bullet
    Case "ListItem2"                        'If it's "ListItem2"
        StartOfLine                        'go to the start of the line
        Insert "-" + Chr$(9)                'and insert a hyphen and a tab
    Case Else                            'Otherwise
        MsgBox "Not a list style"        'display a message
End Select

The following example demonstrates how you can use the Is and To keywords in Case instructions to test for a range of values. The example uses the Rnd() function to generate a random number from 0 (zero) to 10. The Case instructions test the number generated by Rnd() and display a corresponding message.

Select Case Int(Rnd() * 10)         'Select a random number from 0 to 10
    Case 0,1,3                    'If it is 0, 1, or 3
        Print "0, 1, or 3"        'print this message
    Case Is > 8                    'If it is greater than 8
        Print "Greater than 8"    'print this message
    Case 4 To 8                     'If it is between 4 and 8
        Print "Between 4 and 8"    'print this message
    Case Else                     'Otherwise
        Print "It's 2"             'print this message
End Select

The second Case instruction uses the Is keyword and the greater than (>) operator to test for any value greater than 8. The third Case instruction uses the To keyword to test for a value that falls in the range of values between 4 and 8.

The Goto Statement

Goto isn't a conditional or a loop, but it is included in this section because, like a conditional or loop, it controls the flow of a macro — the order in which Word interprets a macro's instructions. Goto tells Word to go to a line in the macro and carry out the instructions from that line forward. Among programmers, Goto is infamous for having the potential to create difficult-to-read code, often referred to as "spaghetti code" because it can make the flow of a program tangled and difficult to follow. Used sparingly, though, Goto can be useful in some situations. Also, it is usually necessary in WordBasic to use Goto with error-handling instructions (for information on error handling, see Chapter 7, "The Well-Behaved Macro").

Here is the syntax for Goto:

Goto Label

Word goes to the line in the macro that starts with Label, which must be within the same subroutine or user-defined function as the Goto instruction (see "Subroutines and User-Defined Functions" later in this chapter). A line label must begin at the start of a line (it cannot be preceded by a space or tab character) and end with a colon (:). The rules for Label names are the same as those for variable names (see "Variables" in Chapter 3, "WordBasic Fundamentals").

You can also use a line number with a Goto instruction instead of a label, although it's unusual to use line numbers in WordBasic macros. Line numbers are supported primarily for compatibility with old Basic programs in which line numbers were required. Like a label, a line number must begin at the start of a line; the line number can be as high as 32759. Unlike a text label, a line number does not need a colon following it.

The following example uses the InputBox$() function to request a social security number, then tests to see whether the number typed by the user is longer than 11 characters. If it is, the example displays a message box that asks the user to try entering the social security number again.

tryagain:
answer$ = InputBox$("Please enter your social security number: ")
If Len(answer$) > 11 Then
    MsgBox "Too many characters. Please try again."
    Goto tryagain
End If

The Goto instruction sends Word to the tryagain: label, so that the entire sequence of instructions is repeated. Note that when the Goto instruction refers to the tryagain: label, the ending colon (:) is dropped.

Nesting Conditionals and Loops

It's often useful to nest conditionals and loops — that is, to place a conditional or loop within another conditional or loop. The following example uses an If conditional within a Select Case conditional to assign 29 to the lastday variable if month is 2 (February) and it's a leap year:

Select Case this month 'Select the value of month

Case 4,6,9,11 'If month is 4,6,9, or 11

lastday = 30 'the month has 30 days

Case 2 'If month is 2 (February)

If leapyear = 1 Then 'If it's a leap year

lastday = 29 'the month has 29 days

Else 'Otherwise

lastday = 28 'the month has 28 days

End If 'End of If conditional

Case Else 'Otherwise

lastday = 31 'the month has 31 days

End Select

WordBasic supports up to 16 levels of nesting. Generally, though, it's best to limit nesting to no more than three or four levels; the more levels you use, the more obscure the logic of the macro can become.


Array Variables

An array variable gives a single name to a group of related values and organizes them in a list or table. Here are some of the advantages that using an array can provide over using regular variables:

  • A group of related variables can be easier to work with when ordered within an array.
  • A For…Next loop can be used with an array to assign values efficiently to many variables.
  • By changing the size of an array, a macro can create variables as it runs, so you don't need to know in advance how many variables your macro may need. For example, if you want to create a variable for the name of each style in a document, you cannot know how many variables will be needed (different documents can store different numbers of styles). If you use an array, your macro can create the necessary number of variables to store the values each time it runs.

Arrays are not difficult to use or understand, but they're not usually used in simple macros. Unless your macro needs to handle a lot of values, you probably don't need to use an array. The most common use for arrays in WordBasic is to list items in a custom dialog box. For more information on using arrays in custom dialog boxes, see Chapter 5, "Working with Custom Dialog Boxes."

Defining an Array

Each variable within an array is called an element and shares a common name — the array name. Elements are distinguished from each other by a subscript, a unique number assigned to each element. Before you can assign values to the elements of an array, you must specify how many elements the array contains. To do so, you use the Dim statement. Here is the syntax:

Dim ArrayVariableName(LastElementNumber)

The first element of a WordBasic array is always numbered 0 (zero). This can be confusing because it means that the subscript number of the last element is one less than the number of elements. For example:

Dim Months$(11)                    'Define an array with 12 elements

This instruction defines an array with 12 elements to hold the names of the months of the year. Because the first element is numbered 0 (zero), the twelfth element is numbered 11.

An array variable can be defined to hold either numbers or strings — a single array cannot hold both. The name of an array that contains string values must end with the dollar sign ($), just like a regular string variable.

Assigning Values to an Array

After you have used the Dim statement to define an array, you can assign values to the elements within it. You can assign values to array elements just as you do to regular variables. Here is an example:

Dim FourWinds$(3)                'Define an array with four elements
FourWinds$(0) = "East"
FourWinds$(1) = "West"
FourWinds$(2) = "North"
FourWinds$(3) = "South"

Sometimes, it's useful to ignore an array's first element, numbered 0 (zero), so that you can assign your first value to the element whose subscript is 1, the second value to the element whose subscript is 2, and so on. The following example assigns string values to the array Weekdays$(7) so that the subscripts of elements 1 through 7 correspond to a number returned by the Weekday() function:

Dim Weekdays$(7)                    'Define an array with eight elements
Weekdays$(0) = ""                'Assign no value to first element
Weekdays$(1) = "Sunday"
Weekdays$(2) = "Monday"
Weekdays$(3) = "Tuesday"
Weekdays$(4) = "Wednesday"
Weekdays$(5) = "Thursday"
Weekdays$(6) = "Friday"
Weekdays$(7) = "Saturday"
MsgBox "Today is " + Weekdays$(WeekDay(Today()))

You can use a For…Next loop to assign values to some arrays. The following example first defines an array that has as many elements as the number of available fonts, a value returned by the CountFonts() function. Then a For…Next loop inserts the names of all the fonts into the array. Note that the array is dimensioned so that the number of the last element is CountFonts() - 1, since CountFonts() starts its count at 1, whereas (as noted earlier) array subscript numbering starts at 0 (zero).

Dim fontnames$(CountFonts() - 1)                'Define an array
For count = 0 To (CountFonts() - 1)            'Repeat CountFont() times
    fontnames$(count) = Font$(count + 1)        'Assign font name Font$()
Next

You could use the fontnames$() array to present the list of font names in a custom dialog box. For information on using arrays in this way, see Chapter 5, "Working with Custom Dialog Boxes."

Resizing an Array

At times, it's useful for a macro to change the size of an array. For example, a macro that defines an array to hold all the fonts available on the current printer could later select another printer and reuse the original array to hold the new list of fonts. Because the second printer could have a different number of fonts available, the macro should resize the array before reusing it.

You use the Redim statement to resize an array. The syntax for Redim is exactly the same as for Dim:

Redim ArrayVariableName(LastElementNumber)

Note that when you resize an array, you also clear its contents. If you try to use the Dim statement to resize an existing array, Word generates an error.

Arrays with More Than One Dimension

The examples presented so far use arrays to order variables in a list. But you can also use arrays to order variables in a table. Suppose, for example, you wanted to create a variable for each day of the year. One way would be to define an array that lists 365 variables. For example:

Dim Year(364)                'Define an array with 365 variables

However, you could give more structure to these variables by placing them in a table. You could order them, for example, so that each row of a table represented a month and each column corresponded to a day:

Dim Year(11,30)                'Define an array with 12 rows and 31 columns

This kind of array is called a two-dimensional array, while those presented earlier in the chapter are one-dimensional arrays. You can create arrays with three or more dimensions — as many as there is room for in memory — but in practice, arrays with more than two dimensions are rare.

You define an array with more than one dimension by listing the number of elements in each dimension in the standard Dim statement. Here is the syntax for a two-dimensional array:

Dim ArrayVariableName(LastElementNumber1, LastElementNumber2)

In the following example of a two-dimensional array, both dimensions have five elements:

Dim MailingList$(4,4)        'Define a 5-by-5 two-dimensional array

Here is a visual representation of the 25 elements contained in the array.

Each cell in the table represents an element in the array — a slot for a string, because Dim MailingList$(4,4) defines a string array variable. Each pair of numbers represents the subscript for an element of the array. For example, MailingList$(2,1) indicates the second element in the third row. You could use this array to store five names, each with its own street address, city, state or province, and postal code. The first column would list the names, the second column would list the street addresses, and so on.

The following example creates a two-dimensional array that contains a multiplication table up to, and including, the number 10, and inserts the table into the active document:

Dim MultTable(10,10)
For N = 1 to 10
    For M = 1 to 10
        MultTable(N,M) = N * M
        Insert Str$(MultTable(N,M)) + Chr$(9)
    Next
    EditClear -1
    InsertPara
Next

In the example, the inner loop multiplies N and M, assigns the value to the element MultTable(N,M), and then inserts the product and a tab character into the active document. At the end of each row, the macro deletes the last tab character in the row and inserts a paragraph mark to start a new row.

Sorting Arrays

You can use the SortArray statement to sort arrays in alphabetical or numerical order. The following example assigns the available font names to the array fontnames$() and sorts the array:

Dim fontnames$(CountFonts() - 1)                'Define an array
For count = 0 To (CountFonts() - 1)            'Repeat CountFont() times
    fontnames$(count) = Font$(count + 1)        'Assign font name Font$()
Next
SortArray fontnames$()                        'Sort font names

For detailed information, see SortArray in Part 2, "WordBasic Reference."


Subroutines and User-Defined Functions

As your macros become more complicated, you can split the code into self-contained units called subroutines and user-defined functions. A subroutine carries out a task; it is like a custom-made statement. A user-defined function returns information and may also carry out a task. Subroutines and functions offer at least two advantages:

  • Instructions stored in a subroutine or function are reusable. A complex macro may need to carry out a task more than once. Rather than duplicating the instructions, you can store them in a subroutine or function that the macro "calls" when needed. Moreover, subroutines and functions are available not just to the current macro but to other macros that might need them.
  • Subroutines and functions allow you to break down complex tasks into smaller pieces. Instead of developing your macro in terms of one long process, you can break it down into manageable parts. Each subroutine or function can be tested separately, so you can more easily isolate problems and test the macro as a whole.

Subroutines

A subroutine is a kind of macro within a macro. It carries out a particular task, just as the macro as a whole does. Virtually any part of a macro can be placed in a subroutine, but usually it only makes sense to create a subroutine for a part that is self-contained or that will be used more than once. For this reason, subroutines are generally not needed in simple macros.

Every macro has a main subroutine that begins with the instruction Sub MAIN. A subroutine that you create is defined in the same way as the main subroutine, but requires a different name:

Sub SubroutineName[(ArgumentList)]
Series of instructions
End Sub

The SubroutineName is whatever name you choose that isn't a reserved word or a variable name. The limitations are the same as those for variable names (see "Variables" in Chapter 3, "WordBasic Fundamentals"). ArgumentList is a list of variables, separated by commas, that accept values passed to the subroutine. See "Sharing Values Among Subroutines and Functions" later in this chapter.

The Sub…End Sub instructions cannot be placed within the main subroutine or within any other subroutine. In other words, you cannot nest subroutines as you can WordBasic control structures, such as For…Next loops or If conditionals.

On the other hand, the instruction that runs, or "calls," the subroutine is placed within another subroutine. You can use the Call statement to run a subroutine, or you can use just the name of the subroutine as the instruction. (The Call keyword makes the macro easier to read — it's clear that a subroutine and not a built-in WordBasic statement is being run.) After the instructions in the subroutine have been carried out, control reverts to the routine that called the subroutine, as shown in the following diagram.

In the following example, the BeepMsgExit subroutine is called if the user chooses the Yes button in a message box that asks if he or she wants to quit Word:

Sub MAIN
    response = MsgBox("Do you want to quit Word?", 4)
    If response = -1 Then
        Call BeepMsgExit
    End If
End Sub

Sub BeepMsgExit
    Beep
    MsgBox("Quitting Word now...", -8)
    FileExit 1
End Sub

User-Defined Functions

User-defined functions are similar to subroutines — they are self-contained units of code that are called from one or more subroutines. But unlike a subroutine, a user-defined function returns a value, just as built-in WordBasic functions do. The rules for using functions you create are the same as those for built-in functions. Generally, you define a function because WordBasic does not include a function designed to return the particular value you need.

You define new functions in a manner similar to subroutines, except that instead of using the Sub instruction, you use the Function instruction. The syntax is as follows:

Function FunctionName[(ArgumentList)]
Series of instructions
 FunctionName = value
End Function

The ArgumentList is a list of variables, separated by commas, that accept values passed to the function. The function returns a value by assigning it to the function name itself, using the syntax FunctionName = value. A user-defined function can return either a numeric or string value. Functions that return string values have function names that end with the dollar sign ($).

In the following example, the MyDateTime$ function is called by the main subroutine to display the date and time in a message box. Note that no arguments are passed to this function, so it does not end with parentheses as a built-in Word function would (for example, Font$()); it looks just like a variable.

Sub MAIN
    MsgBox "The date and time is: " + MyDateTime$
End Sub

Function MyDateTime$
    mDate$ = Date$()
    mTime$ = Time$()
    MyDateTime$ = mDate$ + " " + mTime$
End Function

Sharing Values Among Subroutines and Functions

By default, a variable is available only within the subroutine or function in which it is initially used. However, subroutines and functions often need to exchange or share values. The following two methods are available:

  • You can use a Dim Shared instruction to declare a shared variable.
  • You can pass values to a specific subroutine or function.

Shared Variables

A shared variable can be used in any subroutine or function in the macro. Here is the syntax for declaring a shared variable:

Dim Shared Var, Var1, Var2…

A single Dim Shared instruction can be used to declare several shared variables. Every type of variable, including number, string, and array variables, can be declared as shared. A Dim Shared instruction is not placed inside a subroutine or function since it applies to all the subroutines and functions within the macro. Generally, you declare shared variables at the beginning of a macro, before the main subroutine.

In the following example, the variable num is declared as shared:

Dim Shared num                    'Declare "num" as a shared variable
Sub MAIN
    num = 6                        'Set the value of num
    AddTenRoutine                'Call the routine
End Sub

Sub AddTenRoutine
    num = num + 10                'Increase the value of num by 10
    Print num                    'Display the new value of num
End Sub

The main subroutine sets num equal to 6, and then calls the AddTenRoutine subroutine. The subroutine adds 10 to num and then displays the value 16. If num was not declared as a shared variable, the value displayed would be 10, because num would have no value at the start of the AddTenRoutine subroutine.

Any subroutine can affect the value of a shared variable. If you have many subroutines, shared variables can be a source of problems. For example, you might intend to use a variable named "count" in two subroutines. Later on, if you forget that you've already used "count" and you use it in a new subroutine, you could create an error that might be difficult to find. You can avoid this problem by passing variable values through subroutine or function arguments.

Passing Values to Subroutines and Functions

You can pass values from one subroutine or user-defined function directly to another through arguments. Arguments are variables in a subroutine or function that initially receive their values from the calling subroutine or function. Unlike shared variables, whose values can be affected by any subroutine or function, values passed to subroutines and user-defined functions can be affected only by the subroutines or functions involved.

Here is the syntax for subroutine arguments in the Call statement:

[Call] SubroutineName [argument1, argument2, …]

The syntax for passing values to a user-defined function is similar; the main difference is that the arguments are enclosed in parentheses:

FunctionName[(argument1, argument2, …)]

Note that you can pass any number of values, each separated by a comma.

Here is an example of passing a value to the AddTenRoutine shown earlier:

Sub MAIN
    num = 6                    'Set the value of num
    AddTenRoutine num        'Call the routine and specify "num"
End Sub

Sub AddTenRoutine(var1)
    var1 = var1 + 10            'Increase the value of var1 by 10
    Print var1                'Display the new value of var1
End Sub

The following example uses a function called FindAverage() to average two numbers. The variables a and b, defined as 6 and 10, are passed to the FindAverage() function, which averages the two values. The main subroutine then displays the result.

Sub MAIN
    a = 6
    b = 10
    Print FindAverage(a, b)
End Sub

Function FindAverage(firstnum, secondnum)
    FindAverage = (firstnum + secondnum) / 2
End Function

Note that the variable names in the subroutine or user-defined function do not have to match the names of the variables passed to it, but the order of the arguments must match. In the previous example, the value of the a variable is passed to the firstnum variable, and the value of b is passed to secondnum.

You can pass strings, numbers, and arrays to subroutines and user-defined functions. In the following example, the fontnames$() array is passed to the FillFontArray subroutine, which fills the array with the list of available font names.

Sub MAIN
    lastelement = CountFonts() - 1
    Dim fontnames$(lastelement)
    FillFontArray$(fontnames$(), lastelement)
End Sub

Sub FillFontArray(array$(), maxcount)
    For arraycount = 0 To maxcount
        array$(arraycount) = Font$(arraycount + 1)
    Next
End Sub

Passing Arguments "by Value"

Normally, when you pass a variable to a subroutine or user-defined function, the subroutine or function can change the value of that variable not only within the subroutine or function itself but also in the calling subroutine. This is known as passing an argument "by reference." In the following example, the greeting$ variable is passed to the ChangeGreeting subroutine by reference. The main subroutine then displays the greeting, which the ChangeGreeting subroutine has changed from "Hello" to "What's up?"

Sub MAIN
    greeting$ = "Hello"
    ChangeGreeting greeting$
    MsgBox greeting$
End Sub

Sub ChangeGreeting(change$)
    change$ = "What's up?"
End Sub

You can pass an argument and ensure that its value in the calling subroutine remains unchanged by passing the argument "by value." To pass an argument by value in WordBasic, you enclose it in parentheses.

In the following example, the greeting$ argument is passed by value, so when the main subroutine displays the greeting, the greeting remains "Hello."

Sub MAIN
    greeting$ = "Hello"
    ChangeGreeting (greeting$)
    MsgBox greeting$
End Sub

Sub ChangeGreeting(change$)
    change$ = "What's up?"
End Sub

In the following example, the variable a is passed by reference, while b is passed by value:

Sub MAIN
    a = 6
    b = 10
    OnePlusAverage a,(b)
    MsgBox "a =" + Str$(a) + " and b =" + Str$(b)
End Sub

Sub OnePlusAverage(firstval, secondval)
    firstval = firstval + 1
    secondval = secondval + 1
    avg =  (firstval + secondval) / 2
    Print avg
End Sub

The OnePlusAverage subroutine adds 1 to each value passed to it, and then displays the average of the two values in the status bar. When the OnePlusAverage subroutine ends and control returns to the main subroutine, the main subroutine displays the following message box, which shows that the argument passed "by reference" changed, while the argument passed "by value" did not.

Note that if you are passing more than one argument to a subroutine and you want to pass the first argument by value, you must enclose the list of arguments in parentheses. For example, if you wanted to pass a by value and b by reference, you would specify the following instruction:

OnePlusAverage((a),b)

This issue doesn't arise when you're passing arguments to a user-defined function, since the list of arguments passed to a function must always be enclosed in parentheses.

Using Subroutines and Functions from Other Macros

You can call subroutines and functions that are stored in other macros. This technique lets you create libraries of subroutines and functions so that you can avoid copying or rewriting code you use often.

To call a subroutine stored in another macro, use the following syntax:

[Call] MacroName.SubroutineName[(ArgumentList)]

MacroName is the name of the macro containing the subroutine, and SubroutineName is the name of the subroutine you want to use. The optional ArgumentList is the list of values to be passed to the subroutine in the same way values are passed within the same macro. You can pass string and numeric values and arrays, just as you can within a macro.

The template in which the specified macro is stored can be the active template, the Normal template, or a loaded global template. Subroutines and functions stored in the Normal template are always available. For information on loading a template as a global template, see "Macros and Templates" in Chapter 2, "Getting Started with Macros."

The following example is a subroutine contained in a macro called Library:

Sub MyBeep
    Beep : Beep : Beep                        'Beep three times
    For t = 1 to 100 : Next                    'Pause
    Beep : Beep : Beep                        'Beep three times again
End Sub

Here's an example of a macro that calls the MyBeep subroutine:

Sub MAIN
    YES = -1
    answer = Msgbox("Listen to MyBeep?", 36)    'Prompt user
    If answer = YES Then Library.MyBeep        'If yes, run MyBeep
End Sub

To use a function stored in another macro, use the following syntax:
MacroName.FunctionName [(ArgumentList)]. For example, suppose the following function is stored in the Library macro:

Function MyDateTime$
    mDate$ = Date$()
    mTime$ = Time$()
    MyDateTime$ = mDate$ + " " + mTime$
End Function

In a macro called CheckDateTime, you could call this function as follows:

Sub MAIN
    MsgBox "The date and time is: " + Library.MyDateTime$
End Sub

Running Another Macro from Within Your Macro

In addition to being able to call subroutines and functions stored in other macros, you can run entire macros from within your macro. It can be useful to call a macro for a specific task from within a larger macro that performs several tasks. You can call a macro in the same way you call a subroutine or function, with or without the optional Call keyword. For example, to call a macro named ChangeSettings, you can use the following instruction:

Call ChangeSettings

Or you can omit the Call keyword:

ChangeSettings

You can also use ToolsMacro to run a macro:

ToolsMacro .Name = "ChangeSettings", .Show = 3, .Run

One advantage of using ToolsMacro to run a macro is that you can specify the template where the macro you want to run is stored. In the previous example, ToolsMacro will run the ChangeSettings macro stored in the template attached to the active document. When you use the Call statement, Word looks for the called macro first in the template that contains the calling macro. Only if the macro is not found there does Word look in other templates. This distinction between ToolsMacro and Call can make a difference if different available templates contain macros with the same names.

Here are some points to be aware of when calling subroutines or functions from another macro:

  • Shared variables declared in one macro are not available in another. Each time a macro calls a subroutine or function from another macro, any shared variables declared in the macro being called are reinitialized.
  • You can pass values to a macro's main subroutine just as you can pass values to any other subroutine. Note, however, that the main subroutine must be set up to receive values. For example, a main subroutine or function set up with the instruction Sub MAIN(a, b) requires two values from a macro that calls it. If you set up a main subroutine to accept values in this way, you can only run the macro that contains it by calling it from another macro.
  • A macro cannot use the syntax for calling a subroutine or function in another macro to call a subroutine or function within itself. For example, if the macro CheckDateTime contained the MyBeep subroutine within it, the instruction Call CheckDateTime.MyBeep would generate an error. Similarly, a subroutine or function called from another macro cannot call a subroutine or function from the macro that is calling it.
  • Limit calls between macros to four or five levels of nesting. For example, when macro A calls a subroutine in macro B that in turn calls a subroutine in macro C that calls macro D, three levels of nesting are involved.
  • If more than one macro with a specified name is available, Word first looks for the macro stored in the same template as the calling macro. For example, suppose the Normal template and another template called Sample both contain a macro called Welcome. If a macro stored in the Normal template opens a document attached to the Sample template and then calls a subroutine within Welcome, Word runs the subroutine in the Welcome macro stored in the Normal template, even though Sample is the active template (since it is attached to the active document). If the called subroutine does not exist in the Welcome macro stored in Normal, Word generates an error (Word does not look for the subroutine in the Sample template's Welcome macro).

Important

You cannot call a subroutine or user-defined function stored in another macro if the name of the subroutine or function is the same as the name of an argument for a WordBasic statement that corresponds to a dialog box. For example, Library.Wrap generates an error because .Wrap is an argument for the EditFind statement.


Working with Dialog Records

You can create a special variable called a dialog record that stores the settings of a Word dialog box. You can use dialog records for Word dialog boxes in the following two ways:

  • To retrieve or change the settings of dialog box options without displaying the dialog box.
  • To display a Word dialog box and change the settings of options in the dialog box. Generally, when you display a dialog box, its settings reflect the current state of the active document or of Word itself. But you might want to change the settings displayed in a dialog box. For example, the Summary Info dialog box (File menu) normally shows the name of the document's original author. A macro can place a value in a dialog record for the Summary Info dialog box so that when the dialog box is displayed, the original author's name is automatically replaced with a different name.

Defining a Dialog Record

You use the Dim statement to define a dialog record. Here is the syntax:

Dim DialogRecord As DialogBoxName

DialogRecord can be any name you choose that isn't a reserved word. The limitations are the same as those for string and numeric variables (see "Variables" in Chapter 3, "WordBasic Fundamentals"). DialogBoxName can be any WordBasic statement name that corresponds to a dialog box. For example, the WordBasic statement that corresponds to the Open dialog box on the File menu is FileOpen, so "FileOpen" is a valid DialogBoxName. If you're not sure what the valid DialogBoxName for a dialog box is, see "Language Summary" and "Statements and Functions" in Part 2, "WordBasic Reference."

Here are some examples of dialog records:

Dim FPrec As FormatParagraph            'Define a dialog record "FPrec" for
                            'the FormatParagraph dialog box

Dim Fontrecord As FormatFont            'Define a dialog record "Fontrecord"
                            'for the FormatFont dialog box

Dim TOVrec As ToolsOptionsView        'Define a dialog record "TOVrec"
                            'for the ToolsOptionsView dialog box

As the last example shows, you can sometimes specify the tab as well as the dialog box name for dialog boxes that contain tabs. That is, you can specify "ToolsOptionsView," not merely "ToolsOptions." To check whether you can specify a tab in this way for a particular dialog box, see the entry for the statement that corresponds to the dialog box in Part 2, "WordBasic Reference."

Retrieving and Changing Dialog Box Settings

Once you define a dialog record for a dialog box, you use the GetCurValues statement to place the current values of the dialog box into the dialog record. The following example copies the current settings of the View tab in the Options dialog box (Tools menu) into the TOVrec dialog record:

Dim TOVrec As ToolsOptionsView        'Define a dialog record "TOVrec"
GetCurValues TOVrec                    'Get the current values

You can change or retrieve the values of the dialog box settings stored in a dialog record by referring to them with the following syntax:

DialogRecord.DialogBoxOption

DialogBoxOption is an argument for the WordBasic statement that corresponds to the dialog box whose options are stored in DialogRecord. For the list of valid arguments, see the entry for the corresponding WordBasic statement in Part 2, "WordBasic Reference."

The following example retrieves the current setting of the Picture Placeholders check box on the View tab in the Options dialog box (Tools menu) and places it in the variable picture:

Dim TOVrec As ToolsOptionsView
GetCurValues TOVrec
picture = TOVrec.PicturePlaceHolders

You change the value of an option in a dialog record by assigning it a value, just as you assign a value to any other variable. For example:

Dim TOVrec As ToolsOptionsView
GetCurValues TOVrec
TOVrec.PicturePlaceHolders = 1
ToolsOptionsView TOVrec

In this example, the .PicturePlaceHolders argument is given a value of 1, which corresponds to selecting the Picture Placeholders check box. The final instruction in the example (ToolsOptionsView TOVrec) puts the values stored in the TOVrec into effect. This instruction is required because changing values in a dialog record does not in itself cause changes to occur in Word. Only the WordBasic statement that corresponds to the dialog box can put the changes into effect.

The following WordBasic instruction is equivalent to the four instructions in the previous example:

ToolsOptionsView .PicturePlaceHolders = 1

As you can see, it's not very efficient to use a dialog record to change the value of a single option in a dialog box. But if you create a dialog record to retrieve dialog box values, you can use the dialog record to change a value conditionally. The most common use of this technique is to "toggle" a dialog box option.

Using a Dialog Record to Toggle a Check Box

To toggle something means to reverse its current "state" or value. You can toggle a check box in a dialog box because it has two "opposite" values — selected and cleared. The same is true of some Word commands. For example, when you choose the Ruler command from the View menu, Word hides the ruler if it was displayed or displays the ruler if it was hidden. The current state of the ruler (displayed or hidden) is reversed each time.

Using the appropriate dialog record, you can create a macro to toggle any check box. You can then assign the macro to a shortcut key or menu for quick access. The following macro toggles the Paragraph Marks check box on the View tab in the Options dialog box (Tools menu) to show or hide paragraph marks:

Sub MAIN
    Dim TOVrec As ToolsOptionsView    'Define a dialog record "TOVrec"
    GetCurValues TOVrec                'Get the current values
    If TOVrec.Paras = 1 then            'If on
        TOVrec.Paras = 0                'turn off
    Else                                'Otherwise
        TOVrec.Paras = 1                'turn on
    End If
    ToolsOptionsView TOVrec            'Reset the dialog
End Sub

The following macro uses a slightly different technique to show or hide hidden text:

Sub MAIN
    Dim TOVrec As ToolsOptionsView            'Define a record "TOVrec"
    GetCurValues TOVrec                         'Get the current values
    TOVrec.Hidden = Abs(TOVrec.Hidden - 1)    'Reverse state
    ToolsOptionsView TOVrec                     'Reset the dialog
End Sub

This macro uses the expression Abs(TOVrec.Hidden - 1) to toggle the value of the Hidden Text check box on the View tab in the Options dialog box. Here's how it works. The Hidden Text check box can have the value 0 (zero) if it is not selected or 1 if it is selected:

  • If the check box is not selected, then TOVrec.Hidden - 1 is equivalent to 0–1, or –1. The Abs() function makes the negative number positive, so the final result of Abs(TOVrec.Hidden - 1) is 1, which selects the check box.
  • If the check box is selected, then TOVrec.Hidden - 1 is equivalent to 1–1, or 0 (zero). The Abs() function has no effect in this case, and the final result of Abs(TOVrec.Hidden - 1) is 0 (zero), which clears the check box.

Displaying a Dialog Box

Once you have created a dialog record, you can use the Dialog statement or Dialog() function to display the corresponding dialog box. This is useful if you want your macro to present a dialog box so that a user can set the options he or she wants before the macro continues. The following example displays the Options dialog box (Tools menu) with the View tab showing and then runs ToolsOptionsView after the user closes the dialog box.

Dim TOVrec As ToolsOptionsView    'Define a dialog record "TOVrec"
GetCurValues TOVrec                'Place current values in record
Dialog TOVrec                    'Display dialog box
ToolsOptionsView TOVrec            'Run ToolsOptionsView with new settings

Note that the GetCurValues instruction is necessary. Without this instruction, the macro would display the dialog box with no values — it would not reflect the current state of Word. The ToolsOptionsView instruction is necessary for the settings that the user chooses in the dialog box to have an effect. If this instruction were left out, the user could change settings and then choose the OK button, but Word would not carry out the command.

If you want to modify dialog box settings before displaying the dialog box for the user, you just change the settings of the dialog record options before running Dialog or Dialog(). The following example creates a dialog record for the Summary Info dialog box (File menu) and changes the contents of the Author box:

Dim FSIrecord as FileSummaryInfo        'Define a dialog record "FSIrecord"
GetCurValues FSIrecord                'Get the current values
FSIrecord.Author = "Louis Caspary"    'Place a name in the Author box
Dialog FSIrecord                        'Display Summary Info dialog box
FileSummaryInfo FSIrecord            'Do FileSummaryInfo instruction

The Dialog instruction displays the Summary Info dialog box with the name "Louis Caspary" in the Author box, as shown in the following illustration.

Checking How a Dialog Box Is Closed

When a macro displays a dialog box, it also needs to test how the user closes the dialog box. If the user chooses the OK button, the macro should carry out the command associated with the dialog box. If the user chooses the Cancel button, the macro should not carry out the command. The way you check how a dialog box is closed depends on whether you use the Dialog statement or the Dialog() function to display a dialog box:

  • If a dialog box is displayed with the Dialog() function, the Dialog() function returns a value corresponding to the button used to dismiss the dialog box. You can then use that value in a conditional statement to determine how the macro should proceed.
  • If a dialog box is displayed with the Dialog statement and the user chooses the OK button or the Close button, Word moves to the next statement in the macro. But if the user chooses the Cancel button, Word generates an error that you can handle with an On Error statement.

Here is an example that uses the Dialog() function and an If conditional to test whether the user chooses the OK button or the Cancel button to dismiss a dialog box:

Dim FSIrecord as FileSummaryInfo        'Define a dialog record "FSIrecord"
GetCurValues FSIrecord                'Get the current values
FSIrecord.Author = "Louis Caspary"    'Place a name in the Author box
choice = Dialog(FSIrecord)            'Display dialog and return button
If choice = -1 Then                     'If "OK" then
    FileSummaryInfo FSIrecord        'do FileSummaryInfo with changes
End If

The OK button returns a value of –1; the Cancel button returns 0 (zero). In this example, the value returned by Dialog(FSIrecord) is stored in the variable choice. If the user chooses the OK button, then the macro runs the FileSummaryInfo statement — the WordBasic statement corresponding to the Summary Info dialog box. Otherwise, nothing happens.

In the following example, the On Error Goto statement is used to trap the error generated by the Cancel button when the Dialog statement is used to display the Open dialog box:

Dim FOrecord as FileOpen                'Define a dialog record "FOrecord"
GetCurValues FOrecord                'Get the current values
On Error Goto trap                    'Go to the "trap" label if the user
                                    'chooses the Cancel button
Dialog FOrecord                        'Display the Open dialog box
FileOpen FOrecord                    'Carry out FileOpen with changes
Goto bye                                'Go to the "bye" label
trap:                                'Label for On Error Goto statement
MsgBox "Macro cannot proceed."        'Error message
bye:                                    'Label for Goto statement

This more elaborate example uses an On Error Goto instruction to present a message to the user if he or she chooses the Cancel button. The MsgBox instruction informs the user that the macro cannot continue because the user did not open a file. For more information on error trapping, see Chapter 7, "The Well-Behaved Macro."


Chapter 5 Working with Custom Dialog Boxes

You can create custom dialog boxes for your macros. This chapter describes how to design a custom dialog box with the Dialog Editor and then use the dialog box in a macro. The last section of the chapter deals with dynamic dialog boxes — dialog boxes that can respond to user actions while they are displayed. These dialog boxes are more complex to set up but deliver many useful capabilities.

In this chapter:

  • Dialog box controls
  • Using the Dialog Editor to create a dialog box
  • Using custom dialog boxes
  • Using dynamic dialog boxes


Dialog Box Controls

WordBasic supports most of the standard Windows and Macintosh dialog box controls. This section introduces the controls available for custom dialog boxes and provides guidelines for using them.

OK, Cancel, and Push Buttons

Every custom dialog box must contain at least one "command" button — an OK button, a Cancel button, or a push button. WordBasic includes separate dialog box definition statements for each of these three types of buttons. A common use for a push button is to display another dialog box.

List Boxes, Drop-Down List Boxes, and Combo Boxes

You use a list box, drop-down list box, or combo box to present a list of items from which the user can select. A drop-down list box saves space (it can drop down to cover other dialog box controls temporarily). A combo box allows the user either to select an item from the list or type a new item. The items displayed in a list box, drop-down list box, or combo box are stored in an array that is defined before the instructions that define the dialog box.

Check Boxes

You use a check box to make a "yes or no" or "on or off" choice. For example, you could use a check box to display or hide a toolbar or to apply or remove formatting for selected text.

Text Boxes and Text

A text box control is a box in which the user can enter text while the dialog box is displayed. By default, a text box holds a single line of text, but you can also size it to hold multiple lines of text (text wraps within a multiple-line text box, and the user can also press Enter to start a new line). A text control displays text that the user cannot change. It is often used to label a text box.

Option Buttons and Group Boxes

You use option buttons to allow the user to choose one option from several. Typically, you use a group box to surround a group of option buttons, but you can also use a group box to set off a group of check boxes or any related group of controls.

Pictures and File Preview

A custom dialog box can include graphics, or "pictures," and a file preview box, which displays a thumbnail representation of any Word document. A dialog box can include only one file preview box. A graphic can be stored as a file, an AutoText entry, an item marked with a bookmark in a document, or an item on the Clipboard.


Using the Dialog Editor to Create a Dialog Box

You can use the Dialog Editor to create a new dialog box or to edit an existing one. Here's the sequence for creating and using a custom dialog box:

1. Design the dialog box using the Dialog Editor application.

2. Select the completed dialog box and copy it into the macro in which you want to use it.

3. Add the instructions needed to display the dialog box and to retrieve information from it.

Starting the Dialog Editor

The Dialog Editor is a separate application included in the Word package. If you chose not to install the Dialog Editor when you set up Word, you can run the Word Setup program again to install it.

The Dialog Editor button (Macro toolbar)

To start the Dialog Editor, click the Dialog Editor button on the Macro toolbar. In Windows, you can also run the Dialog Editor from Program Manager or File Manager. On the Macintosh, you can run the Dialog Editor by double-clicking the Dialog Editor icon in the Word folder.

Note

In Windows, the Dialog Editor does not support 3-D dialog effects. However, when a WordBasic macro displays a dialog box created with the Dialog Editor in Windows, the dialog box has the same 3-D look as built-in Word dialog boxes, assuming the 3-D Dialog And Display Effects check box is selected on the General tab in the Options dialog box (Tools menu).

Adding Items to a Dialog Box

When you start the Dialog Editor, it displays an empty dialog box to which you can add dialog box controls such as buttons, text, and list boxes. In the Dialog Editor, controls are called items. You use the Item menu to add them to the dialog box.

After you have used the Item menu to insert an item, the item remains selected. You can press ENTER to create a copy of the selected item. For example, when a check box is selected you can press ENTER to insert another check box. When an OK button or push button is selected and you press ENTER, the Dialog Editor inserts a Cancel button if there isn't one already; likewise, when a Cancel button or a push button is selected and you press enter, the Dialog Editor inserts an OK button if there isn't one already. If both an OK button and a Cancel button are present, pressing enter when any command button is selected inserts a new push button.

Adding a Group of Option Buttons

An easy way to create a group of option buttons is to insert a group box, press ENTER to insert the first option button, and continue to press ENTER to insert additional option buttons. To insert a group box, choose Group Box from the Item menu. Immediately after creating each option button, type a name for it. (When an option button is selected, you can replace the default text, "Option Button," by typing new text.)

Adding a Picture Item

Using the Picture command on the Item menu, you can add graphics to your dialog boxes. When you choose the Picture command from the Item menu, it displays the New Picture dialog box, in which you can indicate how the graphic you're adding is stored — as a file, an AutoText entry, an item marked with a bookmark, or an item on the Clipboard. In the Text$ box of the Information dialog box (Info command, Edit menu) for the picture item, type the path and filename of the graphics file, the name of the AutoText entry, or the name of the bookmark, or just type Clipboard. The Dialog Editor does not display the graphic, but you can position and size the picture item just as you can any other item. Don't worry if you don't know the name of the file or the picture type; you can specify it later.

Adding a Multiple-Line Text Box

When you use the Dialog Editor to insert a text box control, the text box is sized to hold a single line of text. To make the text box into a multiple-line text box, you change the text box's height so that it can accommodate more than one line. Initially, however, the Dialog Editor doesn't allow you to change a text box's height. This is to prevent you from accidentally changing the height as you change the width. To change the height, you have to double-click the text box to display the Information dialog box, which displays settings pertinent to the selected dialog box item, and then clear the Auto check box next to Height. You can then adjust the height of the text box to make it into a multiple-line text box.

Adding a File Preview Box

The Dialog Editor does not have a command to insert a File Preview box. However, you can use another item that can be sized in a similar way as a placeholder. A group box, for example, makes a good placeholder. When you paste the dialog box into your macro, you can then change the name of the item's instruction to FilePreview. Keep in mind that a dialog box can include only one File Preview box; also, when a dialog box includes a File Preview box, it must call a dialog function. For information on dialog functions, see "Using Dynamic Dialog Boxes" later in this chapter. For more information, see FilePreview in Part 2, "WordBasic Reference."

Positioning and Sizing Items

Once you have added an item, you can use the mouse to position and size it.

The mouse pointer
for positioning

Positioning

You can position an item by dragging it with the mouse. When the mouse pointer is positioned over an item, the pointer changes to a four-headed arrow.

The mouse pointers for sizing

Sizing

You can size an item by dragging its borders with the mouse. When the mouse pointer is positioned over a border, the pointer changes to a double-headed arrow.

Positioning and Sizing Precisely

Using the SHIFT key to align

If you hold down the SHIFT key just before you move an item, you can drag only vertically or only horizontally, depending on which direction you first move the mouse.

Using the arrow keys

You can use the arrow keys to position or size a selected item. You can position an item by pressing an arrow that corresponds to the direction you want to move the item. To size an item, hold down the SHIFT key and press an arrow key. In Windows, the selected item is moved or sized by four X or Y units each time you press an arrow key. To move or size the item by just one X or Y unit, hold down the Ctrl key while moving or sizing. For example, to increase the width of a selected item by one X unit in Windows, you could press Ctrl+Shift+right arrow. In Windows, you must press ENTER to finish moving or sizing an item; you can press ESC to cancel. On the Macintosh, the selected item is moved or sized one X or Y unit each time you press an arrow key; you can hold down the OPTION key to move or size an item by four X or Y units each time you press an arrow key. For example, to increase the width of a selected item by one X unit on the Macintosh, you could press Shift+right arrow.

Using the Information dialog box

The Information dialog box displays the exact position and size of an item, so that you can set it precisely. You can also see at a glance whether or not an item is precisely aligned with another item. For example, if you want to align two items horizontally, a good technique is to do it first by eye and then use the Information dialog box to get the Y coordinates of the items; if one of them is off by one or two Y units, you can adjust its position accordingly. To display the Information dialog box for an item, double-click the item, or select it and choose Info from the Edit menu.

What Do X and Y Represent?

The Dialog Editor positions and sizes items in X units for horizontal positioning and width, and Y units for vertical positioning and height. Because monitors have different resolutions, these units are defined in relative rather than absolute terms. X units are increments of 1/8 of the System font in Windows or the dialog font on the Macintosh. Y units are increments of 1/12 of the System font in Windows or the dialog font on the Macintosh.

Note that in Windows, the System font is not the same as the font used to display text in a custom dialog box. Generally, the dialog font and the System font are scaled in proportion to each other, but some display drivers install a System font that is easier to read and disproportionately large. For example, the Windows Super VGA 1024 x 768 (large fonts) display driver uses this technique. When one of these display drivers is installed, the Word dialog font does not expand to the degree the System font does. This means that dialog boxes and controls, whose size is dependent on the System font, expand more than dialog box text, which appears a little shrunken. Likewise, if you design a dialog box with a large-fonts display driver installed and then display the dialog box with a small- or normal-fonts display driver installed, dialog box text may be truncated (since dialog box controls shrink more than the text they contain).

To avoid this problem, either design your dialog boxes with a standard VGA resolution driver installed or, if you're designing with a large-fonts display driver installed, make sure that controls containing text (such as text label and option button controls) are a little larger than necessary so that text has room to expand when displayed with a different display driver.

Selecting Multiple Items

You can select more than one item by holding down the SHIFT key and clicking the additional items you want to select. This is useful if you want to move several items as a group. You can select every item in a dialog box by using the Select All Items command on the Edit menu.

Selecting a Group

When you move option buttons or other items within a group box, you typically want to move them as a group. The Dialog Editor provides a Select Group command to select all the items within a group box, including the group box. A group box is most often used to group option buttons, but you can include any item within it.

Positioning and Sizing Automatically

The Dialog Editor automatically positions or sizes some items. When an Auto check box is selected for an item, you cannot change the item's position or size. Automatic sizing is a useful way to fix the size of items you generally don't want to resize, such as OK buttons and Cancel buttons. To select or clear automatic positioning and sizing for any item, double-click the item and select or clear the appropriate Auto check boxes in the Information dialog box.

Note that if you select Auto for the position of an item you've already moved, it returns to the position where the Dialog Editor originally inserted it; this may conflict with the position of other items you have moved. However, you can set automatic positioning for an item just after inserting it to force it to move with the item that precedes it. For example, if you select Auto for the position of a text box inserted beneath a text item, you can move them together by dragging only the text item.

Sizing the Dialog Box

When you have added all the items the dialog box will contain, you can drag the borders of the dialog box (Windows) or drag the sizing box at the bottom-right corner (Macintosh) to fit the items. You can also choose the Resize command from the Edit menu or double-click the dialog box border (Windows) or click the zoom box (Macintosh) to have the Dialog Editor size the dialog box for you.

Deleting Items

You can delete one or more selected items by choosing Clear from the Edit menu. In Windows, you can also press the Delete key; on the Macintosh, you can press either Del or COMMAND+Delete (on the Macintosh, the Delete key deletes text in an item label, not the item itself). To delete all of the items in a dialog box, select the dialog box itself or choose Select All Items from the Edit menu before deleting. To start from scratch with a new, empty dialog box with the default label and default size and position, choose New from the File menu.

Changing Labels and Identifiers

When you insert an item, it has a default label such as "Check Box," "Option Button," or "Text." Immediately after you've inserted an item, while it is selected, you can replace the default label by typing the one you want. Once you have changed the default text, you can select the item and use the Backspace key (Windows) or the Delete key (Macintosh) to delete what you typed, or you can use the Information dialog box to edit it.

To display the Information dialog box, double-click the item or select the item and choose the Info command from the Edit menu. In the Information dialog box, you edit the label by changing the text in the Text$ box. The Auto Quote check box is selected by default; it inserts quotation marks around the item's label when you paste the dialog box definition into a macro. If you want to use a variable name as a label, you can clear the Auto Quote check box (since a variable name should not be enclosed in quotation marks). On the Macintosh, the Auto Quote check box is not included in the Dialog Editor.

Many dialog box items are designed to return a value to the macro that displays the dialog box. In your macro, you use an item's identifier to access the value associated with that dialog box item. The Dialog Editor assigns these items default identifiers such as .CheckBox1 or .ListBox2. You can use the .Field box in the Information dialog box to change an item's identifier to something less generic. The .Field box is so named because the values returned by dialog box items are stored in a dialog record. In programming terminology, values stored in a record are "fields." In this book, the term "identifier" is used instead because identifiers serve not only to indicate fields within records but also to identify dialog box items to other instructions within a macro.

Comments

In the Comment box, you can add a comment that will appear in the dialog box definition when the dialog box is copied from the Dialog Editor into a macro. In your macro, the comment will be located on the same line as the WordBasic instruction associated with the item.

Access keys

Access keys allow quick keyboard access to items in a dialog box. When an access key is defined for an item in a custom dialog box, the user can press ALT+the specified letter (Windows) or COMMAND+the specified letter (Macintosh) to activate a text box, select or clear a check box, or choose a command button, for example. In the Information dialog box, you define an access key for an item by including an ampersand (&) character before a letter in the Text$ box. In the dialog box, the letter appears underlined. (Note that on the Macintosh, you must hold down the COMMAND key for a second or two before the letter appears underlined.) To define an access key for a text box, you define one for a text item associated with the text box. To associate a text item with a text box, insert the text item first, then insert a text box. In the dialog box definition created when the dialog box is pasted into a macro, the Text instruction must immediately precede the TextBox instruction.

Copying a Dialog Box to a Macro

When you're ready to insert a dialog box into the macro that will display it, you select the dialog box in the Dialog Editor and copy it. You don't have to select each item in the dialog box; you just select the dialog box itself. You can do this by clicking the dialog box title bar or by choosing the Select Dialog command from the Edit menu.

When the dialog box is selected, choose the Copy command from the Edit menu to copy it. In Word, open the macro and position the insertion point where you want to insert the dialog box definition. Then paste the dialog box definition. It will appear as a series of instructions enclosed by a Begin Dialog ¼ End Dialog instruction.

Exiting the Dialog Editor

In the Dialog Editor, choose Exit (Windows) or Quit (Macintosh) from the File menu. If you've created a new dialog box or changed an existing one and have not copied your work, the Dialog Editor asks if you want to copy it to the Clipboard. If you want to use the dialog box in Word, choose the Yes button. If you choose the No button, the new dialog box or any changes made to an existing one will be lost.

Editing an Existing Dialog Box

You can change a custom dialog box in any macro by copying the dialog box definition from the macro to the Clipboard and then pasting it from the Clipboard into the Dialog Editor. You can then edit the dialog box in the Dialog Editor. Note that when you select a dialog box definition, the selection must start with the Begin Dialog instruction and end with the End Dialog instruction.

Tips for Using the Dialog Editor

The following tips can save you time and effort when building custom dialog boxes with the Dialog Editor.

Build a dialog box from top to bottom and from left to right

Within the Dialog Editor, everything is relative to the upper-left corner of the dialog box. When you resize a dialog box, items aligned with the top and left borders of the dialog box will keep their position relative to the top and left borders, but items aligned with the bottom and right borders will lose their position.

Use the SHIFT key to align items with the mouse

If you hold down the SHIFT key before moving an item with the mouse, you will only be able to move the item in the direction you first move it. You can confidently position the item without worrying that you'll accidentally move it out of alignment in the other direction. You can also use the SHIFT key to select multiple items and move them together so they maintain their positions relative to each other.

Select an item, then add an item below it

You can minimize the amount of rearranging you have to do if you keep in mind that when you add an item, the Dialog Editor positions it below the currently selected item. For example, if you know you want to add a text box with a text label, add the text label first, then add the text box (assuming that you want the text label to appear above the text box, as it usually does).

Add a group box first

If you want to enclose items such as option buttons or check boxes within a group box, add the group box first. If you add the check boxes or option buttons first, the group box will hide rather than enclose them.

Use a group box to create a rectangle

A group box normally includes a text label, but if you delete the label, the group box forms a rectangle that you can use as a design element.

Use the arrow keys to make small adjustments

In Windows, when you press an arrow key, you move the selected dialog box item four X or Y units; when you press CTRL+an arrow key, you move the item one X or Y unit. To size an item, press SHIFT+an arrow key or CTRL+SHift+an arrow key. Press ENTER to complete positioning or sizing or ESC to cancel it.

On the Macintosh, when you press an arrow key, you move the selected item one X or Y unit; when you press OPTION+an arrow key, you move the item four X or Y units. To size an item, hold down SHIFT and press an arrow key or OPTION+an arrow key.

Always include a command button

A dialog box must include at least one command button. That is, it must include either an OK button, a Cancel button, or a push button. Otherwise, Word will generate an error when you run the macro to display the dialog box.

Avoid a "value out of range" error

Sometimes when you insert a large item such as a group box into a dialog box, the item's boundaries fall outside the dialog box border. If you paste the dialog box into a macro and run it, Word will display a "value out of range" error. You can avoid this error by simply repositioning the item that causes the error. A macro can't display an item in a dialog box unless it lies entirely within the dialog box. (Drop-down list boxes can drop slightly outside the dialog box, but no more than an eighth of an inch or so.)

A Glossary of Dialog Box Terms

The vocabulary associated with dialog boxes can be confusing. Here's a glossary of terms.

Custom dialog box A dialog box defined by WordBasic instructions. Usually, the Dialog Editor is used to design a custom dialog box, which is then copied into a macro. A custom dialog box is used to display and return information. Also known as a user-defined dialog box.

Dialog box control An element of a dialog box such as a command button, check box, text label, or list box. Within the Dialog Editor, a dialog box control is referred to as an "item." For descriptions of the dialog box controls available for custom dialog boxes, see "Dialog Box Controls" earlier in this chapter.

Dialog box control identifier A string used to identify a particular dialog box control. The identifier is used with a dialog record to insert and retrieve values from dialog boxes and to reference dialog box controls.

Dialog box definition The set of WordBasic instructions used in a macro to define a custom dialog box. These instructions are enclosed within a Begin Dialog ¼ End Dialog instruction. The Dialog Editor automatically generates a dialog box definition.

Dialog function A special user-defined function that can be called while a custom dialog box is displayed. The dialog function can make a custom dialog box "dynamic" by responding to events while the dialog box is displayed. See "Using Dynamic Dialog Boxes" later in this chapter.

Dialog record A variable that contains the values returned by a Word dialog box or by a custom dialog box. Each setting in a dialog box is stored in a field within the record associated with the dialog box. For more information, see "Working with Dialog Records" in Chapter 4, "Advanced WordBasic."

Dynamic dialog box A custom dialog box whose contents can change dynamically in response to user actions while the dialog box is displayed. See "Using Dynamic Dialog Boxes" later in this chapter.

Word dialog box A dialog box built into Word. Most dialog boxes are displayed by choosing a menu command, but some, like the Organizer dialog box, are available only by choosing buttons in other dialog boxes.


Using Custom Dialog Boxes

A custom dialog box is designed to display and return information. Once you have built a dialog box in the Dialog Editor and copied it into a macro, you need to add instructions to put information into the dialog box, display the dialog box, and retrieve information from it. Here's an overview of the steps involved:

1. Define the dialog box. You use the Dialog Editor to define the dialog box. The instructions the Dialog Editor generates are called a dialog box definition.

2. Create a dialog record. You use a Dim statement to create a dialog record for a custom dialog box, just as you do for a built-in dialog box.

3. Put values into the dialog box. If the dialog box includes a list box, drop-down list box, or combo box, you probably want to fill it with items. You may also want to place default text in a text box or select check boxes before displaying the dialog box.

4. Display the dialog box. You use a Dialog instruction to display the dialog box. As with built-in dialog boxes, you can use either the Dialog statement or the Dialog() function.

5. Retrieve values from the dialog box. The settings of dialog box controls are stored in the dialog record, so you retrieve information from the dialog record after the dialog box is closed.

The Dialog Box Definition

A dialog box definition is the set of instructions that defines the contents of a dialog box as well as its size and position. When you create a dialog box in the Dialog Editor, it generates these instructions.

Dialog box definition instructions are enclosed within the Begin Dialog ¼ End Dialog statement. Here is the syntax:

Begin Dialog UserDialog [HorizPos, VertPos,] Width, Height, Title$
[, .DialogFunction]
Series of instructions to define controls in the dialog box
End Dialog

The optional HorizPos and VertPos arguments position the dialog box; if they are omitted, Word displays the dialog box at the center of the Word window. Width and Height size the dialog box. The Title$ argument is the text that appears in the dialog box title bar. If you do not specify HorizPos and VertPos, you can omit Title$; you can omit Title$ even if you specify HorizPos and VertPos if you also specify .DialogFunction. If you omit Title$, "Microsoft Word 6.0" appears in the title bar. The .DialogFunction argument is used only if you want to create a dynamic dialog box. For information on dynamic dialog boxes, see "Using Dynamic Dialog Boxes" later in this chapter. For complete information, see Begin Dialog ¼ End Dialog in Part 2, "WordBasic Reference."

The following dialog box includes every dialog box control.

Here is the dialog box definition that defines the dialog box:

Begin Dialog UserDialog 612, 226, "Every Dialog Box Control", \
        .DlgFunction
    ComboBox 8, 76, 176, 111, MyList$(), .ComboBox1
    CheckBox 198, 79, 180, 16, "&Check Box", .CheckBox1
    ListBox 195, 102, 189, 83, MyList$(), .ListBox1
    DropListBox 417, 5, 179, 108, MyList$(), .DropListBox1
    Text 417, 186, 35, 13, "&Text"
    TextBox 417, 199, 179, 18, .TextBox1
    GroupBox 7, 4, 177, 65, "&Group Box"
    OptionGroup  .OptionGroup1
        OptionButton 17, 16, 148, 16, "Option Button &1"
        OptionButton 17, 33, 148, 16, "Option Button &2"
        OptionButton 17, 50, 148, 16, "Option Button &3"
    Picture 199, 7, 181, 62, "BIRD", 1, .Picture1
    FilePreview 417, 31, 179, 148, .fileprev
    PushButton 10, 199, 108, 21, "&PushButton"
    CancelButton 131, 199, 108, 21
    OKButton 253, 199, 108, 21
End Dialog

Note that each dialog box control has its own instruction within the dialog box definition. The first pair of numbers that follows each instruction for a control positions the control relative to the upper-left corner of the dialog box; the second pair defines the control's width and height.

Controls that store a value, such as combo boxes and check boxes, include in their instructions identifiers that begin with a period. For example, the CheckBox instruction includes the identifier .CheckBox1. These identifiers are used to access the control's value or setting in a dialog record.

To see the full syntax for a dialog box definition statement such as CheckBox or ListBox, see the corresponding entry in Part 2, "WordBasic Reference."

Creating a Dialog Record

A dialog record stores the values that you put into and retrieve from a dialog box. A dialog record for a custom dialog box is defined in much the same way as one for a built-in Word dialog box:

Dim DialogRecord As UserDialog

The DialogRecord argument can be any variable name. As UserDialog identifies the dialog record as the record for a custom dialog box (just as As FormatFont in a Dim instruction identifies a dialog record for the Font dialog box). You can include as many custom dialog boxes in a macro as you need, but you can define only one UserDialog record at a time.

Placing Values into a Dialog Box

It's often necessary to place initial values into a custom dialog box and to specify the default settings of some controls before the dialog box is displayed. The values you can place in a dialog box and the settings you can control include the following:

  • The items in a list box, drop-down list box, or combo box
  • The default text in a text box
  • Check box values
  • The initial focus (the item that has the focus when the dialog box is first displayed)

Placing Items into a List Box, Drop-Down List Box, or Combo Box

The items displayed in a list box, drop-down list box, or combo box control are stored as elements of an array. Therefore, before you display a dialog box containing one of these controls, you must define an array and fill it with the items to be listed; you then refer to the array in the instruction for the control in the dialog box definition. For example, if you want a dialog box to present a list of fonts, as in the following illustration, you first create an array to hold the font names.

Here are the instructions that define and fill an array, FontArray$(), for the font names:

lastElement = CountFonts() - 1
Dim FontArray$(lastElement)                'Define the array
For count = 0 To lastElement                'Fill the array
    FontArray$(count) = Font$(count + 1)
Next

To place the array elements into a list box, you refer to the array in the ListBox instruction. For example:

ListBox 10, 25, 160, 84, FontArray$(), .ListBox1

Putting it all together, here are the complete instructions for displaying the Show Font List dialog box in the preceding illustration. The array is defined first, then the dialog box, and finally the dialog record used in the Dialog() instruction to display the dialog box.

lastElement = CountFonts() - 1
Dim FontArray$(lastElement)                'Define the array
For count = 0 To lastElement                'Fill the array
    FontArray$(count) = Font$(count + 1)
Next
Begin Dialog UserDialog 362, 122, "Show Font List"
    ListBox 10, 9, 206, 100, FontArray$(), .FontList
    OKButton 265, 7, 88, 21
    CancelButton 265, 31, 88, 21
End Dialog
Dim dlg As UserDialog                    'Define the dialog record
buttonchoice = Dialog(dlg)                'Display the dialog box

Placing Default Text in a Text Box and Setting Check Box Values

A text box — a box in which the user can enter text — is usually empty when the dialog box is first displayed. But in some cases, you may want to place default text in a text box. For example, in the following dialog box the user is prompted to type his or her name and phone number. Most of the time that text will not change, so rather than force the user to type the text each time the dialog box is displayed, you can make the name and phone number default text.

You place default text in a text box (or combo box) by assigning it to the dialog identifier that corresponds to the text box. Recall that the dialog record contains a value corresponding to the identifier for each dialog box control that can return a value. The identifier is part of the instruction that defines the control. The following instructions define the text boxes in the Personal Info dialog box shown in the previous illustration:

TextBox 7, 21, 160, 18, .Name$
TextBox 7, 64, 160, 18, .Phone$

Note that .Name$ and .Phone$ are the identifiers for the text boxes (the dollar signs ($) aren't necessary, but indicate that the fields in the dialog record corresponding to these identifiers hold string values). You could use the following instructions to assign default text to these identifiers, where PersonalInfoDlgRec is the name of the dialog record:

PersonalInfoDlgRec.Name = "Michel Gabor"
PersonalInfoDlgRec.Phone = "(206) 555-1234"

Of course, you must define a dialog record before you can assign values to identifiers within it. Here are the complete instructions to display the dialog box:

Begin Dialog UserDialog 320, 102, "Personal Info"
    Text 7, 5, 89, 13, "Your &Name:"
    TextBox 7, 21, 160, 18, .Name$
    TextBox 7, 64, 160, 18, .Phone$
    Text 7, 47, 157, 13, "Your &Phone Number:"
    OKButton 225, 3, 88, 21
    CancelButton 225, 27, 88, 21
End Dialog
Dim PersonalInfoDlgRec As UserDialog            'Define dialog record
PersonalInfoDlgRec.Name$ = "Michel Gabor"    'Assign value to .Name$
PersonalInfoDlgRec.Phone$ = "(206) 555-1234"    'Assign value to .Phone$
x = Dialog(PersonalInfoDlgRec)                'Display dialog box

You can use the same method of assigning values to text boxes to specify the initial setting of a check box. After defining the dialog record, you assign one of three values to the identifier for the check box: 0 (zero) to clear the check box (this is the default), 1 to select the check box, and –1 to make it indeterminate.

Setting the Initial Focus and Tab Order

When a control is active, it is said to have the focus, which means that you can act on it. For example, if a text box has the focus, you can type in it. You can use the tab key to move the focus and activate controls in a dialog box. The tab order is the order in which controls become active when you use the tab key to move to them. The tab key is particularly useful for dialog boxes that contain more than one text box; if you're typing in a text box, it's natural to use the tab key to move to the next text box.

The control that has the focus when the dialog box is first displayed is said to have the initial focus. The initial focus is important in dialog boxes in which the user is prompted to type something. For example, in the dialog box shown in the following illustration, the initial focus should be on the Fax Number text box. If it isn't and the user starts typing, nothing will happen; the dialog box will seem not to work properly.

The order of the instructions within the dialog box definition determines the initial focus and the tab order: The first control in a dialog box definition has the initial focus, the second control has the focus next, and so on. Items that cannot be active, such as the text control, are ignored. (On the Macintosh, only text box and combo box controls can have the focus.)

Here are the instructions for the Fax Info dialog box shown in the previous illustration. Note that the first instruction is a Text instruction. Since a text control cannot have the focus, the initial focus is on the text box defined by the TextBox instruction.

Begin Dialog UserDialog 370, 92, "Fax Info"
    Text 14, 7, 96, 13, "Fax Number:"
    TextBox 14, 23, 160, 18, .TextBox1
    CheckBox 14, 57, 211, 16, "Add To Fax Number List", .FaxList
    OKButton 270, 6, 88, 21
    CancelButton 270, 30, 88, 21
End Dialog
Dim dlg As UserDialog
buttonchoice = Dialog(dlg)

Displaying the Dialog Box

You use the Dialog statement or the Dialog() function to display a custom dialog box in the same way that you can use them to display a dialog box built into Word.

In general, the Dialog() function rather than the Dialog statement is the best choice for custom dialog boxes. If you use the Dialog statement, Word generates an error if the user chooses the Cancel button in the dialog box. You can use the On Error statement to handle this error, but you can avoid it entirely by using the Dialog() function. Also, if your dialog box contains a push button, you need to use the Dialog() function to determine whether the push button was chosen (or which one was chosen if the dialog box contains more than one).

For complete information on the Dialog statement and the Dialog() function, see the entry in Part 2, "WordBasic Reference."

The Default Command Button

You can use the DefaultButton argument of the Dialog statement or the Dialog() function to determine the default command button. The default command button is the button that is highlighted when the dialog box is first displayed. It is also the command button that is chosen if a control other than a command button has the focus when the user presses ENTER. Unless you specify otherwise, the OK button is the default command button.

For the DefaultButton argument to have any effect, the instruction for the specified button must be preceded in the dialog box definition by an instruction for a non-command button dialog box control that can receive the focus, such as a list box or check box. (Note that because a text control cannot receive the focus, it does not meet this criterion.) Otherwise, the first button in the dialog box definition is the default command button.

Retrieving Values from the Dialog Box

Once a custom dialog box has been displayed and the user has closed it, the macro can retrieve the settings of the dialog box controls. These values are stored in the dialog record, so retrieving values is a matter of accessing the appropriate identifiers in the dialog record.

The following table shows the values that different dialog box controls store in the dialog record.

Control | Value stored in the dialog record
Check box | If the check box is selected, 1; if the check box is clear, 0 (zero); if the check box is indeterminate, –1
Option group | A number corresponding to the option button selected
List box or drop-down list box | The number of the item chosen, beginning with 0 (zero)
Combo box | A text string (what the user typed or selected in the list of items)
Text box | A text string

Examples

The following example tests the value of the Add To Fax Number List check box in the Fax Info dialog box (shown in the following illustration) to determine whether the user selected that control.

Two nested If conditionals are used to test two conditions. The first If instruction uses the condition buttonchoice = -1 to test whether the user chose the OK button to dismiss the dialog box (Dialog() returns –1 if the user chose the OK button). If this condition is true, the second If instruction tests the value of the Add To Fax Number List check box, which is stored in dlg.FaxList. If the check box is selected, meaning the fax number should be added to the list of fax numbers, the dialog record identifier for the check box is equal to 1. The macro then runs the instructions to add the fax number to the list of numbers.

Begin Dialog UserDialog 370, 92, "Fax Info"
    Text 14, 7, 96, 13, "Fax Number:"
    TextBox 14, 23, 160, 18, .TextBox1
    CheckBox 14, 57, 211, 16, "Add To Fax Number List", .FaxList
    OKButton 270, 6, 88, 21
    CancelButton 270, 30, 88, 21
End Dialog
Dim dlg As UserDialog
buttonchoice = Dialog(dlg)
If buttonchoice = -1 Then
    If dlg.CheckBox1 = 1 Then
        'Series of instructions to add fax number to list.
    End If
End If

The following example formats the selected text with the font selected in the Show Font List dialog box shown in the following illustration.

As in the previous example, the If instruction tests whether the user chose the OK button to dismiss the dialog box (rather than the Cancel button to indicate that the dialog box should not carry out an action). If the user chose the OK button, the instruction Font FontArray$(dlg.FontList) formats the selection with or prepares to insert text in the font the user selected in the dialog box. The FontArray$() array stores the names of the fonts displayed in the dialog box. The dlg.FontList setting in the dialog record contains the number of the font selected in the list box.

Begin Dialog UserDialog 362, 122, "Show Font List"
    ListBox 10, 9, 206, 100, FontArray$(), .FontList
    OKButton 265, 7, 88, 21
    CancelButton 265, 31, 88, 21
End Dialog
Dim dlg As UserDialog                    'Define the dialog record
buttonchoice = Dialog(dlg)                'Display the dialog box
If buttonchoice = - 1 Then
    Font FontArray$(dlg.FontList)        'Format selected text
End If


Using Dynamic Dialog Boxes

A dynamic dialog box is one whose contents can change while it is displayed. Many dialog boxes built into Word are dynamic in this sense. For example, the Open dialog box (File menu) is a dynamic dialog box: If you double-click a folder, Word updates the list of files to show the files in the folder you double-clicked.

What Can You Do with a Dynamic Dialog Box?

Here are some examples that demonstrate the capabilities of dynamic dialog boxes. The macros that produce the sample dialog boxes shown in this section are stored in the EXAMPLES.DOT template (Windows) and the MACRO EXAMPLES template (Macintosh) on the Microsoft Word Developer's Kit disk.

Change button names and other text

It can be useful to change the names of buttons and other controls in a dialog box in response to an action. When you choose the Start button in the StopWatch custom dialog box shown in the following illustration, the Start button becomes the Stop button, and the Pause button is enabled. While the dialog box is displayed, the text label that displays the time is updated every second.

Update lists

In a dynamic dialog box, the list of items in a list box can change in response to a user's actions. For example, in the File Browser custom dialog box, shown in the following illustration, the user can double-click a directory in the Directories list box, and the list of files and directories changes in the two list boxes.

Show or hide parts of the dialog box

You can create a dialog box with more than one "panel" of controls, in which one panel is displayed and one or more other panels are hidden. This sort of dialog box is similar to the dialog boxes built into Word that have "tabs" with which you can display different controls. In the Master Document Macro custom dialog box, you can click the Master Document or Subdocuments option buttons to display two different panels of controls.

Display a built-in dialog box

It is sometimes useful to provide access from within a custom dialog box to a dialog box built into Word. In the Close File custom dialog box, shown in the following illustration, you can choose the Word Count button to check the word count of the file before closing it. When you dismiss the Word Count dialog box, you return to the Close File dialog box. Note that you cannot display a second custom dialog box while the Close File dialog box is displayed; only one custom dialog box can be displayed at a time.

Enable and disable controls

With a dynamic dialog box, you can enable and disable controls as appropriate. In the Add File custom dialog box shown in the following illustration, the Info To Record option buttons are disabled by default but are enabled if the user selects the Record Addition In Log check box.

How to Make a Dialog Box Dynamic

A dynamic dialog box begins with a standard dialog box definition. You then add three elements to make the dialog box dynamic:

  • A dialog function. The dialog function responds to events and changes the appearance of the dialog box. The dialog function, in short, is what makes a dialog box dynamic. All the instructions that are carried out while the dialog box is displayed are either placed within this function or in subroutines and user-defined functions called from this function.
  • A dialog function argument in the Begin Dialog instruction that calls the dialog function.
  • Identifiers for any dialog box controls that the dialog function acts on or gets information from. Most of the instructions in a custom dialog box definition already include identifiers for the controls they describe.

How a Dialog Function Works

When Word reads the Dialog or Dialog() instruction that displays the dialog box, it calls the dialog function and begins initializing the dialog box. Initialization happens between the time the dialog function is called and the time the dialog box appears on the screen. Word calls the dialog function and says, in effect, "Is there anything you'd like to do before the dialog box is displayed?" The dialog function can do nothing or can respond in some way.

Typical actions that a dialog function might take during initialization include disabling or hiding dialog box controls. By default, dialog box controls are enabled, so if you want a control to be disabled when a dialog box is first displayed, it must be disabled during initialization. Likewise, all dialog box controls are shown by default rather than hidden, so if you want to create a dialog box with more than one panel of controls, any controls that you don't want to show when the dialog box is first displayed must be hidden during initialization.

After initialization, Word displays the dialog box. When the user takes an action, such as selecting an option button, Word calls the dialog function and passes values to the function to indicate the kind of action taken and the control that was acted upon. For example, if the dialog box contains a list of graphics filenames, and you click one of the filenames, the dialog function will be called and could respond by displaying the selected graphics file in a picture control.

Word also calls the dialog function when the dialog box is "idle" — that is, while the user is not acting on the dialog box. In fact, as soon as the dialog box begins initializing and for as long as it is displayed, Word sends a continuous stream of idle messages to the dialog function — more than one a second. This stream is interrupted only when the user acts on the dialog box in some way. Most dialog functions are designed to ignore idle messages, but they can be used to continuously update a dialog box (as in the StopWatch custom dialog box example described earlier in this section).

Calling the Dialog Function

The link between the dialog box and its function is established in the dialog box definition. Specifically, a .FunctionName argument is added to the Begin Dialog instruction, where .FunctionName matches the name of the dialog function. Here's the syntax for the instruction:

Begin Dialog UserDialog [HorizPos, VertPos,] Width, Height, Title$, .FunctionName

Dialog Box Control Identifiers

A dialog function needs an identifier for each dialog box control that it acts on or gets information from. Normally, the dialog function uses string identifiers, but it can also use numeric identifiers. For information on numeric identifiers, see "Numeric Identifiers," which follows.

String identifiers are the same as the identifiers used with a dialog record. If you use the Dialog Editor to create a dialog box, the Dialog Editor automatically creates an identifier for any control that can store a value in a dialog record. For example, in the following instruction, .CheckBox1 is the string identifier created by the Dialog Editor:

CheckBox 398, 24, 109, 16, "Check Box", .CheckBox1

Don't confuse a dialog box control's label and its identifier. An identifier begins with a period (.) and is the last argument in a dialog box control instruction. In the previous instruction, "Check Box" is a check box label and .CheckBox1 is its identifier.

Unlike other elements of WordBasic, string identifiers are case-sensitive. When an instruction in a dialog function refers to an identifier, it must match the case of the identifier.

Numeric Identifiers

Numeric identifiers are an alternative way of referring to dialog box controls. You can use numeric identifiers to improve the performance of a dialog function when a dialog box contains many controls. But instructions that use numeric identifiers are more difficult to read than instructions that use string identifiers.

Numeric identifiers are numbers, starting at 0 (zero), that correspond to the positions of dialog box control instructions within a dialog box definition. The following example shows the numeric identifiers for four dialog box controls. Note that the numeric identifier is not included in the instruction for a dialog box control; the number associated with a control is determined by the control's place within the dialog box definition. If the position of the control changes, so does its numeric identifier. For example, in the following dialog box definition, the Text instruction is first and so has a numeric identifier of 0 (zero). If you moved the instruction so that it was the last one in the dialog box definition, it would have an identifier of 3 (assuming no new instructions were added).

Begin Dialog UserDialog 370, 92, "Fax Info"
    Text 14, 7, 96, 13, "Fax Number:"        'Numeric identifier is 0
    TextBox 14, 23, 160, 18, .Fax$            'Numeric identifier is 1
    OKButton 270, 6, 88, 21                    'Numeric identifier is 2
    CancelButton 270, 30, 88, 21                'Numeric identifier is 3
End Dialog

Dialog Function Syntax

A dialog function is just like any other user-defined function except that it takes three required arguments. The syntax is as follows:

Function FunctionName(ControlID$, Action, SuppValue)
Series of instructions to determine a value
FunctionName = value
End Function

The function will generate an error if one of the three mandatory arguments — ControlID$, Action, and SuppValue — is missing or if an additional argument is added. The arguments are variables, however, and you can use any variable name you want. For example, you could use id$ instead of ControlID$ as the name for the first argument.

A dialog function returns a value when the user chooses a command button — the OK button, Cancel button, or a push button. Word acts on the value returned by either closing the dialog box associated with the function or continuing to display it. By default, the dialog function returns 0 (zero), which causes Word to close the dialog box, regardless of which button was chosen. But if you assign a nonzero value to the dialog function, the dialog box remains displayed. By keeping the dialog box displayed, the dialog function allows the user to carry out more than one command from the same dialog box. For examples, see "Responding to a Double-Click" and "Responding to a Push Button" later in this chapter.

The DialogFunctionDemo macro, stored in the EXAMPLES.DOT template (Windows) and the MACRO EXAMPLES template (Macintosh) on the Microsoft Word Developer's Kit disk, displays the values of the arguments passed to a dialog function while a custom dialog box is displayed. You may find this macro, along with the following discussion, a useful starting place when you begin to work with dialog functions.

Here is a closer look at each dialog function argument.

ControlID$

Receives the identifier string of the dialog box control associated with a call to the dialog function. For example, if the user selects a check box, the dialog function is called and the ControlID$ argument receives the identifier for the check box.

Action

Identifies the action that calls the dialog function. There are six possible actions that can call the dialog function, each with a corresponding Action value.

Action value | Meaning
1 | Corresponds to dialog box initialization. This value is passed before the dialog box becomes visible.
2 | Corresponds to choosing a command button or changing the value of a dialog box control (with the exception of typing in a text box or combo box). When Action is 2, ControlID$ corresponds to the identifier for the control that was chosen or changed.
3 | Corresponds to a change in a text box or combo box. This value is passed when a control loses the focus (for example, when the user presses the TAB key to move to a different control) or after the user clicks an item in the list of a combo box (an Action value of 2 is passed first). Note that if the contents of the text box or combo box do not change, an Action value of 3 is not passed. When Action is 3, ControlID$ corresponds to the identifier for the text box or combo box whose contents were changed.
4 | Corresponds to a change of control focus. When Action is 4, ControlID$ corresponds to the identifier of the control that is gaining the focus. SuppValue corresponds to the numeric identifier for the control that lost the focus. A dialog function cannot display a message box or dialog box in response to an Action value of 4.

Action value | Meaning
5 | Corresponds to an idle state. As soon as the dialog box is initialized, Word continuously passes an Action value of 5 while no other action occurs. If the dialog function responds to an Action value of 5, the dialog function should return a nonzero value. (If the dialog function returns 0 (zero), Word continues to send idle messages only when the mouse moves.) When Action is 5, ControlID$ is an empty string (""); SuppValue corresponds to the number of times an Action value of 5 has been passed so far.
6 | Corresponds to the user moving the dialog box. This value is passed only when screen updating is turned off (using a ScreenUpdating instruction). When screen updating is turned off and the user moves the dialog box, the screen is refreshed once. As a result, any changes that were made by the macro after screen updating was turned off will suddenly appear. A dialog function can prevent this problem by responding to an Action value of 6 and controlling what will be displayed when the screen refreshes. For example, if a new document (created after screen updating was turned off) deactivates the visible document, the dialog function could activate the visible document again. Note that Word does not refresh the screen until after an Action value of 6 has been passed and the dialog function has ended. When Action is 6, ControlID$ is an empty string (""); SuppValue is equal to 0 (zero).

SuppValue

Receives supplemental information about a change in a dialog box control. The information SuppValue receives depends on which control calls the dialog function. The following SuppValue values are passed when Action is 2 or 3.

Control | SuppValue passed
List box, drop-down list box, or combo box | Number of the item selected, where 0 (zero) is the first item in the list box, 1 is the second item, and so on
Check box | 1 if selected, 0 (zero) if cleared
Option button | Number of the option button selected, where 0 (zero) is the first option button within a group, 1 is the second option button, and so on
Text box | Number of characters in the text box
Combo box | If Action is 3, number of characters in the combo box
Command button | A value identifying the button chosen. This value is not often used, since the same information is available from the ControlID$ value. If the OK button is chosen, SuppValue is 1; if the Cancel button is chosen, SuppValue is 2. The SuppValue for push buttons is an internal number used by Word. This number is not the same as the numeric identifier for a push button, but it does change if the instruction that defines the push button changes position within the dialog box definition.

Dialog Functions and Variables

Like variables in other user-defined functions, variables defined in a dialog function lose their values when the function ends. A dialog function is available for as long as a dialog box is displayed, so it's easy to imagine that variables in the dialog function last that long as well. But the dialog function is called not once but many times while the dialog box is displayed, and the dialog function's variables lose their values after each call. If you need variables used in a dialog function to last as long as a dialog box is displayed, you must use the Dim statement to declare them as shared variables.

Pressing ESC to Cancel a Dynamic Dialog Box

Normally, you can press ESC to cancel a dialog box—to cancel any settings you might have changed and close the dialog box. If you press ESC while a dynamic dialog box is displayed, however, Word interrupts the macro. (In Windows, the dialog box remains displayed when the macro is interrupted; on the Macintosh, it disappears, but will reappear if you choose the Continue button on the Macro toolbar to continue running the macro.) You can include a DisableInput instruction to allow the ESC key to cancel a dynamic dialog box. The DisableInput instruction must run before the ESC key is pressed. If you only want to disable the macro-interrupting capability of the ESC key while the dynamic dialog box is displayed, a good strategy is to place a DisableInput 1 instruction immediately before the Dialog() instruction that displays the dialog box and a DisableInput 0 instruction immediately after it. For example:

DisableInput 1 'Prevent ESC key from interrupting

choice = Dialog(dlg) 'Display dynamic dialog box

DisableInput 0 'Allow ESC key to interrupt

Dialog Function Techniques

This section provides examples that demonstrates how to carry out common dialog function tasks. These examples use a set of WordBasic statements and functions used only within dialog functions. You can recognize these statements and functions in that they all begin with "Dlg." For example, DlgEnable and DlgFocus are two statements used only in dialog functions. For a complete list of these statements and functions, see "Statements and Functions Used in Dialog Functions" later in this chapter. The macros shown in this section are stored in the EXAMPLES.DOT template (Windows) and the MACRO EXAMPLES template (Macintosh) on the Microsoft Word Developer's Kit disk.

Responding to Clearing or Selecting a Check Box

When the user selects or clears a check box, Word calls the dialog function. In the following example, a dialog function causes an option button group to be enabled or disabled when the user selects or clears the Record Addition In Log check box.

Word passes these values to the dialog function when the user selects or clears a check box: an Action value of 2, a ControlID$ value containing the identifier for the check box, and a SuppValue that indicates whether the check box is selected or cleared.

The following dialog function uses a Select Case control structure to check the value of Action. (The SuppValue is ignored in this function.) An If conditional then checks the value of the ControlID$. If the identifier is "RecordAddition" — the identifier assigned to the Record Addition In Log check box — DlgEnable either enables or disables the option buttons. Because the option buttons are disabled when the dialog box is first displayed and the check box is cleared, selecting the check box corresponds to enabling the option buttons.

Sub MAIN
Begin Dialog UserDialog 376, 158, "Add File ", .EnableFunction
    Text 8, 10, 73, 13, "Filename:"
    TextBox 8, 26, 160, 18, .Filenametext
    CheckBox 8, 56, 203, 16, "Record Addition in Log", .RecordAddition
    GroupBox 8, 79, 356, 70, "Info to Record:", .Group
    OptionGroup  .InfoChoice
        OptionButton 18, 100, 189, 16, "Author Information", .Authorinf
        OptionButton 18, 118, 159, 16, "File History", .History
    OKButton 277, 8, 88, 21
    CancelButton 277, 32, 88, 21
End Dialog
Dim dlg As UserDialog
DisableInput 1
x = Dialog(dlg)
DisableInput 0
End Sub

Function EnableFunction(id$, action, suppval)
Select Case action
Case 1                                'Dialog box initializes
    DlgEnable "Group", 0                'Disable group box
    DlgEnable "InfoChoice", 0        'Disable option buttons
Case 2                                'User selects a dialog box option
    If id$ = "RecordAddition" Then
        DlgEnable "Group"            'Enable/disable group box
        DlgEnable "InfoChoice"        'Enable/disable option buttons
    End If
Case Else
End Select
End Function

Responding to Selecting an Item in a List Box, Drop-Down List Box, or Combo Box

Word calls the dialog function associated with a dialog box when the user selects an item in a list box, drop-down list box, or combo box. The dialog function can identify the item selected and act accordingly. In the following example, the dialog box presents a list of graphics and displays the graphic corresponding to the selected name. When the user selects a different name, the dialog function changes the graphics display.

In the following dialog function, the If conditional tests for an Action value of 2, which indicates that the user has acted on a control. A nested If conditional then tests ControlID$ to see if the user acted on the list box, which has the identifier "ListBox1." Then the DlgText$() function is used to return the text of the item selected in the list box. The text is the name of a graphic stored in an AutoText entry, which the DlgSetPicture instruction then displays. The dialog box definition that defines the dialog box is not shown in this example.

Function ShowPicture(id$, action, suppval)
If action = 2 Then     'The user selects a control
    If id$ = "ListBox1" Then
        picturename$ = DlgText$("ListBox1")
        DlgSetPicture "Picture1", picturename$, 1
    End If
End If
End Function

Responding to a Double-Click

In most built-in dialog boxes in Word, you can double-click an option button or an item in a list to close the dialog box and carry out the settings of the dialog box. Double-clicking is usually a shortcut for selecting an item and then choosing the OK button. Custom dialog boxes work this way by default.

In some Word dialog boxes, though, double-clicking an item in a list does not close the dialog box. For example, in the Open dialog box (File menu), when you double-click a folder, Word displays the files in that folder and does not close the dialog box. Using a dialog function, you can make a custom dialog box behave in the same way. The following example shows how a custom dialog box allows the same action.

Here is the dialog function, with some instructions removed for clarity:

Function FileBrowserFunction(id$, action, suppval)
If action = 2 Then
    If id$ = "OK" And DlgFocus$() = "listdirs" Then
        'Series of instructions to update the directory and file lists
        FileBrowserFunction = 1
    End If
End If
End Function

The first If conditional tests for an Action value of 2, meaning that the user has acted on a control. The nested If conditional then tests for two conditions: when the ControlID$ value is "OK" (the identifier for the OK button) and when the focus is on the Directories list box (whose identifier is "listdirs"). This compound condition is met only when the user double-clicks an item in the Directories list box (if the user clicks just once, the ControlID$ is "listdirs" rather than "OK").

The final key instruction is FileBrowserFunction = 1. By default, when the user chooses a command button such as the OK button, Cancel button, or a push button, Word closes the dialog box. In this case, when the user double-clicks an item in a list box, it has the same effect. But a dialog box remains displayed if the dialog function returns a nonzero value; that is the purpose of the FileBrowserFunction = 1 instruction.

The technique described here works not only with the OK button, but with any default command button specified with the DefaultButton argument of a Dialog() instruction. The dialog box does not need to contain an OK button. For more information on setting a default command button, see "Displaying the Dialog Box" earlier in this chapter or Dialog in Part 2, "WordBasic Reference."

Responding to a Push Button

In the following example, the user can choose the Word Count button to display the built-in Word Count dialog box; the Close File custom dialog box remains displayed and will be available when the user closes the Word Count dialog box. Note that you cannot display a second custom dialog box while the Close File dialog box is displayed; only one custom dialog box can be displayed at a time.

Here is the dialog function, with some instructions removed for clarity. The key instruction that allows the Close File dialog box to remain displayed after the Word Count button is chosen is CloseFileFunction = 1, which causes the dialog box to remain displayed.

Function CloseFileFunction(id$, action, suppval)
If action = 2 Then
    If id$ = "wordcount" Then
        'Series of instructions to display the Word Count dialog box
        CloseFileFunction = 1
    End If
End If
End Function

Responding to Typing in a Text Box or Combo Box

After the user types in a text box or combo box and uses the mouse or the TAB key to move to a different dialog box control, Word calls the dialog function and passes the following values:

  • A ControlID$ value equal to the identifier of the text box or combo box
  • An Action value of 3 (rather than 2, as with all the other controls)
  • A SuppValue value indicating the number of characters the user typed

In the following example, the dialog function is called when the user leaves the first text box. If the user does not type a valid social security number, the dialog function displays a message box.

Here is the dialog function:

Function TestNumber(id$, action, suppval)
    If action = 3 Then
            If id$ = "socsecnum" And suppval <> 11 Then
                MsgBox "Not a valid " + Chr$(13) + \
                         "social security number."
                wrongnumberflag = 1
            End If
    ElseIf action = 4 Then
            If wrongnumberflag = 1 Then
                DlgFocus "socsecnum"
                wrongnumberflag = 0
            End If
    End If
End Function

Note that the function tests for Action values 3, corresponding to a text change, and 4, corresponding to a change of focus. When an Action 3 value is passed, the function uses the SuppValue argument to test the number of characters in the text box. If the number of characters doesn't correspond to the number required for a correct social security number, the dialog function displays a message box and sets the variable wrongnumberflag to 1. Immediately after the Action 3 value is passed, an Action value of 4 is passed. If wrongnumberflag is set to 1, the dialog function returns the focus to the social security text box and resets wrongnumberflag to 0 (zero). You cannot use the DlgFocus statement when Action has a value of 3, because the Action 4 value that follows overrides it, changing the focus back to wherever the user intended to move it. Hence the wrongnumberflag variable is needed to indicate whether the focus should be changed when the Action 4 value is passed.

Responding to a Change in the Focus

Whenever the user moves the focus from one dialog box control to another, Word calls the dialog function and passes the following values:

  • A ControlID$ value equal to the identifier for the control that is gaining the focus
  • An Action value of 4
  • A SuppValue value corresponding to the numeric identifier for the control that lost the focus

In the following example, the dialog function changes the "banter" text (the text that appears at the bottom of the dialog box) according to which control has the focus. For example, when the focus is on the Phone Number text box, the dialog function changes the banter text to read "Please enter a phone number."

The following instructions would be added to the Action 4 instructions in the TestNumber dialog function (shown in the previous example) to include the banter text functionality:

If id$ = "socsecnum" Then
    DlgText$ "Text1", "Please enter a social security number."
ElseIf id$ = "phone" Then
    DlgText$ "Text1", "Please enter a phone number."
End If

Displaying More Than One Panel of Controls

Dialog functions let you define more than one panel of controls in a dialog box. By organizing controls into panels, you can present a large number of controls in a single dialog box. This example shows a two-panel dialog box.

To create a two-panel dialog box, you use the Dialog Editor to design two separate dialog boxes corresponding to the two panels of the single dialog box; you then merge the two dialog box definitions into a single definition. When Word first displays the dialog box, one of the panels must be hidden; you'll have a mess if both panels are displayed at the same time.

When the dialog box in the following illustration is first displayed, it shows the Subdocuments controls, which means that the Master Document controls must be hidden while the dialog box is being initialized.

To hide the controls in the Master Document panel, the dialog function calls a subroutine named ShowHidePanel:

Sub ShowHidePanel(FirstCtrl, LastCtrl, ShowOrHide)
For count = FirstCtrl To LastCtrl
    DlgVisible count, ShowOrHide
Next
End Sub

In this subroutine, a For ¼ Next loop and a DlgVisible instruction are used to show or hide controls in a panel. The instructions to define the Master Document controls are grouped together in the dialog box definition. They have the numeric identifiers 13 through 18 (the first Master Document control is the thirteenth instruction within the dialog box definition). The For ¼ Next loop counts from FirstCtrl to LastCtrl—13 to 18, in this case. For each iteration, the DlgVisible instruction shows or hides the control with the numeric identifier count. If the ShowOrHide variable is 1, DlgVisible shows the controls; if it is 0 (zero), DlgVisible hides them.

In Word version 6.0 for the Macintosh and Windows NT and in Word version 7.0, a single DlgVisible instruction can be used to show or hide a range of controls, so a separate subroutine such as ShowHidePanel is not needed. For example, to hide the Master Document controls in the preceding example, the dialog function would simply run the following instruction:

DlgVisible 13, 18, 0

For more information, see DlgVisible in Part 2, "WordBasic Reference."

To switch panels while the dialog box is displayed, the dialog function must hide the panel of controls currently displayed and show the other panel. Here is the If conditional that checks which panel is selected. Note that Case 2 matches an Action value of 2, which indicates that the user has acted on a control.

Case 2
    If identifier$ = "masterdocs" Then
        ShowHidePanel 13, 18, 1            'Show master doc controls
        ShowHidePanel 7, 12, 0            'Hide subdoc controls
    ElseIf identifier$ = "subdocs" Then
        ShowHidePanel 13, 18, 0            'Hide master doc controls
        ShowHidePanel 7, 12, 1            'Show subdoc controls
    End If

The If conditional calls the ShowHidePanel subroutine and uses it to show or hide the panels as appropriate.

Numeric identifiers and For ¼ Next loops provide an efficient way to manipulate panels of controls. Since the numeric identifier of a control depends on its place within the dialog box definition, you must be careful about changing the order of instructions within the dialog box definition.

The wizards that come with Word use this technique to manage the panels of a wizard dialog box. For a detailed description of managing panels in wizards, see "Creating a Wizard" in Chapter 9, "More WordBasic Techniques."

Tip

Many Word dialog boxes with tabs "remember" which tab was selected when the dialog box was last closed. The theory is that the user is most likely to want to use the panel of controls that was last displayed. You can achieve this effect in WordBasic by storing the final dialog box setting in a settings file. For information on using settings files, see Chapter 9, "More WordBasic Techniques."

Updating Text Continuously in a Dialog Box

You can use a dialog function to update a dialog box continuously. In the example shown and described here, the dialog function updates the text item displaying the time elapsed every second.

Here is the dialog function, with all but one Case in the Select Case control structure removed for clarity:

Function Stopwatch(id$, action, suppval)
Select Case action
    Case 5
        If startflag = 1 Then
            newnow = (Now() - oldnow)
            thissecond$ = LTrim$(Str$(Second(newnow)))
                If thissecond$ <> thissecondold$ Then
                    thishour$ = Str$(Hour(newnow))
                    thisminute$ = LTrim$(Str$(Minute(newnow)))
                    fullstring$ = thishour$ + ":" + thisminute$ + ":"\
                                     + thissecond$
                    DlgText$ "Text1", fullstring$
                    thissecondold$ = thissecond$
                End If
        End If
        Stopwatch = 1
    Case Else
End Select
End Function

Word begins sending "idle" (Action 5) messages to the dialog function as soon as the dialog box is initialized. As long as no other action takes place, Word continues sending this idle message until the dialog box is closed. However, the text should only update after the user chooses the Start button. Therefore, all the statements following Case 5 depend on whether startflag is equal to 1 (earlier in the dialog function, startflag is set to 1 when the user chooses the Start button); if startflag is not equal to 1, the text is not updated.

A second point to observe is that Word sends idle messages to the dialog function at the rate of more than one a second. If the text were updated each time it received the idle message, the text would be jittery. The second If conditional therefore tests whether the time has changed and only updates the text every second. Note that startflag and thissecondold$ must be declared as shared variables before the main subroutine; if they were not declared as shared variables, they would lose their value each time the dialog function was called.

Storing and Loading Dynamic Dialog Box Settings

It's often useful to store a dialog box's settings when the user closes it and to load the settings the next time the dialog box is displayed so that the settings are the same as the ones the user last saw. For example, the dialog box for the Master Document macro, shown in the following illustration, contains a number of check boxes whose settings it would be useful to save.

In Windows, you use the SetPrivateProfileString and GetPrivateProfileString$() instructions to store dialog box settings. For information on using these instructions, see "Using Settings Files and Document Variables" in Chapter 9, "More WordBasic Techniques."

On the Macintosh, you can use the DlgStoreValues and DlgLoadValues() instructions to store and load settings. Unlike SetPrivateProfileString and GetPrivateProfileString$(), which require a separate instruction for each setting stored or loaded, a single DlgStoreValues or DlgLoadValues() instruction can store or load all of the settings in a dialog box. For dialog boxes with a large number of settings to store and load, DlgStoreValues or DlgLoadValues() offer a significant improvement in performance. DlgStoreValues and DlgLoadValues() require a dialog function; if you want to use them with a dialog box that would not otherwise need a dialog function, you can simply create a dialog function just for these intstructions.

The following dialog function (with some instructions removed for clarity) shows how DlgStoreValues and DlgLoadValues() can be used to store and load check-box settings:

Function MyDlgFunction(id$, action, suppval)
Select Case action
    Case 1
        success = DlgLoadValues("Dialog Settings", "MasterDocDialog")
    Case 2
        If id$ = "OK" Then
            DlgStoreValues "Dialog Settings", "MasterDocDialog")
        End If
    Case Else
End Select
End Function

The DlgLoadValues() instruction runs when the dialog box is initialized (Action 1). The DlgStoreValues instruction runs when the the user closes the dialog box by choosing the OK button. Note that if the user closes the dialog box by choosing the Cancel button, the dialog box settings are not stored. By default, DlgStoreValues and DlgLoadValues() store and load most dialog box settings, but you can also control whether or not individual settings are stored and loaded. For more information, see DlgStoreValues and DlgLoadValues() in Part 2, "WordBasic Reference."

Statements and Functions Used in Dialog Functions

WordBasic includes a set of statements and functions that are used only within dialog functions. The statements act on dialog box controls and the dialog functions return information about them. For example, you use the DlgVisible statement to hide or display a dialog box control; DlgVisible() returns a value determined by whether the control is displayed or hidden.

For complete information on these statements and functions, see the corresponding entries in Part 2, "WordBasic Reference."

Statement or function | Action or result
DlgControlId() | Returns the numeric equivalent of Identifier$, the string identifier for a dialog box control.
DlgEnable, DlgEnable() | The DlgEnable statement is used to enable or disable a dialog box control. When a control is disabled, it is visible in the dialog box, but is dimmed and not functional. DlgEnable() is used to determine whether or not the control is enabled.
DlgFilePreview, DlgFilePreview$() | The DlgFilePreview statement is used to display a file in the file preview item. DlgFilePreview$() returns the path and filename of the document displayed.
DlgFocus, DlgFocus$() | The DlgFocus statement is used to set the focus on a dialog box control. (When a dialog box control has the focus, it is highlighted.) DlgFocus$() returns the identifier of the control that has the focus.
DlgListBoxArray, DlgListBoxArray() | The DlgListBoxArray statement is used to fill a list box or combo box with the elements of an array. It can be used to change the contents of a list box or combo box while the dialog box is displayed. DlgListBoxArray() returns an item in an array and the number of items in the array.
DlgLoadValues() | Loads dialog box settings. Available on the Macintosh only.
DlgSetPicture | Sets the graphic displayed in the Picture dialog box control.
DlgStoreValues | Stores dialog box settings. Available on the Macintosh only.
DlgText, DlgText$() | The DlgText statement is used to set the text or text label for a dialog box control. The DlgText$() function returns the text or label of a control.
DlgUpdateFilePreview | Updates a file preview item.
DlgValue, DlgValue() | The DlgValue statement is used to select or clear a dialog box control. The DlgValue() function returns the setting of a control.
DlgVisible, DlgVisible() | The DlgVisible statement is used to hide or show a dialog box control. The DlgVisible() function is used to determine whether a control is visible or hidden.


Chapter 6 Debugging

According to one of the most famous anecdotes in computing lore, computer pioneer Grace Hopper couldn't get her program to run one day and discovered that the problem was caused by a moth. The moth had become lodged in one of the computer's switches. When the moth was removed, Hopper reported that she had "debugged" the computer — hence the terms "bug," which has come to mean any error in a program, and "debugging," which means tracking down errors and removing them.

Debugging plays a part in developing all but the simplest macros. This chapter describes the kinds of errors you're likely to encounter and the debugging tools Word provides.

In this chapter:

  • Common WordBasic errors
  • Ways to avoid WordBasic errors
  • Debugging tools


Common WordBasic Errors

The WordBasic errors described in this section are errors that prevent a macro from running. These errors occur when an instruction breaks one of the rules that govern the way you can use the WordBasic language. Word displays an error message as soon as it encounters a line containing an error. If you have the macro open in a macro-editing window, Word highlights the offending line in red. Every WordBasic error message box contains a Help button. When you choose the Help button, Word provides suggestions about what may have caused the error.

Note

Word does not highlight all the errors in a macro at once. If you have many typos or syntax errors in your macro, you will get an error message each time you run your macro, until all the errors are corrected.

Syntax Error

This is by far the most common error message. The following are some of the causes of syntax error messages.

A missing quotation mark

A string must be enclosed by quotation marks. An error is generated if one or both are missing.

A missing, misplaced, or extra comma

Each argument for a statement or function must be separated by a comma. A missing, misplaced, or extra comma generates an error.

A missing period

Each argument for a statement that corresponds to a dialog box must begin with a period. For example, .FileName is an argument for the FileOpen statement.

A missing parenthesis at the end of a function

A function is always followed by an opening and closing parenthesis. A syntax error is generated if one or both are missing.

A missing reserved word

Some WordBasic instructions include more than one reserved word. For example, an If ¼ Then ¼ Else instruction must include the Then reserved word.

A reserved word name conflict

WordBasic generates a syntax error if you create a variable name that matches a reserved word. For example, a variable named "Then" conflicts with the reserved word Then, which is part of the If ¼ Then ¼ Else statement.

Type Mismatch

This error occurs when an instruction requires a particular data type but doesn't get it. Because there are only two data types in WordBasic — strings and numbers — the error means that a string was used when a number was required, or vice versa. In the following example, pet is meant to be a string variable, but it is missing a dollar sign ($), so Word interprets it as a numeric variable and generates an error:

pet = "poodle"            'Should be: pet$ = "poodle"

This error is also generated when you provide a function with an argument of the wrong type. Here is an example:

a$ = Str$("4")            'Should be: a$ = Str$(4)

Wrong Number of Parameters

This error is generated when a statement or function has too many or too few arguments (also known as "parameters"). Here are some examples:

a$ = Chr$()                'Chr$() requires an argument
a$ = Str$()                'Str$() requires an argument
a$ = Selection$(1)        'Selection$() does not take an argument
MsgBox                'MsgBox requires an argument
ChDir                'ChDir requires an argument

Unknown Command, Subroutine, or Function

This error message usually means that you have misspelled a function or statement name. It can also occur if you omit the dollar sign ($) from a function that returns a string. Each of the following instructions generates this error message:

MgsBox "Hello"            'Should be: MsgBox "Hello"
EditFnd "muskrat"        'Should be: EditFind "muskrat"
quote$ = Chr(34)            'Should be: quote$ = Chr$(34)

In addition, this error can occur if an instruction that should be two words is typed as one — EndDialog, for example, instead of End Dialog (though both EndIf and End If are accepted).

Undefined Dialog Record Field

This error message is displayed if you misspell the argument for a statement that corresponds to a dialog box, as in the following example:

EditFind "sasquatch", .WhleWord = 1            'Should be: .WholeWord = 1

The error also occurs if you include an argument that doesn't belong, as in the following:

EditFind "skunk", .WholeWord = 1, .Musk = 1    '"Musk" is not valid

Bad Parameter

This message is displayed if the value for an argument is outside the range of accepted values, as in the following example:

ChangeCase 50                        '"50" is too large a value

Duplicate Label

This error occurs if the macro includes two subroutines or user-defined functions with the same name. It also occurs if you create two Goto labels that have the same name.


Ways to Avoid WordBasic Errors

Whenever you type a new instruction, you run the risk of misspelling a reserved word or leaving out a comma or a period and thereby creating an error. The techniques described in this section can help you reduce errors by reducing the number of instructions you type from scratch.

Use the Record Next Command Button

The Record Next Command button

If you need to include an unfamiliar statement in your macro and can't remember the names for the arguments you need, use the Record Next Command button on the Macro toolbar to record the instruction. The Record Next Command button turns on the macro recorder and records the next command you choose; Word then inserts the corresponding instruction in the macro-editing window. If a macro-editing window is not open, the Record Next Command button does nothing.

To use the Record Next Command button, position the insertion point in a macro-editing window at the place where you want to insert the instruction. If the command you want to record is not available in the macro-editing window, switch to a document window. Click the Record Next Command button, and then choose the command you want to record. If the command has a dialog box associated with it, set the options you want in the dialog box and then choose the OK or Close button (if you choose the Cancel button, the command is not recorded).

If you need to switch to a document window to record a command, be sure to switch before clicking the Record Next Command button. Otherwise, Word will record your switch to the document window rather than recording the command you choose. Of course, if the command is available in the macro-editing window, you do not have to switch to a document window.

Copy Syntax from Help

As useful as the Record Next Command button is, you can't use it to record WordBasic functions, nor can you record statements that do not correspond to Word commands. For these statements and functions, copying from Help is the solution.

If you know the statement or function name, you can type it in a macro-editing window and then, with the insertion point on the same line, press F1 (Windows) or HELP or COMMAND+/ (Macintosh) to display the Help topic for that statement or function. The Help topic for each statement and function includes its complete syntax. You can use the syntax simply to jog your memory or you can copy it directly into your macro. Many topics offer examples you can copy as well.

Store Instructions as AutoText Entries

Another way to minimize errors is to store frequently used instructions as AutoText entries. The capitalized letters in statement and function names lend themselves to a consistent and easy-to-remember naming system. You could store the EndOfLine statement, for example, in an AutoText entry named "eol." You may also want to store frequently used control structures such as If conditionals. As a further refinement, you could record a macro that not only inserts an If conditional, but also moves the insertion point to an appropriate place within the control structure so that you can begin typing immediately. If you create AutoText entries as you're working on a macro, it's not much of a chore, and in a short time you'll have a collection of entries that can help you put macros together very quickly.


Debugging Tools

The Macro toolbar is displayed whenever you open a macro-editing window, and it provides a number of debugging tools. In addition, WordBasic includes some statements used primarily for debugging. This section describes these debugging tools and statements.

Trace

The Trace button

When you click the Trace button, Word runs the active macro and highlights each instruction as it runs it. Tracing happens very quickly because the macro runs at approximately its normal speed. Tracing can be useful for macros with many conditionals and loops, in which the flow is complex. You can use tracing to quickly determine, for example, whether a particular branch of an If control structure is run.

Of course, the macro-editing window must be visible, or you cannot see the instructions as they are highlighted. You can use the Arrange All command on the Window menu to layer a document window and a macro-editing window horizontally. You may also want to arrange the windows vertically, as in the following illustration, so that you can see more macro instructions at the same time.

Step

The Step button

The Step button, along with its close relative the Step Subs button, is probably the most useful debugging tool. You can use the Step button to run a macro literally step by step. Each time you click the Step button, Word highlights an instruction and pauses; when you click the Step button again, Word runs the instruction and highlights the next one. In this way, you can monitor the effect of each instruction in your macro. This capability is especially useful for macros that move the insertion point in complex ways.

As you're stepping through a macro, you can click the Stop button to stop running the macro or the Continue button to run the remaining instructions consecutively without pausing.

Note

If the active macro calls a subroutine or function in another macro, Word steps through the called subroutine or function as well. To see Word step through the instructions, open the macro or macros being called and arrange the macro-editing windows so they are all visible in the Word window before clicking the Step button.

Stepping through long macros can be inefficient, particularly if most of the macro works fine and you're stepping through a lot of instructions just to get to the one in which the problem occurs. The solution is to use a Stop instruction to pause the macro just before the point where the error occurs, and then use the Step button to step through the instructions that generate the error. For more information on using Stop, see "Statements Useful for Debugging" later in this section.

Step Subs

The Step Subs button

The Step Subs button works just like the Step button except that it doesn't step through subroutines or user-defined functions; it only steps through the main subroutine. This button is useful when you know that the problem you're trying to isolate is not contained in a macro's subroutines or user-defined functions. For macros with only a main subroutine, choosing this button has the same effect as choosing the Step button.

Show Variables

The Show Variables button

The Show Variables button displays the Macro Variables dialog box, in which you can see and change the values of variables. The Show Variables button is active only when the macro is paused. You can pause a macro by using the Step button to step through it, or you can use a Stop instruction to pause it at a certain point.

The Macro Variables dialog box can display variables defined in the main subroutine, variables defined in subroutines and user-defined functions, and variables shared by all subroutines; variables in the active subroutine are listed first. Variable names are preceded by the name of the subroutine or function for which they are defined, separated by an exclamation point. For example, in the following illustration, the string variable searchtext$ in the main subroutine is listed as MAIN!SEARCHTEXT$. The string variable owner$ in the FindAddress subroutine is listed as FINDADDRESS!OWNER$. The shared variable animal$ is listed as !ANIMAL$.

You can use the Set button in the Macro Variables dialog box to display the Set Variable dialog box, where you can change the value of the selected variable. It's particularly useful to change the values of variables that control loops. After running the loop enough times to test it, you can change the value of the controlling variable so that the macro can escape from the loop early.

Note

The Macro Variables dialog box does not display the values of array variables or dialog records. Use the MsgBox or Print statements to display the values of array elements.

Add/Remove REM

The Add/Remove REM button

One of the most useful debugging techniques is to deactivate part of your macro by "commenting it out." You do so by turning instructions into comments, either by placing an apostrophe (') in front of them or by placing a REM instruction in front of the line. The Add/Remove REM button does the latter.

For example, you may want to test a macro that includes an instruction to print a document, but you probably don't want to print each time you test the macro. The solution is to comment out the FilePrint instruction as follows:

REM   FilePrint "LETTER.DOC"

When you've finished testing the macro, you can select the instructions you commented out, and then click the Add/Remove REM button again to remove the REM statements and reactivate the instructions.

Statements Useful for Debugging

The following are WordBasic statements you can insert as instructions in your macro to assist in debugging.

Stop

When Word is running a macro and it encounters a Stop instruction, it pauses the macro at the Stop instruction. You can use a Stop instruction to pause a macro just before or after the place where you suspect a problem.

By default, the Stop statement produces a message box to notify you that it has paused the macro.

This message box is unnecessary if the macro-editing window is visible because Word highlights the Stop instruction in red. You can add an argument to the Stop instruction so that it does not display a message box — the instruction Stop -1 suppresses the message box.

ShowVars

This statement displays the Macro Variables dialog box. It's the equivalent of pausing the macro and choosing the Show Variables button at a given point in your macro.

MsgBox

Although you can check the status of most variables using the Macro Variables dialog box, that dialog box does not display array variables or dialog records. You can use the MsgBox statement to display and monitor these values. The MsgBox statement does not display numeric values, but you can use the Str$() function to convert numeric values into strings.

Print

The Print statement is useful for the same reasons MsgBox is, but it does not interrupt the macro as a message box does. You can also use it to display numeric values — you don't have to convert them to strings first, as you do with the MsgBox statement.


An Example: Debugging the InsertTab Macro

The InsertTab macro in this example is meant to insert a tab character in front of every paragraph in a selection. It uses the CopyBookmark statement to mark the selection with a bookmark called "temp." Then it goes to the start of the selection and moves the insertion point paragraph by paragraph through the document, inserting a tab character in front of each paragraph until it moves outside the area marked with the "temp" bookmark. The macro uses CmpBookmarks("\Sel", "temp") to compare the location of the insertion point (represented by the predefined bookmark " \ Sel") with the "temp" bookmark, which marks the original selection. When the insertion point is no longer within the original selection, the macro should end. Here are the macro instructions:

Sub MAIN
CopyBookmark "\Sel", "temp"                'Copy selection into bookmark
ParaUp                                    'Go to start of first paragraph
While CmpBookmarks("\Sel", "temp") <> 1
    Insert Chr$(9)                        'Insert tab character
    ParaDown                                'Go to next paragraph
Wend
End Sub

When tested, the macro sometimes inserts an additional tab character in front of the first paragraph after the selection. For some reason, the CmpBookmarks("\Sel", "temp") <> 1 condition doesn't always trigger the end of the While ¼ Wend loop at the right time.

Because the problem has something to do with the CmpBookmarks("\Sel", "temp") <> 1 condition, a good way to start investigating it would be to check the value returned by the CmpBookmarks() function with each iteration of the While ¼ Wend loop. You can do this by inserting the following instruction inside the While ¼ Wend loop and then using the Step button to step through the macro:

MsgBox Str$(CmpBookmarks("\Sel", "temp"))

Using this technique, you can discover that when the original selection includes the paragraph mark of the last paragraph in the selection, CmpBookmarks("\Sel", "temp") returns a value of 10 at the beginning of the next paragraph, rather than 1 as expected. When CmpBookmarks() returns a value of 10, it means that the two bookmarks being compared end at the same place but the second bookmark is longer. In this example, that means the insertion point and the "temp" bookmark end at the same place and "temp" marks more text than " \ Sel," which only marks the insertion point.

The corrected macro needs to exit the While ¼ Wend loop when CmpBookmarks() returns either 10 or 1:

Sub MAIN
CopyBookmark "\Sel", "temp"        'Copy selection into bookmark
ParaUp                            'Go to start of first para in selection
While CmpBookmarks("\Sel", "temp") <> 1 And \
        CmpBookmarks("\Sel", "temp") <> 10
    Insert Chr$(9)
    ParaDown
Wend
End Sub


Chapter 7 The Well-Behaved Macro

The well-behaved macro is one that can anticipate and respond to a variety of situations. Good macro behavior encompasses preventing errors, handling them when they do occur, being stable enough to perform under various conditions, and not leaving a mess behind for the user to clean up.

In this chapter:

  • Handling errors
  • Bulletproofing
  • Cleaning up


Handling Errors

When Word is asked to do something it can't do, an error condition occurs, and Word displays an error message box. An error condition is different from the WordBasic language errors described in the previous chapter; those errors are errors in the way a macro is written. However, a macro can be thoroughly debugged and still encounter error conditions. Here are some macro actions that can cause errors:

  • Trying to open a file that isn't available
  • Trying to create a bookmark with an invalid name
  • Trying to use a command that isn't available — for example, trying to use the Annotations command (View menu) when the document doesn't contain annotations

When you encounter these errors as you're working on documents in Word, you just close the error message box and continue working. But when a macro encounters an error, it stops, and the rest of the instructions in the macro are not carried out — unless you include instructions to trap, or handle, the error. When a macro handles an error, it can respond to it and continue. WordBasic includes several statements you can use to handle errors.

WordBasic and Word Errors

When you're working on documents in Word, the only errors you encounter are Word errors. A macro, however, can also generate WordBasic errors. Some WordBasic errors, such as syntax errors (discussed in the previous chapter), prevent a macro from running. Others — the ones you might want to trap — occur only when a macro is running in specific situations.

The distinction between WordBasic and Word errors is important because a macro can prevent a WordBasic error message box from being displayed, but cannot prevent a Word error message box from being displayed.

For example, if you run a macro that includes a command that is not available, WordBasic displays a WordBasic error message box, as shown in the following illustration. If you include instructions in your macro to handle that error, the error message box will not be displayed; the macro will carry out the error-handling instructions. The error-handling instructions could move the insertion point to a context in which the command is available, for example.

On the other hand, if a macro tries to move the insertion point to a bookmark that doesn't exist, Word generates a Word error and will display an error message box whether or not the macro includes error-handling instructions. The error-handling instructions do make a difference, however. Without them, Word stops the macro where the error occurs. With them, the macro can continue after the user closes the error message box, and the macro can respond to the error, perhaps by requesting the name of another bookmark.

Every error has a number. WordBasic errors have numbers below 1000; Word errors have numbers of 1000 or above. You can use these numbers in a macro to test for and respond to different types of errors. There are a few WordBasic errors, such as "Syntax error" and "Unknown Command, Subroutine, or Function," that prevent a macro from running and that you cannot trap.

For a complete list of WordBasic and Word error messages, see "Error Messages" in Part 2, "WordBasic Reference."

Error-Handling Instructions

WordBasic provides three forms of the On Error statement; the special variable Err; and the Error statement for handling errors in your macros.

On Error Goto Label

This form of the On Error statement enables error handling. It must be placed before the instruction that can generate an error. When an error occurs, Word goes to the line indicated by Label.

The following example displays an input box in which the user can type the name of a file to open. If the user chooses the Cancel button when the input box is displayed, a WordBasic error is generated. (You may not consider choosing the Cancel button an error, but WordBasic does.)

To trap the error, you place the On Error Goto Label instruction before the instruction that displays the input box. If the user chooses the Cancel button, the error is trapped, and Word goes to the line indicated by Label. In this case the label is bye, which is at the end of the macro. So if the user chooses the Cancel button in the input box, the macro ends without displaying an error message box.

Sub MAIN
On Error Goto bye
ans$ = InputBox$("Please type the name of a file to open:")
FileOpen ans$
'Series of instructions that operate on the file that was opened
bye:
End Sub

On Error Goto Label places the number of the error generated when the user chooses the Cancel button in the special variable Err, described later in this section.

On Error Resume Next

This form of the On Error statement allows a macro to trap errors and ignore them. When an error occurs, the macro simply resumes and goes to the next instruction as if nothing had happened. Using On Error Resume Next is sometimes the simplest way to deal with an error.

The following version of the previous example shows another way to deal with the error that occurs if the user chooses the Cancel button to close an input box. In this example, if the user chooses the Cancel button, the error is ignored. The If conditional tests whether a value was placed in the ans$ variable. No value is placed in it if the user chooses Cancel, so the FileOpen instruction doesn't run in that case.

Sub MAIN
On Error Resume Next
ans$ = InputBox$("Please type the name of a file to open:")
If ans$ <> "" Then FileOpen ans$
'Series of instructions that operate on the file that was opened
End Sub

After an On Error Resume Next instruction, Word continues to ignore any errors that might occur until the macro ends or until it encounters an instruction that disables error trapping, such as On Error Goto 0. As useful as it can be to have Word ignore specific errors, such as the one generated by the Cancel button, to have all errors ignored can cause problems: A macro may not work properly after an unexpected error occurs. So it's a good idea to disable error trapping (or use On Error Goto Label to reset error trapping) after using On Error Resume Next.

On Error Resume Next sets the value of the special variable Err to 0 (zero). Err is described later in this section.

On Error Goto 0

This form of the On Error statement is used to disable error trapping. While both On Error Goto Label and On Error Resume Next allow the macro to continue when an error occurs, On Error Goto 0 ensures that if an error is encountered, an error message is displayed and the macro stops.

You can use On Error Goto 0 to limit error handling to a specific part of your macro. In the following example, On Error Goto 0 is used to disable the error handling enabled by On Error Resume Next. Because the rest of the macro is meant to operate on an open file, the macro should end if no file is opened. On Error Goto 0 ensures that the macro is stopped if the FileOpen instruction generates an error.

Sub MAIN
On Error Resume Next
ans$ = InputBox$("Please type the name of a file to open:")
On Error Goto 0
If ans$ <> "" Then FileOpen ans$
'Series of instructions that operate on the file that was opened
End Sub

Err

When error trapping is enabled with On Error Goto Label, the number of any error that occurs is stored in the special variable Err. By testing this value, the macro can take different actions according to the type of error that occurs.

In the following example, the On Error Goto trap instruction enables error handling. The error-handling instructions, beginning after the label trap, test for three different values. If Err is equal to 102, it means that the user chose the Cancel button in the input box, in which case the Goto bye instruction ends the macro. If Err is equal to 1078 or 1177, the user typed either an invalid filename or the name of a file that isn't stored in the current folder. In either case, the macro displays a message box that asks the user if he or she would like to try to open the file again. If the user chooses the Yes button, the macro resets Err to 0 (zero) and goes to the tryagain label.

By default, Err has a value of 0 (zero). Once an error occurs and Err is assigned a nonzero value, error trapping is disabled until Err is reset to 0 (zero). In the following example, Err must be reset to 0 (zero) or error trapping will not work when the instructions after the tryagain label are repeated:

Sub MAIN
tryagain:
    On Error Goto trap
    ans$ = InputBox$("Please type the name of a file to open:")
    FileOpen ans$
    'Series of instructions that operate on the file that was opened
    Goto bye
trap:
    If Err = 102 Then Goto bye            'User cancels input box
    If Err = 1078 Or Err = 1177 Then        'Not found/invalid filename
        response = MsgBox("Couldn't open the file. Try again?", 4)
                If response = -1 Then
                Err = 0
                Goto tryagain
        End If
    End If
bye:
End Sub

You can look up the number that corresponds to any Word or WordBasic error message in "Error Messages" in Part 2, "WordBasic Reference."

Error

You can use the Error statement to generate an error so that you can test whether your error trap works as intended, without having to create an actual error situation. Here is an example:

On Error Goto trap
Error 502                'Simulate error 502
trap:
If Err = 502 Then MsgBox "Error was trapped."

If error trapping is not enabled before an Error instruction runs, Word highlights the Error instruction in the macro-editing window and stops the macro. If the error you specified is a WordBasic error, Word displays the corresponding error message box; if it is a Word error, no message is displayed.


Bulletproofing

Many macros are fragile initially: Everything must be just so, or they won't run properly. Fragile macros are fine if you're the only one who uses them. But if you're writing a macro others might use, you have to consider all the conditions in which someone might run it. Bulletproofing is the process of making a macro less dependent on a particular set of conditions.

The following is a checklist of questions to consider.

Where is the insertion point or selection when the macro begins?

A macro that uses editing statements may not work correctly if the insertion point or selection is in a table or a frame. If the insertion point or selection is in a macro-editing window or a header, footer, footnote, or annotation pane, a macro may not run because many commands are not available. You can use the SelInfo() function to determine whether the insertion point or selection is in a macro-editing window or a pane.

Is there a selection?

Often, macros that are designed to help with editing assume that text is either selected or not selected. A bulletproofed macro would use the SelType() function to test that assumption and quit if the selection were inappropriate.

Which view is the document in?

A macro that runs properly in normal view may not work in outline view or page layout view.

Is a window open?

Most Word commands are unavailable when no document window is open.

What are the current Word settings?

The settings in the Options dialog box (Tools menu) can often determine whether a macro runs properly. For example, a macro that pastes text onto or types over a selection depends on whether the Typing Replaces Selection check box on the Edit tab is selected. If a macro searches for or edits hidden text, hidden text must be visible; however, if a macro repaginates (or compiles an index or table of contents), page numbering may be thrown off if hidden text is visible. Use the WordBasic statements that control the Options dialog box to ensure the current settings are appropriate for your macro.

Could the macro trigger an auto macro?

If the macro performs any of the actions that can trigger an auto macro (such as opening an existing document or creating a new one), it may be disrupted or perform unnecessary actions. You can disable auto macros using the DisableAutoMacros statement.

What if the user interrupts the macro?

Usually, it's convenient to be able to cancel a macro by pressing the Esc key. But if a macro is carrying out a critical operation, canceling it could create problems. You can use the DisableInput statement to prevent the user from canceling a macro.

Bulletproofing and Speed

Every bulletproofing precaution slows your macro down. For long, complex macros, the added robustness is well worth a slight delay at the start. For short, quick macros, however, speed may be critical — if they take too long, they're not worth using. Use your judgment as to what level of bulletproofing is appropriate for a given macro.


Cleaning Up

The well-behaved macro cleans up after itself. In the course of carrying out its various tasks, a macro may open and close documents, change the settings of various options, and make other modifications before it is finished. Some of these changes may not be desirable to the user after the macro is done. For example, a macro designed to work on selected text may create a bookmark to mark an area of the document. The macro needs this bookmark, but the user doesn't; the macro should remove the bookmark when it's no longer needed.

Here's a checklist of possible cleanup tasks for your macro:

  • Close any documents the macro opened that the user doesn't need.
  • Save a document with changes that should be saved.
  • Close a document without saving it if the macro made changes that should not be saved. If the document should be open but unchanged when the macro ends, close it without saving changes, and then reopen it.
  • Restore the settings of any options the macro may have changed for its own purposes. For example, if hidden text was not displayed when the macro began, it should not be displayed when the macro ends (unless that is part of the purpose of the macro).
  • Delete any temporary bookmarks created by the macro.
  • Restore the original selection or return the insertion point to the appropriate location.
  • Restore the original size of the document window.
  • Re-enable auto macros if the macro disabled them. Auto macros remain disabled for the entire Word session if the macro does not re-enable them before it ends.
  • Return to the original folder.


Chapter 8 Communicating with Other Applications

Word supports several ways of communicating and sharing information with other applications. The simplest is through the Clipboard, using the standard Cut, Copy, and Paste commands (Edit menu). A more useful technique for WordBasic macros is dynamic data exchange (DDE), a protocol your macro can use to extract information from other applications, automatically update them with new information, and even send commands or keystrokes to manipulate them by remote control.

Word also offers limited support for object linking and embedding (OLE) Automation. OLE Automation is the successor to DDE and offers additional capabilities. An application such as Microsoft Excel can use OLE Automation to control Word and request information.

In Windows, you can use the messaging application programming interface (MAPI) to integrate Word with applications that support MAPI, such as Microsoft Mail. On the Macintosh, you can use built-in WordBasic statements and functions that support Apple Open Collaboration Environment (AOCE) messaging.

In this chapter:

  • Using dynamic data exchange
  • Using OLE Automation with Word
  • Using MAPI and AOCE


Using Dynamic Data Exchange

Dynamic data exchange (DDE) is a mechanism supported by Microsoft applications in Windows and on the Macintosh that enables two applications to "talk" to each other. DDE automates the manual cutting and pasting of information between applications, providing a faster vehicle for updating information.

More specifically, DDE provides three capabilities:

  • You can request information from an application. For example, in a DDE conversation with Microsoft Excel, a Word macro can request the contents of a cell or range of cells in a Microsoft Excel worksheet.
  • You can send information to an application. In a DDE conversation with Microsoft Excel, a Word macro can send text to a cell or range of cells.
  • You can send commands to an application. For example, in a DDE conversation with Microsoft Excel, a Word macro can send a command to open a worksheet from which it wants to request information. Commands sent to an application must be in a form the application can recognize.

Note

Not all applications support DDE. Consult the documentation for your other applications to see if they support DDE.

Clients, Servers, and Conversations

Two applications exchange information by engaging in a DDE conversation. In a DDE conversation, the application that initiates and controls the conversation is the client and the application that responds is the server. The client application requests information from the server and sends information and commands to it. The server application, as its name implies, serves the needs of the client application by returning information, accepting information, and carrying out commands. There is nothing special about an application that makes it a client or a server; these are simply roles an application can adopt. In fact, an application can be engaged in several DDE conversations at the same time, acting as the client in some and the server in others. Each conversation is identified by a separate channel number.

Application Names, Topics, and Items

When a client application begins a DDE conversation, it must specify two things:

  • The name of the application it wants to talk to (the server)
  • The subject of the conversation (the topic)

When a server application receives a request for a conversation concerning a topic it recognizes, it responds and the conversation is started. Once established, a conversation cannot change applications or topics. The combination of application and topic uniquely identifies the conversation, and the combination remains constant for the duration of the conversation. If either the client or the server changes the application or the topic, the conversation is terminated.

During the conversation, the client and server may exchange information concerning one or more items. An item is a reference to data that is meaningful to the server application. Either the client or the server can change the item during the conversation.

Together, the application name, topic, and item uniquely identify the information that is being passed between the applications. Each of these is discussed in detail in the sections that follow.

Application Names

Every application that supports DDE has a unique DDE application name. The following are application names for some Microsoft applications.

Application | DDE application name
Microsoft Access | MSAccess
Microsoft Excel for Windows | Excel
Microsoft Excel for the Macintosh | Excel
Microsoft FoxPro® for Windows | FoxPro
Microsoft Project for Windows | WinProj
Microsoft Project for the Macintosh | MSProject
Microsoft Word for Windows | WinWord
Microsoft Word for the Macintosh | MSWord or WinWord
Microsoft Windows 3.x Program Manager | ProgMan

In Windows, the application name of an application is usually, but not always, the name of the executable file for that application without the .EXE filename extension. If you're not sure what the DDE application name for an application is, check the application's documentation. Application names are not case-sensitive.

Note

Visual FoxPro™ 3.0 can act as both a server and a client to send data to and receive data from other applications such as Word. For more information see "DDE Functions" in Microsoft Visual FoxPro Help.

Topics

Every DDE conversation is with both a server application and a topic the server application supports. Most applications support the names of open files as topics. Some possible topics are a Microsoft Excel worksheet (for example, "DAILYORD.XLS"), a Word document (for example, "SALESREP.DOC"), or an object in a Microsoft Access database (for example, "NORTHWIND.MDB;TABLE Shippers").

A special topic that many applications recognize is "System." Unlike other topics, which may or may not be available depending on whether a file is open, the System topic is always available and provides a list of the other topics that are currently available as well as other information about the application.

Items

With the server's application name and a topic name, a client can initiate a DDE conversation. But for a client to exchange information with the server, one other essential piece of information is needed: the items available in the topic of the DDE conversation. An item is a kind of subtopic that identifies the information actually being exchanged during the DDE conversation. For example, Microsoft Excel recognizes cell references (such as R1C1) as items in a conversation. In Word, a bookmark is an item. Microsoft Access recognizes several items, including SQL statements.

Initiating a DDE Conversation

A key requirement for a DDE conversation is that both applications be running. If an application isn't running, a client can't initiate a DDE conversation with it. For that reason, a macro that initiates a DDE conversation usually includes instructions that carry out the following three steps:

1. Determine whether the application you want to talk to is running

2. Start the application if it isn't already running

3. Initiate the DDE conversation

Step One: Determine Whether the Application Is Running

You can use the AppIsRunning() function to determine whether an application is running. Here is the syntax:

AppIsRunning(Title$)

In Windows, Title$ is the name of the application as it appears in the title bar of the application window (Title$ also appears in the Task List). For example, to determine if Microsoft Excel is running, you can use the following instruction:

status = AppIsRunning("Microsoft Excel")

Note that the Title$ is not the same as the DDE application name. Word does not generate an error if you specify the wrong name for an AppIsRunning() instruction, but the instruction will give unexpected results.

On the Macintosh, Title$ is the application name. You can also use the MacID$() function to specify an application's signature instead of the application name. For example:

status = AppIsRunning(MacID$("XCEL"))

Note

In Windows, when a document window is maximized, the document window name is included in the title bar of the application window, but you don't have to specify the document window part of the title. For example, if Microsoft Excel is running and "BUDGET.XLS" is opened in a maximized document window, the application window title is "Microsoft Excel - BUDGET.XLS." But you can specify just "Microsoft Excel" for Title$.

Step Two: Start the Application If Necessary

If the server application is not running, you can use the Shell statement to start it. Here is the syntax:

Shell Application$ [, WindowStyle]

Application$ must be the actual application filename. For example, "EXCEL.EXE" is acceptable in Windows; on the Macintosh, "Microsoft Excel" is accepted. In Windows, the optional WindowStyle argument specifies how the application window is displayed (for example, as an icon or a maximized window); on the Macintosh, WindowStyle specifies whether the application should be activated. If the application you want to start is not in the current folder, or not on a path recognized by the operating system, you must specify the path as well as the filename. Here is a Windows example:

Shell "C:\EXCEL\EXCEL.EXE", 0            'Start Excel minimized

Here is the same example on the Macintosh:

Shell "HD1:EXCEL:Microsoft Excel", 0        'Start Excel and activate

On the Macintosh, it's a good idea to use the MacID$() function to specify an application signature rather than a specific application filename, since it isn't uncommon for Macintosh users to change application filenames. The application signature provided by MacID$() ensures that the Shell statement will run the specified application, regardless of the filename. Here is an example:

Shell MacID$("XCEL"), 0

To open a document at the same time you start the application, you can specify a document filename with the application filename or just the document filename, assuming the operating system can associate the filename with the application you want to start. Here is a Windows example:

Shell "C:\EXCEL\EXAMPLES\BUDGET.XLS", 0

Here is the same example on the Macintosh:

Shell "HD1:EXCEL:My Budget", 0

Here's how you might use AppIsRunning() and Shell together in Windows:

If AppIsRunning("Microsoft Excel") = 0 Then Shell "EXCEL.EXE", 0

In Windows, the AppIsRunning() instruction is necessary because with most applications, Shell starts a second instance of the application if one instance is already running — not usually the effect you want. On the Macintosh, Shell does not start a second instance of an application. If the application is already running, Shell either activates it or has no effect, depending on the value of the WindowStyle argument. Here's an example:

Shell MacID$("XCEL"), 4

The WindowStyle argument of 4 specifies that Microsoft Excel is not to be activated; if Microsoft Excel is already running, this instruction has no effect.

Note

In Word version 6.0 for Windows NT and Word version 7.0, you cannot depend on a program started with Shell to be finished loading before the instructions following the Shell statement in your macro are run. A DDEInitiate instruction that tries to communicate with an application that has not finished loading will generate errors. To avoid this problem, you can use a For...Next loop to delay the DDEInitiate instruction until the other application is loaded. For example:

If AppIsRunning("Microsoft Access") = 0 Then
    Shell "MSACCESS.EXE", 0
    For i = 1 To 2000
        x = i
    Next i
End If
chan = DDEInitiate("MSAccess", "System")

Step Three: Initiate the DDE Conversation

When you have established that the application you want to talk to is running, you are ready to initiate a DDE conversation with DDEInitiate(). Here is the syntax:

DDEInitiate(Application$, Topic$)

Application$ is the DDE application name of the application you want to initiate a conversation with. Topic$ is the name of a topic the application currently supports. For example, the following instruction initiates a conversation with Microsoft Excel for Windows or Microsoft Excel for the Macintosh on the System topic:

chan = DDEInitiate("Excel", "System")

If DDEInitiate() is successful in initiating a conversation with the specified server application and topic, it returns a channel number. You use this channel number as an argument in other DDE statements and functions to refer to this DDE conversation.

An error occurs if the application isn't running or if the application doesn't recognize the topic. For example, if you specify "SALES.XLS" as the topic, but SALES.XLS isn't open, an error is generated.

Requesting Information

Once you have initiated a conversation with another application, you can use the DDERequest$() function to obtain information from an item within the specified topic. Here is the syntax:

DDERequest$(ChanNum, Item$)

ChanNum is the number of a channel returned by the DDEInitiate() instruction. Item$ is an item supported by the topic of the DDE conversation.

You can use DDERequest$() to query the System topic in Microsoft Excel to get a list of the currently supported topics, as shown in the following Windows example:

If AppIsRunning("Microsoft Excel") = 0 Then Shell "EXCEL.EXE", 4
chan = DDEInitiate("Excel", "System")
topics$ = DDERequest$(chan, "Topics")

Here is the same example on the Macintosh:

If AppIsRunning(MacID$("XCEL")) = 0 Then Shell MacID$("XCEL"), 4
chan = DDEInitiate("Excel", "System")
topics$ = DDERequest$(chan, "Topics")

"Topics" is an item in the System topic that lists all the topics currently available. You can add an Insert instruction such as the following:

Insert topics$

This instruction inserts the list of topics in a document.

Topic names are separated by tab marks. In this example, [SALES.XLS]Sales Report and [SAMPLES.XLS]Amortization Table are the names of Microsoft Excel worksheets that can be accessed as topics in DDE conversations.

If the specified channel number doesn't refer to an active DDE conversation, DDERequest$() generates an error. You'll also get an error if the specified item is not recognized by the other application.

Note that since DDERequest$() is a string function, information is always returned to the Word macro in the form of a string. For an example that retrieves information from a range of cells in Microsoft Excel, see "Using Microsoft Excel as a Server" later in this chapter.

You can use InStr() to determine whether a file is currently open. The following Windows example determines if SALES.XLS is an available DDE topic (the file is open):

If AppIsRunning("Microsoft Excel") = 0 Then Shell "EXCEL.EXE", 4
chan = DDEInitiate("Excel", "System")
topics$ = DDERequest$(chan, "Topics")
If InStr(topics$, "SALES.XLS") <> 0 Then
    Print "File is Open"
End If

Sending Information

Although the client in a DDE conversation usually obtains information from the server, the client can supply information to the server as well. To do so, you use the DDEPoke statement. Here is the syntax:

DDEPoke ChanNum, Item$, Data$

ChanNum is the channel number returned by the DDEInitiate() instruction that began the DDE conversation. Item$ is the name of an item supported by the topic of the DDE conversation. Data$ is the information — in the form of a string — that you want to "poke" (or insert) into the item. To send a number, you must first convert it into a string.

The following example pokes the numeric value 100 into the first cell of the Microsoft Excel worksheet that is the topic of the DDE conversation. The Str$() function is used to convert the value into a string:

DDEPoke chan1, "R1C1", Str$(100)

Sending Commands

You can use the DDEExecute statement to send a command recognized by the server application:

DDEExecute ChanNum, Command$

ChanNum is the channel number returned by the DDEInitiate() instruction that began the DDE conversation. In Microsoft Excel and many other applications that support DDE, Command$ is a statement or function in the application's macro language. For example, in Microsoft Excel the XLM macro statement that creates a new worksheet is NEW(1). (Microsoft Excel does not accept Visual Basic instructions through DDE.) To send the same command through a DDE channel, you would use the following instruction:

DDEExecute chan1, "[NEW(1)]"

Many applications, including Microsoft Excel, require that each command received through a DDE channel be enclosed in brackets. You can use a single DDEExecute instruction to send more than one command, with each command enclosed in brackets. For example, the following instruction tells Microsoft Excel to open and then close a worksheet:

DDEExecute chan1, "[NEW(1)][FILE.CLOSE(0)]"

Note that there must be no spaces between bracketed commands in a single DDEExecute instruction; otherwise, an error will occur. The preceding instruction is equivalent to the following two instructions:

DDEExecute chan1, "[NEW(1)]"
DDEExecute chan1, "[FILE.CLOSE(0)]"

Many commands require arguments in the form of strings enclosed in quotation marks. Because the quotation mark indicates the beginning and end of a string in WordBasic, you must use Chr$(34) to include a quotation mark in a command string. For example, to send the Microsoft Excel macro instruction OPEN("SALES.XLS"), you would use the following instruction:

DDEExecute chan1, "[OPEN(" + Chr$(34) + "SALES.XLS" + Chr$(34) + ")]"

Terminating DDE Conversations

DDE channels are not closed automatically until you exit Word. If you don't close a channel, it remains open, even after the macro has ended. Because each channel uses some system resources, you should always close channels when you no longer need them. You terminate a DDE conversation with DDETerminate. Here is the syntax:

DDETerminate ChanNum

ChanNum is the channel number returned by the DDEInitiate() instruction that began the conversation.

When you close Word, it automatically terminates all active DDE conversations. However, you might want to terminate all conversations without closing Word. To do so, you could use several consecutive DDETerminate statements or a loop. However, WordBasic provides DDETerminateAll as a shortcut. DDETerminateAll terminates all active DDE conversations that Word has initiated (it does not terminate DDE conversations that another application may have initiated with Word as the server). If you are debugging a macro that performs DDE and are often interrupting and restarting the macro, it's a good idea to use DDETerminateAll periodically to close any channels you may have inadvertently left open.

Using Microsoft Excel as a Server

Here are some points to keep in mind about DDE conversations with Microsoft Excel:

  • The DDE application name for Microsoft Excel in Windows and on the Macintosh is Excel.
  • Microsoft Excel supports the standard System topic, which supports the following items.
Item | Description
SysItems | Provides a list of the items in the System topic
Topics | Provides a list of the currently valid topics, including all open documents

Item | Description
Status | Indicates whether Microsoft Excel is ready to receive DDE messages ("Busy" or "Ready")
Formats | Provides the list of formats supported
Selection | Indicates the currently selected cell or range of cells
Protocols | Not applicable
EditEnvItems | Not applicable

  • Any open document is a valid DDE topic in Microsoft Excel.
  • A cell or range of cells is an item within a worksheet, macro sheet, or slide-show document. To specify a cell or range of cells as an item, you can use a name defined in Microsoft Excel that identifies them, or you can indicate the cells themselves. You must use the "R1C1" convention to refer to cells rather than the "A1" convention. For example, to refer to a cell in the second column of the fourth row, you specify "R4C2" rather than "D2." Note that you don't need to change the corresponding Workspace option in Microsoft Excel.
  • Using the DDEExecute statement, you can send Microsoft Excel XLM macro commands enclosed in brackets. You can send more than one command with a single DDEExecute statement; each macro command must be enclosed in brackets.

    Microsoft Excel does not accept Visual Basic instructions through a DDE channel. However, you can send an XLM macro command to run an available XLM macro or Visual Basic procedure. For example, the following instruction runs a Visual Basic procedure called FormatCells stored in a module called VBAMacros:

    DDEExecute chan, "[run(" + Chr$(34) + "VBAMacros!FormatCells" + \
        Chr$(34) + ")]"
  • You cannot initiate a DDE link if the formula bar in Microsoft Excel is active. If you try to initiate a link when the formula bar is active, WordBasic will display an error message saying that the application does not respond.
  • Microsoft Excel includes an option to prevent other applications from initiating DDE conversations with it. To check the setting of this option, choose Options from the Tools menu in Microsoft Excel, and select the General tab. If the Ignore Other Applications check box is selected, you cannot initiate a DDE conversation. If you try to initiate a conversation when the Ignore Other Applications check box is selected, Word will display a message saying that the "remote data" is not accessible and will ask if you want to start another instance of Microsoft Excel. To initiate a DDE conversation successfully at that point, you must first clear the Ignore Other Applications check box in Microsoft Excel.

Example

The following example initiates a DDE conversation with SALES.XLS (a sample workbook supplied with Microsoft Excel), requests some sales figures, and inserts them into a Word document:

chan = DDEInitiate("Excel", "[SALES.XLS]Sales Report")
figures$ = DDERequest$(chan, "R4C2:R8C4")
Insert figures$
DDETerminate chan

You could also use a name defined in Microsoft Excel to refer to the cell range R4C2:R8C3. For example, if the cells were defined with the name "JanuarySales," you could use the following instruction:

figures$ = DDERequest$(chan, "JanuarySales")

Note that when the figures are inserted into Word, each cell is delimited by a tab character and each row by a paragraph mark, as shown in the following illustration. A paragraph mark is inserted after the last row in Windows, but not on the Macintosh.

Since DDERequest() returns the figures as a string, they lose any formatting that was applied in Microsoft Excel. Instead, they acquire the formatting of the paragraph in which the insertion point is located in Word.

You can use the following instructions to have the preceding macro select the figures after it inserts them and convert them into a table. The first instruction creates a temporary bookmark at the location where the figures from Microsoft Excel will be inserted. The remaining instructions select the figures and convert them into a table.

CopyBookmark "\Sel", "temp"
Insert figures$
ExtendSelection
EditGoTo "temp"
TableInsertTable .ConvertFrom = 1

Note that you cannot have the macro pour the figures into the selected cells of an existing table, as you can when you use the Paste command (Edit menu) to copy cells from Microsoft Excel using the Clipboard.

Using Microsoft Access as a Server

Microsoft Access version 7.0 provides a wide variety of topics to allow you to access tables and queries. You can also send SQL statements to a database and launch macros. For information on the topics and items supported, see the Microsoft Access Help topic "Using Microsoft Access as a DDE Server."

Here are some other points to keep in mind when using Microsoft Access as a server:

  • The DDE application name for Microsoft Access is MSAccess.
  • Microsoft Access supports the standard System topic, which supports the following items.
Item | Description
SysItems | Provides a list of the items in the System topic
Topics | Provides a list of all open databases
Status | Indicates whether Microsoft Access is ready to receive DDE messages ("Busy" or "Ready")
Formats | Provides a list of formats Microsoft Access can copy to the Clipboard

  • The Topics item in the System topic does not provide a comprehensive list of the topics available in Microsoft Access; it lists only the open databases. For a complete list of the available topics, see the Microsoft Access Help topic "Using Microsoft Access as a DDE Server."
  • Like Microsoft Excel, Microsoft Access includes an option to prevent another application from initiating a DDE conversation. To check the setting of this option, choose Options from the Tools menu in Microsoft Access, and then click the Advanced tab. If the Ignore DDE Requests check box is selected, Microsoft Access will not respond to DDEInitiate(). You must clear the check box before initiating a DDE conversation.
  • You can use the DDEExecute statement to run a macro in the active database or carry out an action in Visual Basic using one of methods of the DoCmd object. You can also use the OpenDatabase and CloseDatabase actions to open or close a database.
  • You cannot use DDEPoke to send information to Microsoft Access.
  • You cannot send a parameter query to Microsoft Access.

Examples

The following example inserts the contents of the Shippers table into a Word document. The Shippers table is a table in the NORTHWIND.MDB sample database included with Microsoft Access version 7.0. Note that Microsoft Access has its own internal syntax for specifying a table in a database as a topic, and this differs from the syntax used to specify a worksheet in Microsoft Excel, for example. This syntax is described in the Microsoft Access Help topic "Using Microsoft Access as a DDE Server."

Sub MAIN
chan1 = DDEInitiate("MSAccess", "System")
DDEExecute chan1, "[OpenDatabase C:\MSOffice\Access\Samples\NORTHWIND.MDB]"
chan2 = DDEInitiate("MSAccess", "NORTHWIND;TABLE Shippers ")
figures$ = DDERequest$(chan2, "All")
Insert figures$
DDETerminateAll
End Sub

As with figures imported from Microsoft Excel worksheets, fields are separated by tab characters and records by paragraph marks (although the last record does not end with a paragraph mark).

You can also access queries in a Microsoft Access database using the Query topic. For example:

chan = DDEInitiate("MSAccess", "NORTHWIND;QUERY Ten Most Expensive Products")

The following example sends an SQL statement to the NORTHWIND database to return a list of customers stored in the database:

Sub MAIN
chan1 = DDEInitiate("MSAccess", "System")
DDEExecute chan1, "[OpenDatabase C:\MSOffice\Access\Samples\NORTHWIND.MDB]"chan2 = DDEInitiate("MSAccess", "NORTHWIND;SQL SELECT DISTINCTROW" + \
 " Customers.CompanyName FROM Customers" + \
 " ORDER BY Customers.CompanyName;")
list$ = DDERequest$(chan2, "Data")
Insert list$
DDETerminateAll
End Sub

An easy way to create SQL statements is to first create the query in Microsoft Access, and then copy the SQL statement into your Word macro. To see the SQL statement for a query in Microsoft Access, open the query in Design mode and choose SQL from the View menu to display the SQL dialog box.

Using Word as a Server

So far, this chapter has described Word as the client application, but Word can also be used as a DDE server. Here are some points to keep in mind when using Word as a server:

  • In Windows, the DDE application name for Word is WinWord; on the Macintosh, it is MSWord or WinWord.
  • Word supports the standard System topic, which supports the following items:
Item | Description
SysItems | Provides a list of the items in the System topic
Topics | Provides a list of the currently valid topics, including all open documents
Formats | Provides a list of all the Clipboard formats supported by Word

  • Word supports all open documents, macros, and templates as topics. A template is considered to be open if it is attached to an open document, if it is loaded as a global template, or if it is open in a document window. It's best to include the complete path when specifying a document or template as a topic; otherwise, Word won't find the document if it isn't located in the current folder.
  • In documents and templates, Word supports bookmarks as items. Three of the predefined bookmarks are supported as items: " \ StartOfDoc," " \ EndOfDoc," and " \ Doc." An error will occur if an application requests an "empty" bookmark — one that marks a location in a document but not any text. For example, the predefined bookmark " \ StartOfDoc" does not mark any text and so an error will occur if an application requests it. You can, however, poke information into an empty bookmark; you could use the " \ StartOfDoc" bookmark to poke information into the beginning of a document.
  • You do not have to write any WordBasic code to use Word as a server. For example, if you want to use Microsoft Excel or Microsoft Access as the client and Word as the server, you write a procedure in Visual Basic; you don't have to write a Word macro.
  • The client application can use its equivalent of the DDEExecute statement to send WordBasic instructions to Word. The following Visual Basic instruction sends instructions to open two documents in Word:

    DDEExecute chan%, "[FileOpen ""JOE.DOC""][FileOpen ""REPORT.DOC""]"

    Note that each WordBasic instruction is enclosed in brackets and that you can send more than one WordBasic instruction with a single Visual Basic DDEExecute instruction. Visual Basic uses a pair of quotation marks to indicate one quotation mark within a string.

    You can also send macro names to have Word start a macro. For example, the following Visual Basic instruction runs the Word macro SortHeadings:

    DDEExecute chan%, "[SortHeadings]"

    Do not send instructions that display dialog boxes in Word — Word will not become the active application window, and the DDE conversation will time out, waiting for the user to respond to the dialog box.

  • Word can open a DDE channel with another instance of itself. One instance of Word becomes the client and the other becomes the server. Word can even open a DDE channel to a single instance of itself (although it cannot poke information into itself when only one instance is running). This capability can be useful for testing macros.

Examples

The following Microsoft Excel procedure opens a Word document, retrieves the text marked by a bookmark, and places it in a series of cells in a worksheet. First it defines returnlist as an object variable equivalent to six cells. Then it opens a DDE channel to the Word System topic and uses the DDEExecute method to send the WordBasic instruction FileOpen "TEST.DOC". Note that the instruction is enclosed in brackets and that "TEST.DOC" is enclosed in pairs of quotation marks, which Visual Basic uses to indicate quotation marks within a string. Once TEST.DOC is open, the macro closes the DDE channel to the System topic and opens a new one to the TEST.DOC topic. Finally, it uses the DDERequest method to request the text marked by the bookmark "listitems," which is returned to the object variable returnlist.

Sub ReturnWordBookmarkText()
   Dim returnList As Object
   Set returnList = ActiveSheet.Range(Cells(1, 1), Cells(6, 1))
   channelNumber = Application.DDEInitiate("WinWord", "System")
   Application.DDEExecute channelNumber, "[FileOpen ""TEST.DOC""]"
   Application.DDETerminate channelNumber
   channelNumber = Application.DDEInitiate("WinWord", "TEST.DOC")
   returnList.value = Application.DDERequest(channelNumber, "listitems")
   Application.DDETerminate channelNumber
End Sub

The following WordBasic macro establishes a DDE conversation with the same instance of Word and displays a message box, such as the one that follows, showing the list of currently valid topics. The While ¼ Wend loop replaces the tab characters between topics with paragraph marks so that the list is easier to read. Note that a WordBasic message box cannot display more than 255 characters, so the macro displays a message if the list of topics is too long.

Sub MAIN
chan = DDEInitiate("winword", "system")
topics$ = DDERequest$(chan, "topics")
tab$ = Chr$(9)
para$ = Chr$(13)
While InStr(topics$, tab$)
    tab = InStr(topics$, tab$)
    leftside$ = Left$(topics$, tab - 1)
    rightside$ = Right$(topics$, Len(topics$) - tab)
    topics$ = leftside$ + para$ + rightside$
Wend
msg$ = "The topics available are: " + para$ + para$ + topics$
If Len(msg$) > 255 Then
    MsgBox "Sorry, the list of topics is too long to display " + \
            "in a message box. (255 characters is the maximum.)"
Else
    MsgBox msg$, "Word DDE Topics"
End If
DDETerminate chan
End Sub


Using OLE Automation with Word

OLE Automation is a protocol intended to replace DDE. As with DDE, an application can use OLE Automation to share data or control another application.

In OLE Automation, Word provides another application (called the "container" application) with an object — a unit of information similar to a topic in DDE. Word supports a single object called "WordBasic" for OLE Automation. You use the "WordBasic" object to send WordBasic instructions to Word. The technique is similar to sending commands to Word through DDE, but with OLE Automation, WordBasic instructions can return numbers or strings directly to the container application. This makes it possible to use WordBasic instructions as an extension of the container application's macro or programming language.

Note that Word can provide an object to another application for OLE Automation, but it cannot use OLE Automation to access objects in other applications. In other words, applications that support OLE Automation, such as Microsoft Excel or a Visual Basic application, can use OLE Automation to access Word, but Word cannot use OLE Automation to access them. (In DDE terms, Word can act as a server for another application but cannot act as the client.)

Microsoft Visual FoxPro version 3.0 includes an OLE Automation client example. For information about how to run and view the code associated with the OLE Automation example, see "OLE Automation Sample" in Microsoft Visual FoxPro Help.

Note

Throughout this section, the term "Visual Basic" is used to refer to either Visual Basic version 3.0 or later (Windows) or Visual Basic in Microsoft Access version 7.0 (Windows) and Microsoft Excel version 5.0 or later (Windows or Macintosh), unless otherwise indicated.

Accessing Word

The first step toward making Word available to a container application is to define an object variable that will reference the "WordBasic" object in Word. In Visual Basic, you declare a variable of type Object. For example:

Dim WordObj As Object

You then make the "WordBasic" object available to the container application by "creating" it for the application and assigning it to the object variable. In Visual Basic, you use the CreateObject function to create an object and the Set keyword to assign to the object variable. Here is the syntax:

Set ObjectVar = CreateObject("Application.ObjectType")

For example, in Visual Basic you could use the following instruction:

Set WordObj = CreateObject("Word.Basic")

This instruction makes the "WordBasic" object in Word available to the container application for OLE Automation.

If Word version 6.0 is not running when another application needs to access it, OLE Automation starts a visible instance of Word. You don't need to include a separate instruction to start Word, as you do with DDE. An error occurs if Word cannot be found. While a visible instance is useful for debugging a Visual Basic procedure, you may want to hide the instance in the final macro. To do so, use the WordBasic AppHide statement:

Set WordObj = CreateObject("Word.Basic")
WordObj.AppHide

If Word version 7.0 is not running when another application needs to access it, OLE Automation starts a hidden instance of Word. While a hidden instance is useful for the final macro, you may want to make the instance visible while debugging the Visual Basic procedure. To do so, use the WordBasic AppShow statement:

Set WordObj = CreateObject("Word.Basic")
WordObj.AppShow

Applications that fully support OLE Automation make their documents available as objects. Since Word supports only the "WordBasic" object for OLE Automation, you cannot use OLE Automation to directly access a Word document as an object (unless the document is embedded in the container application; see "Accessing an Embedded Word Object" later in this chapter). For example, you cannot use the GetObject function in Visual Basic to access a Word document. Instead, you use WordBasic instructions to access Word and to act on Word documents, as described in the following section.

If OLE Automation starts a Word session, OLE Automation will close Word when the object variable that references the "WordBasic" object expires — when either the procedure ends or the container application is closed. In Visual Basic, you can use the Set statement with the Nothing keyword to clear an object variable, which has the same effect as closing the container application.

Note that the "WordBasic" object does not support a method to close itself. That is, if Word is running when OLE Automation starts, you cannot close Word through OLE Automation; you can only close a Word session if you also used OLE Automation to start it.

Using WordBasic Statements and Functions

Once you have made the "WordBasic" object available to the container application, you can use most WordBasic statements or functions to act on Word and Word documents. You use WordBasic instructions in OLE Automation in the same way you use them in Word macros.

WordBasic statements and functions not available to OLE Automation include the following: control structures, such as While ¼ Wend and If ¼ Then ¼ Else; declaration statements such as Dim; statements associated with custom dialog boxes; the FileExit statement; and statements or functions that require array variables as arguments.

WordBasic functions that return strings end in a dollar sign ($). When using these functions in OLE Automation, you can either leave off the dollar sign or enclose it in brackets. The following instruction shows the GetBookmark$() function as it might appear in a WordBasic macro:

mark$ = GetBookmark$("Address")

In Visual Basic, the same instruction might be specified as either of the following two instructions, where mark is a string variable:

mark = WordObj.[GetBookmark$]("Address")
mark = WordObj.GetBookmark("Address")

Note

The following WordBasic functions that return strings require the dollar sign and must be enclosed in brackets: Font$(), GetSystemInfo$(), and Language$(). These WordBasic functions have the same keywords as WordBasic statements (for example, there is a Font statement as well as a Font$() function); without the dollar sign WordBasic has no way to distinguish them from WordBasic statements.

The following example opens the Word document LETTER.DOC and then uses a WordBasic GetBookmark$() instruction to retrieve the text of the "Address" bookmark in LETTER.DOC and display it in a message box:

Dim mark As String
Dim WordObj As Object
Set WordObj = CreateObject("Word.Basic")
WordObj.FileOpen Name:= "LETTER.DOC"
mark = WordObj.GetBookmark("Address")
MsgBox mark

The following example retrieves the list of bookmarks from the active document and displays their contents in a series of message boxes. These instructions use WordBasic instructions just as if they were part of the Visual Basic language. In effect, these instructions extend the functionality of Visual Basic. The only difference is that since WordBasic is not an object-oriented language with methods and properties like those of Visual Basic, the syntax of the WordBasic instructions does not match Visual Basic syntax.

Dim WordObj As Object
Set WordObj = CreateObject("Word.Basic")
Dim count As Integer, countmarks As Integer
countmarks = WordObj.CountBookmarks()
If countmarks <> 0 Then
ReDim bmarks$(1 To countmarks)
For count = 1 To countmarks
    bmarks$(count) = WordObj.BookmarkName(count)
Next count
For count = 1 To countmarks
    MsgBox bmarks$(count)
Next
End If

In the following example, the instructions toggle the bold formatting of the selected paragraph in Word:

Dim WordObj As Object
Set WordObj = CreateObject("Word.Basic")
WordObj.EditGoto "\Para"        'Select the current paragraph
If WordObj.Bold() <> 0 Then
    WordObj.Bold 0            'Remove bold from the selected text
Else
    WordObj.Bold 1            'Apply bold to the selected text
End If

What Does the Instruction Act On?

A significant difference between Visual Basic and WordBasic is that in Visual Basic, whatever a statement (or "method") acts on is specified in the statement itself. In WordBasic, however, that is not always the case. For example, an EditCut WordBasic instruction might cut anything from a single character to an entire document: it cuts whatever is selected in the active document when the instruction runs. Most WordBasic formatting and editing instructions work this way. If you're used to the Visual Basic way of doing things, keep in mind that when using WordBasic instructions, you usually need to be aware of the current selection or location of the insertion point.

Accessing an Embedded Word Object

So far, this section has described accessing Word as a separate application. But you can also access a Word object such as a Word document or Word picture embedded in the container application. In Visual Basic, you use the Object property to access the document or picture and to use WordBasic statements and functions to act on it. Here is the syntax for Visual Basic version 3.0 or later (not available on the Macintosh):

Set ObjectVar = OLEControlName.Object.Application.WordBasic

ObjectVar is a previously declared object variable; OLEControlName is the name of the OLE control in which the Word object is embedded. For example, you could use the following instructions to access a document embedded in an OLE control called OLE1:

Dim WordObj As Object
Set WordObj = OLE1.Object.Application.WordBasic

In Microsoft Excel Visual Basic, you use the OLEObjects method to return the embedded Word object. The following example accesses a Word document object with the name Picture 1 (the name given to the object in Microsoft Excel, not a document filename) in the active worksheet:

Dim WordObj As Object
Set WordObj = ActiveSheet.OLEObjects("Picture 1")

In Microsoft Access Visual Basic, you use the Object property to access an embedded Word document. For example, you could use the following instructions to access a document embedded in an OLE control called OLE1:

Dim WordObj As Object
Set WordObj = Me!OLE1.Object.Application.WordBasic

The embedded object must be activated before it can be accessed. You can either include an instruction to activate the OLE control, or you can assume the object is activated in some other way (for example, the user double-clicks it). In Visual Basic version 3.0, you can use the Action property to activate OLE control. For example:

OLE1.Action = 7

In this instruction, OLE1 is the name of the OLE control in which the Word object is embedded.

In Visual Basic version 4.0, you can activate an OLE control using the Action property or the DoVerb method. For example, the following two instructions are equivalent:

OLE1.DoVerb(vbOLEShow)
OLE1.Action = 7

In Microsoft Excel Visual Basic, you use the Activate method to activate the Word object. In the following example, WordObj is an object variable in which the Word document object is stored:

WordObj.Activate

In Microsoft Access Visual Basic, you use the Action property to activate the Word object. For example:

Me!OLE1.Action = acOLEActivate

The following example accesses a Word object embedded in a Visual Basic version 4.0 container application. Then it uses the WordBasic EditSelectAll statement to select all the text, and the WordBasic Bold statement to format it as bold. The Check1.SetFocus instruction deactivates the embedded Word object and returns the focus to a checkbox named "Check1."

Dim WordObj As Object
OLE1.DoVerb(vbOLEShow)
Set WordObj = OLE1.Object.Application.WordBasic
WordObj.EditSelectAll
WordObj.Bold
Check1.SetFocus
Set WordObj = Nothing

Here is the same example using Microsoft Excel Visual Basic. The final instruction, Range("B6").Activate, deactivates the embedded Word object and activates cell B6 in the active worksheet.

Dim WordObj As Object
Set WordObj = ActiveSheet.OLEObjects("Picture 1")
WordObj.Activate
With WordObj.Object.Application.WordBasic
    .EditSelectAll
    .Bold
End With
Range("B6").Activate

Here is the same example using Microsoft Access Visual Basic. The final instruction, DoCmd.GoToControl "Check1", activates the check box named "Check1."

Dim WordObj As Object
Set WordObj = Me!OLE1.Object.Application.WordBasic
Me!OLE1.Action = acOLEActivate
WordObj.EditSelectAll
WordObj.Bold
DoCmd.GoToControl "Check1"
Set WordObj = Nothing

Retrieving Word Dialog Box Settings

You can retrieve Word dialog box settings when you're using OLE Automation to access either Word itself (through the "Basic" object) or an embedded Word document. To do so, you first create an object variable to hold the settings, and then place the settings in the object variable. For example:

Dim TOVvar As Object
Set TOVvar = WordObj.CurValues.FileOpen

The first instruction defines an object variable to hold the dialog box settings. The second instruction assigns the variable the current settings of the dialog box — in this case, the settings of the Open dialog box (File menu). WordObj is the object variable defined to access WordBasic. CurValues returns the dialog box settings from the dialog box specified. To specify a dialog box, you use the name of the WordBasic statement that corresponds to a Word dialog box. For example, FileOpen is the name of the WordBasic statement that corresponds to the Open dialog box (File menu). If you don't know the name to use for a dialog box, see "Language Summary" and "Statements and Functions" in Part 2, "WordBasic Reference."

Once you have placed the dialog box settings in an object variable, you use the following syntax to access them:

DialogObjectVar.DialogBoxSettingName

DialogBoxSettingName is the name of an argument for the WordBasic statement that corresponds to the dialog box whose settings are stored in DialogObjectVar. For the list of valid arguments, see the entry for the WordBasic statement in Part 2, "WordBasic Reference."

The following Visual Basic example toggles the Draft Font setting on the View tab in the Options dialog box (Tools menu). Note that if you are using Visual Basic version 3.0, you cannot use the instruction WordObj.ToolsOptionsView DraftFont := 0 since DraftFont is a named argument. Instead, you specify the argument positionally, as described in "Using Positional Arguments in Visual Basic Version 3.0" later in this chapter.

Dim WordObj As Object
Dim TOVvar As Object
Set WordObj = CreateObject("Word.Basic")
Set TOVvar = WordObj.CurValues.ToolsOptionsView
If TOVvar.DraftFont = 1 Then
    WordObj.ToolsOptionsView DraftFont := 0
Else
    WordObj.ToolsOptionsView DraftFont := 1
End If

Running Word Macros and Displaying Dialog Boxes

You can run a Word macro through OLE Automation, just as you can from within another Word macro. After the macro runs, control returns to the procedure that called it. You use the WordBasic ToolsMacro statement to run a macro. For example, the following instruction runs a macro called CountOpenWindows:

WordObj.ToolsMacro "CountOpenWindows", True

Word must be the active application if the macro displays a dialog box, message box, input box, or anything that requires a response from the user before the macro can continue. If Word is not the active application, the macro comes to a halt and eventually an OLE Automation error occurs. To make Word the active application, you can use an instruction similar to the WordBasic AppActivate statement in the container application's macro or programming language.

You can't directly define and display a dialog box through OLE Automation, but you can run a Word macro to display the dialog box. If the dialog box is a dialog box built into Word, you can then use the CurValues method to retrieve its settings. If the dialog box is a custom dialog box, the macro that displays the dialog box can save the dialog box settings so that they remain after the macro is finished. For example, the macro could save the settings in a settings file. For information on settings files, see "Using Settings Files and Document Variables" in Chapter 9, "More WordBasic Techniques."

Passing Values to a Word Macro

You cannot directly pass arguments to a Word macro or macro subroutine through OLE Automation. Within WordBasic, you can use the syntax MacroName.Subroutine [(ArgumentList)] to call subroutines in other macros and pass arguments to them, but this syntax is not supported by OLE Automation. If you want your Visual Basic code to run a WordBasic macro and to pass values to that macro, you must store those values in a location the macro can access. For example, you could store values in a settings file or in Word document variables. For information on settings files and document variables, see "Using Settings Files and Document Variables" in Chapter 9, "More WordBasic Techniques."

The following Visual Basic example runs a Word macro called CreateAndSaveNewDoc and displays a message when the macro is finished. The Visual Basic AppActivate statement is used to activate Word before the macro runs, since the macro will display the Save As dialog box.

Dim WordObj As Object
Set WordObj = CreateObject("Word.Basic")
AppActivate "Microsoft Word"
WordObj.ToolsMacro "CreateAndSaveNewDoc", True
MsgBox "The CreateAndSaveNewDoc macro is done."

You can also run this example in a Visual Basic version 3.0 application, but the Visual Basic version 3.0 AppActivate statement requires as an argument the same text that appears in the Word application window title bar. This text may change if a document window is maximized, so you need to add an If conditional to check whether this is the case and change the text specified in AppActivate accordingly. The following conditional uses the WordBasic functions CountWindows, DocMaximize(), and WindowName$() to accomplish this task:

If WordObj.CountWindows() > 0 Then
    If WordObj.DocMaximize() = True Then
        AppActivate "Microsoft Word - " + WordObj.WindowName()
    Else
        AppActivate "Microsoft Word"
    End If
Else
    AppActivate "Microsoft Word"
End If

Here is the CreateAndSaveNewDoc macro:

Sub MAIN
AppMaximize "Microsoft Word"
On Error Goto bye
FileNew
FileSave
AppActivate "Microsoft Excel"
bye:
End Sub

This macro maximizes the Word window (in case Word is minimized when the macro is called), then creates a new file and uses the FileSave statement to display the Save As dialog box (File menu). (This dialog box is displayed because the file has never been saved.) The AppActivate instruction at the end of the macro activates Microsoft Excel so that control returns to the routine that called the macro. If you are using Visual Basic version 4.0, you can use the AppActivate statement with the text from the application title bar (i.e. AppActivate "Form1")

Using Positional Arguments in Visual Basic Version 3.0

WordBasic statements that correspond to Word dialog boxes use named arguments — arguments whose values are associated with names. For example, .Font is the named argument in the following instruction:

FormatDropCap .Font = "Arial"

In Visual Basic version 4.0, Microsoft Excel Visual Basic, and Microsoft Access Visual Basic, you can call WordBasic instructions using named arguments, as shown in the following example:

WordObj.FormatDropCap Font:="Arial"

You cannot call a WordBasic instruction from Visual Basic version 3.0 using named arguments. Instead, you identify arguments by position. The following example shows a WordBasic instruction as it could appear in a Word macro:

FormatDropCap .Position = 1, .Font = "Arial", .DropHeight = 3, .DistFromText = 6

To use this instruction in a Visual Basic version 3.0 procedure, you would write the following:

WordObj.FormatDropCap 1, "Arial", 3, 6

In this instruction, WordObj is an object variable that refers to WordBasic. If you want to leave out an argument, you must indicate the missing argument with a comma, as shown in the following instruction:

WordObj.FormatDropCap , "Arial", , 6

Trailing commas can be omitted (for example, WordObj.FormatDropCap 1, "Arial" is valid; it isn't necessary to specify WordObj.FormatDropCap 1, "Arial", , ,).

Boolean "true" and "false" values are used to specify command buttons. For example, the following WordBasic instruction runs the macro CountOpenWindows:

ToolsMacro .Name = "CountOpenWindows", .Run

where .Run is the named argument equivalent to the Run button in the Macro dialog box. In a Visual Basic version 3.0 procedure, the instruction might appear as follows:

WordObj.ToolsMacro "CountOpenWindows", True

A true value is equivalent to choosing a command button; false is equivalent to not choosing it. The following instruction opens the CountOpenWindows macro for editing:

WordObj.ToolsMacro "CountOpenWindows", False, True

In WordBasic, the third argument is .Edit, so in Visual Basic version 3.0 a true value in the third position is equivalent to choosing the Edit button. Omitting a command button argument is equivalent to giving it a value of false.

Note

The syntax line for most statement and function entries in WordBasic Help describes the correct positional order of arguments. There are some exceptions, however. For a complete list of these exceptions and the correct order of their arguments, see POSITION.TXT on the Microsoft Word Developer's Kit disk (Windows).


Using MAPI and AOCE

In Windows, you can use the messaging application programming interface (MAPI) to provide a macro with the same kind of access to Microsoft Mail — and other mail applications that support MAPI — as it has to Word through WordBasic. Using MAPI, a macro can extract messages, retrieve names from the Microsoft Mail Address Book, send or read messages, and so on.

MAPI uses data types that WordBasic doesn't support — they are similar to WordBasic dialog records in that they combine values of different types (strings, numbers, and others). So WordBasic requires extensions of the MAPI functions to make the data available in a way that WordBasic can access it. These extensions are provided in WBMAPI.DLL on the Microsoft Word Developer's Kit disk. For more information on integrating Word and Microsoft Mail with WBMAPI.DLL, see Appendix A, "Workgroup Extensions for Microsoft Word," in Part 3, "Appendixes."

On the Macintosh, you can access Apple Open Collaboration Environment (AOCE) services from within WordBasic by using a set of WordBasic statements and functions provided for that purpose. For a list of these messaging statements and functions, see "Language Summary" in Part 2, "WordBasic Reference."


Chapter 9 More WordBasic Techniques

The first two sections of this chapter introduce different ways macros can store and retrieve information. Settings files, document variables, document properties, and AutoText entries, described in the first section, provide storage for variable values after a macro has run. Sequential file access, described in the second section, provides quick access to text files.

The third section of the chapter describes how you can use macros to automate
forms. The fourth section documents the STARTER.WIZ template (Windows) or the STARTER WIZARD template (Macintosh) supplied on the Microsoft Word Developer's Kit disk. This template is a starting point for developing wizards and provides the basic interface shared by every Word wizard.

The fifth section describes techniques for successfully calling routines from dynamic-link libraries (DLLs), which you can use to increase the capabilities
of your WordBasic macros.

The last sections describe developing WordBasic macros that work across all the platforms that support WordBasic (Windows 3.x, Windows 95, Windows NT, and the Macintosh) and techniques for distributing and optimizing macros.

In this chapter:

  • Storing values when a macro ends
  • Using sequential file access
  • Automating forms
  • Creating a wizard
  • Calling routines in DLLs and WLLs
  • Developing macros for more than one platform
  • Distributing macros
  • Optimizing macros


Storing Values When a Macro Ends

When a macro ends, the values stored in its variables are lost. If a macro needs to preserve a value, it must store that value outside itself, preferably in a place from which the value can be easily retrieved. Consider, for example, a document-numbering macro that runs each time a document is created and assigns a unique number to the new document. Each time a document is created, the macro must "remember" the number it assigned to the previous document the last time it ran, so that it can generate an appropriate new number. Then the macro must store the new number so that the number can be referenced the next time the macro runs.

This section describes how a macro can use a settings file, document variables, document properties, or AutoText entries to store information.

Settings Files

A settings file is a file used by programs and macros to store values; you can think of a setting as a variable stored in a file. In Windows terminology, WIN.INI, the settings file used by Microsoft Windows 3.x and many 16-bit Windows-based applications, is a "public" settings file because it can be used by more than one application. Settings files created for use by particular applications are "private" settings files. In Windows, settings files are text files and can be opened by a text editor like any other text file. On the Macintosh, settings files are not text files; they can only be edited directly using the ResEdit™ program.

WordBasic provides the SetPrivateProfileString statement and the GetPrivateProfileString$() function for accessing private settings files. You
use SetPrivateProfileString to assign a setting to a private settings file. Here is
the syntax:

SetPrivateProfileString Section$, KeyName$, Setting$, Filename$

Section$ is the name of a section within the settings file. KeyName$ is the name of the "key" — the equivalent of a variable name. Setting$ is the value you are assigning to the key. Filename$ is the name of the settings file. If the file doesn't exist, SetPrivateProfileString creates it. Here's what a typical Windows settings file might look like if you opened it in a text editor.

The settings files for Windows-based applications usually have filenames with
the .INI filename extension. ("INI" is short for "initialization"; a settings file is
also known as an initialization file because an application that is starting up, or initializing, can use its initialization file to retrieve settings from the last time it ran.) Although you can give any extension to the Windows settings files you create, using the .INI extension helps to make their purpose clear. On the Macintosh, it's similarly useful to include "Settings" in a settings filename. One advantage of creating a settings file with SetPrivateProfileString is that the file is stored automatically in the Windows folder in Windows or in the Preferences folder on the Macintosh (assuming you don't specify a path for Filename$). Since the instruction doesn't specify the name of the Windows or Preferences folder, your macro isn't dependent on a particular folder name or structure, and you can distribute it to other users without modification.

WordBasic does not include statements or functions to handle numeric values in settings files. To store a numeric value, first use the Str$() function to convert it to a string. To retrieve the value, use the Val() function to convert the string setting back to a number.

You use GetPrivateProfileString$() to retrieve the value of the specified KeyName$ stored in a settings file. Here is the syntax:

GetPrivateProfileString$(Section$, KeyName$, Filename$)

Section$, KeyName$, and Filename$ are used in the same way as the arguments in the SetPrivateProfileString statement.

You can use any number of settings files, but it's best to avoid using more files than necessary. In fact, you can use a single settings file for all your macros. Section headings provide a way to group settings and prevent key-name conflicts. For example, two different macros can both use a key called "Directory 1" without conflict, assuming the two key names are associated with different section names. In Windows, a settings file is just a text file, so you're not restricted to only using WordBasic instructions to access it. If you've forgotten what you've stored, you can always use Word to open a Windows settings file in a document window. On the Macintosh, you can use the ResEdit program to edit a settings file.

Examples

Here is a simple document-tracking macro that assigns a number to every new document. The macro is an AutoNew macro that runs whenever a new document is created. The macro uses GetPrivateProfileString$() to retrieve the current document number, increments it by 1, and then uses SetFormResult to insert the number in a form field. Finally, the macro uses SetPrivateProfileString to store the new number in the settings file.

Sub MAIN
docnum$ = GetPrivateProfileString$("DocTracker", "DocNum", "MACRO.INI")
docnum$ = Str$((Val(docnum$) + 1))
SetFormResult "DocNumField", docnum$
SetPrivateProfileString "DocTracker", "DocNum", docnum$, "MACRO.INI"
End Sub

Using a For…Next loop to retrieve or assign a large number of settings is a very useful technique. The following subroutine uses a For…Next loop to retrieve a list of seven folder names from a settings file and load them into an array. The key names for the folder names include numbers: "Dir 1" for the first key,
"Dir 2" for the second key, and so on. The loop uses these numbers to enumerate
the key names so that, instead of requiring a separate GetPrivateProfileString$() for each key name, the subroutine can use just one instruction.

Sub GetDirNames
For count = 1 To 7
    dirListname$ =  "Dir" + LTrim$(Str$(count - 1))
    dirNames$(count - 1) = GetPrivateProfileString$("DirList", \
                            dirListname$, "MACRO.INI")
Next
End Sub

This subroutine is used in the ChangeDirectory macro provided in the EXAMPLES.DOT (Windows) or MACRO EXAMPLES (Macintosh) template supplied on the Microsoft Word Developer's Kit disk. The macro displays the dialog box shown in the following illustration. By selecting one of the folders listed, the user can quickly move to that folder.

Using the WIN.INI File

WIN.INI is the "public" settings file used by Windows 3.x. Using the SetProfileString statement and GetProfileString$() function, you can store information in and retrieve information from the WIN.INI file in the same way you can with private settings files.

In addition to Windows 3.x, 16-bit Windows-based applications such as Word version 6.0 for Windows store settings information in WIN.INI, and this can lead to a large, inefficient file. For this reason, it's usually best not to store private settings in the WIN.INI file. But SetProfileString and GetProfileString$() can be useful for retrieving and changing Windows environment settings in WIN.INI.

Note

Windows 95 and Windows NT do not use the WIN.INI file. Instead, they store settings in the registry. SetProfileString and GetProfileString$() are available in Windows 95 and Windows NT, but there is no reason to use them, as they do not affect settings in the registry; in effect, they become limited versions of SetPrivateProfileString and GetPrivateProfileString$() that work with just one settings file that happens to be called WIN.INI.

Example

This Word version 6.0 example checks the Windows 3.x "long date" format. If the format doesn't match "dddd d MMMM yyyy" (for example, "Sunday 23 May 1993"), SetProfileString changes the setting to that format.

format$ = GetProfileString$("intl", "sLongDate")
If format$ <> "dddd d MMMM yyyy" Then
    SetProfileString "intl", "sLongDate", "dddd d MMMM yyyy"
End If

Accessing WINWORD6.INI and Word Settings (6)

Word version 6.0 for Windows settings are stored in a settings file called WINWORD6.INI; in Word version 6.0 for the Macintosh, they're stored in the Word Settings (6) file. In Windows, you can use GetPrivateProfileString$() and SetPrivateProfileString to retrieve and change settings. On the Macintosh, you can use GetProfileString$() and SetProfileString to change settings in the Word Settings (6) file. For example, the following Word version 6.0 for Windows instruction sets the Word DDETimeOut setting to 100 seconds in WINWORD6.INI:

SetPrivateProfileString "Microsoft Word", "DDETimeOut", \
    "100", "WINWORD6.INI"

Here is the equivalent instruction for Word version 6.0 for the Macintosh:

SetProfileString "Microsoft Word", "DDETimeOut", "100"

Accessing the Windows Registry

In Windows 95 and Windows NT, the registry is a system-wide database used for storing software and hardware configuration settings. The registry is created during system setup and is updated whenever you add or remove software or hardware. Windows 95 and Windows NT store settings in the registry instead of the WIN.INI file. You can view and edit the contents of the registry using the Registry Editor (REGEDIT.EXE in Windows 95, REGEDT32.EXE in
Windows NT).

While most settings for Word version 6.0 for Windows are stored in WINWORD6.INI, most settings for Word version 6.0 for Windows NT and Word version 7.0 are stored in the registry under the following key: HKEY_CURRENT_USER\Software\Microsoft\Word\6.0 (or 7.0).

From WordBasic, you can access the registry information using the GetPrivateProfileString$() function. You use an empty string ("") instead of the name of a settings file to specify the registry. For example, the following instruction assigns the Word version 7.0 document path (DOC-PATH) from the registry to the variable a$:

key$ = "HKEY_CURRENT_USER\Software\Microsoft\Word\7.0\Options"
a$ = GetPrivateProfileString$(key$, "DOC-PATH", "")

You can also modify information in the registry using the SetPrivateProfileString statement. Note that even though you can use SetPrivateProfileString to add keys to the registry, macro settings are best stored in a private settings file to avoid corrupting important application settings.

Example

The DateFormat setting in the registry sets the default date format for Word version 7.0. This example uses the SetPrivateProfileString statement to set the date format to "dddd d MMMM yyyy." A future date is calculated and the result is then displayed in the new date format.

Sub MAIN
key$ = "HKEY_CURRENT_USER\Software\Microsoft\Word\7.0\Options"
SetPrivateProfileString(key$, "DateFormat", "dddd d MMMM yyyy", "")
MsgBox Date$(Now() + 7)
End Sub

Document Variables

A document variable is a variable stored as part of a document. It is available
only when the document in which it is stored is the active document. Document variables are similar to key names in a settings file; they are accessed through the complementary SetDocumentVar statement and GetDocumentVar$() function. Here is the syntax for SetDocumentVar:

SetDocumentVar VariableName$, Text$

VariableName$ is the name of the document variable and Text$ is the string value you are assigning to the variable. Document variables accept only string values. Here is the syntax for GetDocumentVar$():

GetDocumentVar$(VariableName$)

Document variables are available only through WordBasic instructions, so the user cannot inadvertently change them. And since they are contained within the document, they travel with it: If you move the document to another computer, for example, the document variables remain available. A document can contain any number of document variables.

If you add document variables to a template, the variables, including their values, will be stored in all new documents that are subsequently based on the template.

Note

Document variables are not saved when a document is saved in rich-text format (RTF).

If you plan to store a document variable in a document that may contain other document variables, you should ensure that the variable name you are planning to use does not already exist in the document. Two functions are provided for this purpose: CountDocumentVars() and GetDocumentVarName$(). CountDocumentVars() returns the number of document variables stored
in the active document. Given a number between 1 and the value returned by CountDocumentVars(), GetDocumentVarName$() returns the name of the corresponding document variable. For example, the following instructions determine whether a document variable named "TrackingNum" already exists
in a document:

For count = 1 To CountDocumentVars()
    If GetDocumentVarName$(count) = "TrackingNum" Then
        MsgBox "TrackingNum already exists."
        Goto bye
    End If
Next
bye:

Deleting a Document Variable

WordBasic does not include a command to delete document variables, but if you set a document variable to an empty string, the document variable is removed. For example, the following instruction removes a document variable called ReminderMsg:

SetDocumentVar ReminderMsg, ""

The following instructions remove all of the document variables from a document:

For count = 1 To CountDocumentVars()

SetDocumentVar GetDocumentVarName$(1), ""

Next

Another way to remove all of the document variables in a document is to save the document in rich-text format (RTF). Since document variables are not saved in RTF, they will no longer be in the document.

Example

This macro displays a dialog box showing the revision history for a document
and providing a text box in which the user can type a new entry. Each entry in the revision history is stored in a document variable. Before displaying the dialog box, the macro retrieves the revision entries from the document variables and loads them into an array that will be displayed in a list box. If the user creates a new revision entry, the macro adds the current date as a prefix and stores the entry in a new document variable.

Sub MAIN
If CountDocumentVars() > 0 Then
    Dim docVarArray$(CountDocumentVars() - 1)
    For count = 1 To CountDocumentVars()
        docVarArray$(count - 1) = \
                     GetDocumentVar$(GetDocumentVarName$(count))
    Next
Else
    Dim docVarArray$(0)
End If
Begin Dialog UserDialog 508, 214, "Revision History"
    Text 12, 133, 105, 13, "New Revision", .Text2
    TextBox 12, 149, 453, 18, .NewRevision
    OKButton 380, 186, 88, 21
    CancelButton 282, 186, 88, 21
    Text 12, 6, 80, 13, "Revisions:", .Text1
    ListBox 12, 21, 473, 106, docVarArray$(), .ListBox1
End Dialog
Dim dlg As UserDialog
x = Dialog(dlg)
If dlg.NewRevision <> "" Then
    revVarName$ = "rev" + LTrim$(Str$(CountDocumentVars()))
    revText$ = Date$() + " - " + dlg.NewRevision
    SetDocumentVar revVarName$, revText$
End If
End Sub

Here is the dialog box, showing some sample revisions.

Document Properties

Like document variables, document properties allow you to store information along with a document. Document properties can be viewed and modified in the Properties dialog box (File menu). Unlike document variables, document properties can be inserted into a document using the DOCPROPERTY field.

Note

Document properties are available only in Word version 7.0.

Document properties are defined using the SetDocumentProperty statement. Here is the syntax for SetDocumentProperty:

SetDocumentProperty Name$, Type, Value[$], CustomOrBuiltIn

Name$ is the name of the document property and Type specifies the data type you want to store in the document property. Value[$] is the number, string, or date you are assigning to the document property. CustomOrBuiltIn specifies whether you are defining a custom or built-in property. (Document properties include custom properties that you add as well as built-in properties such as "Company.")

Examples

This example prompts for a company name and then set the results in the built-in "Company" document property.

CompanyName$ = InputBox$("Type your company name", "Company Name")
SetDocumentProperty("Company", 0, CompanyName$, 1)

The text you type appears as the company name on the Summary tab in the Properties dialog box (File menu).

The following macro displays a dialog box showing the built-in and custom document properties for the active document. Prior to displaying the dialog box, the macro retrieves the document property names and stores them in an array. If the user chooses OK, the contents of the selected property are inserted into the document.

Sub MAIN
Dim prop$(CountDocumentProperties() - 1)
For count = 1 To CountDocumentProperties()
    prop$(count - 1) = DocumentPropertyName$(count)
Next
Begin Dialog UserDialog 340, 144, "Document Properties"
    OKButton 229, 104, 88, 21
    CancelButton 131, 104, 88, 21
    ListBox 24, 12, 293, 84, prop$(), .property
End Dialog
Dim dlg As UserDialog
n = Dialog(dlg)
If prop$(dlg.property) <> "" And n = - 1 Then
    Insert prop$(dlg.property) + ":" + Chr$(9)
    type = DocumentPropertyType(prop$(dlg.property))
    Select Case type
        Case 0, 2, 3
            text$ = GetDocumentProperty$(prop$(dlg.property))
            Insert text$
        Case 1
            Num = GetDocumentProperty(prop$(dlg.property))
            Insert LTrim$(Str$(Num))
        Case Else
    End Select
End If
End Sub

The previous macro inserts document properties as plain text. You can also insert document properties using the DOCPROPERTY field. For example, the following instruction inserts a field that references the "Company" document property:

InsertField .Field = "DOCPROPERTY Company"

The DOCPROPERTY field ensures that the latest property information appears in your document when the field is updated.

AutoText Entries

AutoText entries can be used to store information in a template. The SetAutoText statement defines a text-only AutoText entry. Here is the syntax:

SetAutoText Name$, Text$ [, Context]

Name$ is the AutoText entry name, Text$ is the text defined with the AutoText entry, and Context indicates where the AutoText entry is stored (the active template or the Normal template). The complementary GetAutoText$() function retrieves the contents of an AutoText entry.

Example

The following macro defines an entry named INVOICE# in the active template (a template other than Normal). Each time the macro is run, the invoice number in the INVOICE# AutoText entry is incremented by one. If this macro were named AutoNew and stored in a special invoice template, the macro would automatically insert an invoice number with each new invoice created.

Sub MAIN
number = Val(GetAutoText$("INVOICE#", 1)) + 1
InvoiceNum$ = LTrim$(Str$(number))
SetAutoText "INVOICE#", InvoiceNum$, 1
Insert "Invoice: " + invoicenum$
End Sub


Using Sequential File Access

WordBasic includes a set of statements and functions you can use to access
text files without opening them in a document window. This kind of interaction
is called file input and output, or file I/O. Using file input, a macro can "read"
a file to retrieve information from it ("input" refers to input from the file into the macro). Using file output, a macro can "write" to a file to store information ("output" refers to output from the macro to the file). WordBasic supports sequential file I/O, or sequential file access, a kind of file I/O supported by most varieties of the Basic programming language. In sequential file access, the information in the file is usually read or written in sequence, from the beginning of the file to the end.

Sequential file access is used most often to provide a macro with information.
For example, a macro designed to work on a series of files can use sequential
file access to retrieve a list of filenames from a text file.

The advantage of sequential file access is that it's fast. If a macro needs to read or store information, sequential file access can do it more quickly than statements that open a file in a document window. The disadvantage, of course, is that sequential file access is more rigid than working with a file in a document window. It's difficult to go directly to a specific place in a file, and you can't
read from a file and write to it at the same time.

Note

Sequential file-access statements and functions are designed to work with text-only files, not Word document files. While it is possible to open a Word document for sequential access, it isn't useful to do so because Word documents contain formatting codes that make the file very difficult to read from or write to through sequential access. To work with a Word document, open it in a document window.

Opening a File for Sequential Access

When you open a file for sequential access, you specify whether you want to read from the file or write to it. If a macro needs both to read from and write to a file, it must open the file to read from it, close it, and then reopen the file to write to it. A macro can have as many as four files open at a time for sequential access.

To open a file for sequential access, you use the Open statement, which has the following syntax:

Open Name$ For Mode As [#]FileNumber

Name$ is the name of the file to open and FileNumber is a number between 1
and 4 that other sequential access instructions use to refer to the open file. Mode indicates how the file is to be used: for input, output, or appending. The modes are described as follows.

Mode | Explanation
Input | Opens the text file so that data may be read from the file into the macro. When you open a file for input you can use Read, Input, Line Input, and Input$() instructions to read from the file. If the specified text file isn't found, an error occurs.
Output | Opens the text file so that data may be written from the macro to the file. When you open a file for output, you can use Write and Print instructions to write to the file. Opening a file for output deletes the existing contents of the file, even if you do not write to the file. If the specified text file isn't found, a new file is created.
Append | Opens the text file so that data may be written from the macro to the file. When you open a file to append, you can use Write and Print instructions to write to the file. The existing contents of the file remain and the information you write is added to the end of the file. If the specified text file isn't found, a new file is created.

The following diagram shows the relationship between a macro and a text file in the different modes, along with the sequential file-access statements and functions available in those modes.

Writing to a File

WordBasic includes two statements for writing to a file: Write and Print. You can use these statements to write both strings and numbers. Each instruction creates a single line in a text file. In Windows, each line of the text file ends with the carriage-return and linefeed characters (character codes 13 and 10); on the Macintosh, each line ends with a single carriage-return (character code 13). You can think of each line as a single data record that can have multiple fields containing different values. Each Write and Print instruction writes sequentially to the text file, adding one line of data after another for as long as the file is open.

Write

The Write statement is designed to write data that can be easily read by the complementary Read statement. The syntax of Write is as follows:

Write #FileNumber, Expression1[$] [, Expression2[$]] [, ¼]

FileNumber refers to the number you assigned to the file when you opened it. An Expression contains the data you're writing to the file. Usually, Expression is a string or numeric variable, but it could also be a numeric expression or a function that returns a string or number. For example, the following instruction writes the currently selected text to a file:

Write #1, Selection$()

Write places quotation marks around string values, but not around numeric values; it places a comma between each value as a delimiter. For example, the instruction

Write #1, name$, age, employeeNum

creates a line such as the following in the text file:

"John Jones", 32, 12345

Print

Unlike Write, the Print statement does not have a complementary statement designed to read whatever it writes. Print is most useful if you want to write data to a file that may be read by another application. You can also use Print to write information to be read by the Line Input statement. The syntax for Print is as follows:

Print #FileNumber, Expression1[$] [; or , Expression2[$]] [; or , ¼]

FileNumber refers to the number you assigned to the file when you opened it. Expression contains the data you're writing to the file, usually a variable, number, or string.

String and numeric values can be separated by either a semicolon or a comma. Values separated by a semicolon are joined together in the text file with a space inserted before numbers. For example, the instruction

Print #1, name$; age; employeeNum

creates a line such as the following in the text file:

John Jones 32 12345

Values separated by a comma are separated by a tab character in the text file. For example, the instruction

Print #1, "Jones", "123 1st Street"

results in the following line, with a tab character between "Jones" and "123 1st Street":

Jones    123 1st Street

None of the WordBasic sequential access instructions that read files recognize
tab characters as delimiters, but many applications support file formats that use
tab characters as delimiters. For example, you could use Print to create a tab-delimited file for a database program.

Reading from a File

The sequential file-access statements Write and Print write information sequentially, adding one line of information after another for as long as the file
is open. The information is read in the same way; after one instruction reads information, the next instruction begins reading the next piece of information, in sequence. All the statements and functions that read sequential files read a line at a time (delimited by a paragraph mark), except Input$(), which reads a specified number of characters.

Read

The Read statement is designed to read information written with Write. Here is the syntax:

Read #FileNumber, Variable1[$] [, Variable2[$]] [, Variable3[$]] [, ¼]

Read can read both numeric and string values and can read multiple values from a single line when the values are delimited by commas. It removes quotation marks from string values (placed there by Write) and can also accept strings that are not enclosed in quotation marks. Read can accept a string with as many as 65,280 characters; longer strings are truncated. The following example reads values into one string variable and two numeric variables:

Read #1, name$, age, employeeNum

Input

Like Read, the Input statement can read multiple values from a single line when the values are delimited by commas. However, Input does not remove quotation marks from strings, so it doesn't work well with Write, which places quotation marks around string values. Input uses the same syntax as Read, as shown in this example:

Input #1, name$, age, employeeNum

Line Input

The Line Input statement reads an entire line, including commas or other delimiters, and places it into a string variable. Here is the syntax:

Line Input #FileNumber, Variable$

Variable must be a string variable, even if the line contains numbers only. A line is delimited by a paragraph mark. Line Input can accept lines as long as 65,280 characters; longer lines are truncated.

Input$()

With the Input$() statement, you specify exactly how many characters to read. Here is the syntax:

Input$(NumChars, [#]FileNumber)

NumChars is the number of characters Input$() reads from the file identified
by FileNumber. Input$() can read any number of lines (as many lines as are contained in the specified number of characters) and returns every character within the specified range of characters, including delimiters such as commas
and carriage returns.

Input$() is generally not as useful as the other statements that read sequential files, but you can use it to read a file that uses delimiters that the other sequential file-access statements and functions don't support.

In the following example, Input$() is used to read a file in which values are delimited by a space character. The file contains 20 employee numbers, which Input$() reads into an array. Each employee number is five characters long and is separated from the following number by a space. Each time Input$() reads five characters, it also moves the point at which data is read five characters ahead, so that the next Input$() instruction begins reading the next character. Because there is a space between each number, the macro includes the instruction space$ = Input$(1, #1), whose purpose is just to read the space preceding the next number. Otherwise, the second Input$() instruction would begin by reading
the space character and miss part of the next employee number.

Dim empNums(19)
Open "EMPNUMS.DAT" For Input As #1
    For count = 0 To 19
        empNums(count) = Val(Input$(5, #1))
        space$ = Input$(1, #1)
    Next
Close #1

Closing a File

As mentioned earlier, once you've opened a file in a specific mode — for input, output, or appending — you have to close it before you can open it in a different mode. For example, if a macro opens a file to read some information from it and then needs to overwrite the existing information or append additional information, it must close the file and then reopen it in the appropriate mode. Here is the syntax of the Close statement:

Close [[#]FileNumber]

FileNumber is the number of the file to close. If FileNumber is not specified, all files opened with the Open statement are closed.

Other Sequential Access Statements and Functions

WordBasic includes four other sequential file-access statements and functions: Eof(), Lof(), Seek, and Seek().

Eof()

The Eof() function returns a value of –1 when the end of a file has been reached. Typically, Eof() is used to control a While ¼ Wend loop that reads a file until it reaches the file's end. Here is the syntax for Eof():

Eof([#]FileNumber)

FileNumber is the number assigned to the file when it was opened. The following example reads a list of Word document filenames from a text file. For each document filename, the corresponding file is opened, the DoFormattingRoutine subroutine (not shown here) performs various formatting actions, and the file is closed. The Eof() function controls a While ¼ Wend loop, so that every filename in FILES.TXT is read until the end of the file is reached.

Sub MAIN
Open "FILES.TXT" For Input As #1
While Not Eof(#1)
    Read #1, file$
    FileOpen file$
    DoFormattingRoutine
    FileClose 1
Wend
Close #1
End Sub

Lof()

The Lof() function returns the length of a file, in bytes, opened with an Open instruction. Each byte corresponds to one character in the file. Among other things, you can use Lof() to determine whether a file contains any information. Here is the syntax for Lof():

Lof([#]FileNumber)

FileNumber is the number you assigned to the file when you opened it. The following example determines whether a file contains any information before opening it for output and overwriting it. After the file is opened for input, the Lof() function is used to determine whether or not the file already contains information. If it does, a message box is displayed, asking if you want to overwrite the file. If you choose the Yes button in the message box, the file
is closed and then reopened for output.

YES = - 1
Open "EMPNUMS.DAT" For Input As #1
If Lof(#1) > 0 Then
    answer = MsgBox("Do you want to overwrite this file?", 4)
    If answer = YES Then
        Close #1
        Open "EMPNUMS.DAT" For Output As #1
        'Series of instructions to write information to the file
    End If
End If
Close #1

Seek, Seek()

The Seek statement changes the point in a file at which information is retrieved or stored. Here is the syntax:

Seek [#]FileNumber, Count

The Seek() function returns the point in the file where information will next be retrieved or stored. Here is the syntax:

Seek([#]FileNumber)

Usually the Seek statement and Seek() function are used together. You use the Seek() function to return the position of an item; then you use the Seek statement to move directly to that location.

You can use Seek with other sequential access statements and functions to write information into the middle of a file rather than appending it at the end, but this technique has limited use. Whatever is written to the file overwrites the corresponding number of characters in the same position in the file.

The following example is part of a macro to sort mail messages by sender and by subject. The text file MSGS.TXT contains sender names and subject categories. This example searches for the heading "Monthly Reports" in the file, records its position in the variable readposition, and then closes the file. Next, the file is opened to append information to the file, and then closed again. Finally, the file is reopened for input and the instruction Seek #1, readposition moves directly to the position where the "Monthly Reports" heading is located.

Open "MSGS.TXT" For Input As #1
While Not Eof(#1) And searchtext$ <> "Monthly Reports"
    readposition = Seek(#1)
    Line Input #1, searchtext$
Wend
Close #1
Open "MSGS.TXT" For Append As #1
    'Series of instructions to append data to the file
Close #1
Open "MSGS.TXT" For Input As #1
Seek #1, readposition


Automating Forms

Macros can be used to automate the process of filling in Word forms. Information that would otherwise have to be typed manually can be filled in automatically. Custom commands can be created that are appropriate for a particular form.

Several types of macros are useful for automating forms. They include the following:

  • "On-entry" and "on-exit" macros. Every form field in a form can have an on-entry macro, triggered when the field is activated, and an on-exit macro, triggered when the user moves to another field.
  • Auto macros. Auto macros such as AutoNew and AutoClose provide a useful starting point for automation. For example, an AutoNew macro, triggered when a new form document is created, can run a series of other macros to guide the user through filling in the form. For more information on auto macros, see Chapter 2, "Getting Started with Macros."
  • Macros assigned to a menu or a toolbar. Users filling in forms customized for a particular task can often benefit from custom commands. Turning macros into custom commands and placing them on menus or a toolbar gives them accessibility and visibility.
  • MACROBUTTON fields. These fields, which trigger macros, provide
    another way to embed macros within a form. For example, you could use a MACROBUTTON field to insert a bitmap of a dialog box button that says "Click Here to Print." A button embedded in a form makes an important command hard to miss.

A form should be made into a template so that whenever a user wants to fill in a new form, he or she creates a new document based on the form template. The new form inherits the form's boilerplate text and formatting. Any macros used to automate the form can be stored in the template. If the template is protected for forms, so are new documents based on it.

Here are some other points to keep in mind when automating a form:

  • A drop-down form field can contain no more than 25 items. Use a dialog box when you want to present more items.
  • You can use the EditGoTo statement to move to a form field. The following instruction selects the form field named "Check1":

    EditGoTo "Check1"
  • "Check1" is the default bookmark name for the first check box form field inserted in a form. You can change a bookmark name for a form field by unprotecting the form and double-clicking the field.
  • For items that the macro will insert into the form — such as an invoice number or part number on an invoice — you can use either bookmarks or form fields to mark where the items are to be inserted. If you use form fields, you can use the SetFormResult statement to set the result of a form field. The following instruction inserts "Hello" into the "Text1" form field.

    SetFormResult "Text1", "Hello"
  • A form field isn't necessary unless you also want to allow the user to insert the information. Even when a document is protected for forms, a macro can insert information into any part of the document (unlike a user, who can type in form fields only). For example, the following instructions insert "Hello" at the beginning of the document:

    StartOfDocument
Insert "Hello"
  • Some WordBasic statements, such as InsertFormField, are not available when a document is protected for forms. In this case, the macro needs to unprotect the document, run the statement and then protect the document for forms. The following instructions unprotect the document, insert a text form field at the top of the document, and then protect the document for forms:

    If DocumentProtection() = 1 Then
    ToolsUnprotectDocument
    StartOfDocument
    InsertFormField .TextType = 0
    ToolsProtectDocument .Type = 2, .NoReset = 1
End If
  • If the .NoReset argument is not specified in a ToolsProtectDocument statement, unlocking and locking a document resets the form fields to their default results. If .NoReset is set to 1, Word does not reset form fields to their default results when a document is protected for forms (.Type = 2).
  • In Word version 7.0, the DocumentProtection() function returns a number indicating the type of document protection. In Word version 6.0, use the CommandValid() function to determine whether a document is protected.
  • You can connect a form to a database in several ways. For example, the invoice form described in this section uses dynamic data exchange (DDE)
    to query a Microsoft Excel database and then displays the information — customer names or products — in a dialog box. If you're working with a large number of items, however, loading them into the dialog box can be slow. Another solution would be to open the database within Microsoft Excel itself: to make it the active application, in other words. A Microsoft Excel macro could then send the information selected in the database to the form in Word.

    Another possibility would be to use the open database connectivity (ODBC) extensions for WordBasic to work with a database. A Word macro could then place the selected information in the appropriate field in the form. For information on using the ODBC extensions, see Appendix B, "ODBC Extensions for Microsoft Word," in Part 3, "Appendixes." Note that the ODBC extensions described in Appendix B are not available on the Macintosh.

  • When the Save Data Only For Forms option is selected (Save tab, Options dialog box, Tools menu), the Save As command (File menu) creates a comma-delimited record of the setting of every form field in a document. The record is the same as a record created with the Write instruction. You can write a macro to retrieve this record and add it to a database file.
  • You can use the SetFormResult statement to set the default result for a
    form field. A form field's default result is displayed each time a document
    is protected for forms. If you create a new document based on a protected template, the new document displays the default results of the form fields it contains.
  • You can use the SetFormResult statement without the Result[$] argument to update a calculation form field. For example, the following instruction updates the "Total" calculation form field:

    SetFormResult "Total"

For a complete list of form statements and functions, see "Language Summary" in Part 2, "WordBasic Reference."

Example

This form, including the macros described here, is available as INVOICE2.DOT (Windows) or INVOICE FORM (Macintosh) on the Microsoft Word Developer's Kit disk.

When a salesperson creates a new invoice, an AutoNew macro inserts a number for the Invoice Number and Customer's P.O. Number, and updates fields that indicate the Invoice Date, Date Ordered, and Date Shipped.

The new document is protected for forms, so the salesperson can type in form fields only and can't inadvertently disturb other parts of the form. Because the form is protected, the salesperson can use the tab key to move from one form field to another.

When the new invoice is created, the first form field — the New Customer check box — is automatically selected. When the user moves to the first form field in the address, an on-entry macro runs. The on-entry macro evaluates whether the New Customer check box is selected or cleared. If the check box is selected, indicating a new customer, the macro displays the New Customer dialog box as shown in the following illustration.

If the New Customer check box is cleared, indicating an existing customer, the macro displays a dialog box that allows the salesperson to query a Microsoft Excel database for the customer's address. He or she can type any part of the customer's name to get a list of customer names that match.

If a match is found, the macro displays a dialog box in which the salesperson can select the address he or she wants.

The macro then places the information in the Sold To area of the form. The salesperson can select the type of terms and shipping method from drop-down form field lists.

When the salesperson moves into the Quantity column, an on-entry macro displays the following dialog box showing a list of the items available.

When the salesperson selects the item and quantity, the macro then inserts this information into the form, along with the corresponding part number, unit price, and total amount. Each item selected by the salesperson is entered on a separate line of the form.

When the salesperson has entered all the items ordered in the invoice, he or she then chooses the Total Orders button in the Order Items dialog box. The macro adds the figures in the Total Amount column, calculates the sales tax (if any), and inserts the appropriate figures.

When the salesperson has completed the form, it is printed out and the data is saved. The modified Close command (File menu) sends the form data to a Microsoft Excel database that stores a record for every invoice.


Creating a Wizard

A wizard is a macro (or a set of macros) that creates a document or carries out
a task as directed by the user.

Like most computer programs, a wizard has two parts: the user interface that requests information from the user, and the behind-the-scenes part that carries
out the actions necessary to accomplish the task. The behind-the-scenes part of
a wizard varies according to what the wizard is designed to accomplish; every wizard is different in that respect. But the wizards that come with Word share
a common user interface, which is described in this section.

The Microsoft Word Developer's Kit disk includes two wizards, the Starter Wizard (STARTER.WIZ on the Windows disk, STARTER WIZARD on the Macintosh disk) and the Wizard Maker Wizard (MKWIZARD.WIZ on the Windows disk, WIZARD MAKER WIZARD on the Macintosh disk), to help you get started creating your own wizards. The Starter Wizard is a "blank" wizard that contains routines (common to all wizards) that manage the user interface. The Wizard Maker Wizard constructs a wizard using the same routines as those contained in the Starter Wizard. You can then complete the new wizard, adding more controls to the wizard dialog box and including routines to carry out the task you want the wizard to accomplish.

Note

This section assumes a familiarity with dynamic custom dialog boxes. If you're not familiar with custom dialog boxes and dynamic dialog boxes, see Chapter 5, "Working with Custom Dialog Boxes."

Wizard Templates

A wizard is stored in a template. In Windows, a wizard is stored in a template saved with the filename extension .WIZ rather than .DOT. When you save a template with the extension .WIZ in your template folder, Word identifies the template as a wizard in the list of templates and wizards displayed in the New dialog box (File menu). On the Macintosh, a wizard is a Word template with the file type WIZ! (you can use the SetFileCreatorAndType statement to change a template's file type). The wizard's filename is the name that appears in the list of templates and wizards displayed in the New dialog box (File menu). To be displayed in the New dialog box, a wizard must be saved in the template folder.

Every Word wizard contains an AutoNew macro that runs when the user creates a new document based on the wizard. The AutoNew macro calls the StartWizard macro, which does all the wizard's work. In effect, the StartWizard macro is the wizard; the template is just the container in which it's stored.

The StartWizard Macro

The StartWizard macro provided in the Starter Wizard template has the same design as the StartWizard macros in the wizard templates provided with Word. Its structure separates those parts of the macro that may need to be modified for a particular wizard from those parts that can be used by every wizard without modification. The following diagram shows how the macro code is organized.

'Global variables used by all wizards
        'Variable declarations
'Global wizard-specific variables
        'Variable declarations

Sub MAIN
        'Dialog box definition
End Sub

'** Wizard-specific subroutines and user-defined functions
        'Subroutines and functions here

'** Subroutines and user-defined functions used by all wizards
        'Subroutines and functions here

Function DialogCtrl(id$, action, sval)
        'Dialog function goes here
End Function

Many routines categorized as "wizard-specific" are shared by all wizards and are included in the Starter Wizard. These routines often do not need to be customized, but they can be. Some of these routines are described in detail later in the chapter, but it isn't necessary to understand how most of the routines work to take advantage of them in wizards you develop.

The following table lists all the wizard-specific routines included in the Starter Wizard and other Word wizards.

Name | Description
DoButtonClick | Responds to the user choosing a button or selecting an option on a dialog box panel.
GetHintName$() | Returns the AutoText name for the current panel's hint. Can be customized to return different AutoText names for different controls on the same panel.
NextPanel | Determines which panel is displayed next.
PrevPanel | Determines which panel was displayed previously.
RstDialog | Retrieves the wizard dialog box settings. Can call RstDlgPref, RstDlgValPref, and RstDlgMultiLinePref.
SaveDialog | Saves wizard settings. Can call SaveDlgPref, SaveDlgValPref, and SaveDlgMultiLinePref.

The following table lists the routines in the Starter Wizard and other Word wizards that are exactly the same in every wizard; they are not designed to be customized.

Name | Description
ChangePanel | Changes the wizard dialog box panel. Calls ShowHideControls.
DisplayHint | Displays a hint when the user chooses the Hint button. Calls the GetHintName$() function.
EnableControls | Enables and disables standard wizard controls. For example, if the last panel is displayed, the Next button is disabled.
ItemsInPanel | Stores the number of controls in a panel, plus the total number of previous controls in the PanelControls array.
RstDlgPref | Retrieves a string setting. Calls xFetchPref$().
RstDlgMultiLinePref | Retrieves a multiple-line text box setting. Calls xFetchPref$().
RstDlgValPref | Retrieves a numeric setting (for example, a check box setting). Calls xFetchPref$().

Name | Description
SaveDlgPref | Saves a string setting. Calls xStorePref.
SaveDlgValPref | Saves a numeric setting (for example, a check box setting). Calls xStorePref.
SaveDlgMultiLinePref | Saves a multiple-line text box setting. Calls xStorePref.
ShowHideControls | Shows or hides the controls in a panel. (Not used on the Macintosh or in Windows NT.)
xFetchPref$() | Retrieves settings from a settings file.
xStorePref | Stores settings in a settings file.

Note

The names of some routines in the Starter Wizard are slightly different from the names of those in the wizards that ship with Word. For example, the ShowHideControls subroutine is called SHControls in the Word wizards. The Starter Wizard uses the term "panel" to refer to a set of dialog box controls displayed at the same time, because that term is used in this book; the wizards that ship with Word use the term "state." Thus, subroutines in the Starter Wizard such as NextPanel and PrevPanel are called NextState and PrevState in the Word wizards.

The Wizard Interface

The interface shared by all the wizards included with Word consists of a dialog box with several panels. Each panel in the dialog box has its own set of controls, and each panel also shares a set of controls used to move between panels and to dismiss the dialog box. These standard controls are shown in the following illustration.

The Wizard Dialog Box Definition

A dialog box definition defines all the controls in a dialog box. Definitions for dialog boxes with more than one panel, such as wizard dialog boxes, are quite long because the definition must include the controls for all the dialog box panels.

In the wizard dialog box definition, the instructions defining the standard controls shared by every panel are defined first, followed by the controls for the first panel, the controls for the second panel, and so on.

Here is the dialog box definition in in the Starter Wizard's StartWizard macro:

Begin Dialog UserDialog 628, 276, wizname$, .DlgControl
'Controls shown in every panel: 0-8
    Picture 0, 238, 500, 11, "LinePic", 1, .LinePicA                    '0
    Picture 128, 238, 500, 11, "LinePic", 1, .LinePicB                '1
    OKButton 11, 215, 73, 21                                            '2
    PushButton 229, 250, 73, 19, "&Hint", .Hint                        '3
    CancelButton 313, 250, 80, 19                                    '4
    PushButton 401, 250, 71, 19, "<&Back", .Back                        '5
    PushButton 471, 250, 71, 19, "&Next>", .Next                        '6
    PushButton 550, 250, 75, 19, "&Finish", .FastForward                '7
    FilePreview 16, 12, 250, 214, .Preview                            '8
    StateItems(0) = 9
'Panel 1
    'Controls for the first panel go here
    ItemsInPanel 0    'The number of controls in 1st panel
'Panel 2
    'Controls for the second panel go here
    ItemsInPanel 0    'The number of controls in 2nd panel
'Panel 3
    'Controls for the third panel go here
    ItemsInPanel 0    'The number of controls in 3rd panel
End Dialog

The dialog box definition in the StartWizard macro is set up with nine standard controls. All these controls — except the file preview box and the OK button —
are displayed in every panel of the wizard dialog box. The file preview box is included in the standard controls because there can be only one per dialog box, and when a Word wizard uses this control in a panel, the control is always in the same location in the dialog box. Note that in Windows the line graphic displayed by the two picture controls is stored as two AutoText entries in the wizard template, rather than in a separate file. This ensures that the graphic is always available. (Two picture controls are necessary to create a line that extends the full width of the dialog box. On the Macintosh, only one picture control is needed, and the graphic is stored in a Macintosh resource fork.) The rest of the dialog box definition has placeholders for three panels, but you can add more panels as you need them.

Two other instructions within the dialog box definition require explanation: PanelItems(0) = 9 and ItemsInPanel 0. PanelItems() is an array defined (before the dialog box definition) with as many elements as the dialog box has panels. Each element of the array will store the number of controls in its corresponding panel, plus the total number of controls defined for previous panels. The standard controls that are defined first are stored in the element numbered 0 (zero), the controls for the first panel are stored in the element numbered 1, and so on. The instruction PanelItems(0) = 9 indicates that there are nine standard controls (or "items").

For the other panels, the subroutine ItemsInPanel is used to assign the number
of items to the PanelItems() array. The ItemsInPanel subroutine increments the array index number and adds the number of controls stored in the current panel to the total number of controls defined to that point in the dialog box definition. For example, if there are two controls in the first panel, the number 2 is added to the number of standard controls, 9, for a total of 11 controls. Other subroutines in the macro will be able to manipulate this array to hide or show the items in a panel, which is the most important task in managing the different panels. Here is the ItemsInPanel subroutine:

Sub ItemsInPanel(howMany)
LastPanel = LastPanel + 1
PanelItems(LastPanel) = howMany + PanelItems(LastPanel - 1)
End Sub

The global variable LastPanel stores the index number of the PanelItems() array. The variable howMany is the number of items in the current panel, which is passed to the subroutine when it is called.

Numeric Identifiers

The order of the controls in the StartWizard dialog box definition is important because the instructions in the dialog function that display and hide these controls use numeric identifiers. The numeric identifier for a control is determined by its position within the dialog box definition. Numeric identifiers are used because they are much faster than string identifiers in dialog boxes with many controls. Numeric identifiers are also efficient because you can use loops to operate on a group of controls. In wizards, loops are used to hide and display all the controls
in a dialog box panel.

As you're developing a wizard, you should use string identifiers rather than numeric ones, so that you can add and delete controls from the dialog box definition without having to change all the instructions that act on those controls. Then, when you have finished the dialog box, you can convert to numeric identifiers for better performance.

Managing the Dialog Box Panels

Each time the user chooses a button to move to a different panel, the controls
in the current panel must be hidden and the controls in the new panel must be displayed. In addition, if the user moves to the first panel, the Back button must be disabled; if the user moves to the last panel, the Next button must be disabled. The task of managing panels is shared among the various subroutines described here.

Before turning to those subroutines, though, consider a portion of the dialog function that determines which action to take if a user chooses one of the standard wizard buttons. Each Case instruction in the following Select Case control structure corresponds to the numeric identifier of one of the wizard's standard buttons. Note that Case 5 and Case 6 correspond to the user choosing the Back and Next buttons. In both cases, the ChangePanel subroutine is called.

Select Case idnum
    Case 3                'Hint
        DisplayHint
    Case 4                'Cancel, so exit dialog box
        fRet = 0
    Case 5                '<Back
        ChangePanel(Panel, PrevPanel(Panel))
    Case 6                'Next>
        ChangePanel(Panel, NextPanel(Panel))
    Case 7                'Finish, so exit dialog box
        fRet = 0
    Case Else
        'Shouldn't happen...
End Select

The ChangePanel subroutine takes two arguments: Panel (the number of
the current panel) and PrevPanel(Panel) if the Back button is chosen or NextPanel(Panel) if the Next button is chosen. PrevPanel() and NextPanel()
are user-defined functions that determine which panel is the next panel. Usually,
this is simply Panel + 1 or Panel - 1. Here is the NextPanel() function:

Function NextPanel(oldPanel)        'Determine the panel following oldPanel
If oldPanel = LastPanel Then
    NextPanel = oldPanel            'Safeguard -- do not modify
Else
    NextPanel = oldPanel + 1        'The normal, default case
End If
End Function

ChangePanel

The ChangePanel subroutine calls the ShowHideControls subroutine to hide the current panel and display the new one. Also, ChangePanel either hides or shows the FilePreview control and calls the EnableControls subroutine. The old argument corresponds to the current panel that will be hidden; the new argument indicates the new panel that will be displayed.

Sub ChangePanel(old, new)
ShowHideControls(PanelItems(old - 1), PanelItems(old), 0)
DlgVisible "preview", 1 - HideFilePreview(new)
ShowHideControls(PanelItems(new - 1), PanelItems(new), 1)
Panel = new
EnableControls
End Sub

ShowHideControls

This subroutine is called to hide the current panel and display the new one. (This subroutine is only necessary in Word version 6.0 for Windows. In Word version 6.0 for the Macintosh and Windows NT, and in Word version 7.0, a single DlgVisible instruction can show or hide a range of dialog box controls.) If ShowHideVal is equal to 1, the controls are shown; if it's equal to 0 (zero), they're hidden. The variables FirstControl and LastControl are the key values. They control the For ¼ Next loop, which hides or shows all the controls in a panel: FirstControl corresponds to the numeric identifier of the first control in a panel and (LastControl - 1) corresponds to the numeric identifier of the last control in a panel.

When the ChangePanel subroutine calls ShowHideControls to hide the current panel, it passes PanelItems(old - 1) as FirstControl. Each element in the array PanelItems(), you recall, corresponds to a panel in the dialog box. The number assigned to each element is the total number of dialog box controls defined up through the last control on the corresponding panel. For example, if 25 controls are defined for the first two panels (including the standard controls), PanelItems(2) is assigned the value of 25. If the third panel has 10 items, PanelItems(3) is assigned a value of 35. One final piece of the puzzle: WordBasic assigns numeric identifiers to dialog box controls starting with 0 (zero). So if a dialog box definition contains 35 controls, the last control is numbered 34. To hide the 10 controls in the third panel, you could write a loop that iterates from 25 to 35 – 1:

For i = 25 To (35 - 1)
    DlgVisible i, 0
Next

That is just what the ShowHideControls subroutine does:

Sub ShowHideControls (FirstControl, LastControl, ShowHideVal)
For i = FirstControl To LastControl - 1
    DlgVisible i, ShowHideVal
Next
End Sub

EnableControls

This subroutine controls which wizard button has the focus and which buttons are enabled. When the first panel is displayed, the Next button gets the focus and the Back button is disabled. When the last panel is displayed, the Next button is disabled and the Finish button gets the focus. Otherwise, both the Back button and the Next button are enabled, and the focus remains on the button chosen last.

Sub EnableControls
    If Panel = 1 Then
        DlgFocus 6                    'Give the Next> button the focus
        DlgEnable 5, 0                'Disable the <Back button
    ElseIf Panel = 2 Then
        DlgEnable 5, 1                'Enable the <Back button
    ElseIf Panel = LastPanel - 1 Then
        DlgEnable 6, 1                'Enable the Next> button
    ElseIf Panel = LastPanel Then
        DlgFocus 7                    'Give the Finish button the focus
        DlgEnable 6, 0                'Disable the Next> button
    EndIf
End Sub

Storing Wizard Settings

Every wizard contains a set of subroutines that save and retrieve settings, so
the wizard can "remember" the user's choices and present them as defaults the
next time the user runs the wizard. Some of the subroutines are designed to be customized for different wizards and some remain the same in every wizard.

On the Macintosh, DlgStoreValues and DlgLoadValues() are used to save and retrieve multiple settings. These instructions are not available in Windows, so the subroutines to save and retrieve settings are more complex. This section describes the Windows subroutines.

The SaveDialog subroutine saves the wizard dialog box settings. You can call three subroutines from the SaveDialog subroutine: SaveDlgValPref to save numeric values such as check box settings; SaveDlgPref to save the contents of a text box; and SaveDlgMultiLinePref to save the contents of a multiple-line text box. Each of these subroutines takes as an argument the string identifier of the control whose setting is to be saved. For example, the following instruction saves the setting of the control with the identifier Panel4CheckBox:

SaveDlgValPref "Panel4CheckBox"

Here is the framework of the SaveDialog subroutine:

Sub SaveDialog
'Panel 1
'Statements to save settings in panel 1 go here
'Panel 2
'Statements to save settings in panel 2 go here
'Panel 3
'Statements to save settings in panel 3 go here
'Panel 4
'Statements to save settings in panel 4 go here
End Sub

Likewise, there are three corresponding subroutines you can call from the RstDialog subroutine to restore settings to a newly opened wizard dialog
box: RstDlgValPref, RstDlgPref, and RstDlgMultiLinePref. Each subroutine takes two arguments: the string identifier of the control whose setting is to be restored and a default setting. The default setting is used only when there is no value to restore (the first time the wizard is used). For example, the following instruction restores the setting of the control with the identifier Panel4CheckBox; the default value is 0 (zero), which means the check box
is cleared:

RstDlgValPref "Panel4CheckBox", 0

The following example restores the setting of a text box with the identifier "Panel2TextBox"; the default text is an empty string (leaving an empty text box):

RstDlgPref "Panel2TextBox", ""

Here is the framework of the RstDialog subroutine:

Sub RstDialog
'Panel 1
'Statements to restore settings in panel 1 go here
'Panel 2
'Statements to restore settings in panel 2 go here
'Panel 3
'Statements to restore settings in panel 3 go here
'Panel 4
'Statements to restore settings in panel 4 go here
End Sub


Calling Routines in DLLs

In Windows, a macro can call routines in a dynamic-link library (DLL) or Word add-in library (WLL) to access capabilities that aren't directly available in WordBasic. Calls are often made to Windows API (application programming interface) routines, but they can be made to routines in any DLL that makes routines available for other programs. WLLs are a special kind of DLL written specifically for Word; WordBasic can call routines in a WLL in the same way it calls routines from a DLL.

On the Macintosh, DLL files are not available, but you can call routines stored in WLLs. In this section, the term DLL is used to refer to DLLs in Windows and Word add-in libraries in Windows or on the Macintosh.

Note

For information about writing Word add-in libraries using the Word API, see Appendix C, "Microsoft Word Application Programming Interface," in Part 3, "Appendixes."

Because DLL routines reside in files that are external to Word, you must let WordBasic know where it can find the routines you want to use. You provide this information with the Declare statement. Once you have declared a DLL routine, you can use it in your code like any other routine (although you have to be especially careful about the arguments that you pass to DLL routines).

There are two steps to using a DLL routine:

1. Tell WordBasic about the routine by using a Declare statement.

2. Make the actual call.

You declare a DLL routine only once in a macro. You then can call it any number of times from any subroutine or user-defined function used in the macro.

Declaring a DLL Routine

To declare a DLL routine, place a Declare statement outside a subroutine or
user-defined function. Typically, Declare statements are placed at the start of
the macro before any other statements.

If the routine does not return a value, declare it as a subroutine. For example:

Declare Sub SetWindowTextA Lib "User32" (hWnd As Long,\
    lpString As String)

If the routine returns a value, declare it as a function. For example:

Declare Function GetSystemMetrics Lib "User32" (num As Long) \
    As Long

In Windows 95 and Windows NT, function names are case-sensitive and must be declared exactly as they appear in the DLL.

Here are the same declarations in Word version 6.0 for Windows:

Declare Sub SetWindowText Lib "User" (hWnd As Integer, \
    lpString As String)
Declare Function GetSystemMetrics Lib "User" (num As Integer) As Integer

Note the Lib keyword in the Declare statement. The Declare statement can also contain an optional Alias keyword. The use of these keywords is explained under "Special Considerations When Declaring DLL Routines" later in this section.

For the complete syntax of the Declare statement, see Part 2, "WordBasic Reference."

Calling a DLL Routine

Once a routine is declared, you can then call it just as you would a WordBasic statement or function. The following example uses the GetSystemMetrics Windows API routine to determine whether a mouse is installed. The value 19 assigned to SM_MOUSEPRESENT is one of a number of values that can be passed to the GetSystemMetrics function. These values are listed in the Microsoft Win32® Software Development Kit.

Declare Function GetSystemMetrics Lib "User32" (num As Long) \
    As Long

Sub MAIN
    SM_MOUSEPRESENT = 19
    If GetSystemMetrics(SM_MOUSEPRESENT) Then MsgBox "Mouse installed"
End Sub

Important

WordBasic can't verify that you are passing correct values to a DLL routine. If you pass incorrect values, the routine may fail, which may cause unexpected behavior or errors in Word or the operating system. Take care when experimenting with DLL routines, and save your work often.

Special Considerations When Declaring DLL Routines

As you have probably realized, the declarations for DLL routines can be quite complex. The Microsoft Word Developer's Kit disk for Windows includes the text files WIN16API.TXT and WIN32API.TXT, which list WordBasic DLL routine declarations for the Windows API. You can search for the declarations you want in the text files, copy them, and paste them into your macro.

Once you have pasted the appropriate DLL routine declarations into your code, you simply call the routines like any other routine in your application. Because you have to take extra care when passing values to DLL routines, however, you should first read "Calling DLL Routines with Specific Variable Types" later in this section.

If you are attempting to call a routine in a DLL that is not part of the operating environment, you should consult the documentation for the DLL to determine the proper declaration for it.

Specifying the Library

The Lib LibName$ clause in the Declare statement tells WordBasic where to find the dynamic-link library. For the Windows 95 and Windows NT operating environment DLLs, this is either "User32," "GDI32," "Kernel32," or one of the other system DLLs such as "MMSystem." For Windows 3.x, this is either "User," "GDI," "Kernel," or one of the other system DLLs. For other DLLs, the LibName$ is a file specification that can include a path. For example:

Declare Function EnvString Lib "c:\win\strings.dll" (stringbuffer$, \
    stringnum As Long) As Long

If you are declaring a function in a loaded DLL or WLL, you do not need to specify the path.

Using an Alias

You can use the Alias keyword to call a routine by a different name within a macro. You may need to do this if the routine name is not a valid subroutine or function name in WordBasic. If a routine has a long name, you can use Alias to substitute a shorter one. For example, this Declare statement substitutes the name WinDir for the routine's longer name (GetWindowsDirectory):

Declare Function WinDir Lib "Kernel32" Alias "GetWindowsDirectoryA" \
    (stringbuffer$, stringnum As Long) As Long

Note that the routine's real name, GetWindowsDirectoryA, follows the Alias keyword and that the alias WinDir (the name given to the routine within the macro) follows the Function keyword.

Here is the same Declare statement for Windows 3.x:

Declare Function WinDir Lib "Kernel" Alias "GetWindowsDirectory" \
    (stringbuffer$, stringnum As Integer) As Integer

Now you can use this shorter name to call the GetWindowsDirectory routine:

WinPath$ = String$(145, "*")
worked = WinDir(WinPath$, Len(WinPath$))
MsgBox WinPath$

Calling DLL Routines with Specific Variable Types

Many DLL routines require or return variable types that are not supported in WordBasic. WordBasic, in turn, supports variable-length strings, which are not supported by most DLL routines. Therefore, you must take care when passing variables to and receiving variables from DLL routines.

DLL Routines That Use Strings

Windows 95 or Windows NT functions that use strings are typically available in two versions: ANSI and Unicode. Word version 7.0 and Word version 6.0 for Windows NT are ANSI applications and must, therefore, use ANSI versions of the API functions. The ANSI API functions have an "A" appended to the function name. For instance, the Windows 3.x function GetWindowsDirectory is GetWindowsDirectoryA in Windows 95 and Windows NT.

DLL Routines That Modify Strings

A DLL routine can modify a WordBasic string variable it receives as an argument. (Strings are always passed to DLL routines by reference.) Be careful when calling a DLL routine that modifies a string. A DLL cannot increase the length of a WordBasic string; it simply writes beyond the end of the string if
it is not long enough. This corrupts other areas of memory. You can avoid this problem by making the string argument long enough that the DLL routine can never write past the end of it.

For example, the GetWindowsDirectory routine returns the path for the Windows folder in its first argument:

Declare Function GetWindowsDirectoryA Lib "Kernel32" \
    (stringbuffer As String, stringnum As Long) As Long

A safe way to call this routine is to make the returned argument at least 255 characters long by filling it with characters — in this case, asterisk (*) characters — before it is passed by reference to the DLL routine:

path$ = String$(255, "*")
worked = GetWindowsDirectory(path$, Len(path$))

Most DLL routines (and all the routines in the Windows API) expect standard
C strings, which end in a "null character" (ANSI 0). Word converts all strings that
it passes to DLL routines to null-terminated strings. Visual Basic includes the ByVal keyword to specify that a string should be passed as a null-terminated string, but this keyword is not supported (or necessary) in WordBasic.

Note

Windows DLL routines generally do not return strings longer than 255 characters. While this is true of many other libraries, always consult the documentation for the routine in question.

The Double, Integer, and Long Variable Types

Two variable types are supported within WordBasic: strings and numbers (double-precision floating-point numbers). But in the Declare statement only, WordBasic supports two additional types, Integer and Long:

  • An Integer variable stores an integer value between -32,768 and 32,767 or between 0 and 65,535.
  • A Long variable stores a value between -2,147,483,648 and -2,147,483,647 or 0 and 4,294,967,295.

Integer and Long variables are used to export values from and import values to WordBasic. When WordBasic receives an Integer or Long value from a DLL routine, the value is converted into a double-precision floating-point value, the standard WordBasic numeric type.

If a function in Windows 3.x uses the type Integer, the corresponding function in Windows 95 and Windows NT uses Long.

In addition, the variable type Double is available in Declare. Double is a double-precision floating-point number equivalent to the standard WordBasic numeric type. When you define a variable as Double in a Declare instruction, it is the same as defining it as a numeric variable elsewhere in WordBasic.

Structured Variable Limitation

Some DLL routines take or receive variables referred to as "structures" in C,
as "records" in Pascal, or as "user-defined types" in Visual Basic. DLL documentation often uses the C terminology. WordBasic does not support structured variables (other than dialog records), so these routines calling DLL routines that return or require structured variables may cause unpredictable results.

Arrays

You can pass individual elements of an array in the same way you pass any variable. For example, you can use the sndPlaySound routine to play a series of .WAV files stored in an array:

Declare Function sndPlaySoundA Lib "WINMM"(sound$, flag As Integer) \
    As Long

Sub MAIN
WAVEFILECOUNT = 10
Dim WaveFile$(WAVEFILECOUNT - 1)
For i = 0 To WAVEFILECOUNT - 1
    worked = sndPlaySoundA(WaveFile$(i), 0)
Next i
End Sub

WordBasic does not support passing entire arrays to DLL routines.

Converting Common Declarations

The routines in DLLs are most commonly documented using C language syntax. To call them from WordBasic, you must translate them into valid Declare statements and call them correctly. When translating, you may find the following table useful; it lists common C language declarations and their WordBasic equivalents.

C language declaration | In WordBasic declare as |  | Call with
Pointer to a string (LPSTR) | S As String or S$ |  | A string variable
Pointer to an integer (LPINT) |  | L As Long |  | A long variable
Pointer to a long integer (LPDWORD) | L As Long |  | A long variable
Pointer to a structure (for example, LPRECT) | No equivalent |  | No equivalent

C language declaration | In WordBasic declare as | Call with
Integer (INT, UINT, WORD, BOOL) | L As Long (I As Integer in Windows 3.x) | A long variable (an integer variable in Windows 3.x)
Handle (hWnd, hDC, hMenu, and so on) | h As Long (h As Integer in Windows 3.x) | A long variable (an integer variable in Windows 3.x)
Long (DWORD, LONG) | L As Long | A long variable
Pointer to an array of integers | No equivalent | No equivalent
Pointer to a void (void *) | No equivalent | No equivalent

If the routine's return value is void, it should be declared as a subroutine (see "Declaring a DLL Routine" earlier in this section).


Developing Macros for More Than One Platform

The WordBasic macro language is shared across platforms, but there are a few things to take into account when developing cross-platform macros. This section organizes cross-platform issues into three areas:

  • Using platform-specific instructions and arguments
  • Handling platform-level differences
  • Moving cross-platform macros between platforms

Most of this section deals with differences between the Macintosh and Windows platforms. There are very few WordBasic differences between the Windows 3.x, Windows 95, and Windows NT versions of Word. For the most part, you don't need to worry about Windows differences unless you're declaring external functions, which may need to be declared differently in Windows 95 and Windows NT (see "Using the Declare Statement to Call External Routines" later in this section).

You use the AppInfo$() function to return the name of the current platform. In Windows, AppInfo$(1) returns a string containing "Windows," "Windows 95," or "Windows NT" and the version number; on the Macintosh, it returns a string containing "Macintosh" and the system software version number. After you've determined the platform, you use a control structure to run the appropriate block of instructions for that platform.

The following example uses InStr() to determine whether the string returned by AppInfo$(1) contains the word "Macintosh"; if it does, the flag variable, MacintoshFlag, is set to 1. A control structure then tests the value of the MacintoshFlag variable to determine whether to run instructions for Windows or for the Macintosh.

If Instr(AppInfo$(1), "Macintosh") <> 0 Then MacintoshFlag = 1
If MacintoshFlag = 0 Then
    ChDir "C:\WINWORD6\TEMPLATE"
    FileOpen "ARTICLE.DOT"
Else
    ChDir "HD:MICROSOFT WORD 6:TEMPLATES"
    FileOpen "ARTICLE TEMPLATE"
End If

Using Platform-Specific Instructions and Arguments

WordBasic includes a number of statements and functions that are specific to a particular platform. A statement or function intended for use on one platform only will produce an error if run on another platform. In addition, some dialog-equivalent statements take arguments that are valid on one platform only. Once you use AppInfo() to determine which platform the macro is running on, you can use a control structure to ensure that platform-specific statements, functions, and arguments run only when the macro is running on the appropriate platform.

The following paragraphs describe significant areas where Windows and Macintosh statements differ. For a complete list of Macintosh- and Windows-specific statements and functions, see "Language Differences Across Versions of Word" in Part 2, "WordBasic Reference."

Differences in Page Setup

Because of differences in printing and page setup in Windows and on the Macintosh, the FilePageSetup statement is available only in Windows. A separate set of statements is provided for page setup on the Macintosh: FileDocumentLayout, FileMacPageSetup, FileMacCustomPageSetupGX, and FileMacPageSetupGX. On a Macintosh with QuickDraw™ GX installed, use FileMacCustomPageSetupGX and FileMacPageSetupGX instead of FileMacPageSetup.

You can use the GetSystemInfo$() function to determine whether QuickDraw GX is installed. The return value of GetSystemInfo$(519) is "Yes" if QuickDraw GX is installed and "No" if it is not.

Custom Dialog Box Accelerators

When you display a custom dialog box on the Macintosh, accelerators specified in the dialog box definition do not appear with an underline. However, the accelerators do work as expected. After the user presses the COMMAND key, an underline appears under the specified characters.

To automatically display accelerators in a dialog box (without the user pressing the COMMAND key), add a MenuMode instruction to the macro before displaying the custom dialog box, as shown in the following macro:

Sub MAIN
MenuMode
Begin Dialog UserDialog 320,144, "Microsoft Word"
OKButton 10, 6, 88, 21
CancelButton 10, 30, 88, 21
CheckBox 150, 84, 100, 18, "C&heck Box", .CheckBox1
End Dialog
Dim dlg As UserDialog
n = Dialog(dlg)
End Sub

Differences in WordBasic Sort Order

The ANSI character sort order differs between the Macintosh and Windows. The specific sort order of ANSI characters is relevant when you write WordBasic macros that compare strings. The sort order is predictable for alphabetic and numeric characters (for example, "A" comes before "B" and "3" comes before "4"). However, the sort order for the remaining characters is not predictable. To determine whether "!" is greater than or less than "?" on the current platform, you can create an array of those characters and use the SortArray() function to sort them.

Screen Updating

In Windows, the ScreenUpdating statement turns off screen updating so that changes to document and application windows are not displayed on the screen. On the Macintosh, changes within document windows are not displayed, but changes to the document window frame are displayed. For example, if a document window is moved while screen updating is turned off, the document window frame is shown in the new position. Likewise, if a document is opened while screen updating is turned off, the document's window frame will be displayed (the document itself will appear blank until screen updating is turned on, or until the macro ends).

Using SendKeys

On the Macintosh, a SendKeys instruction can send no more than 10 keystrokes, and can send them only to Word; SendKeys cannot be used to send keystrokes to another application. You can send a SHIFT key combination using the plus sign (+), but you cannot send key combinations including OPTION or COMMAND. For a list of keystrokes supported by SendKeys, see Part 2, "WordBasic Reference."

Differences in Custom Dialog Box Capabilities

On the Macintosh, you can store the picture displayed in a picture dialog box control in a "resource fork" (you can use Picture or DlgSetPicture to specify a resource fork as the storage place). Also available on the Macintosh are two instructions, DlgStoreValues and DlgLoadValues(), with which you can store and load custom dialog box settings. In Word version 6.0 for the Macintosh, Word version 6.0 for Windows NT, and Word version 7.0, you can use a single DlgVisible instruction to show or hide a range of controls (in Windows 3.x, a single DlgVisible instruction can affect one control only).

The DlgFocus statement does not change the focus in a Word version 6.0 for the Macintosh custom dialog box.

The following commands, which control the size or position of custom dynamic dialog boxes in the Windows versions of Word, are not available and generate errors in Word version 6.0 for the Macintosh: AppSize, AppMove, AppWindowHeight, AppWindowWidth, AppWindowPosTop, AppWindowPosLeft

Making a Network Connection

In Windows, you can use the Connect statement to connect to a network drive; on the Macintosh, you can use the MountVolume statement. You can use Connect to display the Connect dialog box; MountVolume does not have a dialog box associated with it.

Handling Platform-Level Differences

Even when a WordBasic statement or function has the same result on all platforms, the code may need to be different. Different platforms have different system-specific functionality such as file-naming conventions that need to be considered in cross-platform macros.

Specifying Filenames and Paths

In Windows, you use the question mark (?) and asterisk (*) wildcards to specify a group of files. Wildcards are not accepted on the Macintosh, but you can use the MacID$() function to specify files of a certain type. A Macintosh file type is a unique four-letter label assigned to every file created by a Macintosh application (you can use the FileType$() function to determine a file's type).

The following example creates a list of all the text files in a folder (the MacintoshFlag variable has been set earlier in the macro):

If MacintoshFlag = 0 Then
    textfilename$ = Files$("*.TXT")
Else
    textfilename$ = Files$(MacID$("TEXT"))
End If
Insert textfilename$
While textfilename$ <> ""
    textfilename$ = Files$()
    Insert textfilename$
Wend

MacID$() can also be used to specify file types with the FileOpen and Kill statements. The following instructions display the Open dialog box showing a list of all the template files in a folder (the MacintoshFlag variable has been set earlier in the macro):

Dim dlg as FileOpen
GetCurValues dlg
If MacintoshFlag = 0 Then
    Chdir "C:\WINWORD\TEMPLATE"
    dlg.Name = "*.DOT"
Else
    Chdir "HD1:WORD:TEMPLATES"
    dlg.Name = MacID$("WTBN")
End If
choice = Dialog(dlg)
If choice Then FileOpen dlg

Note

Although MacID$() appears to return a string, it actually returns a value that doesn't correspond to any WordBasic data type. Consequently, MacID$() should be used only with the statements described here that accept the internal value it returns. In addition, you cannot concatenate the value returned by MacID$() with a path string; instead, you use ChDir to change the current folder.

You can use MacID$() with a Macintosh application signature to specify an application. MacID$() can be used to specify an application with the following instructions: AppActivate, AppClose, AppCount, AppGetNames, AppGetNames(), AppIsRunning(), and Shell. MacID$() provides a more reliable way to specify an application than the application name, because the user may change the application name but is not likely to change the Macintosh application signature. The following example uses MacID$() with AppIsRunning() and Shell to determine whether Microsoft Excel is running, and to start it if it isn't.

If AppIsRunning(MacID$("XCEL")) = 0 Then Shell MacID$("XCEL")

Note that you don't need to specify a path or folder when you use MacID$() to specify an application.

Using Settings Files

There are a few differences to be aware of when working with settings files in Windows 3.x and on the Macintosh.

  • If you don't specify a path in the filename for SetPrivateProfileString or GetPrivateProfileString, Word stores or looks for the file in the Windows folder in Windows or the Preferences folder on the Macintosh.
  • In Windows, settings files are text files and they can be opened by a text editor like any other text file. On the Macintosh, settings files are not text files; they can be edited directly using the ToolsAdvancedSettings command or the ResEdit program.
  • The Macintosh does not include an equivalent of the Windows WIN.INI file that can be accessed by SetProfileString and GetProfileString$().
  • In Word version 6.0 for Windows, settings are stored in a settings file called WINWORD6.INI; in Word version 6.0 for the Macintosh, they're stored in a file called Word Settings (6). You can use SetPrivateProfileString and GetPrivateProfileString$() to change settings in WINWORD6.INI or Word Settings (6). For example:

    a$ = GetPrivateProfileString$("Microsoft Word", "USER-DOT-PATH", \
        "Word Settings (6)")

Note

Windows 95 and Windows NT do not use the settings files WIN.INI and WINWORD6.INI. Instead, settings are stored in the registry. For information about returning and setting values in the registry, see "Accessing the Windows Registry" earlier in this chapter.

Working with DDE

When an application runs on more than one platform, the same application may have a different application name in Windows and on the Macintosh. For example, in Windows, the DDE application name for Microsoft Word is "WinWord," whereas on the Macintosh, it's "MSWord," although "WinWord" is also accepted.

The instructions used to initiate DDE conversations are the same in Windows and on the Macintosh, but since DDE application names may be different on different platforms, separate instructions may be necessary for each platform. Also, it's a good idea to use MacID$() to specify an application on the Macintosh if you use the AppIsRunning() and Shell instructions when initiating a DDE conversation. In the following example, a different block of instructions for each platform is used to initiate a DDE conversation with Microsoft Excel (the MacintoshFlag variable has been set earlier in the macro). Note that Microsoft Excel has the same DDE application name in Windows and on the Macintosh, so separate DDEInitiate() instructions are not needed.

If MacintoshFlag = 0 Then
    If AppIsRunning("Microsoft Excel") = 0 Then Shell "EXCEL.EXE", 4
    chan = DDEInitiate("Excel", "System")
Else
    If AppIsRunning(MacID$("XCEL")) = 0 Then Shell MacID$("XCEL"), 4
    chan = DDEInitiate("Microsoft Excel", "System")
End If
chan = DDEInitiate("Excel", "System")
topics$ = DDERequest$(chan, "Topics")
Insert topics$

Using the Declare Statement to Call External Routines

In Windows, you can use the Declare statement to call routines stored in a dynamic-link library (DLL) or a Word add-in library (WLL). On the Macintosh, only routines stored in a WLL can be called. When a macro created in a Windows version of Word is converted to Word version 6.0 for the Macintosh, any Declare statements that refer to Windows DLLs will return the WordBasic error 543, "Unable to open specified library."

Declare instructions in macros ported from Word version 6.0 for Windows to Word version 7.0 or Word version 6.0 for Windows NT need to be modified. Because you cannot declare an external routine in a 16-bit library from a 32-bit application, such as Word version 7.0 or Word version 6.0 for Windows NT, you must update macros that declare routines in 16-bit libraries to identify the 32-bit versions of those libraries. Also the names, locations, and parameters of many Windows 3.x operating system routines (often referred to as API calls) changed in Windows 95 and Windows NT. You must update macros that declare Windows 3.x API calls to declare the correct routines in Windows 95 or Windows NT. Windows 95 and Windows NT function libraries are documented in the Microsoft Win32 Software Development Kit.

Unlike routine names in Windows 3.x, routine names are case-sensitive in Windows 95 and Windows NT. In addition, some routines need to be declared with different variable types in Windows 95 or Windows NT: INT return values or parameters must be declared as LONG; handles must be declared as LONG. For more information on using the Declare statement, see "Calling Routines in DLLs" earlier in this chapter.

Moving a Cross-Platform Macro Between Platforms

There are two potential problems that can occur when you move a macro with platform-specific instructions between Word version 6.0 for Windows and Word version 6.0 for the Macintosh. These problems occur when one version of Word does not recognize instructions that are supported in another version. Specifically, Word version 6.0, 6.0a, and 6.0c for Windows do not support the Macintosh-specific WordBasic statements and functions available in Word version 6.0 for the Macintosh. In this situation, the following two problems can occur:

  • If you develop a macro in Word version 6.0, 6.0a, or 6.0c for Windows and then move the macro to Word version 6.0 for the Macintosh, instructions specific to the Macintosh version of Word will produce an error — error 124, "Unknown command, subroutine, or function" — until the macro is edited on the Macintosh (the macro must be "dirtied").
  • If you develop a macro in Word version 6.0 for the Macintosh, move the macro to Word version 6.0 or 6.0a for Windows, and then edit and save the macro in Windows, Macintosh-specific keywords will be removed from the macro; they will not be restored if the macro is moved back to the Macintosh. (The macro should still run correctly in Windows, since the Macintosh-specific instructions should not run on the Windows platform anyway. But the macro will no longer run correctly if it is moved back to the Macintosh.) Note that this problem does not occur in Word version 6.0c for Windows.

Note

These problems do not occur if you develop cross platform macros in Word version 7.0 or Word version 6.0 for Windows NT.

Typically, a cross-platform macro is developed on one platform and then tested on the other platforms for which it is intended. If you're working with Word version 6.0 or 6.0a for Windows, you need to avoid editing the macro on more than one platform. That is, once you choose a platform for developing a Word 6.0 or 6.0a cross-platform macro, you must stick with it; if you edit the macro on more than one platform, you may encounter problems.

If you develop cross-platform macros in Word for Windows, you need to make sure the macros run properly on the Macintosh before you distribute them. You may want to distribute your cross-platform macros in execute-only format so that they cannot be edited (you use the MacroCopy statement to make a macro execute-only). If you don't want to distribute your cross-platform macros in execute-only format (that is, if you don't want to disable editing), you run the risk that a user will edit the macro.

Moving a Macro with Extended Characters Between Platforms

In Windows and on the Macintosh, different character codes are used to represent international characters. If you create a macro that contains string values with international characters in them (for example, á, ç, and ö), these characters will change when the macro is opened or run on another platform. To avoid this result, use the following steps to move the macro between platforms:

1. Copy the text of the macro from the macro-editing window into a new document and save the document.

2. Open the document on the other platform, save it in Text Only format, close it, and then open it again.

3. Copy the text from the document into a new macro-editing window.

Note that distributing a macro as execute-only does not correct this behavior. If you need to distribute a macro with extended characters in string values, you must create separate templates with unique versions of the macro for each platform.


Distributing Macros

Once you've created a few macros, you may want to distribute your macros to other Word users. The way in which you distribute your macros depends on how you intend others to store, run, or modify them. There are also important issues to consider before distributing a macro for use in another language version of Word.

Distributing Macros with a Local Template

Distributing your macros to others can be as easy as distributing the template where your macros are stored. For example, if you've created a template for an automated form or a Wizard, you can distribute your macros by giving the template to others. They can then copy the template to their User Templates location specified on the File Locations tab in the Options dialog box (Tools menu). Alternatively, you can write a setup macro or program that automatically copies the template to the appropriate location using the CopyFile statement. You can use the GetPrivateProfileString$() function to retrieve the User Templates location from the system settings file or the registry.

Note

Most users have a Normal template on their computer, so if your macros are currently stored in your Normal template you shouldn't distribute them by giving others your Normal template. Instead, create a new template and use the Organizer to copy the appropriate macros into the new template. Save and distribute the new template instead of your Normal template.

Prior to distributing a macro, you can make it "execute-only" so that other people can only run your macro. When a macro is execute-only, the Edit button in the Macro dialog box (Tools menu) is unavailable (dimmed) when the macro name is selected. The execute-only format is best used when you don't want other people to be able to view or edit your macro. To make a macro execute-only, use the MacroCopy statement in another macro. Be sure to make a backup copy of your macro prior to making it execute-only. Once the macro is execute-only, you won't be able to view or edit the instructions.

If you're working in a workgroup setting and want everyone to have access to your macros, you can copy your template to the Workgroup Templates location specified on the File Locations tab in the Options dialog box (Tools menu). The Workgroup Templates location allows multiple users to access a group of templates from one network share. Templates that are used by everyone in the workgroup are copied to this location. Templates from the User Templates and Workgroup Templates locations are available in the New dialog box (File menu). When you update your macros, you can copy the updated template to the Workgroup Templates location. This distribution technique ensures that everyone is using the latest version of your macros.

Distributing Macros with a Global Template

If the macros you want to distribute are not specific to a particular type of document, users may want to run your macro from any document (regardless of the attached template). To be run this way, the macro needs to be stored in a loaded global template. Users can temporarily load a global template by selecting the template in the Templates And Add-ins dialog box (Templates command, File menu). Alternatively, you can write a setup macro that uses the AddAddIn statement to load a template as a global template. The template is not, however, permanently loaded as a global template.

Templates stored in the Startup folder are automatically loaded as global templates when Word starts. If you want your global template loaded automatically, you can ask users to manually copy the file to their Startup folder, or you can write a setup macro. The setup macro can copy the template to the Startup folder using the CopyFile statement (use the GetPrivateProfileString$() function to retrieve the Startup folder location from the system settings file or the registry).

Loading templates globally consumes memory. A way to control this is to allow the user to dynamically load or unload the template at the click of a button. As a result, the template is only loaded into memory when the user needs to run the macros in the template. The following macro uses the AddInState statement to load or unload a global template.

Sub MAIN
state = AddInState("agenda.dot")        'check current state
If state = 1 Then
    AddInState "agenda.dot", 0        'load template
Else
    AddInState "agenda.dot", 1        'unload template
End If
End Sub

During an installation macro, this macro can be copied to the user's Normal template and assigned to a toolbar button. Use the MacroCopy or the Organizer statement to copy a macro to the Normal template, and use AddButton to add a toolbar button.

Another distribution technique is to write an AutoOpen macro that copies macros from the current template to the user's Normal template. Use the MacroCopy or Organizer statement to copy macros between templates. However, because users may have a number of macros already in their in Normal template or may have macros with the same names as the macros you want to copy, this technique is not the preferred way of distributing macros.

Distributing Macros Without a Template

If you want to distribute a macro without a template, you can save your macro as a text file. Open your macro in a macro-editing window and choose Save Copy As from the File menu. Type a file name and then choose Save. You can send the text file to another Word user. To run the macro, the user can copy the instructions from the text file into a new macro.

Distributing Macros Internationally

Microsoft Word is available in many different languages. At some point, you may need to distribute your macro to someone using a different language version of Word. Functionally, the programs are the same, but distributing macros between different language versions of Word requires some forethought.

WordBasic macros that are stored in templates are stored in a "tokenized" format. Macro keywords (statements and arguments such as "EditFind" and ".Name") are compressed and stored as three-byte tokens. When you edit a macro, the tokens are decoded into keywords for the current language of Word. For example, if a macro is written in the English (US) version of Word and then opened in the German version of Word, the WordBasic keywords will appear in German. The command to open a new document appears as "FileNew" in the English version of Word and "DateiNeu" in the German version of Word.

While macro keywords are translated, string values are not translated between languages. The following table demonstrates how English instructions are translated into German. The text enclosed in quotation marks is not translated.

English instruction | Instruction translated into German
Insert "Hello World" | Einfügen "Hello World"
Style "Tag Line" | Formatvorlage "Tag Line"
EditGoTo "Bookmark2" | BearbeitenGeheZu "Bookmark2"
MsgBox "Insert Disk A" | MsgBox "Insert Disk A"

To run in multiple language versions of Word, your macro must determine the current language version and then use the appropriate string values for that version. Use the AppInfo$() function to determine the current language version, as shown in the following example.

Sub MAIN
lang$ = AppInfo$(16)                'Determine the language version
Select Case lang$
Case "English (US)"                'English version
    sometext$ = "Hello World"
Case "Deutsch"                    'German version
    sometext$ = "Hallo Welt"
Case Else
End Select
Insert sometext$
End Sub

For a list of language names returned by the AppInfo$() function, see ToolsLanguage in Part 2, "WordBasic Reference."

Tip

Macros that use numerous strings can either use arrays to store strings for each language or return strings stored in a text file by using sequential file access.

The default measurement unit specified on the General tab in the Options dialog box (Tools menu) and the decimal separator in most languages is different from the defaults in the English (US) version of Word. Because of this, measurements you specify in statements such as FormatParagraph and FilePageSetup may not work as expected or may cause syntax errors when the macro is run in another language version of Word.

You can use the same technique described earlier for creating message string values to create measurement unit string values.

Sub MAIN
lang$ = AppInfo$(16)                'Determine the language version
Select Case lang$
Case "English (US)"                'English version
    points$ = "pt"
Case "Espagñol"                    'Spanish version
    points$ = "pto"
Case Else
End Select
FormatParagraph .LeftIndent = "36" + points$
End Sub

An alternative is to specify a numeric value for arguments that accept either a numeric or string value, because the default measurement unit of a numeric value for a given argument is the same across multiple language versions of Word. For example, the default unit for a numeric value specified for the .LeftIndent argument of FormatParagraph is points. Therefore, the following statement works in any language version of Word.

FormatParagraph .LeftIndent = 36            '36 points in any language

For information about the default measurement units of numeric values for an argument of a specific statement, see the corresponding entry in Part 2, "WordBasic Reference."

The English (US) version of Word uses a period (.) for a decimal separator, while most European countries use a comma (,). You can use the AppInfo$() function to determine the decimal separator. Once you know the character, you can create a string that includes the decimal separator ("12.5" or "12,5" in the following example).

dec$ = AppInfo$(18)    'Get the decimal separator
FormatParagraph .LeftIndent = "12" + dec$ + "5 pt"

No matter which language version of Word you are using, if you specify a numeric value for an argument that accepts either a numeric or string value, you must use a period for the decimal separator. A comma decimal separator generates a syntax error. For example, if the following statements in an English (US) macro were opened in the German version of Word, the translated versions would be equivalent:

FormatParagraph .LeftIndent = "12,5 pt"
FormatParagraph .LeftIndent = 12.5


Optimizing Macros

When you first start to write macros, you'll probably be satisfied with simply getting the job done. However, when you write a macro that will be used many times or that will be used by other people, you should consider optimizing the macro so that it requires less time and memory to run. The following techniques will help you write smaller, faster macros.

  • Specify only the arguments you need. The macro recorder explicitly sets all available arguments. For example, the macro recorder records the following instruction when you close the Paragraph dialog box.

    FormatParagraph .LeftIndent = "0" + Chr$(34), .RightIndent = "0" + Chr$(34), .Before = "0 pt", .After = "0 pt", .LineSpacingRule = 2, .LineSpacing = "", .Alignment = 0, .WidowControl = 1, .KeepWithNext = 0, .KeepTogether = 0, .PageBreak = 0, .NoLineNum = 0, .DontHyphen = 0, .Tab = "0", .FirstIndent = "0" + Chr$(34)

    However, if you only want to change the line spacing to double, you can delete the additional arguments from the FormatParagraph instruction. For example:

    FormatParagraph .LineSpacingRule = 2
  • A macro that changes the appearance of a document — such as a macro that changes the formatting of every table in a large document — will run faster when screen updating is turned off. Use the ScreenUpdating statement at the beginning of your macro to prevent screen updates while the macro is running. You can use the Print statement to let the user know the progress of the macro (for example, Print "Working...").

    If you want to show changes on the screen while a macro is running, you can improve performance by switching to normal view, using picture placeholders, disabling background repagination, and using the draft font, all of which are accomplished by the following instructions:

    ViewNormal
ToolsOptionsView .PicturePlaceHolders = 1, .DraftFont = 1
ToolsOptionsGeneral .Pagination = 0

    At the end of the macro, be sure to restore the settings back to the user's original settings.

  • Minimize the use of global variables. Reuse local or temporary variables instead of defining additional variables. Also, reuse arrays and dialog records by using the Redim statement to reset the variables.
  • Keep variable names, label names, and text between quotation marks short. These items don't "tokenize" when a macro is run and can slow down processing time. Remark statements (REM) and blank lines also don't tokenize and can slow down a macro.

    Note that while these tips may improve performance, your macro will lose readability. For this reason, it may be best to make these changes just before distributing a macro.

  • The Select Case control structure executes faster than a complex If...Then...Else condition. The For...Next loop is faster than the While...Wend loop.
  • The GetText$() function is faster than selecting text and using the Selection$() function. You can often use GetSelStartPos(), GetSelEndPos(), and SetSelRange instead of bookmarks. These commands are faster than setting and using bookmarks.
  • Calling a subroutine in another macro is slower than calling a subroutine in the same macro. You may want to copy frequently called subroutines into the same macro.
  • You cannot turn off the Undo or Redo commands on the Edit menu, nor can you change the maximum number of actions Word stores in the Undo or Redo lists (Word stores up to approximately 100 or the total number of actions in one document). If you are experiencing out-of-memory errors or slow performance, try periodically clearing the Undo and Redo lists by calling the following subroutine.

    Sub ClearUndoList
Dim Dlg As ToolsRevisions
GetCurValues Dlg
ToolsRevisions .MarkRevisions = Abs(Dlg.MarkRevisions - 1)
ToolsRevisions .MarkRevisions = Dlg.MarkRevisions
End Sub
  • If you are experiencing out-of-memory errors with a macro that makes extensive edits to a document, save the document periodically without fast saves active. For example, the following macro replaces all semicolons with tabs in a document. The If statement and count variable are used to save the document after every 50 replacements.

    Sub MAIN
ToolsOptionsSave .FastSaves = 0
StartOfDocument
count = 0
EditFindClearFormatting
EditFind .Find = ";", .Direction = 0
While EditFindFound()
    count = count + 1
    EditClear
    Insert Chr$(9)
    If count = 50 Then
        FileSave
        count = 0
    End If
    RepeatFind
Wend
End Sub
  • If possible, move commonly used routines into a Word add-in library (WLL). Word add-in libraries are faster and more efficient than thier equivalent WordBasic macros. For information on creating Word add-in libraries, see Appendix C, "Microsoft Word Application Programming Interface."


Language Differences Across Versions of Word

The Microsoft Word Developer's Kit documents the WordBasic programming language for the following versions of Microsoft Word:

  • Microsoft Word versions 6.0, 6.0a, and 6.0c for Windows (referred to as Microsoft Word version 6.0 for Windows)
  • Microsoft Word version 6.0 for the Macintosh
  • Microsoft Word version 6.0 for Windows NT
  • Microsoft Word for Windows 95 (referred to as Microsoft Word version 7.0)

All these versions of Word share a majority of WordBasic's functionality. However, there are a handful of differences in WordBasic between each version. For example:

  • Word version 6.0 for the Macintosh cannot run statements such as AppActivate and AppSendMessage that rely on Windows features, while the Windows versions of Word cannot run statements such as EditPublish and EditSubscribe that rely on Macintosh features.
  • None of the versions of Word earlier than Word version 7.0 can run statements and functions for Word features that were added to Word for Windows 95.
  • In Word version 6.0 for Windows NT and Word version 7.0, the arguments for GetPrivateProfileString$() and SetPrivateProfileString changed to allow setting and returning values in the registry.

The following sections list these and other differences in detail. You can use this information along with the cross-platform programming guidelines in Chapter 9, "More WordBasicTechniques," (Part 1, "Learning WordBasic") to develop WordBasic macros that run without error in any version of Word listed earlier.


Statements and Functions Used Only in the Windows Versions of Word

The following table lists WordBasic statements and functions that rely on Windows features and therefore cannot be run in Word version 6.0 for the Macintosh.

Statement or function | Description
AppActivate; AppClose; AppCount(); AppGetNames, AppGetNames(); AppHide; AppIsRunning(); AppMaximize, AppMaximize(); AppMinimize, AppMinimize(); AppMove; AppRestore, AppRestore(); AppSendMessage; AppShow; AppSize; AppWindowHeight, AppWindowHeight(); AppWindowPosLeft, AppWindowPosLeft(); AppWindowPosTop, AppWindowPosTop(); AppWindowWidth, AppWindowWidth() | Control application windows
Connect | Connects to a disk or directory shared across the network
ControlRun | Runs the Clipboard or Control Panel
Environ$() | Returns a string associated with an MS-DOS environment variable
ExitWindows | Exits Windows
FilePrintSetup | Changes the active printer or its options
HelpWordPerfectHelp; HelpWordPerfectHelpOptions | Control the Help For WordPerfect™ Users feature
MicrosoftAccess; MicrosoftPublisher; MicrosoftSchedule; RunPrintManager | Start the specified application
ToggleScribbleMode | Toggles hand annotation mode on and off


Statements and Functions Used Only in Word Version 6.0 for the Macintosh

The following table lists WordBasic statements and functions that rely on Macintosh features and therefore cannot be run in any of the Windows versions of Word.

Statement or function | Description
AOCEAddRecipient; AOCEAuthenticateUser(); AOCEClearMailerField; AOCECountRecipients(); AOCEGetRecipient$(); AOCEGetSender$(); AOCEGetSubject$(); AOCESendMail; AOCESetSubject; FileAOCEAddMailer; FileAOCEDeleteMailer; FileAOCEExpandMailer; FileAOCEForwardMail; FileAOCENextLetter; FileAOCEReplyAllMail; FileAOCEReplyMail; FileAOCESendMail | Send and receive letters through PowerTalk™ and return information about the active letter
DlgStoreValues; DlgLoadValues, DlgLoadValues() | Save or retrieve custom dialog box settings
EditCopyAsPicture | Copies the selected text or object to the Clipboard as a picture
EditCreatePublisher; EditPublishOptions; EditSubscribeOptions; EditSubscribeTo | Use the publishing and subscribing features in Word for the Macintosh

Statement or function | Description
EditFindBorder; EditFindFrame; EditFindTabs; EditReplaceBorder; EditReplaceFrame; EditReplaceTabs | Specify additional formats in find and replace operations
FileCreator$(); FileType$(); SetFileCreatorAndType | Set and determine Macintosh application signatures and file types
FileDocumentLayout; FileMacCustomPageSetupGX; FileMacPageSetup; FileMacPageSetupGX | Control page formatting for the entire document or specified sections
FilePrintOneCopy | Prints a single copy of the active document
FileQuit | Exits Word
MacID$() | Converts a Macintosh application signature or file type to a value for use with AppActivate, AppClose, AppCount, AppGetNames, AppGetNames(), AppIsRunning(), Files$(), FileOpen, Kill, or Shell
MacScript, MacScript$() | Runs an AppleScript script
MountVolume | Connects to a disk or folder shared across the network
Outline, Outline(); Shadow, Shadow() | Apply additional character formats
ShowClipboard | Displays the Clipboard and its contents


Statements and Functions Used Only in Word Version 7.0

The following statements and functions were added to Word version 7.0 and therefore cannot be run in earlier versions of Word. For more detailed lists and descriptions of each new WordBasic statement and function, see "What's New in WordBasic" in Word version 7.0 Help.

Statement or function | Description
CountAutoCorrectExceptions(); GetAutoCorrectException$(); IsAutoCorrectException(); ToolsAutoCorrectCapsLockOff, ToolsAutoCorrectCapsLockOff(); ToolsAutoCorrectExceptions | Control new AutoCorrect features
AddAddress; GetAddress$(); InsertAddress; MailMergeUseAddressBook | Add addresses to or return addresses from the default MAPI address book

Statement or function | Description
Highlight; HighlightColor, HighlightColor() | Apply highlighting format
CountDocumentProperties(); DeleteDocumentProperty; DocumentPropertyExists(); DocumentPropertyName$(); DocumentPropertyType(); FileProperties; GetDocumentProperty(), GetDocumentProperty$(); IsCustomDocumentProperty(); IsDocumentPropertyReadOnly(); SetDocumentProperty; SetDocumentPropertyLink | Set and access built-in and custom document properties
EditFindHighlight; EditFindNotHighlight; EditReplaceHighlight; EditReplaceNotHighlight | Specify additional formats in find and replace operations
AutomaticChange; HelpMSN; ShowMe; TipWizard | Use new Help features
DocumentHasMisspellings(); NextMisspelling; SpellChecked, SpellChecked(); ToolsSpellingRecheckDocument | Control background spelling features
DocumentProtection() | Indicates the level of protection for the active document
FilePost | Posts the active document to a public folder in Microsoft Exchange
MailCheckNames; MailHideMessageHeader; MailMessageDelete; MailMessageForward; MailMessageMove; MailMessageNext; MailMessagePrevious; MailMessageProperties; MailMessageReply; MailMessageReplyAll; MailSelectNames | Manage Word Mail messages


Statements with Version-Specific Arguments

The following statements, which correspond to Word dialog boxes, have arguments that are ignored or are not available in every version of Word.

Statement | Version-specific arguments
ConvertObject | The .IconFilename and .DisplayIcon arguments are ignored in Word version 6.0 for the Macintosh.
DlgVisible | The LastIdentifier argument is not valid in Word version 6.0 for Windows.
EditFindFont | The .Outline and .Shadow arguments are valid in Word version 6.0 for the Macintosh only.
EditReplaceFont | The .Outline and .Shadow arguments are valid in Word version 6.0 for the Macintosh only.
FileFind | The .ShowFolders argument is valid in Word version 6.0 for the Macintosh only. The .SearchName, .Options, .PatternMatch, .View, .SortBy, .ListBy, .SelectedFile, .ShowFolders, .Add, and .Delete arguments are ignored in Word version 7.0.
FilePrint | The .OutputPrinter argument is valid in Word version 6.0 for the Macintosh only.
FilePrintSetup | The .DoNotSetAsSysDefault argument is valid in Word version 7.0 only.
FormatBordersAndShading | The .FineShading argument is ignored in the Windows versions of Word.
FormatFont | The .Outline and .Shadow arguments are valid in Word version 6.0 for the Macintosh only.
HelpTipOfTheDay | The .StartupTips argument is not valid in Word version 7.0.
InsertObject | The .IconFilename and .DisplayIcon arguments are ignored in Word version 6.0 for the Macintosh.
ToolsAutoCorrect | The .CapsLock argument is valid in Word version 7.0 only.
ToolsOptionsAutoFormat | The .ApplyBulletedLists, .ReplaceOrdinals, .ReplaceFractions, .ApplyBorders, .ApplyNumberedLists, and .ShowOptionsFor arguments are valid in Word version 7.0 only.

Statement | Version-specific arguments
ToolsOptionsCompatibility | The .ShowBreaksInFrames, .SwapBordersFacingPages, .SuppressTopSpacingMac5, .SpacingWholePoints, .PrintBodyTextBeforeHeader, .NoLeading, and .MWSmallCaps arguments are not valid in Word version 6.0 for Windows. The .NoSpaceForUL, .NoExtraLineSpacing, .TruncateFontHeight, and .SubFontBySize arguments are valid in Word version 7.0 only.
ToolsOptionsEdit | The .TabIndent argument is valid in Word version 7.0 only.
ToolsOptionsGeneral | The .Effects3D argument is ignored in Word version 7.0. The .ConfirmConversions and .TipWizardActive arguments are valid in Word version 7.0 only.
ToolsOptionsPrint | The .Draft and .Background arguments are ignored in Word version 6.0 for the Macintosh.
ToolsOptionsRevisions | The .HighlightColor argument is valid in Word version 7.0 only.
ToolsOptionsSpelling | The .AutomaticSpellChecking, .HideSpellingErrors, and .RecheckDocument arguments are valid in Word version 7.0 only.
ToolsOptionsView | The .Highlight argument is valid in Word version 7.0 only.
ViewToolbars | The .ToolTipsKey argument is valid in Word version 7.0 only.


Statements and Functions with Version-Specific Behavior

The following statments and functions exhibit different behavior depending on the version of Word in which they are run.

Statement or function | Version-specific behavior
AppInfo$() | The strings returned by the values 9 and 10 are meaningful only in Word version 6.0 for Windows running in Windows 3.x and Word version 6.0 for the Macintosh. The value 26 is valid in Word version 7.0 only.
Beep | In the Windows versions of Word, the sound produced by Beep is determined by the ErrorType argument; in Word version 6.0 for the Macintosh, Beep always produces the sound selected in the Sound control panel.

Statement or function | Version-specific behavior
DDEExecute | In Word version 6.0 for the Macintosh, you cannot use DDEExecute to send keystrokes to another application.
Declare | In Word version 6.0 for Windows, you can only declare external functions in 16-bit libraries. In Word version 6.0 for the Macintosh, you can only declare external functions in Word add-in libraries (WLLs). In Word version 6.0 for Windows NT and Word version 7.0, you can only declare external functions in 32-bit libraries. In addition, external function names are case-sensitive. For detailed information about using Declare in all versions of Word, see "Calling Routines in DLLs" in Chapter 9, "More WordBasic Techniques" (Part 1, "Learning WordBasic").
DlgSetPicture | In Word version 6.0 for the Macintosh, PictureName$ accepts a value to indicate a PICT file stored in the resource fork of the template containing the macro.
DOSToWin$(), WinToDos$() | In Word version 6.0 for the Macintosh, these statements perform no translation and return the original string unchanged.
FileFind | In Word version 6.0 for the Macintosh, you use the . ShowFolders argument to group filenames by folder. In Word version 7.0, you cannot specify multiple folders with .SearchPath, and you cannot display the Find File dialog box using a Dialog or Dialog() instruction.
FileNameInfo$() | In Word version 6.0 for the Macintosh, FileNameInfo$(3) and FileNameInfo$(4) return the same value (since Macintosh filenames do not have "extensions"). In Word version 6.0 for the Macintosh, FileNameInfo$(6) returns a string that begins with the zone and computer name where the specified file is stored.

Statement or function | Version-specific behavior
FileOpen | In Word version 6.0 for the Macintosh, you can use this statement to open only one file at a time. In Word version 6.0 for the Macintosh, if you open a document with FileOpen, the case of the document window's title will match the case of text specified by the .Name argument. For example, the instruction FileOpen .Name = "my file" opens a document called "My File" in a document window with the title "my file."
Files$() | In the Windows versions of Word, the question mark (?) and asterisk (*) wildcards are accepted as file specifiers. On the Macintosh, wildcards are not accepted; MacID$() is used instead.
GetAttr() | In Word version 6.0 for the Macintosh, the System and Archive attributes are not supported.
GetPrivateProfileString$() | In Word version 6.0 for Windows and Word version 6.0 for the Macintosh, the arguments specify sections and key names in a particular settings file. In Word version 6.0 for Windows NT and Word version 7.0, the arguments can specify keys and values in the registry.
GetSystemInfo, GetSystemInfo$() | In the Windows versions of Word, Type is a value from 21 to 32, and the size of the array filled by GetSystemInfo is 12 elements. In Word version 6.0 for the Macintosh, Type is a value from 512 to 523, and the size of the array is 15 elements. The strings returned by the values 23, 25 and 27 are meaningful only in Word version 6.0 for Windows running in Windows 3.x.
HelpExamplesAndDemos, HelpQuickPreview | In Word version 6.0 for Windows NT and Word version 7.0, the examples, demonstrations, and previews are not available and these statements generate errors.
InputBox$() | In the Windows versions of Word, if the user presses enter in an input box, InputBox$() returns Chr$(11)+Chr$(10); in Word version 6.0 for the Macintosh, Chr$(13) is returned.
InsertSound | In the Windows versions of Word, starts Sound Recorder; in Word version 6.0 for the Macintosh, starts Microsoft Voice Annotation.
Kill | In the Windows versions of Word, the question mark (?) and asterisk (*) wildcards are accepted. On the Macintosh, wildcards are not accepted; MacID$() is used instead.

Statement or function | Version-specific behavior
ListCommands | This statement is not valid in Word version 6.0 for Windows.
MailMergeCreateDataSource; MailMergeDataSource$(); MailMergeEditDataSource; MailMergeOpenDataSource; MailMergeQueryOptions | ODBC functionality is not supported in Word version 6.0 for the Macintosh.
MsgBox, MsgBox() | In the Windows versions of Word, a Type value of 32 produces a question symbol; in Word version 6.0 for the Macintosh, it produces an information symbol. In Word version 6.0 for the Macintosh, a message box will not have a title bar if Title$ is an empty string ("").
Name | In the Windows versions of Word, you can use this statement to move a file to another directory; in Word version 6.0 for the Macintosh, Name does not provide this capability.
Picture | In Word version 6.0 for the Macintosh, PictureName$ accepts a value to indicate a PICT file stored in the resource fork of the template containing the macro.
ScreenUpdating | In Word version 6.0 for the Macintosh, the contents of document windows are not updated when screen updating is turned off, but document frames remain visible.
SendKeys | In Word version 6.0 for the Macintosh, you can use SendKeys to send keystrokes (10 or fewer) only to Word; you cannot use SendKeys to send keystrokes to other applications. Also, you can send a key combination that includes SHIFT by using the plus sign (+), but you cannot send key combinations that include OPTION or COMMAND.
SelInfo() | The value 37 is valid in Word version 7.0 only.
SetAttr | In Word version 6.0 for the Macintosh, the System and Archive attributes are not supported.
SetPrivateProfileString | In Word version 6.0 for Windows and Word version 6.0 for the Macintosh, the arguments specify settings, sections, and key names in a particular settings file. In Word version 6.0 for Windows NT and Word version 7.0, the arguments can specify settings, keys, and values in the registry.
ShadingPattern, ShadingPattern() | In Word version 6.0 for the Macintosh, shading pattern values 35 through 61 apply shading patterns in 2.5% increments.

Statement or function | Version-specific behavior
Shell | In the Windows versions of Word, the WindowStyle argument determines how an application started by Shell is displayed; in Word version 6.0 for the Macintosh, WindowStyle determines whether or not the application is activated. In Word version 6.0 for the Macintosh, you can use MacID$() to specify an application name.
ToolsAdvancedSettings | In Word version 6.0 for Windows NT and Word version 7.0, you cannot use this statement to modify settings in the registry.
ToolsCustomizeKeyboard | The Windows CTRL key is equivalent to the Macintosh COMMAND key; the Windows ALT key is equivalent to the Macintosh OPTION key. An additional value is available to assign the Macintosh COntrol key.


Language Summary

WordBasic keywords are listed here by category. Refer to this section when you know what you want to do but not which commands you need to accomplish the task, or when you want to learn about related statements and functions. Keywords appear alphabetically in each list; some keywords appear in more than one category.


Address Book

  • AddAddress
  • GetAddress$()
  • InsertAddress
  • MailMergeUseAddressBook


Application Control

  • AppActivate
  • AppClose
  • AppCount()
  • AppGetNames, AppGetNames()
  • AppHide
  • AppInfo$()
  • AppIsRunning()
  • AppMaximize, AppMaximize()
  • AppMinimize, AppMinimize()
  • AppMove
  • AppRestore, AppRestore()
  • AppSendMessage
  • AppShow
  • AppSize
  • AppWindowHeight, AppWindowHeight()
  • AppWindowPosLeft, AppWindowPosLeft()
  • AppWindowPosTop, AppWindowPosTop()
  • AppWindowWidth, AppWindowWidth()
  • ControlRun
  • DDEExecute
  • DDEInitiate()
  • DDEPoke
  • DDERequest$()
  • DDETerminate
  • DDETerminateAll
  • DialogEditor
  • ExitWindows
  • FileExit
  • FileQuit
  • GetSystemInfo, GetSystemInfo$()
  • MacID$()
  • MacScript, MacScript$()
  • MicrosoftApplication
  • RunPrintManager
  • SendKeys
  • Shell
  • ShowClipboard


AutoCorrect

  • CountAutoCorrectExceptions()
  • GetAutoCorrect$()
  • GetAutoCorrectException$()
  • IsAutoCorrectException()
  • ToolsAutoCorrect
  • ToolsAutoCorrectCapsLockOff, ToolsAutoCorrectCapsLockOff()
  • ToolsAutoCorrectDays, ToolsAutoCorrectDays()
  • ToolsAutoCorrectExceptions
  • ToolsAutoCorrectInitialCaps, ToolsAutoCorrectInitialCaps()
  • ToolsAutoCorrectReplaceText, ToolsAutoCorrectReplaceText()
  • ToolsAutoCorrectSentenceCaps, ToolsAutoCorrectSentenceCaps()
  • ToolsAutoCorrectSmartQuotes, ToolsAutoCorrectSmartQuotes()


AutoText

  • AutoText
  • AutoTextName$()
  • CountAutoTextEntries()
  • EditAutoText
  • GetAutoText$()
  • InsertAutoText
  • Organizer
  • SetAutoText


Basic File Input/Output

  • Close
  • Eof()
  • Input
  • Input$()
  • Line Input
  • Lof()
  • Open
  • Print
  • Read
  • Seek, Seek()
  • Write


Bookmarks

  • BookmarkName$()
  • CmpBookmarks()
  • CopyBookmark
  • CountBookmarks()
  • EditBookmark
  • EmptyBookmark()
  • ExistingBookmark()
  • GetBookmark$()
  • SetEndOfBookmark
  • SetStartOfBookmark


Borders and Frames

  • BorderBottom, BorderBottom()
  • BorderInside, BorderInside()
  • BorderLeft, BorderLeft()
  • BorderLineStyle, BorderLineStyle()
  • BorderNone, BorderNone()
  • BorderOutside, BorderOutside()
  • BorderRight, BorderRight()
  • BorderTop, BorderTop()
  • FormatBordersAndShading
  • FormatDefineStyleBorders
  • FormatDefineStyleFrame
  • FormatFrame
  • InsertFrame
  • RemoveFrames
  • ShadingPattern, ShadingPattern()
  • ViewBorderToolbar


Branching and Control

  • Call
  • For¼Next
  • Function¼End Function
  • Goto
  • If¼Then¼Else
  • On Error
  • OnTime
  • Select Case
  • Stop
  • Sub¼End Sub
  • While¼Wend


Bullets and Numbering

  • DemoteList
  • FormatBullet
  • FormatBulletDefault, FormatBulletDefault()
  • FormatBulletsAndNumbering
  • FormatDefineStyleNumbers
  • FormatMultilevel
  • FormatNumber
  • FormatNumberDefault, FormatNumberDefault()
  • PromoteList
  • RemoveBulletsNumbers
  • SkipNumbering, SkipNumbering()
  • ToolsBulletListDefault
  • ToolsBulletsNumbers
  • ToolsNumberListDefault


Character Formatting

  • AllCaps, AllCaps()
  • Bold, Bold()
  • CharColor, CharColor()
  • CopyFormat
  • CountFonts()
  • CountLanguages()
  • DottedUnderline, DottedUnderline()
  • DoubleUnderline, DoubleUnderline()
  • Font, Font$()
  • FontSize, FontSize()
  • FontSizeSelect
  • FontSubstitution
  • FormatAddrFonts
  • FormatChangeCase
  • FormatDefineStyleFont
  • FormatDefineStyleLang
  • FormatFont
  • FormatRetAddrFonts
  • GrowFont
  • GrowFontOnePoint
  • Hidden, Hidden()
  • Highlight
  • HighlightColor, HighlightColor()
  • Italic, Italic()
  • Language, Language$()
  • NormalFontPosition
  • NormalFontSpacing
  • Outline, Outline()
  • PasteFormat
  • ResetChar, ResetChar()
  • Shadow, Shadow()
  • ShrinkFont
  • ShrinkFontOnePoint
  • SmallCaps, SmallCaps()
  • Strikethrough, Strikethrough()
  • Subscript, Subscript()
  • Superscript, Superscript()
  • SymbolFont
  • ToolsLanguage
  • Underline, Underline()
  • WordUnderline, WordUnderline()


Customization

  • AddButton
  • ChooseButtonImage
  • CopyButtonImage
  • CountKeys()
  • CountMenuItems()
  • CountMenus()
  • CountToolbarButtons()
  • CountToolbars()
  • DeleteButton
  • EditButtonImage
  • KeyCode()
  • KeyMacro$()
  • ListCommands
  • MenuItemMacro$()
  • MenuItemText$()
  • MenuMode
  • MenuText$()
  • MoveButton
  • MoveToolbar
  • NewToolbar
  • PasteButtonImage
  • RenameMenu
  • ResetButtonImage
  • SizeToolbar
  • ToolbarButtonMacro$()
  • ToolbarName$()
  • ToolbarState()
  • ToolsCustomize
  • ToolsCustomizeKeyboard
  • ToolsCustomizeMenuBar
  • ToolsCustomizeMenus


Date and Time

  • Date$()
  • DateSerial()
  • DateValue()
  • Day()
  • Days360()
  • Hour()
  • InsertDateField
  • InsertDateTime
  • InsertTimeField
  • Minute()
  • Month()
  • Now()
  • OnTime
  • Second()
  • Time$()
  • TimeSerial()
  • TimeValue()
  • Today()
  • ToolsRevisionDate()
  • ToolsRevisionDate$()
  • Weekday()
  • Year()


Definition and Declaration

  • Declare
  • Dim
  • Let
  • Redim


Dialog Box Definition and Control

  • Begin Dialog¼End Dialog
  • CancelButton
  • CheckBox
  • ComboBox
  • Dialog, Dialog()
  • DialogEditor
  • DlgControlId()
  • DlgEnable, DlgEnable()
  • DlgFilePreview, DlgFilePreview$()
  • DlgFocus, DlgFocus$()
  • DlgListBoxArray, DlgListBoxArray()
  • DlgLoadValues, DlgLoadValues()
  • DlgSetPicture
  • DlgStoreValues
  • DlgText, DlgText$()
  • DlgUpdateFilePreview
  • DlgValue, DlgValue()
  • DlgVisible, DlgVisible()
  • DropListBox
  • FilePreview
  • GetCurValues
  • GroupBox
  • InputBox$()
  • ListBox
  • MsgBox, MsgBox()
  • OKButton
  • OptionButton
  • OptionGroup
  • Picture
  • PushButton
  • Text
  • TextBox


Disk Access and Management

  • ChDefaultDir
  • ChDir
  • Connect
  • CopyFile
  • CountDirectories()
  • DefaultDir$()
  • Files$()
  • GetAttr()
  • GetDirectory$()
  • Kill
  • MkDir
  • MountVolume
  • Name
  • PathFromMacPath$()
  • PathFromWinPath$()
  • RmDir
  • SetAttr


Documents, Templates, and Add-ins

  • AddAddIn, AddAddIn()
  • AddInState, AddInState()
  • ClearAddIns
  • Converter$()
  • ConverterLookup()
  • CopyFile
  • CountAddIns()
  • CountDocumentVars()
  • CountFiles()
  • CountFoundFiles()
  • DeleteAddIn
  • DisableInput
  • DocClose
  • DocumentStatistics
  • FileClose
  • FileCloseAll
  • FileConfirmConversions, FileConfirmConversions()
  • FileCreator$()
  • FileDocumentLayout
  • FileFind
  • FileList
  • FileMacCustomPageSetupGX
  • FileMacPageSetup
  • FileMacPageSetupGX
  • FileName$()
  • FileNameFromWindow$()
  • FileNameInfo$()
  • FileNew
  • FileNewDefault
  • FileNumber
  • FileOpen
  • FilePageSetup
  • FilePrint
  • FilePrintDefault
  • FilePrintOneCopy
  • FilePrintPreview,
    FilePrintPreview()
  • FilePrintPreviewFullScreen
  • FilePrintPreviewPages, FilePrintPreviewPages()
  • FilePrintSetup
  • FileQuit
  • FileRoutingSlip
  • Files$()
  • FileSave
  • FileSaveAll
  • FileSaveAs
  • FileSendMail
  • FileSummaryInfo
  • FileTemplates
  • FileType$()
  • FoundFileName$()
  • GetAddInID()
  • GetAddInName$()
  • GetAttr()
  • GetDocumentVar$()
  • GetDocumentVarName$()
  • InsertFile
  • Kill
  • LockDocument, LockDocument()
  • MacroFileName$()
  • Name
  • Organizer
  • PathFromMacPath$()
  • PathFromWinPath$()
  • SaveTemplate
  • SelectionFileName$()
  • SetAttr
  • SetDocumentVar, SetDocumentVar()
  • ToolsOptionsFileLocations
  • ToolsOptionsPrint


Document Properties

  • CountDocumentProperties()
  • DeleteDocumentProperty
  • DocumentPropertyExists()
  • DocumentPropertyName$()
  • DocumentPropertyType()
  • GetDocumentProperty(), GetDocumentProperty$()
  • IsCustomDocumentProperty()
  • IsDocumentPropertyReadOnly()
  • SetDocumentProperty
  • SetDocumentPropertyLink


Drawing

  • DrawAlign
  • DrawArc
  • DrawBringForward
  • DrawBringInFrontOfText
  • DrawBringToFront
  • DrawCallout
  • DrawClearRange
  • DrawCount()
  • DrawCountPolyPoints()
  • DrawDisassemblePicture
  • DrawEllipse
  • DrawExtendSelect
  • DrawFlipHorizontal
  • DrawFlipVertical
  • DrawFreeformPolygon
  • DrawGetCalloutTextbox
  • DrawGetPolyPoints
  • DrawGetType()
  • DrawGroup
  • DrawInsertWordPicture
  • DrawLine
  • DrawNudgeDown
  • DrawNudgeDownPixel
  • DrawNudgeLeft
  • DrawNudgeLeftPixel
  • DrawNudgeRight
  • DrawNudgeRightPixel
  • DrawNudgeUp
  • DrawNudgeUpPixel
  • DrawRectangle
  • DrawResetWordPicture
  • DrawReshape
  • DrawRotateLeft
  • DrawRotateRight
  • DrawRoundRectangle
  • DrawSelect, DrawSelect()
  • DrawSelectNext
  • DrawSelectPrevious
  • DrawSendBackward
  • DrawSendBehindText
  • DrawSendToBack
  • DrawSetCalloutTextbox
  • DrawSetInsertToAnchor
  • DrawSetInsertToTextbox
  • DrawSetPolyPoints
  • DrawSetRange, DrawSetRange()
  • DrawSnapToGrid
  • DrawTextBox
  • DrawUngroup
  • DrawUnselect
  • EditCopyAsPicture
  • FormatCallout
  • FormatDrawingObject
  • FormatPicture
  • InsertDrawing
  • SelectDrawingObjects
  • ToggleScribbleMode
  • ViewDrawingToolbar


Dynamic Data Exchange (DDE)

  • DDEExecute
  • DDEInitiate()
  • DDEPoke
  • DDERequest$()
  • DDETerminate
  • DDETerminateAll
  • FileCreator$()
  • FileType$()
  • MacID$()
  • SendKeys
  • SetFileCreatorAndType


Editing

  • AutoMarkIndexEntries
  • Cancel
  • ChangeCase, ChangeCase()
  • CopyText
  • DeleteBackWord
  • DeleteWord
  • EditClear
  • EditCopy
  • EditCopyAsPicture
  • EditCut
  • EditFind
  • EditGoTo
  • EditLinks
  • EditObject
  • EditPaste
  • EditPasteSpecial
  • EditPicture
  • EditRedo
  • EditRepeat
  • EditReplace
  • EditTOACategory
  • EditUndo
  • ExtendMode()
  • Insert
  • InsertAddCaption
  • InsertAutoCaption
  • InsertBreak
  • InsertCaption
  • InsertCaptionNumbering
  • InsertColumnBreak
  • InsertCrossReference
  • InsertIndex
  • InsertPageBreak
  • InsertPageNumbers
  • InsertSpike
  • InsertSymbol
  • InsertTableOfAuthorities
  • InsertTableOfContents
  • InsertTableOfFigures
  • MarkCitation
  • MarkIndexEntry
  • MarkTableOfContentsEntry
  • MoveText
  • OK
  • Overtype, Overtype()
  • Spike
  • ToolsOptionsEdit


Electronic Mail and Routing

  • AOCEAddRecipient
  • AOCEAuthenticateUser()
  • AOCEClearMailerField
  • AOCECountRecipients()
  • AOCEGetRecipient$()
  • AOCEGetSender$()
  • AOCEGetSubject$()
  • AOCESendMail
  • AOCESetSubject
  • FileAOCEAddMailer
  • FileAOCEDeleteMailer
  • FileAOCEExpandMailer
  • FileAOCEForwardMail
  • FileAOCENextLetter
  • FileAOCEReplyAllMail
  • FileAOCEReplyMail
  • FileAOCESendMail
  • FilePost
  • FileRoutingSlip
  • FileSendMail
  • MailCheckNames
  • MailHideMessageHeader
  • MailMessageDelete
  • MailMessageForward
  • MailMessageMove
  • MailMessageNext
  • MailMessagePrevious
  • MailMessageProperties
  • MailMessageReply
  • MailMessageReplyAll
  • MailSelectNames


Environment

  • AppInfo$()
  • Beep
  • CommandValid()
  • DOSToWin$()
  • Environ$()
  • Err
  • Error
  • GetPrivateProfileString$()
  • GetProfileString$()
  • GetSystemInfo, GetSystemInfo$()
  • IsDocumentDirty()
  • IsExecuteOnly()
  • IsMacro()
  • IsTemplateDirty()
  • LockDocument, LockDocument()
  • MacroFileName$()
  • MicrosoftSystemInfo
  • ScreenRefresh
  • ScreenUpdating, ScreenUpdating()
  • SelInfo()
  • SelType, SelType()
  • SetDocumentDirty
  • SetPrivateProfileString, SetPrivateProfileString()
  • SetProfileString
  • SetTemplateDirty
  • ViewMenus()
  • WaitCursor
  • WinToDOS$()


Fields

  • CheckBoxFormField
  • CountMergeFields()
  • DoFieldClick
  • DropDownFormField
  • EnableFormField
  • FormFieldOptions
  • GetFieldData$()
  • GetMergeField$()
  • InsertDateField
  • InsertDateTime
  • InsertField
  • InsertFieldChars
  • InsertFormField
  • InsertMergeField
  • InsertPageField
  • InsertTimeField
  • LockFields
  • MergeFieldName$()
  • NextField, NextField()
  • PrevField, PrevField()
  • PutFieldData
  • TextFormField
  • ToggleFieldDisplay
  • ToolsManageFields
  • UnlinkFields
  • UnlockFields
  • UpdateFields
  • UpdateSource
  • ViewFieldCodes, ViewFieldCodes()


Finding and Replacing

  • EditFind
  • EditFindBorder
  • EditFindClearFormatting
  • EditFindFont
  • EditFindFound()
  • EditFindFrame
  • EditFindHighlight
  • EditFindLang
  • EditFindNotHighlight
  • EditFindPara
  • EditFindStyle
  • EditFindTabs
  • EditReplace
  • EditReplaceBorder
  • EditReplaceClearFormatting
  • EditReplaceFont
  • EditReplaceFrame
  • EditReplaceHighlight
  • EditReplaceLang
  • EditReplaceNotHighlight
  • EditReplacePara
  • EditReplaceStyle
  • EditReplaceTabs
  • RepeatFind


Footnotes, Endnotes, and Annotations

  • AnnotationRefFromSel$()
  • EditConvertAllEndnotes
  • EditConvertAllFootnotes
  • EditConvertNotes
  • EditSwapAllNotes
  • GoToAnnotationScope
  • InsertAnnotation
  • InsertFootnote
  • NoteOptions
  • ResetNoteSepOrNotice
  • ShowAnnotationBy
  • ViewAnnotations, ViewAnnotations()
  • ViewEndnoteArea, ViewEndnoteArea()
  • ViewEndnoteContNotice
  • ViewEndnoteContSeparator
  • ViewEndnoteSeparator
  • ViewFootnoteArea, ViewFootnoteArea()
  • ViewFootnoteContNotice
  • ViewFootnoteContSeparator
  • ViewFootnotes, ViewFootnotes()
  • ViewFootnoteSeparator


Forms

  • AddDropDownItem
  • CheckBoxFormField
  • ClearFormField
  • DocumentProtection()
  • DropDownFormField
  • EnableFormField
  • FormFieldOptions
  • FormShading, FormShading()
  • GetFormResult(), GetFormResult$()
  • InsertFormField
  • RemoveAllDropDownItems
  • RemoveDropDownItem
  • SetFormResult
  • TextFormField
  • ToolsProtectDocument
  • ToolsProtectSection
  • ToolsUnprotectDocument


Help

  • Help
  • HelpAbout
  • HelpActiveWindow
  • HelpContents
  • HelpExamplesAndDemos
  • HelpIndex
  • HelpKeyboard
  • HelpMSN
  • HelpPSSHelp
  • HelpQuickPreview
  • HelpSearch
  • HelpTipOfTheDay
  • HelpTool
  • HelpUsingHelp
  • HelpWordPerfectHelp
  • HelpWordPerfectHelpOptions
  • ShowMe
  • TipWizard


Macros

  • CommandValid()
  • CountMacros()
  • DisableAutoMacros
  • IsExecuteOnly()
  • IsMacro()
  • KeyMacro$()
  • MacroCopy
  • MacroDesc$()
  • MacroFileName$()
  • MacroName$()
  • MacroNameFromWindow$()
  • MenuItemMacro$()
  • OnTime
  • Organizer
  • PauseRecorder
  • REM
  • ShowVars
  • ToolbarButtonMacro$()
  • ToolsMacro


Mail Merge

  • CountMergeFields()
  • GetMergeField$()
  • InsertMergeField
  • MailMerge
  • MailMergeAskToConvertChevrons, MailMergeAskToConvertChevrons()
  • MailMergeCheck
  • MailMergeConvertChevrons, MailMergeConvertChevrons()
  • MailMergeCreateDataSource
  • MailMergeCreateHeaderSource
  • MailMergeDataForm
  • MailMergeDataSource$()
  • MailMergeEditDataSource
  • MailMergeEditHeaderSource
  • MailMergeEditMainDocument
  • MailMergeFindRecord
  • MailMergeFirstRecord
  • MailMergeFoundRecord()
  • MailMergeGotoRecord, MailMergeGotoRecord()
  • MailMergeHelper
  • MailMergeInsertAsk
  • MailMergeInsertFillIn
  • MailMergeInsertIf
  • MailMergeInsertMergeRec
  • MailMergeInsertMergeSeq
  • MailMergeInsertNext
  • MailMergeInsertNextIf
  • MailMergeInsertSet
  • MailMergeInsertSkipIf
  • MailMergeLastRecord
  • MailMergeMainDocumentType, MailMergeMainDocumentType()
  • MailMergeNextRecord
  • MailMergeOpenDataSource
  • MailMergeOpenHeaderSource
  • MailMergePrevRecord
  • MailMergeQueryOptions
  • MailMergeReset
  • MailMergeState()
  • MailMergeToDoc
  • MailMergeToPrinter
  • MailMergeUseAddressBook
  • MailMergeViewData, MailMergeViewData()
  • MergeFieldName$()
  • ToolsAddRecordDefault
  • ToolsRemoveRecordDefault


Moving the Insertion Point and Selecting

  • AtEndOfDocument()
  • AtStartOfDocument()
  • Cancel
  • CharLeft, CharLeft()
  • CharRight, CharRight()
  • ColumnSelect
  • EditSelectAll
  • EndOfColumn, EndOfColumn()
  • EndOfDocument, EndOfDocument()
  • EndOfLine, EndOfLine()
  • EndOfRow, EndOfRow()
  • EndOfWindow, EndOfWindow()
  • ExtendMode()
  • ExtendSelection
  • GetSelEndPos()
  • GetSelStartPos()
  • GetText$()
  • GoBack
  • GoToAnnotationScope
  • GoToHeaderFooter
  • GoToNextItem
  • GoToPreviousItem
  • HLine
  • HPage
  • HScroll, HScroll()
  • Insert
  • LineDown, LineDown()
  • LineUp, LineUp()
  • NextCell, NextCell()
  • NextField, NextField()
  • NextObject
  • NextPage, NextPage()
  • NextWindow
  • OtherPane
  • PageDown, PageDown()
  • PageUp, PageUp()
  • ParaDown, ParaDown()
  • ParaUp, ParaUp()
  • PrevCell, PrevCell()
  • PrevField, PrevField()
  • PrevObject
  • PrevPage, PrevPage()
  • PrevWindow
  • SelectCurAlignment
  • SelectCurColor
  • SelectCurFont
  • SelectCurIndent
  • SelectCurSentence
  • SelectCurSpacing
  • SelectCurTabs
  • SelectCurWord
  • SelType, SelType()
  • SentLeft, SentLeft()
  • SentRight, SentRight()
  • SetSelRange
  • ShrinkSelection
  • StartOfColumn, StartOfColumn()
  • StartOfDocument, StartOfDocument()
  • StartOfLine, StartOfLine()
  • StartOfRow, StartOfRow()
  • StartOfWindow, StartOfWindow()
  • TableSelectColumn
  • TableSelectRow
  • TableSelectTable
  • VLine
  • VPage
  • VScroll, VScroll()
  • WordLeft, WordLeft()
  • WordRight, WordRight()


Object Linking and Embedding

  • ActivateObject
  • ConvertObject
  • EditCreatePublisher
  • EditLinks
  • EditObject
  • EditPasteSpecial
  • EditPicture
  • EditPublishOptions
  • EditSubscribeOptions
  • EditSubscribeTo
  • FileClosePicture
  • InsertChart
  • InsertDatabase
  • InsertEquation
  • InsertExcelTable
  • InsertObject
  • InsertPicture
  • InsertSound
  • InsertWordArt


Outlining and Master Documents

  • CreateSubdocument
  • DemoteToBodyText
  • InsertSubdocument
  • MergeSubdocument
  • OpenSubdocument
  • OutlineCollapse
  • OutlineDemote
  • OutlineExpand
  • OutlineLevel()
  • OutlineMoveDown
  • OutlineMoveUp
  • OutlinePromote
  • OutlineShowFirstLine, OutlineShowFirstLine()
  • OutlineShowFormat
  • RemoveSubdocument
  • ShowAllHeadings
  • ShowHeadingNumber
  • SplitSubdocument
  • ViewMasterDocument, ViewMasterDocument()
  • ViewOutline, ViewOutline()
  • ViewToggleMasterDocument


Paragraph Formatting

  • CenterPara, CenterPara()
  • CloseUpPara
  • CopyFormat
  • FormatDefineStylePara
  • FormatDefineStyleTabs
  • FormatDropCap
  • FormatParagraph
  • FormatTabs
  • HangingIndent
  • Indent
  • InsertPara
  • JustifyPara, JustifyPara()
  • LeftPara, LeftPara()
  • NextTab()
  • OpenUpPara
  • ParaKeepLinesTogether, ParaKeepLinesTogether()
  • ParaKeepWithNext, ParaKeepWithNext()
  • ParaPageBreakBefore, ParaPageBreakBefore()
  • ParaWidowOrphanControl, ParaWidowOrphanControl()
  • PasteFormat
  • PrevTab()
  • ResetPara, ResetPara()
  • RightPara, RightPara()
  • SpacePara1, SpacePara1()
  • SpacePara15, SpacePara15()
  • SpacePara2, SpacePara2()
  • TabLeader$()
  • TabType()
  • UnHang
  • UnIndent


Proofing

  • CountToolsGrammarStatistics()
  • DocumentHasMisspellings()
  • NextMisspelling
  • SpellChecked, SpellChecked()
  • ToolsGetSpelling, ToolsGetSpelling()
  • ToolsGetSynonyms, ToolsGetSynonyms()
  • ToolsGrammar
  • ToolsGrammarStatisticsArray
  • ToolsHyphenation
  • ToolsHyphenationManual
  • ToolsOptionsGrammar
  • ToolsOptionsSpelling
  • ToolsSpelling
  • ToolsSpellingRecheckDocument
  • ToolsSpellSelection
  • ToolsThesaurus


Section and Document Formatting

  • CloseViewHeaderFooter
  • FileDocumentLayout
  • FileMacCustomPageSetupGX
  • FileMacPageSetup
  • FileMacPageSetupGX
  • FormatAutoFormat
  • FormatColumns
  • FormatHeaderFooterLink
  • FormatHeadingNumber
  • FormatHeadingNumbering
  • FormatPageNumber
  • FormatSectionLayout
  • GoToHeaderFooter
  • InsertSectionBreak
  • ShowNextHeaderFooter
  • ShowPrevHeaderFooter
  • ToggleHeaderFooterLink
  • ToggleMainTextLayer
  • TogglePortrait
  • ToolsOptionsAutoFormat
  • ViewFooter, ViewFooter()
  • ViewHeader, ViewHeader()


Strings and Numbers

  • Abs()
  • Asc()
  • Chr$()
  • CleanString$()
  • InStr()
  • Int()
  • LCase$()
  • Left$()
  • Len()
  • LTrim$()
  • Mid$()
  • Right$()
  • Rnd()
  • RTrim$()
  • Selection$()
  • Sgn()
  • SortArray
  • Str$()
  • String$()
  • UCase$()
  • Val()


Style Formatting

  • CountStyles()
  • FormatDefineStyleBorders
  • FormatDefineStyleFont
  • FormatDefineStyleFrame
  • FormatDefineStyleLang
  • FormatDefineStyleNumbers
  • FormatDefineStylePara
  • FormatDefineStyleTabs
  • FormatStyle
  • FormatStyleGallery
  • NormalStyle
  • Organizer
  • Style
  • StyleDesc$()
  • StyleName$()


Tables

  • FieldSeparator$, FieldSeparator$()
  • InsertExcelTable
  • NextCell, NextCell()
  • PrevCell, PrevCell()
  • TableAutoFormat
  • TableAutoSum
  • TableColumnWidth
  • TableDeleteCells
  • TableDeleteColumn
  • TableDeleteRow
  • TableFormula
  • TableGridlines, TableGridlines()
  • TableHeadings, TableHeadings()
  • TableInsertCells
  • TableInsertColumn
  • TableInsertRow
  • TableInsertTable
  • TableMergeCells
  • TableRowHeight
  • TableSelectColumn
  • TableSelectRow
  • TableSelectTable
  • TableSort
  • TableSortAToZ
  • TableSortZToA
  • TableSplit
  • TableSplitCells
  • TableToText
  • TableUpdateAutoFormat
  • TextToTable


Tools

  • DocumentProtection()
  • ToolsAdvancedSettings
  • ToolsCalculate, ToolsCalculate()
  • ToolsCompareVersions
  • ToolsCreateEnvelope
  • ToolsCreateLabels
  • ToolsCustomize
  • ToolsHyphenation
  • ToolsHyphenationManual
  • ToolsLanguage
  • ToolsMergeRevisions
  • ToolsOptions
  • ToolsOptionsAutoFormat
  • ToolsOptionsCompatibility
  • ToolsOptionsEdit
  • ToolsOptionsFileLocations
  • ToolsOptionsGeneral
  • ToolsOptionsPrint
  • ToolsOptionsRevisions
  • ToolsOptionsSave
  • ToolsOptionsUserInfo
  • ToolsOptionsView
  • ToolsProtectDocument
  • ToolsProtectSection
  • ToolsRepaginate
  • ToolsReviewRevisions
  • ToolsRevisionAuthor$()
  • ToolsRevisionDate()
  • ToolsRevisionDate$()
  • ToolsRevisions
  • ToolsRevisionType()
  • ToolsShrinkToFit
  • ToolsUnprotectDocument
  • ToolsWordCount


View

  • ClosePreview
  • CloseViewHeaderFooter
  • FilePrintPreview, FilePrintPreview()
  • FilePrintPreviewFullScreen
  • FilePrintPreviewPages, FilePrintPreviewPages()
  • Magnifier, Magnifier()
  • ShowAll, ShowAll()
  • ShowNextHeaderFooter
  • ShowPrevHeaderFooter
  • ToggleFull
  • TogglePortrait
  • ToolsOptionsView
  • ViewAnnotations, ViewAnnotations()
  • ViewBorderToolbar
  • ViewDraft, ViewDraft()
  • ViewDrawingToolbar
  • ViewEndnoteArea, ViewEndnoteArea()
  • ViewEndnoteContNotice
  • ViewEndnoteContSeparator
  • ViewEndnoteSeparator
  • ViewFieldCodes, ViewFieldCodes()
  • ViewFooter, ViewFooter()
  • ViewFootnoteArea, ViewFootnoteArea()
  • ViewFootnoteContNotice
  • ViewFootnoteContSeparator
  • ViewFootnotes, ViewFootnotes()
  • ViewFootnoteSeparator
  • ViewHeader, ViewHeader()
  • ViewMasterDocument, ViewMasterDocument()
  • ViewMenus()
  • ViewNormal, ViewNormal()
  • ViewOutline, ViewOutline()
  • ViewPage, ViewPage()
  • ViewRibbon, ViewRibbon()
  • ViewRuler, ViewRuler()
  • ViewStatusBar, ViewStatusBar()
  • ViewToggleMasterDocument
  • ViewToolbars
  • ViewZoom
  • ViewZoom100
  • ViewZoom200
  • ViewZoom75
  • ViewZoomPageWidth
  • ViewZoomWholePage


Windows

  • Activate
  • AppActivate
  • AppClose
  • AppCount()
  • AppGetNames, AppGetNames()
  • AppHide
  • AppMaximize, AppMaximize()
  • AppMinimize, AppMinimize()
  • AppMove
  • AppRestore, AppRestore()
  • AppShow
  • AppSize
  • AppWindowHeight, AppWindowHeight()
  • AppWindowPosLeft, AppWindowPosLeft()
  • AppWindowPosTop, AppWindowPosTop()
  • AppWindowWidth, AppWindowWidth()
  • ClosePane
  • CountWindows()
  • DocClose
  • DocMaximize, DocMaximize()
  • DocMinimize, DocMinimize()
  • DocMove
  • DocRestore
  • DocSize
  • DocSplit, DocSplit()
  • DocWindowHeight, DocWindowHeight()
  • DocWindowPosLeft, DocWindowPosLeft()
  • DocWindowPosTop, DocWindowPosTop()
  • DocWindowWidth, DocWindowWidth()
  • ExitWindows
  • FileNameFromWindow$()
  • HelpActiveWindow
  • IsMacro()
  • NextWindow
  • OtherPane
  • PrevWindow
  • Window()
  • WindowArrangeAll
  • WindowList
  • WindowName$()
  • WindowNewWindow
  • WindowNumber
  • WindowPane()


Statements and Functions

Statements and functions are listed alphabetically. Each statement or function name appears as a bold heading in the margin. One or more syntax statements follow the bold heading. Here is a syntax example:

CharLeft [Count] [, Select]

When you type an instruction, you must include all the items in the syntax that
are formatted in bold. Items enclosed in brackets are optional. Do not type the brackets when including an optional item. Italic formatting indicates argument names or value placeholders that you replace with actual values or variables to which you've already assigned values.

For example, you could use any of the following CharLeft instructions in a macro:

CharLeft
CharLeft 1
CharLeft 1, 1

If you assigned acceptable values to the numeric variables move and extend, you could use the following CharLeft instruction:

CharLeft move, extend

Note that you must separate arguments with commas. The acceptable values for arguments are listed in the remarks following the syntax, usually in a table. Some syntax examples include required arguments. For example:

EditReplaceStyle .Style = text

To use this statement, you must include the .Style argument — note the period preceding the argument name. You must type all the text that appears in bold and supply a specific value or variable for the italic placeholder, as in the following examples:

EditReplaceStyle .Style = "Heading 1"
EditReplaceStyle .Style = "Normal"

Other statements and functions include a mixture of required and optional arguments:

EditAutoText .Name = text [, .Context = number] [, .InsertAs = number] [, .Insert] [, .Add] [, .Delete]

According to this syntax, you must include the first argument and a value, but the remaining arguments are optional. As the syntax indicates, every argument in your final macro instruction must be separated by a comma. For example:

EditAutoText .Name = "disclaimer", .Context = 1, .Add

For more information about WordBasic syntax, see Part 1, "Learning WordBasic," which includes many examples of the correct use of WordBasic statements and functions. WordBasic Help and most entries in this reference also include examples of how to use specific statements and functions. For more information about typographic conventions used in this book, see "About This Book" in the front matter.


Abs()

Syntax

Abs(n)

Remarks

Returns the absolute value of n. For example, Abs(-5) returns the value 5.

Example

This example toggles the display of hidden text. You can use this example as
a model for toggling any check box in Word. In a Word dialog box, a selected check box has a value of 1; a cleared check box has a value of 0 (zero). The example reverses the current value of the check box by subtracting 1 from it
and using Abs() to return the absolute value of the result.

Dim dlg As ToolsOptionsView
GetCurValues dlg
dlg.Hidden = Abs(dlg.Hidden - 1)
ToolsOptionsView dlg

See Also

Int(), Rnd(), Sgn()


Activate

Syntax

Activate WindowTitle$ [, PaneNum]

Remarks

Activates the window with the specified WindowTitle$. You can use the WindowName$() function to store the name of a window in a variable and then use this variable with Activate when you need to activate that window. WindowTitle$ must match a window name on the Window menu.

Argument | Explanation
WindowTitle$ | The name of the window to activate, as it appears on the Window menu
PaneNum | The number of the pane to activate: 1 or 2 Top pane 3 or 4 Bottom pane

Example

This example stores the name of the active window, opens a document, and then reactivates the original window:

firstwin$ = WindowName$()
FileOpen "CHAP2.DOC"
Activate firstwin$

See Also

DocSplit, NextWindow, OtherPane, PrevWindow, WindowList, WindowName$(), Window Number, WindowPane()


ActivateObject

Syntax

ActivateObject

Remarks

Activates the selected embedded object for editing, or plays the sound or video file associated with the selected icon (for example, a sound file associated with the microphone icon). ActivateObject is equivalent to double-clicking the selected embedded object.

Example

This example moves the insertion point to the next Microsoft WordArt object and activates it for editing:

EditGoTo "o'MSWordArt.2'"
ActivateObject

See Also

EditGoTo, EditObject


AddAddIn, AddAddIn()

Syntax

AddAddIn AddIn$ [, Load]

AddAddIn(AddIn$ [, Load])

Remarks

The AddAddIn statement adds a template or Word add-in library (WLL) to the list of global templates and add-ins in the Templates And Add-ins dialog box (Templates command, File menu).

Argument | Explanation
AddIn$ | The path and filename of the template or WLL
Load | Specifies whether to load the template or add-in after adding it to the list: 0 (zero) Does not load the template or add-in 1 or omitted Loads the template or add-in

The AddAddIn() function behaves the same as the statement and also returns a value corresponding to the position of the global template or add-in in the list, where 1 is the first template or add-in, 2 is the second, and so on. This value may be used with other add-in statements and functions.

You can use functions defined in a loaded WLL in a macro. Functions that take no arguments may be used just like WordBasic statements; you can return the names of these functions using CountMacros() and MacroName$(). Functions in the WLL that take arguments must be declared using the Declare statement.

For more information on loading global templates and add-ins, see "add-in programs" in Help. For more information on using functions in WLLs, see Chapter 9, "More WordBasic Techniques," in Part 1, "Learning WordBasic."

Example

These examples use AddAddIn() to load a global template and define the variable id as a numeric identifier for the template:

id = AddAddIn("C:\MYDOT\MYLIB.DOT", 1)            'Windows example
id = AddAddIn("HD:TEMPLATES:LIB TEMPLATE", 1)    'Macintosh example

The following example fills an array with the names of functions in loaded WLLs that can be called from a macro just like Word commands:

nonaddins = CountMacros(0) + CountMacros(1)
loaded = CountMacros(0, 0, 1)
size = loaded - 1
If size >= 0 Then
    Dim loaded$(size)
    For count = 0 To size
        pos = (count + 1) + nonaddins
        loaded$(count) = MacroName$(pos, 0, 1)
    Next count
End If

See Also

AddInState, ClearAddIns, CountAddIns(), CountMacros(), DeleteAddIn, GetAddInID(), GetAddInName$(), MacroName$()


AddAddress

Syntax

AddAddress AddressProperties$()

Remarks

Adds a new address to the default address book. AddAddress is available only if Windows 95 and either Microsoft Exchange or Schedule+ version 2.0 are installed. In Word version 6.0, AddAddress is unavailable and generates an error.

Argument | Explanation
AddressProperties$() | A predefined two-dimensional array that contains the information for the new address you want to add. The following example demonstrates how the array should be defined: Dim addrprop$(numprops - 1, 1) where numprops is the number of properties you want to specify for the address. The first dimension of each two-dimensional element (for example, addrprop$(0, 0)) specifies a valid property name. The second dimension (for example, addrprop$(0, 1)) specifies the text value for that property. For a complete list of valid property names available in the Personal Address Book in Microsoft Exchange, see the table of properties later in this topic. For more information about how to create a two-dimensional array, see Dim.

The following is a list of the most common address book properties used to get or define address information. These property names correspond to the options in the Properties dialog box of the Personal Address Book in Microsoft Exchange. You can also use the hexadecimal identifier for any MAPI property supported by Microsoft Exchange or any other application that supports MAPI address books. For a complete list of the MAPI properties and their hexadecimal identifiers, see your MAPI software development kit documentation.

Property | Explanation
PR_ADDRTYPE | The addressee's electronic mail address type
PR_BEEPER_TELEPHONE_NUMBER | The addressee's beeper telephone number
PR_BUSINESS_FAX_NUMBER | The addressee's business fax number
PR_CAR_TELEPHONE_NUMBER | The addressee's car telephone number
PR_CELLULAR_TELEPHONE_NUMBER | The addressee's cellular telephone number
PR_COMMENT | The text included on the Notes tab for the address entry
PR_COMPANY_NAME | The name of the addressee's company
PR_COUNTRY | The addressee's country
PR_DEPARTMENT_NAME | The name of the addressee's department within the company

Property | Explanation
PR_DISPLAY_NAME | The name displayed in the Address Book dialog box
PR_EMAIL_ADDRESS | The addressee's electronic mail address
PR_GIVEN_NAME | The addressee's given name, or first name
PR_HOME_FAX_NUMBER | The addressee's home fax number
PR_HOME_TELEPHONE_NUMBER | The addressee's home telephone number
PR_INITIALS | The addressee's initials
PR_LOCALITY | The addressee's city or locality
PR_LOCATION | The addressee's location, in the format buildingnumber /roomnumber; for example, "16/3000" represents room 3000 in building 16
PR_OFFICE_LOCATION | The addressee's office location
PR_OFFICE_TELEPHONE_NUMBER | The addressee's office telephone number
PR_OFFICE2_TELEPHONE_NUMBER | The addressee's second office telephone number
PR_OTHER_TELEPHONE_NUMBER | The addressee's alternate telephone number (other than home or office)
PR_POSTAL_CODE | The addressee's postal code
PR_PRIMARY_FAX_NUMBER | The addressee's primary fax number
PR_PRIMARY_TELEPHONE_NUMBER | The addressee's primary telephone number
PR_RADIO_TELEPHONE_NUMBER | The addressee's radio telephone number
PR_STATE_OR_PROVINCE | The addressee's state or province
PR_STREET_ADDRESS | The addressee's street address
PR_SURNAME | The addressee's surname, or last name
PR_TITLE | The addressee's job title

Example

This example creates a two-dimensional array with valid MAPI address book properties and their respective values, and it adds the new address to the default address book.

Dim addressText$(6,1)
addressText$(0,0) = "PR_SURNAME"
addressText$(0,1) = "Smith"
addressText$(1,0) = "PR_GIVEN_NAME"
addressText$(1,1) = "Phil"
addressText$(2,0) = "PR_STREET_ADDRESS"
addressText$(2,1) = "12345 55th Avenue #5432"
addressText$(3,0) = "PR_LOCALITY"
addressText$(3,1) = "New York"
addressText$(4,0) = "PR_STATE_OR_PROVINCE"
addressText$(4,1) = "NY"
addressText$(5,0) = "PR_POSTAL_CODE"
addressText$(5,1) = "10023"
addressText$(6,0) = "PR_DISPLAY_NAME"
addressText$(6,1) = "Phil Smith"
AddAddress addressText$()

See Also

GetAddress$(), InsertAddress, ToolsCreateEnvelope, ToolsCreateLabels


AddButton

Syntax

AddButton Toolbar$, Position, Category, Name$ [, ButtonTxtOrImageNum[$]] [, Context] [, CommandValue$]

Remarks

Adds to a toolbar a button that runs a built-in command or macro, applies a font or style, or inserts an AutoText entry.

Argument | Explanation
Toolbar$ | The name of the toolbar as listed in the Toolbars dialog box (View menu).
Position | A number corresponding to the position on the specified toolbar at which to add the button, where 1 is the first position, 2 is the second position, and so on. Note that a list box or space counts as one position.
Category | The type of item to be assigned: 1 Built-in commands 2 Macros 3 Fonts 4 AutoText entries 5 Styles
Name$ | The name of the built-in command, macro, font, AutoText entry, or style to associate with the button. To add a space to a toolbar, specify an empty string ("").

Argument | Explanation
ButtonTxtOrImageNum[$] | The text you want to appear on the button, or a number corresponding to an image for the button in the built-in set of buttons, where 0 (zero) is no image (for a blank button), 1 is the first image, 2 is the second image, and so on. For a list of button images and their associated numbers, see "Toolbar Button Images and Numbers" in Help.
Context | Determines where the new toolbar assignment is stored: 0 (zero) or omitted Normal template 1 Active template
CommandValue$ | Additional text, if any, required for the command specified by Name$. For example, if Name$ is "Color," CommandValue$ specifies the color. For more information, see the second table in ToolsCustomizeMenus.

Example

This example replaces the button at position 11 on the Formatting toolbar with button image 80. The built-in command assigned to the button is Color, which requires that an additional value be specified (in this case, "2" for the color blue).

DeleteButton "Formatting", 11, 0
AddButton "Formatting", 11, 1, "Color", 80, 0, "2"

See Also

ChooseButtonImage, CopyButtonImage, DeleteButton, EditButtonImage, MoveButton, PasteButtonImage, ResetButtonImage


AddDropDownItem

Syntax

AddDropDownItem BookmarkName$, ItemText$

Remarks

Adds an item to a drop-down form field. A drop-down form field can hold as many as 25 items; if you attempt to add more than 25 items, an error occurs.

Argument | Explanation
BookmarkName$ | The name of the bookmark that marks the drop-down form field. If you specify a bookmark that does not mark a drop-down form field, an error occurs.
ItemText$ | The item to add to the drop-down form field.

Example

This example adds three items to the drop-down form field marked by the bookmark "Dropdown1":

AddDropDownItem "Dropdown1", "Red"
AddDropDownItem "Dropdown1", "Blue"
AddDropDownItem "Dropdown1", "Green"

See Also

DropDownFormField, RemoveAllDropDownItems, RemoveDropDownItem


AddInState, AddInState()

Syntax

AddInState AddIn, Load

AddInState AddIn$, Load

AddInState(AddIn)

AddInState(AddIn$)

Remarks

The AddInState statement loads or unloads the specified global template or add-in listed in the Templates And Add-ins dialog box (Templates command, File menu). You can specify the global template or add-in as a number or as text.

Argument | Explanation
AddIn | A number corresponding to the global template or add-in's position in the list of global templates and add-ins, where 1 is the first template or add-in, 2 is the second, and so on
AddIn$ | The path and filename of the global template or add-in
Load | Specifies whether to load or unload the global template or add-in: 0 (zero) Unloads the template or add-in 1 Loads the template or add-in

The AddInState() function returns the following values. Note that the return values are additive. For example, if the specified add-in is loaded, a WLL, and in the Startup folder, AddInState() returns 7 (the sum of 1, 2, and 4).

Value | Explanation
0 (zero) | If none of the following descriptions are true of the global template or add-in.
1 | If the global template or add-in is loaded.
2 | If it is a Word add-in library (WLL).
4 | If the global template or add-in loads automatically; templates and add-ins in the folder specified by the Startup option on the File Locations tab in the Options dialog box (Tools menu) load automatically.

See Also

AddAddIn, ClearAddIns, CountAddIns(), DeleteAddIn, GetAddInID(), GetAddInName$()


AllCaps, AllCaps()

Syntax

AllCaps [On]

AllCaps()

Remarks

The AllCaps statement adds or removes the all caps character format for the current selection, or controls all caps formatting for characters to be inserted at the insertion point.

Argument | Explanation
On | Specifies whether to add or remove the all caps format: 1 Formats the selection as all caps 0 (zero) Removes the all caps format Omitted Toggles the all caps format

The AllCaps() function returns the following values.

Value | Explanation
0 (zero) | If none of the selection is formatted as all caps
–1 | If part of the selection is formatted as all caps
1 | If all the selection is formatted as all caps

Example

This example applies the all caps format to the entire selection if part of the selection is formatted as all caps:

If AllCaps() = -1 Then AllCaps 1

See Also

FormatFont


AnnotationRefFromSel$()

Syntax

AnnotationRefFromSel$()

Remarks

Returns the annotation mark associated with the insertion point or the beginning of the selection. The insertion point must be immediately before an annotation mark in the document window or within an annotation in the annotation pane; otherwise, the characters "[0]" are returned.

Note that because Word treats an entire annotation mark as an individual character, you cannot return the characters within an annotation mark using the Selection$() function.

Example

This example goes to the next annotation mark and sets the variable mark$ to the characters in the annotation mark:

EditGoTo "a"
mark$ = AnnotationRefFromSel$()

See Also

EditGoTo, GoToAnnotationScope, GoToNext Item, GoToPrevious Item, ShowAnnotationBy


AOCEAddRecipient

Syntax

AOCEAddRecipient Recipient$ [, AddressType] [, MailSlot$]

Remarks

Adds the specified recipient address to the mailer attached to the active document. AOCEAddRecipient is available only on the Macintosh and only if PowerTalk™ is installed.

Argument | Explanation
Recipient$ | The address of the recipient
AddressType | Specifies the list to add the recipient to: 13 or omitted "To" list 14 "Cc" list 15 "Bcc" list (the recipient's name appears in neither the "To" nor "Cc" lists)
MailSlot$ | Specifies how the user will receive the document (for example, "AppleTalk®" or "Fax")

See Also

AOCECountRecipients(), AOCEGetRecipient$(), FileAOCEAddMailer


AOCEAuthenticateUser()

Syntax

AOCEAuthenticateUser([AllowPrompt])

Remarks

Returns –1 if the user has logged on to PowerTalk and 0 (zero) if not. A mailer need not be attached to the active document for this function to work. AOCEAuthenticateUser() is available only on the Macintosh and only if PowerTalk is installed.

Argument | Explanation
AllowPrompt | If the user has not logged on to PowerTalk, specifies whether or not to display a dialog box prompting the user to type an access code to unlock the key chain: 0 (zero) No dialog box appears. 1 or omitted The dialog box appears.

See Also

AOCEGetSender$()


AOCEClearMailerField

Syntax

AOCEClearMailerField FieldNumber

Remarks

Clears the specified field in the mailer attached to the active document. AOCEClearMailerField is available only on the Macintosh and only if PowerTalk is installed.

Argument | Explanation
FieldNumber | The field in the mailer you want to clear: 20 "Recipient" field 22 "Subject" field 26 "Enclosures" field The "From" field cannot be cleared.

See Also

FileAOCEDeleteMailer


AOCECountRecipients()

Syntax

AOCECountRecipients(AddressType)

Remarks

Returns the number of recipients in the mailer attached to the active document. AOCECountRecipients() is available only on the Macintosh and only if PowerTalk is installed.

Argument | Explanation
AddressType | The type of recipients to count: 0 (zero) All recipients 13 "To" recipients 14 "Cc" recipients 15 "Bcc" recipients

See Also

AOCEAddRecipient, AOCEGetRecipient$()


AOCEGetRecipient$()

Syntax

AOCEGetRecipient$(RecipientNumber [, AddressType])

Remarks

Returns the address of the specified recipient. AOCEGetRecipient$() is available only on the Macintosh and only if PowerTalk is installed.

Argument | Explanation
RecipientNumber | A number between 1 and AOCECountRecipients(AddressType) specifying the recipient whose address you want to return.
AddressType | Specifies the list from which you want to return an address: 13 or omitted "To" list 14 "Cc" list 15 "Bcc" list

See Also

AOCEAddRecipient, AOCECountRecipients(), AOCEGetSender$(), AOCEGetSubject$()


AOCEGetSender$()

Syntax

AOCEGetSender$()

Remarks

Returns the address in the "From" field in the mailer attached to the active document. AOCEGetSender is available only on the Macintosh and only if PowerTalk is installed.

See Also

AOCEAuthenticateUser(), AOCEGetSubject$(), AOCEGetRecipient$()


AOCEGetSubject$()

Syntax

AOCEGetSubject$()

Remarks

Returns the text in the "Subject" field in the mailer attached to the active document. AOCEGetSubject$() is available only on the Macintosh and only if PowerTalk is installed.

See Also

AOCEGetRecipient$(), AOCEGetSender$(), AOCESetSubject


AOCESendMail

Syntax

AOCESendMail [SignLetter] [, Priority] [, SendAppleMail] [, SendImage] [, SendWordDoc] [, Format$]

Remarks

Sends the active document to the recipients specified in the attached mailer. AOCESendMail is available only on the Macintosh and only if PowerTalk is installed.

Argument | Explanation
SignLetter | If 1, the sender is prompted to select a signer file.
Priority | Sets a priority: 1 Normal 2 Low 3 High
Format$ | If SendWordDoc is 1, the name of the format, as listed under Save File As Type in the Save As dialog box (File menu). Word Document is the default format.

You can specify one or more of the following formats.

Argument | Explanation
SendAppleMail | If 1, the recipient may open the letter from the standard interchange, or "AppleMail," format.
SendImage | If 1, the recipient may open the letter from image, or "Snapshot," format.
SendWordDoc | If 1, the recipient may open the letter from the file format specified by Format$.

See Also

FileAOCEForwardMail, FileAOCESendMail, FileSendMail


AOCESetSubject

Syntax

AOCESetSubject Subject$

Remarks

Inserts the specified text in the "Subject" field of the mailer attached to the active document. AOCESetSubject is available only on the Macintosh and only if PowerTalk is installed.

See Also

AOCEGetSubject$()


AppActivate

Syntax

AppActivate WindowName$ [, Immediate]

Remarks

Activates a running application.

Argument | Explanation
WindowName$ | In Windows, the name of the application window to activate, as it appears in the title bar or Task List. It is not necessary to specify the entire window name. For example, to indicate a window named "Notepad - FILES.TXT," you can specify "Notepad - FILES.TXT," "Notepad," or even "Note." The first window name in the Task List that matches the beginning of the specified string is affected. The case of characters is not significant in WindowName$. On the Macintosh, WindowName$ is the application name or the signature returned by the MacID$() function. It is generally preferable to use the signature instead of the application name (for example, MacID$("XCEL") instead of "Microsoft Excel") because, unlike the application name, the signature never changes.
Immediate | Specifies when to switch to the other application: 0 (zero) or omitted If Word is not active, Word flashes its title bar or icon, waits for the user to activate Word, and then activates the other application. 1 Word immediately activates the other application, even if Word is not the active application.

Example

This Windows example activates File Manager if it is running and starts File Manager if it is not running:

If AppIsRunning("File Manager") Then
    AppActivate "File Manager"
Else
    Shell "WINFILE.EXE"
End If

This Macintosh example activates Microsoft Excel if it is running and starts Microsoft Excel if it is not running.

If AppIsRunning(MacID$("XCEL") Then
    AppActivate MacID$("XCEL")
Else
    Shell MacID$("XCEL")
End If

Note that the Macintosh example could be shortened to Shell MacID$("XCEL") because, unlike in Windows, Shell on the Macintosh does not start a second instance of an application if it is already running.

See Also

AppClose, AppGetNames, AppIsRunning(), MacID$(), Microsoft Application, Shell


AppClose

Syntax

AppClose [WindowName$]

Remarks

Closes the specified application.

Argument | Explanation
WindowName$ | In Windows, a string that matches the beginning of an application window name, as it appears in the title bar or Task List. If omitted, Word is assumed. On the Macintosh, WindowName$ is either the application name or the signature returned by MacID$(). For more information on WindowName$, see AppActivate.

Example

This example closes Microsoft Excel if it is running:

If AppIsRunning("Microsoft Excel") Then
    AppClose "Microsoft Excel"
End If

On the Macintosh, you can rewrite the previous example as follows, using MacID$() to specify the Microsoft Excel signature. This ensures the example will work even if the user has changed the filename for Microsoft Excel.

If AppIsRunning(MacID$("XCEL")) Then
    AppClose MacID$("XCEL")
End If

See Also

AppActivate, AppIsRunning(), FileExit, FileQuit, MacID$(), Shell


AppCount()

Syntax

AppCount()

Remarks

Returns the number of open applications (including hidden applications that do not appear in the Task List (Windows) or on the Application menu (Macintosh)). For an example, see AppGetNames.

See Also

AppGetNames


AppGetNames, AppGetNames()

Syntax

AppGetNames ArrayVariable$()

AppGetNames(ArrayVariable$())

Remarks

The AppGetNames statement fills a previously defined string array with the names of open application windows (including hidden application windows that do not appear in the Task List (Windows) or on the Application menu (Macintosh)). If ArrayVariable$() has fewer elements than the number of open applications, the array is filled with as many names as there are elements, and an error does not occur.

The AppGetNames() function carries out the same action and also returns the number of open application windows (including hidden application windows that do not appear in the Task List (Windows) or on the Application menu (Macintosh)). AppGetNames() returns the same value as AppCount().

Example

This example inserts a list of application window names at the insertion point:

size = AppCount() - 1
Dim winnames$(size)
AppGetNames winnames$()
For i = 0 To size
    Insert winnames$(i)
    InsertPara
Next

See Also

AppActivate, AppClose, AppCount(), AppIsRunning()


AppHide

Syntax

AppHide [WindowName$]

Remarks

In Windows, hides the specified application and removes its window name from the Task List. On the Macintosh, AppHide is not available and generates an error.

Argument | Explanation
WindowName$ | A string that matches the beginning of an application window name, as it appears in the title bar or Task List. If omitted, Word is assumed. For more information on WindowName$, see AppActivate.

See Also

AppClose, AppShow


AppInfo$()

Syntax

AppInfo$(Type)

Remarks

Returns one of 24 types of information about the Word application. Note that the GetSystemInfo$() function returns similar information. Also, you can use the GetSystemInfo statement to fill an array with system information.

Type is one of the following numeric codes, specifying the type of information to return.

Type | Explanation
1 | Environment (for example, "Windows 3.10" or "Macintosh 7.1").
2 | Word version number (for example, "6.0").
3 | Returns –1 if Word is in a special mode (for example, CopyText or MoveText mode).
4 | In Windows, distance from the left edge of the screen to the left border of the Word window, in points (72 points = 1 inch). Note that when Word is maximized, AppInfo$(4) returns a negative value to indicate the borders are beyond the edge of the screen (this value varies depending on the width of the borders). On the Macintosh, AppInfo$(4) returns –1.
5 | In Windows, distance from the top of the screen to the top border of the Word window, in points. Note that when Word is maximized, AppInfo$(5) returns a negative value to indicate the borders are beyond the edge of the screen (this value varies depending on the width of the borders). On the Macintosh, AppInfo$(5) returns 1.
6 | Width of the workspace, in points. In Windows, the width increases as you widen the Word window. Note that increasing the zoom percentage decreases the return value, and vice versa.
7 | Height of the workspace, in points; the height increases as you hide Word screen elements or, in Windows, increase the height of the Word window. Note that increasing the zoom percentage decreases the return value, and vice versa.
8 | Returns –1 if the application is maximized (on the Macintosh, this is always the case).
9 | Total memory, in kilobytes. In Windows 95 and Windows NT, this value returns 0 (zero).
10 | Available memory, in kilobytes. In Windows 95 and Windows NT, this value returns 0 (zero).
13 | Returns –1 if a math coprocessor is installed.
14 | Returns –1 if a mouse is installed.
15 | Available disk space, in kilobytes.
16 | Returns the language version of Word. For example, returns "Français" for the French version of Word. For a list of languages, see ToolsLanguage.

Type | Explanation
17 | Returns the list separator setting.
18 | Returns the decimal setting.
19 | Returns the thousands separator.
20 | Returns the currency symbol.
21 | Returns the clock format.
22 | Returns the A.M. string.
23 | Returns the P.M. string.
24 | Returns the time separator.
25 | Returns the date separator.
26 | In Windows NT, returns 1 if the A.M. and P.M. strings are displayed before time values or 0 (zero) if they are displayed after. In Windows 95, returns 0 (zero). In Word version 6.0, this value is not available and generates an error.

Example

This example displays a message box containing the version number of Word:

ver$ = AppInfo$(2)
MsgBox ver$, "Microsoft Word Version", 64

The following macro shows how you might use a user-defined function to check the current platform before running an instruction. This technique is useful for macros designed to run both in Windows and on the Macintosh.

Sub Main
    If fMac Then MsgBox "Current platform is Macintosh"
End Sub

Function fMac
    a = InStr(AppInfo$(1), "Macintosh")
    If a Then fMac = -1
End Function

See Also

AppGetNames, GetSystemInfo


AppIsRunning()

Syntax

AppIsRunning(WindowName$)

Remarks

Returns –1 if the specified application is running or 0 (zero) if it is not.

Argument | Explanation
WindowName$ | In Windows, a string that matches the beginning of an application window name, as it appears in the title bar or Task List. On the Macintosh, WindowName$ is either the application name or the signature returned by MacID$(). For more information on WindowName$, see AppActivate.

For an example, see AppActivate.

See Also

AppActivate, AppClose, MacID$(), MicrosoftApplication


AppMaximize, AppMaximize()

Syntax

AppMaximize [WindowName$] [, State]

AppMaximize([WindowName$])

Remarks

In Windows, the AppMaximize statement maximizes or restores the specified application.

Argument | Explanation
WindowName$ | A string that matches the beginning of an application window name, as it appears in the title bar or Task List (Windows). If omitted, Word is assumed. For more information on WindowName$, see AppActivate.
State | Specifies whether to maximize or restore the application: 0 (zero) Restores the application 1 Maximizes the application Omitted Toggles between restored and maximized states If the state of the application changes, it is activated. If the state does not change (for example, if you run the instruction AppMaximize "Microsoft Excel", 1 and Microsoft Excel is already maximized), the application is not activated.

The AppMaximize() function returns the following values.

Value | Explanation
–1 | If the application is maximized
0 (zero) | If the application is not maximized

On the Macintosh, AppMaximize and AppMaximize() are not available and generate errors.

See Also

AppMinimize, AppMove, AppRestore, AppSize, DocMaximize


AppMinimize, AppMinimize()

Syntax

AppMinimize [WindowName$] [, State]

AppMinimize([WindowName$])

Remarks

In Windows, the AppMinimize statement minimizes or restores the specified application.

Argument | Explanation
WindowName$ | A string that matches the beginning of an application window name, as it appears in the title bar or Task List (Windows). If omitted, Word is assumed. For more information on WindowName$, see AppActivate.
State | Specifies whether to minimize or restore the application: 0 (zero) Restores the application. 1 Minimizes the application. Omitted Toggles between restored and minimized states. If the application is restored from an icon, it is activated. If the state does not change or if the application is minimized, the application is not activated.

Note

If an untrapped error occurs in a macro while Word is minimized, the macro halts and the Word icon flashes. When Word is restored, it displays a message indicating the nature of the error.

The AppMinimize() function returns the following values.

Value | Explanation
–1 | If the application is minimized
0 (zero) | If the application is not minimized

On the Macintosh, AppMinimize and AppMinimize() are not available and generate errors.

See Also

AppMaximize, AppMove, AppRestore, AppSize, DocMinimize


AppMove

Syntax

AppMove [WindowName$,] HorizPos, VertPos

Remarks

In Windows, moves the specified application window or icon to a position relative to the upper-left corner of the screen. If the application is maximized, an error occurs. On the Macintosh, AppMove is not available and generates an error.

Argument | Explanation
WindowName$ | A string that matches the beginning of an application window or icon name, as it appears in the title bar or Task List (Windows). If omitted, Word is assumed. For more information on WindowName$, see AppActivate.
HorizPos, VertPos | The horizontal (HorizPos) and vertical (VertPos) distance from the upper-left corner of the screen to the upper-left corner of the application window or icon, in points (72 points = 1 inch). Negative measurements are allowed only if you specify WindowName$.

Example

This Windows example starts Microsoft Excel if it is not running and then arranges Word and Microsoft Excel into nonoverlapping windows, each one-half the height of the screen:

If AppIsRunning("Microsoft Excel") = 0 Then MicrosoftExcel
AppRestore
AppMove 0, 0
AppSize 480, 180
AppRestore "Microsoft Excel"
AppMove "Microsoft Excel", 0, 180
AppSize "Microsoft Excel", 480, 180

See Also

AppRestore, AppSize, AppWindowPosLeft, AppWindowPosTop, DocMove


AppRestore, AppRestore()

Syntax

AppRestore [WindowName$]

AppRestore([WindowName$])

Remarks

In Windows, the AppRestore statement restores the specified application from a maximized or minimized state and activates the application. If the specified application is already restored, AppRestore has no effect.

Argument | Explanation
WindowName$ | A string that matches the beginning of an application window name, as it appears in the title bar or Task List (Windows). If omitted, Word is assumed. For more information on WindowName$, see AppActivate.

The AppRestore() function returns the following values.

Value | Explanation
–1 | If the application is restored
0 (zero) | If the application is not restored

For an example, see AppMove.

On the Macintosh, AppRestore and AppRestore() are not available and generate errors.

See Also

AppMaximize, AppMinimize, AppMove, AppSize, DocRestore


AppSendMessage

Syntax

AppSendMessage [WindowName$,] Message, Wparam, Lparam

Remarks

Sends a Windows message and its associated parameters to the application specified by WindowName$. On the Macintosh, AppSendMessage is not available and generates an error.

Argument | Explanation
WindowName$ | A string that matches the beginning of an application window name, as it appears in the title bar or Task List (Windows). If omitted, Word is assumed. For more information on WindowName$, see AppActivate.
Message | A decimal number corresponding to the message you want to send. If you have the Microsoft Windows 3.1 Software Development Kit or the Microsoft Win32 Software Development Kit, you can look up the name of the message in WINDOWS.H and then convert the associated hexadecimal number to a decimal number using Calculator.

Argument | Explanation
Wparam, Lparam | Parameters appropriate for the message you are sending. For information on what these values represent, see the reference topic for the message in the Microsoft Windows 3.1 Programmer's Reference, Volume 3, available in the Microsoft Windows 3.1 Software Development Kit or from Microsoft Press, or in the Programmer's API Reference, Volume 5, available in the Microsoft Win32 Software Development Kit or from Microsoft Press. To retrieve the appropriate values, you may need to use the Spy utility (which comes with the Microsoft Windows 3.1 SDK or the Microsoft Win32 SDK).

Example

This Windows 3.x example starts the Windows Help application and then sends it a message that displays the Open dialog box. The number 273 is the decimal value associated with the message WM_COMMAND and 1101 is the parameter that specifies the Open command. Lparam is ignored in this case, but must still be specified as 0 (zero).

Shell "WINHELP.EXE"
AppSendMessage "Windows Help", 273, 1101, 0

See Also

AppActivate, AppIsRunning(), DDEExecute, DDEPoke


AppSize

Syntax

AppSize [WindowName$,] Width, Height

Remarks

In Windows, sizes an application window to a specified width and height. If the application is maximized or minimized, an error occurs. On the Macintosh, AppSize is not available and generates an error.

Argument | Explanation
WindowName$ | A string that matches the beginning of an application window name, as it appears in the title bar or Task List (Windows). If omitted, Word is assumed. For more information on WindowName$, see AppActivate.
Width, Height | The width and height of the application window, in points (72 points = 1 inch).

For an example, see AppMove.

See Also

AppMove, AppRestore, AppWindowHeight, AppWindowWidth, DocSize


AppWindowHeight, AppWindowHeight()

Syntax

AppWindowHeight [WindowName$,] Height

AppWindowHeight([WindowName$])

Remarks

In Windows, the AppWindowHeight statement adjusts the height of an application window to a specified number of points (if WindowName$ is omitted, Word is assumed). AppWindowHeight allows you to change the height of a window without affecting its width (unlike AppSize). The AppWindowHeight() function returns the height of an application window, in points. For argument descriptions, see AppSize.

On the Macintosh, AppWindowHeight and AppWindowHeight() are not available and generate errors.

See Also

AppSize, AppWindowPosLeft, AppWindowPosTop, AppWindowWidth


AppWindowPosLeft, AppWindowPosLeft()

Syntax

AppWindowPosLeft [WindowName$,] HorizPos

AppWindowPosLeft([WindowName$])

Remarks

In Windows, the AppWindowPosLeft statement moves an application window or icon to a horizontal position specified in points (if WindowName$ is omitted, Word is assumed). AppWindowPosLeft allows you to change the horizontal position of
a window or icon without affecting its vertical position (unlike AppMove). The AppWindowPosLeft() function returns the horizontal position of an application window or icon, in points. For argument descriptions, see AppMove.

On the Macintosh, AppWindowPosLeft and AppWindowPosLeft() are not available and generate errors.

See Also

AppMove, AppWindowHeight, AppWindowPosTop, AppWindowWidth


AppWindowPosTop, AppWindowPosTop()

Syntax

AppWindowPosTop [WindowName$,] VertPos

AppWindowPosTop([WindowName$])

Remarks

In Windows, the AppWindowPosTop statement moves an application window or icon to a vertical position specified in points (if WindowName$ is omitted, Word is assumed). AppWindowPosTop allows you to change the vertical position of a window or icon without affecting its horizontal position (unlike AppMove). The AppWindowPosTop() function returns the vertical position of an application window or icon, in points. For argument descriptions, see AppMove.

On the Macintosh, AppWindowPosTop and AppWindowPosTop() are not available and generate errors.

See Also

AppMove, AppWindowHeight, AppWindowPosLeft, AppWindowWidth


AppWindowWidth, AppWindowWidth()

Syntax

AppWindowWidth [WindowName$,] Width

AppWindowWidth([WindowName$])

Remarks

In Windows, the AppWindowWidth statement adjusts the width of an application window to a specified number of points (if WindowName$ is omitted, Word is assumed). AppWindowWidth allows you to change the width of a window without affecting its height (unlike AppSize). The AppWindowWidth() function returns the width of an application window, in points. For argument descriptions, see AppSize.

On the Macintosh, AppWindowWidth and AppWindowWidth() are not available and generate errors.

See Also

AppSize, AppWindowHeight, AppWindowPosLeft, AppWindowPosTop


Asc()

Syntax

Asc(a$)

Remarks

Returns the character code of the first character in a$. Although "Asc" is short for ASCII, Asc() actually returns ANSI codes. The function name is preserved for compatibility purposes. You can use the syntax Asc(Selection$()) to return the code for the character to the right of the insertion point (for example, to test for a paragraph mark).

Example

This example moves to the beginning of the next paragraph and checks the character to the right of the insertion point. If the character is a paragraph mark, indicating an empty paragraph, a message box is displayed.

ParaDown
If Asc(Selection$()) = 13 Then
    ans = MsgBox("Empty paragraph. Continue?", 4)
End If

See Also

Chr$(), Len()


AtEndOfDocument()

Syntax

AtEndOfDocument()

Remarks

Returns –1 if the insertion point is at the end of the document or 0 (zero) if it is not. Unlike the EndOfDocument() function, AtEndOfDocument() does not move the insertion point.

See Also

AtStartOfDocument(), EndOfDocument


AtStartOfDocument()

Syntax

AtStartOfDocument()

Remarks

Returns –1 if the insertion point is at the beginning of the document or 0 (zero) if it is not. Unlike the StartOfDocument() function, AtStartOfDocument() does not move the insertion point.

See Also

AtEndOfDocument(), StartOfDocument


AutoMarkIndexEntries

Syntax

AutoMarkIndexEntries ConcordanceFilename$

Remarks

Automatically indexes the active document using ConcordanceFilename$, the path and filename of a concordance file. A concordance file is a Word document containing a two-column table with terms to index in the first column and index entries in the second column. The AutoMarkIndexEntries statement inserts an XE (Index Entry) field with the appropriate entry text after each occurrence of the terms listed in the first column of the concordance file.

See Also

MarkIndexEntry


AutomaticChange

Syntax

AutomaticChange

Remarks

Performs an AutoFormat action when there is a change suggested by the TipWizard. The AutomaticChange statement corresponds to the Change button on the TipWizard toolbar. In Word version 6.0, AutomaticChange is unavailable and generates an error.

See Also

Help, ShowMe


AutoText

Syntax

AutoText

Remarks

Displays the AutoText dialog box if there is a selection (and proposes up to the first 32 characters of the selection for the unique entry name) or, if there is no selection, attempts to match the text before or surrounding the insertion point with an AutoText entry and insert the entry (including its formatting, if any). Word looks for the entry first in the active template, then in the Normal template, and finally in each loaded global template in the order listed in the Templates And Add-ins dialog box (File menu). If no match can be made, an error occurs. AutoText corresponds to the AutoText button on the Standard toolbar.

See Also

AutoTextName$(), CountAutoTextEntries(), EditAutoText, GetAutoText$(), InsertAutoText, SetAutoText


AutoTextName$()

Syntax

AutoTextName$(Count [, Context])

Remarks

Returns the name of an AutoText entry in the specified context.

Argument | Explanation
Count | The number of the AutoText entry, from 1 to the total number of AutoText entries defined in the given context (you can obtain the total using CountAutoTextEntries()). AutoText entries are listed in alphabetic order.
Context | The context in which to return the name of an AutoText entry: 0 (zero) or omitted Normal template and any loaded global templates 1 Active template Note that if Context is 1 and the active template is the Normal template, AutoTextName$() generates an error.

Example

This example creates a new document that lists all AutoText entries in the Normal template and any loaded global templates. Entry names are inserted with bold formatting and are followed by the contents of the entry.

FileNewDefault
For count = 1 To CountAutoTextEntries()
    a$ = AutoTextName$(count)
    Bold 1 : Insert a$
    InsertPara
    Bold 0 : EditAutoText .Name = a$, .Insert
    InsertPara : InsertPara
Next

See Also

AutoText, CountAutoTextEntries(), EditAutoText, GetAutoText$(), InsertAutoText, SetAutoText


Beep

Syntax

Beep [ErrorType]

Remarks

Causes the computer's speaker to produce a sound. A typical use of Beep is to signal the end of a long process or to indicate that an error has occurred.

In Windows, Beep produces the sound associated with the specified error type. You associate sounds with error types using the Sound option in Control Panel. If there isn't a sound device installed, Beep produces the default sound through the computer speaker, regardless of the value of ErrorType.

On the Macintosh, Beep produces the sound selected in the Sound control panel, regardless of the value of ErrorType.

Argument | Explanation
ErrorType | In Windows, the type of sound, as specified in Control Panel. -1 Default sound from the computer speaker 0 (zero) or omitted Default sound 16 Critical stop 32 Question 48 Exclamation 64 Asterisk If there is no sound associated with the specified error type, Word produces the default sound.

Note

In Windows 3.x, a beep will not sound if the [Windows] section of WIN.INI includes the line Beep = No. In Windows NT, a beep will not sound if the Beep setting has the value "No" in the HKEY_CURRENT_USER\Control Panel\Sound key.

Examples

This example produces a beep immediately before displaying an input box:

Beep
name$ = InputBox$("The macro has finished running. " + \
                        "Save document as:")

The following example makes the computer beep three times. The second For ¼ Next loop nested within the first one provides a delay between beeps. In effect, the delay loop makes Word count to a thousand before producing the next beep. Without the delay loop, Word would produce beeps so quickly that they would sound like a single, continuous beep. You can vary the delay between beeps by increasing or decreasing the end value of the second For ¼ Next loop. For example, changing the end value to 5000 would increase the delay between beeps; changing it to 100 would decrease the delay.

Sub BeepThreeTimes
    For x = 1 to 3
        Beep
        For timer = 1 To 1000    'Delay loop between beeps
        Next timer
    Next x
End Sub


Begin Dialog...End Dialog

Syntax

Begin Dialog UserDialog [HorizPos, VertPos,] Width, Height, Title$
[, .DialogFunction]
Series of dialog box definition instructions
End Dialog

Remarks

Encloses the instructions that define a dialog box you create within a macro. A dialog box definition consists of a series of instructions that define different elements of the dialog box, such as the OK button, Cancel button, and so on. Dialog box elements are also known as dialog box controls.

The easiest way to create a dialog box is to use the Dialog Editor. With the Dialog Editor, you can use the mouse to design the dialog box. The Dialog Editor then creates the WordBasic code needed to define the dialog box. For information on creating and working with dialog boxes, see Chapter 5, "Working with Custom Dialog Boxes," in Part 1, "Learning WordBasic."

Note

Every custom dialog box must contain at least one command button so the user can close the dialog box. For that reason, a dialog box definition must include either an OKButton, a CancelButton, or a PushButton instruction; otherwise, a WordBasic error will occur when the macro is run.

Argument | Explanation
HorizPos, VertPos | The horizontal and vertical distance of the upper-left corner of the dialog box from the upper-left corner of the Word window, in increments of 1/8 and 1/12 of the System font (Windows) or the dialog font (Macintosh). If HorizPos and VertPos are not specified, Word centers the dialog box within the Word window.
Width, Height | The width and height of the dialog box, in increments of 1/8 and 1/12 of the System font (Windows) or the dialog font (Macintosh).
Title$ | The text that is displayed in the title bar of the dialog box. If you do not specify HorizPos and VertPos, or if you do specify .DialogFunction, you can omit Title$. If Title$ is not specified, the application name is used.
.DialogFunction | The name of a dialog function associated with the dialog box; used for dialog boxes that update dynamically while the dialog box is displayed.

You can use the tab key to move between controls in a dialog box. The order of the instructions in a dialog box definition determines the tabbing order in the dialog box. By default, the dialog control represented by the first instruction in the dialog box definition will be selected when the dialog box is displayed. However, you can override this default by using the DlgFocus statement in a dialog function. You can also use the Dialog statement to specify the default button for a dialog box.

Example

This example defines and displays a dialog box (shown after the instructions) that includes every dialog box control available. Note that the Picture instruction refers to a Windows metafile graphic in the CLIPART folder, installed by Word. On the Macintosh, substitute the path and filename HD:WORD 6:CLIP ART:BIRD.

Once you have defined a dialog box with Begin Dialog ¼ End Dialog, you need two additional instructions to display it: a Dim instruction that defines a dialog record in which the dialog box's values are stored, and a Dialog instruction that displays the dialog box. Note that a dialog function is required to display a document in the FilePreview control. For information on dialog functions, see Chapter 5, "Working with Custom Dialog Boxes," in Part 1, "Learning WordBasic."

Sub MAIN
Dim MyList$(2)
MyList$(0) = "Blue"
MyList$(1) = "Green"
MyList$(2) = "Red"
Begin Dialog UserDialog 612, 226, "Every Dialog Box Control", \
    .DlgFunction
    ComboBox 8, 76, 176, 111, MyList$(), .ComboBox1
    CheckBox 198, 79, 180, 16, "&Check Box", .CheckBox1
    ListBox 195, 102, 189, 83, MyList$(), .ListBox1
    DropListBox 417, 5, 179, 108, MyList$(), .DropListBox1
    Text 417, 186, 35, 13, "&Text"
    TextBox 417, 199, 179, 18, .TextBox1
    GroupBox 7, 4, 177, 65, "&Group Box"
    OptionGroup  .OptionGroup1
        OptionButton 17, 16, 148, 16, "Option Button &1"
        OptionButton 17, 33, 148, 16, "Option Button &2"

END BREAK

        OptionButton 17, 50, 148, 16, "Option Button &3"
    Picture 199, 7, 181, 62, "C:\WINWORD\CLIPART\BIRD.WMF", 0, .Picture1
    FilePreview 417, 31, 179, 148, .fileprev
    PushButton 10, 199, 108, 21, "&PushButton"
    CancelButton 131, 199, 108, 21
    OKButton 253, 199, 108, 21
End Dialog
Dim sampleDlg As UserDialog
DisableInput 1
button = Dialog(sampleDlg)
DisableInput 0
End Sub
Function DlgFunction(identifier$, action, suppvalue)
    'A dialog function is required to display
    'a document in the FilePreview control.
End Function

See Also

CancelButton, CheckBox, ComboBox, Dialog, Dim, DropListBox, FilePreview, GroupBox, ListBox, OKButton, OptionButton, OptionGroup, Picture, PushButton, Text, TextBox


Bold, Bold()

Syntax

Bold [On]

Bold()

Remarks

The Bold statement adds or removes the bold character format for the current selection, or controls bold formatting for characters to be inserted at the insertion point.

Argument | Explanation
On | Specifies whether to add or remove the bold format: 1 Formats the selection as bold 0 (zero) Removes the bold format Omitted Toggles the bold format

The Bold() function returns the following values.

Value | Explanation
0 (zero) | If none of the selection is formatted as bold
–1 | If part of the selection is formatted as bold
1 | If all the selection is formatted as bold

Example

This example applies the bold format to the entire selection if part of the selection is formatted as bold:

If Bold() = -1 Then Bold 1

See Also

FormatFont


BookmarkName$()

Syntax

BookmarkName$(Count)

Remarks

Returns the name of the bookmark specified by Count.

Argument | Explanation
Count | The number of the bookmark, from 1 to the total number of bookmarks defined for the active document (you can obtain the total using CountBookmarks()). The order of bookmark names is determined by the order of the bookmarks in the document. You must specify Count; otherwise, the function returns an error. For example, a$ = BookmarkName$() generates an error.

Example

This example puts a list of every bookmark name in a document into the array mark$(). You could use this array to present a list of bookmark names in a dialog box. Note that the size of the array is one less than the number of bookmarks because the subscript for the first array element is 0 (zero), not 1.

numBookmarks = CountBookmarks()
arraySize = numBookmarks - 1
Dim mark$(arraySize)
For n = 0 To arraySize
    mark$(n) = BookmarkName$(n + 1)
Next

See Also

CountBookmarks(), GetBookmark$()


BorderBottom, BorderBottom()

Syntax

BorderBottom [On]

BorderBottom()

Remarks

The BorderBottom statement applies or removes a bottom border for the selected paragraphs, table cells, or graphic. Note that when you apply a bottom border to a series of paragraphs or table rows, the border appears only beneath the last paragraph or row in the series. If you want a border to separate each paragraph or row, use BorderInside.

Argument | Explanation
On | Specifies whether to apply or remove a bottom border: 1 Applies the border 0 (zero) Removes the border Omitted Toggles the border

The BorderBottom() function returns the following values.

Value | Explanation
0 (zero) | If at least one of the selected items has no bottom border or if the selection contains a mixture of items (for example, a paragraph and a table cell)
1 | If each item in the selection is of the same type and has a bottom border

Example

This example applies a bottom border using one of two line styles, depending on whether the selection is within a table. If the selection is within a table, a double border is applied; otherwise, a thick, single border is applied.

If SelInfo(12) = - 1 Then
    BorderLineStyle 8
    BorderBottom 1
Else
    BorderLineStyle 4
    BorderBottom 1
End If

See Also

BorderInside, BorderLeft, BorderLineStyle, BorderNone, BorderOutside, BorderRight, BorderTop, FormatBordersAndShading, ShadingPattern


BorderInside, BorderInside()

Syntax

BorderInside [On]

BorderInside()

Remarks

The BorderInside statement applies or removes inside borders for the selected paragraphs or table cells. The following illustrations show inside borders within a series of paragraphs and a table.

The BorderInside() function returns either 0 (zero) or 1, depending on whether all the selected paragraphs or table cells are formatted with an inside border. Note that BorderInside() returns 0 (zero) if the selection is a single table cell, regardless of the borders applied to the surrounding group of cells; a single table cell can have bottom, left, right, and top borders, but not inside borders.

For complete descriptions of arguments and return values, see BorderBottom.

See Also

BorderBottom, BorderLeft, BorderLineStyle, BorderNone, BorderOutside, BorderRight, BorderTop, FormatBordersAndShading, ShadingPattern


BorderLeft, BorderLeft()

Syntax

BorderLeft [On]

BorderLeft()

Remarks

The BorderLeft statement applies or removes left borders for the selected paragraphs, table cells, or graphic. The BorderLeft() function returns either
0 (zero) or 1, depending on whether the selected graphic or all the selected paragraphs or table cells are formatted with a left border.

For complete descriptions of arguments and return values, see BorderBottom.

See Also

BorderBottom, BorderInside, BorderLineStyle, BorderNone, BorderOutside, BorderRight, BorderTop, FormatBordersAndShading, ShadingPattern


BorderLineStyle, BorderLineStyle()

Syntax

BorderLineStyle Style

BorderLineStyle()

Remarks

The BorderLineStyle statement specifies the line style for subsequent BorderBottom, BorderInside, BorderLeft, BorderOutside, BorderRight, and BorderTop instructions.

Argument | Explanation
Style | One of 13 line styles: 0 (zero) None 1 2 3 4 5 6 7 8 9 10 11 12 Style 12, which corresponds to the Hairline option, is available only on the Macintosh.

For an example that uses BorderLineStyle, see BorderBottom.

The BorderLineStyle() function returns a number from 0 (zero) to 12 that corresponds to the line style that will be applied by subsequent border instructions. Note that this line style does not necessarily match the line style of borders in the selected paragraphs, table cells, or graphic.

See Also

BorderBottom, BorderInside, BorderLeft, BorderNone, BorderOutside, BorderRight, BorderTop, FormatBordersAndShading, ShadingPattern


BorderNone, BorderNone()

Syntax

BorderNone [Remove]

BorderNone()

Remarks

The BorderNone statement removes or applies all borders (left, right, top, bottom, and inside) for the selected items. You can remove or apply all borders for a series of paragraphs or table rows, but not a combination of paragraphs and table rows. To remove or apply borders for a graphic, you must first select only that graphic.

Argument | Explanation
Remove | Specifies whether to remove or apply all borders for the selection: 0 (zero) Applies borders 1 or omitted Removes borders

The BorderNone() function returns 0 (zero) if the selection contains at least one border and 1 if the selection contains no borders.

See Also

BorderBottom, BorderInside, BorderLeft, BorderLineStyle, BorderOutside, BorderRight, BorderTop, FormatBordersAndShading, ShadingPattern


BorderOutside, BorderOutside()

Syntax

BorderOutside [On]

BorderOutside()

Remarks

The BorderOutside statement applies or removes outside borders for the selected paragraphs, table cells, or graphic. The following illustrations show outside borders applied to a series of paragraphs and an entire table.

The BorderOutside() function returns either 0 (zero) or 1, depending on whether the selected graphic or all the selected paragraphs or table cells are formatted with an outside border.

For complete descriptions of arguments and return values, see BorderBottom.

See Also

BorderBottom, BorderInside, BorderLeft, BorderLineStyle, BorderNone, BorderRight, BorderTop, FormatBordersAndShading, ShadingPattern


BorderRight, BorderRight()

Syntax

BorderRight [On]

BorderRight()

Remarks

The BorderRight statement applies or removes right borders for the selected paragraphs, table cells, or graphic. The BorderRight() function returns either
0 (zero) or 1, depending on whether the selected graphic or all the selected paragraphs or table cells are formatted with a right border.

For complete descriptions of arguments and return values, see BorderBottom.

See Also

BorderBottom, BorderInside, BorderLeft, BorderLineStyle, BorderNone, BorderOutside, BorderTop, FormatBordersAndShading, ShadingPattern


BorderTop, BorderTop()

Syntax

BorderTop [On]

BorderTop()

Remarks

The BorderTop statement applies or removes a top border for the selected paragraphs, table cells, or graphic. Note that when you apply a top border to
a series of paragraphs or table rows, the border appears only above the first paragraph or row in the series. If you want a border to separate each paragraph
or row, use BorderInside.

The BorderTop() function returns either 0 (zero) or 1, depending on whether the selected graphic or all the selected paragraphs or table cells are formatted with a top border.

For complete descriptions of arguments and return values, see BorderBottom.

See Also

BorderBottom, BorderInside, BorderLeft, BorderLineStyle, BorderNone, BorderOutside, BorderRight, FormatBordersAndShading, ShadingPattern


Call

Syntax

[Call] [MacroName][.][SubName] [ArgumentList]

Remarks

Transfers control to a subroutine in the running macro or another macro. To specify a subroutine in another macro, use the syntax MacroName.SubName. If SubName is not specified, the Main subroutine in MacroName runs. Call is optional; it can help distinguish subroutine names from WordBasic keywords when you read and edit macros. Each variable in the comma-delimited ArgumentList must correspond to a value that the subroutine being called is prepared to receive.

Note

When you call another macro, Word looks for the macro in available templates in the following order: the template containing the Call instruction, the active template, the Normal template, and loaded global templates. For example, suppose USER.DOT and NORMAL.DOT both contain a DisplayMessage macro. The following macro in USER.DOT:

FileNew .Template = "Normal"
DisplayMessage

runs the DisplayMessage macro in USER.DOT, even though a document based on NORMAL.DOT is active when the Call instruction is run.

For more information about using subroutines, including how to share variables and pass arguments between subroutines, see Chapter 4, "Advanced WordBasic," in Part 1, "Learning WordBasic."

Example

This example calls the subroutine FindName twice; each line, with or without Call, has the same effect:

Call FindName        'Transfer control to the subroutine FindName
FindName                'Transfer control to the subroutine FindName

See Also

Sub ¼ End Sub


Cancel

Syntax

Cancel

Remarks

Cancels a mode activated by the ColumnSelect, CopyFormat, CopyText, or ExtendSelection statements.

Example

This example pastes the contents of the Clipboard into a document, selects the pasted text, and then places the text of the selection into a variable. To accomplish this task, the macro inserts a bookmark at the insertion point, pastes the text, and then, using ExtendSelection, selects the pasted text. The Cancel statement turns off extend mode, so that when the last instruction moves the insertion point to the end of the document, no text is selected.

CopyBookmark "\Sel", "temp"
EditPaste
ExtendSelection
EditGoTo "temp"
pasted$ = Selection$()
Cancel
EndOfDocument

See Also

OK


CancelButton

Syntax

CancelButton HorizPos, VertPos, Width, Height [, .Identifier]

Remarks

Creates a Cancel button in a custom dialog box. A user chooses the Cancel button to close the dialog box without taking any action.

Argument | Explanation
HorizPos, VertPos | The horizontal and vertical distance of the upper-left corner of the Cancel button from the upper-left corner of the dialog box, in increments of 1/8 and 1/12 of the System font (Windows) or the dialog font (Macintosh).
Width, Height | The width and height of the Cancel button, in increments of 1/8 and 1/12 of the System font (Windows) or the dialog font (Macintosh).
.Identifier | An optional identifier used by statements in a dialog function that act on the Cancel button, such as DlgEnable and DlgVisible. If omitted, "Cancel" is the default identifier.

If you use the Dialog statement to display the dialog box and the user chooses the Cancel button, WordBasic generates an error, which you can trap with On Error.

If you use the Dialog() function to display the dialog box and the user chooses the Cancel button, the function returns 0 (zero) rather than generating an error.

To see an example of CancelButton in a dialog box definition, see Begin Dialog ¼ End Dialog.

See Also

Begin Dialog ¼ End Dialog, Dialog, Err, Error, OKButton, On Error, PushButton


CenterPara, CenterPara()

Syntax

CenterPara

CenterPara()

Remarks

Centers the selected paragraphs.

The CenterPara() function returns the following values.

Value | Explanation
0 (zero) | If none of the selection is centered
–1 | If part of the selection is centered or there is a mix of alignments
1 | If all the selection is centered

See Also

FormatParagraph, JustifyPara, LeftPara, RightPara


ChangeCase, ChangeCase()

Syntax

ChangeCase [Type]

ChangeCase()

Remarks

The ChangeCase statement sets the case of the selected text to sentence case, lowercase, uppercase, or initial capital letters. ChangeCase does not change the character formats associated with the selected text, as do the SmallCaps and AllCaps statements. ChangeCase corresponds to the Change Case command (Format menu).

Argument | Explanation
Type | Specifies the change in case: Omitted If the selection is one sentence or less, alternates the case of the selection among all lowercase, all uppercase, and initial capital letters. If the selection is more than one sentence, alternates among all lowercase, all uppercase, and sentence case. 0 (zero) Sets the text to all lowercase 1 Sets the text to all uppercase 2 Capitalizes the first letter of each selected word 3 Capitalizes the first letter of the selection 4 Capitalizes the first letter of each selected sentence 5 Toggles the case of each selected letter (for example, "Word" becomes "wORD")

If there is no selection, Word selects the word nearest the insertion point, and then changes the case of the selected word.

The ChangeCase() function returns the following values.

Value | Explanation
0 (zero) | If none of the selected text is in uppercase
1 | If all of the selected text is in uppercase
2 | If the text is in a mixture of uppercase and lowercase

Example

This example selects the current paragraph (using the predefined bookmark "\ Para") and capitalizes the first letter of each sentence:

EditGoTo "\Para"
ChangeCase 4

See Also

AllCaps, FormatChangeCase, LCase$(), SmallCaps, UCase$()


CharColor, CharColor()

Syntax

CharColor Color

CharColor()

Remarks

The CharColor statement sets the character color of the selection to the specified color, where Color is one of the following numeric codes.

Color | Explanation
0 (zero) | Auto
1 | Black
2 | Blue
3 | Cyan
4 | Green
5 | Magenta
6 | Red
7 | Yellow
8 | White
9 | Dark Blue
10 | Dark Cyan
11 | Dark Green
12 | Dark Magenta
13 | Dark Red
14 | Dark Yellow
15 | Dark Gray
16 | Light Gray

The CharColor() function returns the same number codes set by the CharColor statement or –1 if all the selected text is not the same color.

Example

This example selects the current paragraph (using the predefined bookmark "\ Para") and applies magenta character color formatting if it contains the string "Comments: ".

EditGoTo "\Para"
If InStr(Selection$(), "Comments: ") Then CharColor 5

See Also

FormatFont, SelectCurColor


CharLeft, CharLeft()

Syntax

CharLeft [Count] [, Select]

CharLeft([Count] [, Select])

Remarks

The CharLeft statement moves the insertion point or the active end of the selection (the end that moves when you press SHIFT+LEFT ARROW) to the left by the specified number of characters.

Argument | Explanation
Count | The number of characters to move. If less than one or omitted, 1 is assumed.
Select | Specifies whether to select text: 0 (zero) or omitted Text is not selected. If there is already a selection, CharLeft moves the insertion point Count–1 characters to the left of the selection. Nonzero Text is selected. If there is already a selection, CharLeft moves the active end of the selection toward the beginning of the document. In a typical selection made from left to right, where the active end of the selection is closer to the end of the document, CharLeft shrinks the selection. In a selection made from right to left, it extends the selection.

If there is a selection, CharLeft 1 changes the selection to an insertion point positioned at the left end of the original selection.

The CharLeft() function behaves the same as the statement and also returns the following values.

Value | Explanation
0 (zero) | If the insertion point or the active end of the selection cannot be moved to the left.
–1 | If the insertion point or the active end of the selection is moved to the left by any number of characters, even if less than Count. For example, CharLeft(10) returns –1 even if the insertion point is only three characters from the start of the document.

Examples

This example moves the insertion point five characters to the left. The If conditional determines whether there is a selection. If there is a selection, the CharLeft 1 instruction changes the selection to an insertion point at the left end of the selection before moving the insertion point five characters to the left. This ensures that the insertion point is moved five characters whether or not there is a selection.

If SelType() = 2 Then
    CharLeft 1
    CharLeft 5
Else
    CharLeft 5
End If

The following example selects the current paragraph and then shrinks the selection by one character, so that the paragraph text is selected, but not the paragraph mark. You might want to do this if you need to copy the text of a paragraph but not its paragraph formatting, which is stored in the paragraph mark.

EditGoTo "\Para"
CharLeft 1, 1

See Also

CharRight, SentLeft, SentRight, WordLeft, WordRight


CharRight, CharRight()

Syntax

CharRight [Count] [, Select]

CharRight([Count] [, Select])

Remarks

The CharRight statement moves the insertion point or the active end of the selection (the end that moves when you press SHIFT+RIGHT ARROW) to the right by the specified number of characters.

Argument | Explanation
Count | The number of characters to move. If less than one or omitted, 1 is assumed.
Select | Specifies whether to select text: 0 (zero) or omitted Text is not selected. If there is already a selection, CharRight moves the insertion point Count–1 characters to the right of the selection. Nonzero Text is selected. If there is already a selection, CharRight moves the active end of the selection toward the end of the document. In a typical selection made from left to right, where the active end of the selection is closer to the end of the document, CharRight extends the selection. In a selection made from right to left, it shrinks the selection.

If there is a selection, CharRight 1 changes the selection to an insertion point positioned at the right end of the original selection.

The CharRight() function behaves the same as the statement and also returns the following values.

Value | Explanation
0 (zero) | If the insertion point or the active end of the selection cannot be moved to the right.
–1 | If the insertion point or the active end of the selection is moved to the right by any number of characters, even if less than Count. For example, CharRight(10) returns –1 even if the insertion point is only three characters from the end of the document.

Examples

This example moves the insertion point to the start of the current sentence and then selects the first five characters to the right:

SentLeft
CharRight 5, 1

The following example first extends the selection five characters to the right, copies the selection, and then moves the insertion point five characters to the right of the selection. Note that CharRight 6 is used to move the selection five characters to the right of the selection. This instruction is equivalent to CharRight 1, which moves the insertion point to the right end of the selection, plus CharRight 5, which then moves it five characters.

CharRight 5, 1
EditCopy
CharRight 6

See Also

CharLeft, SentLeft, SentRight, WordLeft, WordRight


ChDefaultDir

Syntax

ChDefaultDir Path$, Type

Remarks

Sets one of the Word default folders to the specified path. Unlike ToolsOptionsFileLocations, which saves default folder changes in WINWORD6.INI (Windows 3.x), Word Settings (6) (Macintosh), or the registry (Windows 95 and Windows NT), ChDefaultDir changes default folders for the current Word session only. Changes made with ChDefaultDir are not reflected on the File Locations tab in the Options dialog box (Tools menu).

Argument | Explanation
Path$ | The path to which you want to set the default folder specified by Type
Type | A number corresponding to the default folder to set: 0 DOC-PATH 1 PICTURE-PATH 2 USER-DOT-PATH 3 WORKGROUP-DOT-PATH 4 INI-PATH 5 AUTOSAVE-PATH 6 TOOLS-PATH 7 CBT-PATH 8 STARTUP-PATH 15 The style-gallery–template path (this setting is ignored in Word version 7.0) Note that types 9 through 14 cannot be set with ChDefaultDir. To return their values for the current Word session, use DefaultDir$().

Example

This example creates the folder C:\BAK and then sets AUTOSAVE-PATH to that folder for the current session. The instruction On Error Resume Next prevents an error from stopping the macro if the folder already exists. On the Macintosh, substitute a folder name such as HD:BACKUP.

On Error Resume Next
MkDir "C:\BAK"
Err = 0
ChDefaultDir "C:\BAK", 5

See Also

ChDir, DefaultDir$(), Files$(), GetDirectory$(), ToolsOptionsFileLocations


ChDir

Syntax

ChDir Path$

Remarks

Sets the current folder to the drive or folder specified by Path$. If the drive is omitted, the search for the specified path starts at the current folder. You can use ChDir to set the folder so that you do not have to specify the complete path when you use FileOpen to open a document.

Examples

This example changes the folder and then displays the Open dialog box so that you can open a document stored in that folder. You could create a macro like this for a folder you use often and assign the macro to a toolbar button for quick access. On the Macintosh, substitute a folder name such as
HD:WORD 6:LETTERS.

ChDir "C:\WINWORD\LETTERS\PERSONAL"
Dim dlg As FileOpen
button = Dialog(dlg)
If button = -1 Then FileOpen dlg

The following Windows example determines whether the current folder is C:\WINWORD and changes to it if it is not.

If Files$(".") <> "C:\WINWORD" Then ChDir "C:\WINWORD"

Here is the same example, rewritten for the Macintosh:

If Files$(":") <> "HD:WORD 6" Then ChDir "HD:WORD 6"

See Also

Connect, CountDirectories(), Files$(), GetDirectory$(), MkDir, RmDir


CheckBox

Syntax

CheckBox HorizPos, VertPos, Width, Height, Label$, .Identifier

Remarks

Creates a check box in a custom dialog box.

Argument | Explanation
HorizPos, VertPos | The horizontal and vertical distance of the upper-left corner of the rectangle containing the check box and its associated label from the upper-left corner of the dialog box, in increments of 1/8 and 1/12 of the System font (Windows) or the dialog font (Macintosh).
Width, Height | The width and height of the check box, in increments of 1/8 and 1/12 of the System font (Windows) or the dialog font (Macintosh).

Argument | Explanation
Label$ | The label associated with the check box. An ampersand (&) precedes the character in Label$ that is the access key for selecting and clearing the check box.
.Identifier | Together with the dialog record name, .Identifier creates a variable whose value corresponds to the state of the check box. The form for this variable is DialogRecord.Identifier (for example, dlg.MyCheckBox). DialogRecord.Identifier can return the following values: 0 (zero) The check box is cleared. 1 The check box is selected. –1 The check box is filled with gray. The identifier string (.Identifier minus the period) is also used by statements in a dialog function that act on the check box, such as DlgEnable and DlgVisible.

To see an example of CheckBox in a dialog box definition, see Begin Dialog ¼ End Dialog.

See Also

Begin Dialog ¼ End Dialog


CheckBoxFormField

Syntax

CheckBoxFormField

Remarks

Inserts a check box form field at the insertion point. CheckBoxFormField corresponds to the Check Box Form Field button on the Forms toolbar.

See Also

DropDownFormField, InsertFormField, TextFormField


ChooseButtonImage

Syntax

ChooseButtonImage [.Face = number,] .Button = number, [.Context = number,] [.Text = text,] .Toolbar = text

Remarks

Changes the image or text on the specified toolbar button.

Argument | Explanation
.Face | A number corresponding to an image for the button in the built-in set of button images, where 0 (zero) is no image (for a blank button), 1 is the first image, 2 is the second image, and so on. For a list of button images and their associated numbers, see "Toolbar Button Images and Numbers" in Help.
.Button | A number corresponding to the position of the button to change on the specified toolbar, where 1 is the first position, 2 is the second, and so on. Note that a list box or space counts as one position. If you specify a position that corresponds to a space, Word modifies the button to the right of the space.
.Context | Determines where the toolbar change is stored: 0 (zero) or omitted Normal template 1 Active template
.Text | The text you want to appear on the button. If you specify both .Face and .Text, .Text takes precedence.
.Toolbar | The name of the toolbar as listed in the Toolbars dialog box (View menu).

Note

You can choose a button image for a list box on a toolbar; however, the button is displayed only when the toolbar is vertical.

Examples

This example changes the image on the Stop button on the Macro toolbar to button image 50:

ChooseButtonImage .Face = 50, .Button = 9, .Context = 0, \
        .Toolbar = "Macro"

The following example creates a dialog record for the Custom Button dialog box (Toolbar Customization shortcut menu) and then displays the dialog box so you can modify the third button on the Standard toolbar. Note that, unlike those for other dialog records, instructions that set values in a ChooseButtonImage dialog record must precede the GetCurValues instruction.

Dim dlg As ChooseButtonImage
dlg.Toolbar = "Standard"
dlg.Button = 3
GetCurValues dlg
Dialog dlg
ChooseButtonImage dlg

See Also

AddButton, CopyButtonImage, EditButtonImage, MoveButton, PasteButtonImage, ResetButtonImage


Chr$()

Syntax

Chr$(CharCode)

Remarks

Returns the character whose character code is CharCode.

Character codes in the range 0 (zero) to 31, inclusive, match the nonprinting characters of the standard ASCII code. For example, Chr$(13) is a carriage return character and Chr$(9) is a tab character. You can use Chr$(13) to create a new line within a message string used with MsgBox (but not InputBox$()).

The following table lists a few of the special characters you can produce using Chr$().

Value | Character returned
Chr$(9) | Tab character
Chr$(11) | Newline character (SHIFT+ENTER)
Chr$(13) | Paragraph mark Note that paragraph marks in Windows text files and Word for Windows version 2.x documents have the value Chr$(13) + Chr$(10) until you save the file in Word Document format in Word version 6.0.
Chr$(30) | Nonbreaking hyphen
Chr$(31) | Optional hyphen
Chr$(32) | Space character
Chr$(34) | Quotation mark
Chr$(160) | Nonbreaking space (Windows)
Chr$(202) | Nonbreaking space (Macintosh)

The appearance of the symbol assigned to a given character code varies with the font used. Character codes in the range 127 to 255, inclusive, return different symbols, according to the font used.

Because the quotation mark is used to indicate the beginning or end of a string in WordBasic, you use Chr$(34) if you want to include a quotation mark in a string. For example, to create a message box with the message "Type "Yes" or "No"," you would use the following statement:

MsgBox "Type " + Chr$(34) + "Yes" + Chr$(34) + " or " + \
    Chr$(34) + "No" + Chr$(34)

Tip

You can type pairs of quotation marks in an instruction and Word will convert them to the correct syntax using Chr$(34) the first time you run or save the macro. For example, Word converts MsgBox "Type ""Yes"" or ""No""" to the instruction shown previously. Similarly, tab characters are automatically converted to Chr$(9).

Examples

This example displays a message box with two lines:

MsgBox "This is the first line" + Chr$(13) + "This is the second line"

The following example creates a table of symbols between character codes 127 and 255 (often referred to as the extended character set). The first instruction asks the user to name the font for which he or she would like to see the symbols.

fontchoice$ = InputBox$("Please enter the Font Name ", \
                    "Symbol Table", "Symbol")
For i = 127 To 255
    Font "Times New Roman"
    Insert Str$(i) + Chr$(9)
    Font fontchoice$
    Insert Chr$(i)
    InsertPara
Next

See Also

Asc(), Str$()


CleanString$()

Syntax

CleanString$(Source$)

Remarks

Removes nonprinting characters and special Word characters from Source$, or changes them to spaces (character code 32).

In Windows and on the Macintosh, the following characters are changed to spaces, unless otherwise noted.

Character code | Description
1–29 | Nonprinting characters. Character 13 (paragraph mark) is not removed. Character 10 is converted to character 13, unless preceded by character 13, in which case character 10 is removed. Character 7 is removed, unless preceded by character 13, in which case character 7 is converted to character 9 (tab character).
31 | Optional hyphen. Character 31 is removed rather than changed to a space.

In Windows, the following characters are converted as described.

Character code | Description
160 | Nonbreaking space; changed to a space
172 | Optional hyphen symbol; removed
176 | Nonbreaking space symbol; changed to a space
182 | Paragraph mark character; removed
183 | Bullet character; changed to a space

On the Macintosh, the following characters converted as described.

Character code | Description
194 | Optional hyphen symbol; removed
202 | Nonbreaking space; changed to a space

If a field is included in the selection and the field codes are displayed, CleanString$() changes the field characters to spaces.

Example

This example uses CleanString$() to remove any nonprinting characters (except character 13) in the selected text:

temp$ = Selection$()
clean$ = CleanString$(temp$)

See Also

LTrim$(), RTrim$()


ClearAddIns

Syntax

ClearAddIns RemoveFromList

Remarks

Unloads all global templates and Word add-in libraries (WLLs) that appear in the list of global templates and add-ins in the Templates And Add-ins dialog box (Templates command, File menu).

Argument | Explanation
RemoveFromList | Specifies whether to remove the global templates and add-ins from the list in addition to unloading them: 0 (zero) Global templates and add-ins remain in the list. 1 Global templates and add-ins are removed from the list (except for those in the Startup folder).

See Also

AddAddIn, AddInState(), CountAddIns(), DeleteAddIn, GetAddInId(), GetAddInName$()


ClearFormField

Syntax

ClearFormField

Remarks

Clears the text in a text form field selected in a protected form document. ClearFormField behaves like the BACKSPACE key. Note that in an unprotected form document, ClearFormField deletes the selected text form field.

Example

This example is intended to run when the focus moves to a text form field. If the user moves to the form field using the tab key, thereby selecting its contents, the condition GetSelStartPos() <> GetSelEndPos() is true and Word clears the form field. If the user clicks the form field with the mouse, the condition is false and Word takes no action.

If GetSelEndPos() <> GetSelStartPos() Then ClearFormField

See Also

SetFormResult, TextFormField


Close

Syntax

Close [[#]FileNumber]

Remarks

Closes an open sequential file. FileNumber is the number specified in the Open instruction that opened the file for input, output, or appending. If FileNumber is omitted, all files that were opened with Open are closed.

Sequential files, which are opened with Open and closed with Close, are not displayed in document windows. Although you can use Open to open any file, Open and Close are intended to be used with text files. Close does not display
a prompt when it closes a file. For more information about sequential files, see Chapter 9, "More WordBasic Techniques," in Part 1, "Learning WordBasic."

Example

This example opens a file, inserts a list of AutoText entries in the Normal template and any loaded global templates, and then closes the file:

Open "AUTOTEXT.TXT" For Output As #1
For count = 1 To CountAutoTextEntries(0)
    Print #1, AutoTextName$(count)
Next count
Close #1

See Also

Eof(), Input, Input$(), Line Input, Lof(), Open, Print, Read, Seek, Write


ClosePane

Syntax

ClosePane

Remarks

Closes a pane. Use this statement to close the lower pane in a split document window, a footnote pane, or any other kind of pane. ClosePane generates a WordBasic error if no pane is open in the active document. Note that ClosePane does not close a document window.

Example

This example closes the lower pane in the active document if the window is split:

If DocSplit() Then ClosePane

See Also

DocSplit, OtherPane, WindowPane()


ClosePreview

Syntax

ClosePreview

Remarks

Returns the active document from print preview to the previous view. ClosePreview has no effect if the active document is not displayed in print preview.

See Also

FilePrintPreview


CloseUpPara

Syntax

CloseUpPara

Remarks

Removes the paragraph formatting that creates space before the selected paragraphs. CloseUpPara corresponds to setting to 0 (zero) the Before option on the Indents And Spacing tab in the Paragraph dialog box (Format menu).

Example

This macro toggles Before formatting between one line and no lines before the selected paragraphs:

Sub MAIN
    Dim dlg As FormatParagraph
    GetCurValues dlg
    If Val(dlg.Before) <> 0 Then
        CloseUpPara
    Else
        OpenUpPara
    End If
End Sub

See Also

FormatParagraph, OpenUpPara


CloseViewHeaderFooter

Syntax

CloseViewHeaderFooter

Remarks

Hides the Header And Footer toolbar and moves the insertion point to its previous location in the document area. If the insertion point is not in a header or footer, an error occurs.

See Also

GoToHeaderFooter, ShowNextHeaderFooter, ShowPrevHeaderFooter, ViewHeader


CmpBookmarks()

Syntax

CmpBookmarks(Bookmark1$, Bookmark2$)

Remarks

Compares the contents of two bookmarks. Use CmpBookmarks() with the predefined bookmarks in Word to check the location of the insertion point or to create a macro that operates only within an area marked with a bookmark. For example, using the "\ Sel" (current selection) bookmark and the "\ Para" bookmark, you can set up a macro to operate only within a particular paragraph. For more information about predefined bookmarks, see "Operators and Predefined Bookmarks" later in this part.

Argument | Explanation
Bookmark1$ | The first bookmark
Bookmark2$ | The second bookmark

This function returns the following values.

Value | Explanation
0 (zero) | Bookmark1$ and Bookmark2$ are equivalent.
1 | Bookmark1$ is entirely below Bookmark2$.
2 | Bookmark1$ is entirely above Bookmark2$.
3 | Bookmark1$ is below and inside Bookmark2$.
4 | Bookmark1$ is inside and above Bookmark2$.
5 | Bookmark1$ encloses Bookmark2$.
6 | Bookmark2$ encloses Bookmark1$.
7 | Bookmark1$ and Bookmark2$ begin at the same point, but Bookmark1$ is longer.
8 | Bookmark1$ and Bookmark2$ begin at the same point, but Bookmark2$ is longer.
9 | Bookmark1$ and Bookmark2$ end at the same place, but Bookmark1$ is longer.
10 | Bookmark1$ and Bookmark2$ end at the same place, but Bookmark2$ is longer.
11 | Bookmark1$ is below and adjacent to Bookmark2$.
12 | Bookmark1$ is above and adjacent to Bookmark2$.
13 | One or both of the bookmarks do not exist.

Example

This example adds a string of characters in front of every line in a selection.
The example first marks the selected text with a bookmark and then uses a While ¼ Wend loop controlled by three CmpBookmarks() functions to add text in front of each line. The first CmpBookmarks() function tests whether the insertion point and the selection, stored in the "Temp" bookmark, begin at the same point; this is true when the loop begins. The second CmpBookmarks() function tests whether the insertion point is contained within "Temp"; this is true as long as the insertion point is within the original selection. The third CmpBookmarks() function tests whether the insertion point is at the end of the original selection. When the insertion point moves beyond the original selection, the loop ends. Within the While ¼ Wend loop is yet another CmpBookmarks() instruction, which determines whether the selection is at the end of the document, a special case.

CopyBookmark "\Sel", "Temp"
SelType 1
While CmpBookmarks("\Sel", "Temp") = 8 \
        Or CmpBookmarks("\Sel", "Temp") = 6 \
        Or CmpBookmarks("\Sel", "Temp") = 10 \
        And leaveloop <> 1
    EndOfLine
    If CmpBookmarks("\Sel", "\EndOfDoc") = 0 Then leaveloop = 1
    StartOfLine
    Insert "***"
    LineDown
Wend
EditGoTo "Temp"
EditBookmark "Temp", .Delete

See Also

CopyBookmark, EditBookmark, EmptyBookmark


ColumnSelect

Syntax

ColumnSelect

Remarks

Turns on column selection mode to select a column of text, such as numbers aligned at the same tab stop in two or more lines of text. Cancel or any command acting on the column selection ends this mode. ColumnSelect does not select a column in a Word table; use TableSelectColumn for this purpose.

Example

This example selects the numbers and tab characters in the current line and the two subsequent lines of a list, as in the illustration that follows it:

StartOfLine
ColumnSelect
WordRight 2
LineDown 2

See Also

Cancel, ExtendSelection


ComboBox

Syntax

ComboBox HorizPos, VertPos, Width, Height, ArrayVariable$(), .Identifier[$]

Remarks

Creates a combo box — a single control that is a combination of a list box and a text box — in a custom dialog box. A user can either select an item from the list or type a new item in the text box.

Argument | Explanation
HorizPos, VertPos | The horizontal and vertical distance of the upper-left corner of the combo box from the upper-left corner of the dialog box, in increments of 1/8 and 1/12 of the System font (Windows) or the dialog font (Macintosh).
Width, Height | The width and height of the combo box, in increments of 1/8 and 1/12 of the System font (Windows) or the dialog font (Macintosh).
ArrayVariable$() | A text array containing the items to be listed in the combo box.
.Identifier[$] | Together with the dialog record name, .Identifier[$] creates a variable whose value corresponds to the text of the item chosen or the text typed in the combo box. The form for this variable is DialogRecord.Identifier[$] (for example, dlg.MyComboBox$). The dollar sign ($) is optional; you can use it to indicate that the variable is a string variable. The identifier string (.Identifier[$] minus the period) is also used by statements in a dialog function that act on the combo box, such as DlgEnable and DlgVisible.

The macro must define and assign values to the elements in ArrayVariable$() before defining the dialog box containing a combo box. To see an example of ComboBox in a dialog box definition, see Begin Dialog ¼ End Dialog.

See Also

Begin Dialog ¼ End Dialog, Dialog, Dim


CommandValid()

Syntax

CommandValid(CommandName$)

Remarks

Indicates whether CommandName$ is a valid WordBasic statement and, if so, whether it is available in the current context.

The CommandValid() function returns the following values.

Value | Explanation
-1 | If CommandName$ is valid and is available in the current context
0 (zero) | If CommandName$ is valid but is not available in the current context
1 | If CommandName$ is not valid

Example

This example tests whether the Undo command (Edit menu) is available. If it is, the previous editing or formatting command is undone.

If CommandValid("EditUndo") = -1 Then
    EditUndo
End If

See Also

IsMacro()


Connect

Syntax

Connect [.Drive = number,] .Path = text [, .Password = text]

Remarks

In Windows, establishes a connection to a network drive. On the Macintosh, Connect is not available and generates an error; use MountVolume instead.

Argument | Explanation
.Drive | A number corresponding to the letter you want to assign to the network drive, where 0 (zero) corresponds to the first available drive letter, 1 to the second available drive letter, and so on. If you don't specify .Drive, the next available letter is used.
.Path | The path for the network drive (for example, "\\PROJECT\INFO").
.Password | The password, if the network drive is protected with a password.

Example

This example establishes a connection to a network drive protected with the password "smiley" and assigns the network drive to the next available network drive letter:

Connect .Path = "\\PROJECT\INFO", .Password = "smiley"

See Also

ChDir, CountDirectories(), GetDirectory$(), MountVolume


ControlRun

Syntax

ControlRun .Application = number

Remarks

In Windows, runs either the Clipboard or the Control Panel. If you want to run a different program, use the Shell statement. On the Macintosh, ControlRun is not available and generates an error.

Argument | Explanation
.Application | The application to run: 0 (zero) Clipboard (this value is not available and generates an error in Windows 95) 1 Control Panel

Example

This example runs the Control Panel:

ControlRun .Application = 1

See Also

Shell, ShowClipboard


Converter$()

Syntax

Converter$(FormatNumber)

Remarks

Returns the class name of the file format associated with FormatNumber.

Argument | Explanation
FormatNumber | A number corresponding to a file format listed under Save File As Type in the Save As dialog box (File menu): 0 (zero) corresponds to the first format, 1 to the second format, and so on. FormatNumber can also be a value returned by ConverterLookup(). Note that in some cases, the format number returned by ConverterLookup() does not match the position of the format name in the list box. In Windows for example, ConverterLookup("Excel Worksheet") returns 101.

Example

This example inserts at the insertion point a list of file format class names available to Word. The instructions run until a$ is an empty string (""), indicating that the end of the list of available formats has been reached.

x = 0
a$ = Converter$(x)
While a$ <> ""
    Insert a$ + Chr$(13)
    x = x + 1
    a$ = Converter$(x)
Wend

See Also

ConverterLookup(), FileSaveAs


ConverterLookup()

Syntax

ConverterLookup(FormatName$)

Remarks

Returns a number corresponding to the file format specified by FormatName$. You can use this number with the .Format argument in a FileSaveAs instruction to save a file in a different format. If the specified format does not exist, ConverterLookup() returns –1.

Argument | Explanation
FormatName$ | The class name for the format as returned by Converter$(), or the name of a file format as it appears in the Save File As Type box in the Save As dialog box (File menu).

Examples

This Windows example saves the active document in rich-text format (RTF), using the class name "MSRTF" to specify the format:

FileSaveAs .Name = "C:\RTF\TEST.RTF", \
        .Format = ConverterLookup("MSRTF")

The following Macintosh example also saves the active document in RTF, but specifies the format using the name in the Save File As Type box in the Save As dialog box instead of the class name:

FileSaveAs .Name = "HD:RTF:RTF TEST", \
        .Format = ConverterLookup("Rich Text Format")

See Also

Converter$(), FileSaveAs


ConvertObject

Syntax

ConvertObject [.IconNumber = number] [, .ActivateAs = number] [, .IconFilename = text] [, .Caption = text] [, .Class = text] [, .DisplayIcon = number]

Remarks

Converts the selected embedded object from one class to another, allows a different server application to edit the object, or changes how the object is displayed in the document. The arguments for the ConvertObject statement correspond to the options in the Convert dialog box (Object submenu, Edit menu).

Argument | Explanation
.IconNumber | If .DisplayIcon is set to 1, a number corresponding to the icon you want to use in the program file specified by .IconFilename. Icons appear in the Change Icon dialog box (Object command, Insert menu): 0 (zero) corresponds to the first icon, 1 to the second icon, and so on. If omitted, the first (default) icon is used. On the Macintosh, icons for embedded objects cannot be changed; this argument is ignored.
.ActivateAs | Specifies whether Word converts or sets the server application for the selected object: 0 (zero) Converts the selected object to the object type specified by .Class. 1 Uses the server application specified by .Class to edit the object. Note that this setting applies to all objects of the selected type and that Word uses the specified server application when inserting objects of the selected type.
.IconFilename | If .DisplayIcon is set to 1, the path and filename of the program file in which the icon to be displayed is stored. On the Macintosh, icons for embedded objects cannot be changed; this argument is ignored.
.Caption | If .DisplayIcon is set to 1, the caption of the icon to be displayed; if omitted, Word inserts the name of the object.
.Class | A class name specifying the object type to convert to or the server application for editing the object, depending on the setting for .ActivateAs. The class name for a Word document is Word.Document.6 and a Word picture is Word.Picture.6. To look up other class names, insert an object of the type to convert to in a document and view the field codes; the class name of the object follows the word "EMBED."
.DisplayIcon | Specifies whether or not to display the object as an icon: 0 (zero) or omitted Object is not displayed as an icon. 1 Object is displayed as an icon.

Example

This Windows example changes the display of the selected embedded object to an icon stored in PROGMAN.EXE.

ConvertObject .IconNumber = 28, .IconFilename = "PROGMAN.EXE", \
    .Caption = "Caption Text", .DisplayIcon = 1

See Also

InsertObject


CopyBookmark

Syntax

CopyBookmark Bookmark1$, Bookmark2$

Remarks

Sets Bookmark2$ to the insertion point or range of text marked by Bookmark1$. You can use this statement with predefined bookmarks — such as "\ StartOfSel" and "\ EndOfSel" — to set bookmarks relative to the insertion point or selection. For more information about predefined bookmarks, see "Operators and Predefined Bookmarks" later in this part.

Example

This example selects the current section, then sets one bookmark at the start of the section and another bookmark at the end. You can use this technique to define starting points and end points between which your macro operates.

EditGoTo "\Section"
CopyBookmark "\StartOfSel", "SectionStart"
CopyBookmark "\EndOfSel", "SectionEnd"

See Also

CmpBookmarks(), EditBookmark, SetEndOfBookmark, SetStartOfBookmark


CopyButtonImage

Syntax

CopyButtonImage Toolbar$, Tool [, Context]

Remarks

Copies the face of the specified toolbar button so that the face can be pasted onto another button using PasteButtonImage.

Argument | Explanation
Toolbar$ | The name of the toolbar, as it appears in the Toolbars dialog box (View menu).
Tool | A number corresponding to the button face to copy, where 1 is the first button on the specified toolbar, 2 is the second, and so on.
Context | Specifies which button face Word copies: 0 (zero) or omitted The button face that is displayed when a document based on the Normal template is active. 1 The button face that is currently displayed. Note that the button face that is displayed depends on the custom settings, if any, of the active template, any loaded global templates, and the Normal template.

Example

This example pastes the face of the third button on the Standard toolbar (the Save button) onto the first button of a custom toolbar named "TestBar":

CopyButtonImage "Standard", 3
PasteButtonImage "TestBar", 1

See Also

AddButton, ChooseButtonImage, EditButtonImage, MoveButton, PasteButtonImage, ResetButtonImage


CopyFile

Syntax

CopyFile .FileName = text, .Directory = text

Remarks

Copies a file to the specified folder. CopyFile allows you to specify a new name when copying the file.

Argument | Explanation
.FileName | The name of the file to copy. If you do not specify the path, Word copies the file from the current folder.
.Directory | The path of the folder to which the file is copied. Include a filename if you want to rename the file in addition to copying it.

Examples

This example copies the document JULY.DOC to the C:\WINWORD\ MEMOS folder. On the Macintosh, substitute a folder name such as HD:WORD 6:MEMOS.

CopyFile "JULY.DOC", "C:\WINWORD\MEMOS"

This example displays a dialog box that prompts for the folder to which to copy the active document. The proposed folder is C:\BAK. On the Macintosh, substitute a default folder name such as HD:BACKUP.

a$ = FileName$()
Dim dlg As CopyFile
dlg.FileName = a$
dlg.Directory = "C:\BAK"
x = Dialog(dlg)
If x = -1 Then CopyFile dlg

See Also

FileSaveAs, Kill, Name


CopyFormat

Syntax

CopyFormat

Remarks

Copies the character formatting of the first character of the selected text to another text selection. If a paragraph mark is selected, Word copies paragraph formatting in addition to character formatting. For CopyFormat to work, macro instructions

must make a selection immediately before the CopyFormat instruction, make a new selection immediately following CopyFormat, and then use the PasteFormat statement to apply the formatting.

Example

This example copies the character formatting of the first character of the current paragraph (selected using the predefined bookmark "\ Para") to the paragraph immediately above it:

EditGoTo "\Para"
CopyFormat
ParaUp 2
ParaDown 1, 1
PasteFormat

See Also

CopyText, PasteFormat


CopyText

Syntax

CopyText

Remarks

Copies the selected text without putting it on the Clipboard (the same as pressing SHIFT+F2). For CopyText to work, macro instructions must make a selection immediately before the CopyText instruction, make a new selection immediately after CopyText, and then use the OK statement to copy the text.

Example

This example inserts a copy of the current paragraph (selected using the predefined bookmark "\ Para") immediately below the current paragraph:

EditGoTo "\Para"
CopyText
ParaDown
OK

See Also

Cancel, MoveText, OK


CountAddIns()

Syntax

CountAddIns()

Remarks

Returns the number of global templates and Word add-in libraries (WLLs) in the list of global templates and add-ins in the Templates And Add-ins dialog box (Templates command, File menu).

Example

This example unloads all global templates whose filenames contain the text ".DOT" in the list of global templates and add-ins.

For i = 1 To CountAddIns()
    a$ = GetAddInName$(i)
    If InStr(a$, ".DOT") <> 0 Then
        AddInState a$, 0
    End If
Next i

See Also

AddAddIn, AddInState, ClearAddIns, DeleteAddIn, GetAddInId(), GetAddInName$()


CountAutoCorrectExceptions()

Syntax

CountAutoCorrectExceptions(Tab)

Remarks

Returns the number of exceptions listed on the specified tab in the AutoCorrect Exceptions dialog box (AutoCorrect command, Tools menu). In Word version 6.0, CountAutoCorrectExceptions() is unavailable and generates an error.

Argument | Explanation
Tab | The tab from which to return the number of exceptions: 0 (zero) First Letter 1 INitial CAps

For an example, see GetAutoCorrectException$().

See Also

GetAutoCorrectException$(), IsAutoCorrectException(), ToolsAutoCorrectExceptions


CountAutoTextEntries()

Syntax

CountAutoTextEntries([Context])

Remarks

Returns the number of AutoText entries defined for the specified context.

Argument | Explanation
Context | The context in which to count AutoText entries: 0 (zero) or omitted Normal template and any loaded global templates 1 Active template Note that if Context is 1 and the active template is the Normal template, CountAutoTextEntries() returns 0 (zero).

For an example, see AutoTextName$().

See Also

AutoTextName$(), GetAutoText$()


CountBookmarks()

Syntax

CountBookmarks()

Remarks

Returns the number of bookmarks in the active document. As the first example in this entry demonstrates, you can use this function to define an array containing every bookmark in a document.

Examples

This example creates an array containing the name of every bookmark in the active document:

size = CountBookmarks() - 1
Dim marks$(size)
For count = 0 To size
    marks$(count) = BookmarkName$(count + 1)
Next

The following example deletes all the bookmarks in the active document:

For n = 1 To CountBookmarks()
    EditBookmark .Name = BookmarkName$(CountBookmarks()), \
        .Delete
Next

See Also

BookmarkName$(), EditBookmark


CountDirectories()

Syntax

CountDirectories(Directory$)

Remarks

Returns the number of subfolders contained within Directory$. If Directory$ is omitted, the current folder is assumed. If Directory$ does not exist, CountDirectories() returns –1.

Example

This example determines whether there are any subfolders in the Word program folder. On the Macintosh, substitute a folder name such as HD:WORD 6.

dirNum = CountDirectories("C:\WINWORD")
If dirNum = 0 Then
    MsgBox "No subfolders."
Else
    MsgBox "There are" + Str$(dirNum) + " subfolders."
End If

See Also

Files$(), GetDirectory$()


CountDocumentProperties()

Syntax

CountDocumentProperties()

Remarks

Returns the total number of built-in and custom document properties defined for the current document. For a list of the built-in properties available in Word, see DocumentPropertyName$(). In Word version 6.0, CountDocumentProperties() is unavailable and generates an error.

For an example, see DocumentPropertyName$().

See Also

DocumentPropertyName$(), GetDocumentProperty()


CountDocumentVars()

Syntax

CountDocumentVars()

Remarks

Returns the number of document variables set with SetDocumentVar or SetDocumentVar() in the active document.

Example

This example resets each document variable in the active document to an empty string (""). If the document contains no variables, a message box is displayed.

numVars = CountDocumentVars()
If numVars > 0 Then
    For i = 1 To CountDocumentVars()
        name$ = GetDocumentVarName$(1)
        SetDocumentVar name$, ""
    Next
Else
    MsgBox "No document variables to reset."
End If

See Also

GetDocumentVar$(), GetDocumentVarName$(), SetDocumentVar


CountFiles()

Syntax

CountFiles()

Remarks

Returns the number of filenames in the list of most recently used files at the bottom of the File menu.

Example

This example opens the most recently used file. You could use this instruction in an AutoExec macro. It uses CountFiles() to determine that at least one file is listed on the File menu.

If CountFiles() Then File1 Else MsgBox "Sorry, no file listed."

See Also

FileList, FileName$(), File Number


CountFonts()

Syntax

CountFonts()

Remarks

Returns the number of fonts available with the selected printer. This is the number of fonts listed in the Font dialog box (Format menu) or in the Formatting toolbar's font list.

The font list includes fonts installed on the printer, TrueType® fonts (if they are installed), and system fonts.

Example

This example creates a new document and then inserts the available font names, each formatted with the corresponding font:

FileNewDefault
For count = 1 To CountFonts()
    Font Font$(count)
    Insert Font$(count)
    InsertPara
Next

See Also

Font


CountFoundFiles()

Syntax

CountFoundFiles()

Remarks

Returns the number of files found in the last search using FileFind. CountFoundFiles() returns 0 (zero) if no files were found in the last search or
if a search has not been performed during the current Word session.

Example

This example determines whether the last FileFind search was successful:

If CountFoundFiles() = 0 Then MsgBox "No files found."

For another example, see FileFind.

See Also

FileFind, FoundFileName$()


CountKeys()

Syntax

CountKeys([Context])

Remarks

Returns the number of key assignments specified on the Keyboard tab in the Customize dialog box (Tools menu) that differ from the default assignments.

Argument | Explanation
Context | Specifies the template in which to count key assignments: 0 (zero) or omitted Normal template 1 Active template

For an example, see KeyCode().

See Also

KeyCode(), KeyMacro$(), ToolsCustomizeKeyboard


CountLanguages()

Syntax

CountLanguages()

Remarks

Returns the number of available language formats, including the No Proofing format (set with the instruction Language "0"). For the list of valid foreign language names, see ToolsLanguage.

Example

This example fills the array langnames$() with the list of available language formats:

Dim langnames$(CountLanguages())
For count = 1 To CountLanguages()
    langnames$(count) = Language$(count)
Next

See Also

Language, ToolsLanguage


CountMacros()

Syntax

CountMacros([Context] [, All] [, Global])

Remarks

Returns the number of macros available in the specified context.

Argument | Explanation
Context | Specifies the template in which to count macros: 0 (zero) or omitted Normal template 1 Active template Note that if you specify 1 and Normal is the active template, CountMacros() returns 0 (zero).
All | If 1, all available macros, add-in commands, and built-in commands are included in the count.
Global | If 1, only macros stored in loaded global templates and add-in commands are counted.

Example

This example stores the number of built-in commands in builtins and then inserts in the active document a list of the names of the built-in commands:

loaded = CountMacros(0, 0, 1)
active = CountMacros(1)
normal = CountMacros(0)
templates = active + normal
nonbuiltins = loaded + templates
builtins = CountMacros(0, 1) - nonbuiltins
For count = 1 to builtins
    pos = count + nonbuiltins
    Insert Str$(count) + Chr$(9) + MacroName$(pos, 0, 1)
    InsertPara
Next count

See Also

ListCommands, MacroName$()


CountMenuItems()

Syntax

CountMenuItems(Menu$, Type [, Context])

Remarks

Returns the number of menu items on the specified menu. Separators are counted as menu items. In several cases, a list of menu items is counted as one. You can identify these cases in the Position On Menu box on the Menus tab in the Customize dialog box (Tools menu). Examples include the list of filenames on the File menu, the list of windows on the Window menu, and the list of proofing tools on the Tools menu.

Argument | Explanation
Menu$ | The name of a menu or a shortcut menu. Menu names appear in the Menu list box, which is on the Menus tab in the Customize dialog box (Tools menu). Including an ampersand (&) before the underlined letter in the menu name is optional (for example, you can specify either "File" or "&File"). Do not include the parenthetical phrases "(No Document)" and "(Shortcut)" even though that text appears in the Customize dialog box.
Type | The type of menu: 0 (zero) Menus on the menu bar when a document is open 1 Menus on the menu bar when no document is open 2 Shortcut menus
Context | Specifies which menu items to count: 0 (zero) The items that are displayed on the menu when a document based on the Normal template is active 1 or omitted The items that are currently displayed on the menu Note that the items that are displayed on the menu depend on the custom settings, if any, of the active template, any loaded global templates, and the Normal template.

Example

This example inserts a tab-delimited list of the menu items on the Tools menu in the active template:

tab$ = Chr$(9)
For n = 1 To CountMenuItems("T&ools", 0, 1)
    Insert Str$(n) + tab$ + MenuItemText$("T&ools", 0, n, 1)
    InsertPara
Next

See Also

MenuItemMacro$(), MenuItemText$()


CountMenus()

Syntax

CountMenus(Type [, Context])

Remarks

Returns the number of menus of the specified type.

Argument | Explanation
Type | The type of menu to count: 0 (zero) Menus on the menu bar when a document is open 1 Menus on the menu bar when no document is open 2 Shortcut menus
Context | Specifies which menus are counted: 0 (zero) The menus that are available when a document based on the Normal template is active 1 or omitted The menus that are currently available Note that the menus that are available depend on the custom settings, if any, of the active template, any loaded global templates, and the Normal template.

For an example, see MenuText$().

See Also

CountMacros(), CountMenuItems(), MenuText$()


CountMergeFields()

Syntax

CountMergeFields()

Remarks

Returns the number of fields in the header record of the data source or in the header source attached to the active main document. CountMergeFields() returns 0 (zero) if the active document is not a main document, data source, or header source.

Example

This example inserts a list of merge field names in the active document:

For n = 1 To CountMergeFields()
    Insert MergeFieldName$(n)
    InsertPara
Next

See Also

InsertMergeField, MergeFieldName$()


CountStyles()

Syntax

CountStyles([Context] [, All])

Remarks

Returns the number of styles defined for the specified context.

Argument | Explanation
Context | Specifies the location of styles to count: 0 (zero) or omitted Active document 1 Active template
All | Specifies whether to include built-in styles: 0 (zero) or omitted Built-in styles are excluded. 1 Built-in styles are included. Note that Word contains 75 built-in styles, and that two of those built-in styles are defined by default: Default Paragraph Font and Normal.

Examples

This example returns the number of all built-in styles plus the number of user-created styles used in the template attached to the active document:

n = CountStyles(1, 1)

The following example merges styles into the active document from the attached template. Then, the macro finds the number of styles defined just for the document, if any, by subtracting the number of styles defined for the template from the number of styles defined for the document.

FormatStyle .Source = 1, .Merge
n = CountStyles(0, 0) - CountStyles(1, 0)

See Also

StyleName$()


CountToolbarButtons()

Syntax

CountToolbarButtons(Toolbar$ [, Context])

Remarks

Returns the number of toolbar buttons on the specified toolbar. Note that spaces and list boxes are counted as "buttons."

Argument | Explanation
Toolbar$ | The name of the toolbar as it appears in the Toolbars dialog box (View menu)
Context | Specifies which buttons to count: 0 (zero) The buttons that are available when a document based on the Normal template is active 1 or omitted The buttons that are currently available Note that the buttons that are available depend on the custom settings, if any, of the active template, any loaded global templates, and the Normal template.

For an example, see CountToolbars().

See Also

CountToolbars(), ToolbarButtonMacro$(), ToolbarName$()


CountToolbars()

Syntax

CountToolbars([Context])

Remarks

Returns the number of toolbars listed in the Toolbars dialog box (View menu). Note that not all toolbars are listed in all circumstances. For example, the macro toolbar only appears in the Toolbars dialog box when at least one macro-editing window is open.

Argument | Explanation
Context | Specifies which toolbars to count: 0 (zero) The toolbars that are available when a document based on the Normal template is active 1 or omitted The toolbars that are currently available Note that the toolbars that are available depend on the custom settings, if any, of the active template, any loaded global templates, and the Normal template.

Example

This example creates a new document and then inserts a list of toolbar names followed by the number of buttons on each toolbar.

FileNewDefault
For i = 1 To CountToolbars(0)
    name$ = ToolbarName$(i)
    numbuttons = CountToolbarButtons(name$)
    Insert name$ + "," + Str$(numbuttons) + Chr$(13)
Next i

See Also

CountToolbarButtons(), ToolbarButtonMacro$(), ToolbarName$()


CountToolsGrammarStatistics()

Syntax

CountToolsGrammarStatistics()

Remarks

Returns the number of statistics that are stored when you check grammar with the ToolsGrammar statement. You can use this number to define the size of a two-dimensional array that you fill using the ToolsGrammarStatisticsArray statement.

For an example, see ToolsGrammarStatisticsArray.

See Also

ToolsGrammar, ToolsGrammarStatisticsArray, ToolsOptionsGrammar


CountWindows()

Syntax

CountWindows()

Remarks

Returns the number of open document and macro-editing windows, which is also the number of windows listed on the Window menu.

Example

This macro arranges windows side by side instead of stacking them as the Arrange All command (Window menu) does:

Sub MAIN
yours$ = WindowName$()                    'Note which window is active
If DocMaximize() Then DocRestore            'Can't resize if maximized
fullwidth = Val(AppInfo$(6))                'Get workspace width
fulldepth = Val(AppInfo$(7))                'Get workspace depth
width = fullwidth / CountWindows()
For wnd = 1 To CountWindows()            'Move each window, resize it
    x = width *(wnd - 1)
    If DocMinimize() Then DocRestore        'Can't resize if minimized
    DocMove x, 0
    DocSize width, fulldepth - 1
    NextWindow
Next wnd
Activate yours$                            'Reactivate original window
End Sub

See Also

WindowName$(), Window Number


CreateSubdocument

Syntax

CreateSubdocument

Remarks

Converts the selected outline headings into subdocuments. If the active document is not in master document or outline view, or if the selection spans a subdocument boundary, an error occurs. An error is also generated if the first paragraph selected is not a heading.

See Also

InsertSubdocument, MergeSubdocument, OpenSubdocument, RemoveSubdocument, SplitSubdocument, ViewMasterDocument


Date$()

Syntax

Date$([SerialNumber])

Remarks

Returns a date corresponding to SerialNumber, a decimal representation of the date, time, or both. If SerialNumber is omitted, Date$() returns today's date. For information about serial numbers, see DateSerial().

The date format is determined by the "DateFormat=" line in the [Microsoft Word] section of WINWORD6.INI (Windows 3.x), Word Settings (6) (Macintosh), or the registry (Windows 95 and Windows NT). (In Windows 3.x, if there is no "DateFormat=" line, Date$() uses the "sShortDate" setting in the [intl] section of WIN.INI.) You can use SetPrivateProfileString to change the current date format.

Example

This Windows example displays the current date in a message box, in the form MMMM d, yyyy (which produces a date string such as "January 1, 1994"). The first instruction saves the original date format so that it may be restored in the last instruction. On the Macintosh, substitute "Word Settings (6)" for "WINWORD6.INI."

OriginalFormat$ = GetPrivateProfileString$("Microsoft Word", \
    "DateFormat", "WINWORD6.INI")
SetPrivateProfileString "Microsoft Word", "DateFormat", \
    "MMMM d, yyyy", "WINWORD6.INI"
MsgBox "Today is " + Date$() + "."
SetPrivateProfileString "Microsoft Word", "DateFormat", \
    OriginalFormat$, "WINWORD6.INI"

See Also

DateSerial(), DateValue(), Day(), GetPrivateProfileString$(), Month(), Now(), SetPrivateProfileString, Time$(), Today(), Year()


DateSerial()

Syntax

DateSerial(Year, Month, Day)

Remarks

Returns the serial number of the specified date. The serial number corresponds to the number of days between December 30, 1899, and the specified date, up to December 31, 4095. For example, the serial number 1 corresponds to December 31, 1899. DateSerial() generates an error if the specified date is beyond the allowable range.

Argument | Explanation
Year | A number between 0 (zero) and 4095, inclusive, or a numeric expression. To specify a year in the range 1900 to 1999, you can give the last two digits of the year; to specify the year 1899 or a year after 1999, give all four digits of the year.
Month | A number between 1 and 12, inclusive, or a numeric expression representing the month of the year.
Day | A number between 1 and 31, inclusive, or a numeric expression representing the day of the month.

Example

This example prompts the user to enter a date and then displays a message box to indicate the day of the week corresponding to that date:

Dim days$(7)
days$(1) = "Sunday" : days$(2) = "Monday" days$(3) = "Tuesday"
days$(4) = "Wednesday" days$(5) = "Thursday"
days$(6) = "Friday" days$(7) = "Saturday"
datestring$ = Inputbox$("Please enter the date for which " + \
        "you want to determine the weekday (mm/dd/yy):")
monthnum = Val(Left$(datestring$, 2))
daynum = Val(Mid$(datestring$, 4, 2))
yearnum = Val(Right$(datestring$, 2))
dayofweek = DateSerial(yearnum, monthnum, daynum)
MsgBox "The day of the week is " + days$(Weekday(dayofweek)) + "."

See Also

Date$(), DateValue(), Day(), Month(), Now(), TimeSerial(), Today(), Year()


DateValue()

Syntax

DateValue(DateText$)

Remarks

Returns the serial number of the date represented by DateText$. Use DateValue() to convert a date represented by text to a serial number. A serial number is a decimal representation of the date, time, or both. For information about serial numbers, see DateSerial().

Argument | Explanation
DateText$ | A string representing a date in a Word date format. For example, the following are each valid representations of July 8, 1991: 7/8/91 July 8, 1991 8 July 1991 If DateText$ includes only numbers, DateValue() recognizes the order of the components of the date as month, day, year.

DateText$ must represent a date from December 30, 1899, to December 31, 4095. DateValue() generates an error if DateText$ is out of this range. If the year portion of DateText$ is omitted, DateValue() uses the current year from the computer's built-in calendar. DateValue() ignores time information in DateText$.

Example

This example prompts the user to enter an end date, and then displays the number of days between today and that date:

enddate$ = InputBox$("Please enter an end date:")
serialenddate = DateValue(enddate$)
numdays = serialenddate - Today()
numdays = Abs(numdays)
MsgBox "The number of days between now and " + enddate$ + \
    " is" + Str$(numdays) + "."

See Also

Date$(), DateSerial(), Now(), TimeValue(), Today()


Day()

Syntax

Day(SerialNumber)

Remarks

Returns an integer between 1 and 31, inclusive, corresponding to the day component of SerialNumber, a decimal representation of the date, time, or both. For information about serial numbers, see DateSerial().

Argument | Explanation
SerialNumber | The serial number used by Word for date and time calculations. SerialNumber can represent a date or time (or both) from December 30, 1899, through December 31, 4095, where December 30, 1899, is 0 (zero).

Example

This example uses the Day() function to determine the day of the month, and then displays the result in a message box with the appropriate suffix (for example, "3rd"):

daynumber = Day(Now())
Select Case daynumber
    Case 1, 21, 31
        daysuffix$ = "st"
    Case 2, 22
        daysuffix$ = "nd"
    Case 3, 23
        daysuffix$ = "rd"
    Case Else
        daysuffix$ = "th"
End Select
MsgBox "Today is the" + Str$(daynumber) + \
        daysuffix$ + " day of the month."

See Also

DateSerial(), Hour(), Minute(), Month(), Now(), Second(), Today(), Weekday(), Year()


Days360()

Syntax

Days360(StartDate[$], EndDate[$])

Remarks

Returns the number of days between two dates based on a 360-day year (twelve 30-day months). Use this function to help compute payments if your accounting system is based on twelve 30-day months. The arguments StartDate and EndDate are the two dates between which you want to know the number of days. If StartDate occurs after EndDate, Days360() returns a negative number.

Argument | Explanation
StartDate[$] | A text string or a serial number that represents the initial date. For information about available date formats in Word, see DateValue(). For information about serial numbers, see DateSerial().
EndDate[$] | A text string or a serial number that represents the end date.

Example

This example uses Days360() to determine the number of days between January 1, 1992, and February 1, 1993, assuming a 360-day year:

numdays = Days360("1/1/92","2/1/93")

See Also

DateSerial(), DateValue(), Day()


DDEExecute

Syntax

DDEExecute ChanNum, Command$

Remarks

Sends a command or series of commands to an application through a dynamic-data exchange (DDE) channel.

Argument | Explanation
ChanNum | The channel number of the DDE conversation as returned by DDEInitiate(). If ChanNum doesn't correspond to an open channel, an error occurs.
Command$ | A command or series of commands recognized by the server application. In Windows, you can also use the format described under SendKeys to send specific key sequences. If the server application can't perform the specified command, an error occurs.

In Microsoft Excel and many other applications that support DDE, Command$ should be one or more statements or functions in the application's macro language. For example, in Microsoft Excel the XLM macro instruction to create a new worksheet is NEW(1). To send the same command through a DDE channel, you use the following instruction:

DDEExecute channel, "[NEW(1)]"

Note that some applications, including Microsoft Excel, require that each command received through a DDE channel be enclosed in brackets.

You can use a single DDEExecute instruction to send more than one command. For example, the following instruction tells Microsoft Excel to open and then close a worksheet:

DDEExecute channel, "[NEW(1)][FILE.CLOSE(0)]"

Note that there is no space between the bracketed commands; a space character between the commands would cause an error. The preceding instruction is equivalent to the following two instructions:

DDEExecute channel, "[NEW(1)]"
DDEExecute channel, "[FILE.CLOSE(0)]"

Many commands require arguments in the form of strings enclosed in quotation marks. Because quotation marks indicate the beginning and end of a string in WordBasic, you must use Chr$(34) to include a quotation mark in a command string. For example, the following instruction tells Microsoft Excel to open SALES.XLS:

DDEExecute channel, "[OPEN(" + Chr$(34) + "SALES.XLS" + Chr$(34) + ")]"

For more information on sending commands to Microsoft Excel and other applications, see Chapter 8, "Communicating with Other Applications" in Part 1, "Learning WordBasic."

Example

This example starts Microsoft Excel if it is not running and then opens a channel to Microsoft Excel and the System topic (for information on the System topic, see DDERequest$( )). The example then sends commands to open SALES.XLS (Windows) or BLUE SKY SALES (Macintosh) and go to cell R4C2. Unlike a document, which may or may not be open, the System topic is always available when Microsoft Excel is running.

Here is the Windows version of the example:

If AppIsRunning("Microsoft Excel") = 0 Then Shell "C:\EXCEL\EXCEL.EXE"
channel = DDEInitiate("Excel", "System")
q$ = Chr$(34)
cmd1$ = "[OPEN(" + q$ + "C:\EXCEL\EXAMPLES\SALES.XLS" + q$ + ")]"
cmd2$ = "[SELECT(" + q$ + " R4C2" + q$ + ", " + q$ + " R4C2" + q$ + ")]"
bothcmds$ = cmd1$ + cmd2$
DDEExecute channel, bothcmds$

And here is the Macintosh version:

If AppIsRunning(MacID$("XCEL")) = 0 Then Shell MacID$("XCEL")
channel = DDEInitiate("Excel", "System")
q$ = Chr$(34)
cmd1$ = "[OPEN(" + q$ + "HD1:EXCEL:EXAMPLES:BLUE SKY SALES" + q$ + ")]"
cmd2$ = "[SELECT(" + q$ + " R4C2" + q$ + ", " + q$ + " R4C2" + q$ + ")]"
bothcmds$ = cmd1$ + cmd2$
DDEExecute channel, bothcmds$

See Also

DDEInitiate(), DDEPoke, DDERequest$(), DDETerminate, DDETerminateAll


DDEInitiate()

Syntax

DDEInitiate(Application$, Topic$)

Remarks

Initiates a dynamic-data exchange (DDE) conversation with an application and opens a DDE channel through which the conversation takes place. If DDEInitiate() is able to open a channel, it returns the number of the open channel, which is an integer greater than 0 (zero). (The first DDE channel Word opens during a session is channel 1, the second is channel 2, and so on.) All subsequent DDE instructions during the DDE conversation use this number to specify the channel. DDEInitiate() returns 0 (zero) if it fails to open a channel.

Note

In Word version 6.0 for Windows NT and Word version 7.0, you cannot depend on a program started with Shell to be finished loading before the instructions following the Shell statement in your macro are run. A DDEInitiate instruction that tries to communicate with an application that has not finished loading will generate errors. To avoid this problem, you can use a For...Next loop to delay the DDEInitiate instruction until the other application is loaded. For example:

If AppIsRunning("Microsoft Access") = 0 Then
    Shell "MSACCESS.EXE", 0
    For i = 1 to 2000
        x = i
    Next i
End IF
chan = DDEInitiate("MSAccess", "System")

Argument | Explanation
Application$ | The name used to specify an application that supports DDE as a DDE server. In Windows, this is usually the name of the application's .EXE file without the .EXE filename extension. If the application is not running, DDEInitiate() cannot open a channel and returns an error.
Topic$ | The name of a topic recognized by Application$. An open document is a typical topic. (If Topic$ is a document name, the document must be open.) If Application$ doesn't recognize Topic$, DDEInitiate() generates an error. Many applications that support DDE recognize a topic named System, which is always available and can be used to find out which other topics are available. For more information on the System topic, see DDERequest$().

The maximum number of channels that can be open simultaneously is determined by Microsoft Windows and your system's memory and resources. If you aren't using an open channel, you should conserve resources by closing the channel using DDETerminate or DDETerminateAll.

Examples

This example opens a channel to Microsoft Excel and the file SALES.XLS (Windows) or BLUE SKY SALES (Macintosh). The variable channel is assigned the channel number that is returned. If Microsoft Excel is not running or the file is not open, the function returns 0 (zero) and generates an error.

Here is the Windows version of the example:

channel = DDEInitiate("Excel", "C:\EXCEL\EXAMPLES\SALES.XLS")

And here is the Macintosh version:

channel = DDEInitiate("Excel", "HD1:EXCEL:EXAMPLES:BLUE SKY SALES")

The following example first ensures that Microsoft Excel is running, and then opens a channel to Microsoft Excel and the System topic and uses DDERequest$() to get the Topics item. The Topics item, a standard item in the System topic that is always available, is a list of available topics, including the names of open documents.

Here is the Windows version of the example:

If AppIsRunning("Microsoft Excel") = 0 Then
Shell "C:\EXCEL\EXCEL.EXE"
AppActivate "Microsoft Word", 1
End If
channel = DDEInitiate("Excel", "System")
topics$ = DDERequest$(channel, "Topics")
If InStr(topics$, "Sheet1") <> 0 Then
    MsgBox "Sheet1 is an available topic."
End If
DDETerminate channel

And here is the Macintosh version:

If AppIsRunning(MacID$("XCEL")) = 0 Then
Shell MacID$("XCEL")
AppActivate MacID$("MSWD"), 1
End If
channel = DDEInitiate("Excel", "System")
topics$ = DDERequest$(channel, "Topics")
If InStr(topics$, "Sheet1") <> 0 Then
    MsgBox "Sheet1 is an available topic."
End If
DDETerminate channel

See Also

DDEExecute, DDEPoke, DDERequest$(), DDETerminate, DDETerminateAll


DDEPoke

Syntax

DDEPoke ChanNum, Item$, Data$

Remarks

Uses an open dynamic-data exchange (DDE) channel to send data to an application. When you start a DDE conversation using DDEInitiate(), you open
a channel to a specific topic recognized by the server application. In Microsoft Excel, for example, each open document is a separate topic. When you send information to a topic in the server application, you must specify the item in that topic you want to send information to. In Microsoft Excel, for example, cells are valid items and they are referred to using either the "R1C1" format or named references.

DDEPoke sends data as a text string; you cannot send text in any other format, nor can you send graphics.

Argument | Explanation
ChanNum | The channel number of the DDE conversation as returned by DDEInitiate(). If ChanNum doesn't correspond to an open channel, an error occurs.
Item$ | An item within a DDE topic. If the server application doesn't recognize Item$, an error occurs.
Data$ | The string containing the data to send to the server application.

Examples

This example sends the value of the variable Total$ to the second row and third column of the Sheet1 worksheet in Microsoft Excel. On the Macintosh, the application name used in the DDEInitiate() instruction should be MacID$("XCEL") rather than "Excel".

channel = DDEInitiate ("Excel", "Sheet1")
DDEPoke channel, "R2C3", Total$

The following example sends the string "Total: $1,434" to the cell named "QuarterTotal" in the Sheet1 worksheet. On the Macintosh, the application name used in the DDEInitiate() instruction should be MacID$("XCEL") rather than "Excel".

channel = DDEInitiate("Excel", "Sheet1")
DDEPoke channel, "QuarterTotal", "Total: $1,434"

See Also

DDEExecute, DDEInitiate(), DDERequest$(), DDETerminate, DDETerminateAll


DDERequest$()

Syntax

DDERequest$(ChanNum, Item$)

Remarks

Uses an open dynamic-data exchange (DDE) channel to request an item of information from an application. When you start a DDE conversation using DDEInitiate(), you open a channel to a specific topic recognized by the server application. In Microsoft Excel, for example, each open document is a separate topic. When you request information from the topic in the server application, you must specify the item in that topic whose contents you are requesting. In Microsoft Excel, for example, cells are valid items and they are referred to using either the "R1C1" format or named references.

DDERequest$() returns data as a text string only; if the function is unsuccessful, it returns an empty string (""). Text in any other format cannot be transferred, nor can graphics.

Argument | Explanation
ChanNum | The channel number of the DDE conversation as returned by DDEInitiate(). If ChanNum doesn't correspond to an open channel, an error occurs.
Item$ | The item within a DDE topic recognized by the server application. DDERequest$() returns the entire contents of the specified item. If the server application doesn't recognize Item$, an error occurs.

Microsoft Excel and other applications that support DDE recognize a topic named System. Three standard items in the System topic are described in the following table. Note that you can get a list of the other items in the System topic using the item SysItems.

Item in System topic | Effect
SysItems | Returns a list of all items in the System topic
Topics | Returns a list of available topics
Formats | Returns a list of all the Clipboard formats supported by Word

For an example that uses the System topic, see DDETerminate().

Example

This Windows example opens a channel to Microsoft Excel and SALES.XLS and then requests the contents of cell R4C2:

channel = DDEInitiate("Excel", "C:\EXCEL\EXAMPLES\SALES.XLS")
a$ = DDERequest$(channel, "R4C2")
MsgBox a$

Here is the same example for the Macintosh:

channel = DDEInitiate("Excel", "HD1:EXCEL:EXAMPLES:BLUE SKY SALES")
a$ = DDERequest$(channel, "R4C2")
MsgBox a$

See Also

DDEExecute, DDEInitiate(), DDEPoke, DDETerminate, DDETerminateAll


DDETerminate

Syntax

DDETerminate ChanNum

Remarks

Closes the specified dynamic-data exchange (DDE) channel. To free system resources, you should close channels you aren't using.

Argument | Explanation
ChanNum | The channel number of the DDE conversation as returned by DDEInitiate(). If ChanNum isn't an open channel number, an error occurs.

Example

This example opens a DDE channel to request a list of topics from Microsoft Excel. The instructions insert the requested list into the active Word document and then close the channel. On the Macintosh, the application name used in the DDEInitiate() instruction should be MacID$("XCEL") rather than "Excel".

channel = DDEInitiate("Excel", "System")
a$ = DDERequest$(channel, "Topics")
Insert a$
DDETerminate channel

See Also

DDEExecute, DDEInitiate(), DDEPoke, DDERequest$(), DDETerminateAll


DDETerminateAll

Syntax

DDETerminateAll

Remarks

Closes all dynamic-data exchange (DDE) channels opened by Word; DDETerminateAll does not close channels opened to Word by client applications. Using this statement is the same as using a DDETerminate statement for each open channel. DDETerminateAll does not cause an error if no DDE channels are open.

If you interrupt a macro that opens a DDE channel, you may inadvertently leave
a channel open. Open channels are not closed automatically when a macro ends, and each open channel uses system resources. For this reason, it's a good idea to use DDETerminateAll while debugging a macro that opens one or more DDE channels.

See Also

DDEExecute, DDEInitiate(), DDEPoke, DDERequest$(), DDETerminate


Declare

Syntax

Declare Sub SubName Lib LibName$ [(ArgumentList)] [Alias Routine$]

Declare Function FunctionName[$] Lib LibName$ [(ArgumentList)] [Alias Routine$] As Type

Remarks

In Windows, makes available a routine stored in a Windows dynamic-link library (DLL), a Word add-in library (WLL), or the Windows operating system for use as a function or subroutine in a WordBasic macro. On the Macintosh, makes available a routine stored in a Word add-in library (WLL) only. The declaration specifies the name of the routine, the library file in which it is stored, and any arguments the routine takes. Declare instructions are usually placed at the start of a macro, before the main subroutine; they cannot be placed inside a subroutine or function.

Caution

u When experimenting with external routines, save your work often. An invalid argument passed to a routine could result in unpredictable behavior in Word or other applications.

u You cannot declare an external routine in a 16-bit library from a 32-bit application, such as Word for Windows 95 or Word version 6.0 for
Windows NT. You must update macros that declare routines in 16-bit libraries to identify the 32-bit versions of those libraries.

u The names and locations of many Windows 3.x operating system routines (often referred to as API calls) changed in Windows 95 and Windows NT. You must update macros that declare Windows 3.x API calls to declare the correct routines in Windows 95 or Windows NT. Windows 3.x API function libraries are documented in the Microsoft Windows 3.1 Software Development Kit. Windows 95 and Windows NT function libraries are documented in the Microsoft Win32 Software Development Kit.

Argument | Explanation
Sub or Function | Use Function if the function you are declaring returns a value; use Sub if it does not.
SubName or FunctionName[$] | The name used in the macro to call the routine. This name does not have to be the actual name of the routine in the library. You can define the actual name using the Alias part of the statement. If FunctionName returns a string, it should include a dollar sign ($) like other string functions in WordBasic. Note that routine names are case sensitive in Windows 95 and Windows NT; if this name is the actual name of the routine in the library, it should match the documented case.
LibName$ | The filename of the library containing the routine, in quotation marks. In Windows, use the entire filename, including the extension, to prevent ambiguity. In Windows, Word looks for the file in the current folder, the Windows folder, the Windows System folder, the Word program folder, and in the folders listed in the PATH environment variable. If the file is not stored in any of these folders, or is not a loaded add-in libarary (WLL), include the complete path with the filename. On the Macintosh, Word looks for the file in the current folder, the System folder, the Word program folder, the Word Dictionaries folder, and the Microsoft folder. If the file is not stored in any of these folders, or is not a loaded WLL, include the complete path with the filename.
ArgumentList | A list of variables representing arguments that are passed to the routine. See the following table for the syntax used within ArgumentList.

Argument | Explanation
Alias Routine$ | The actual name of the routine in the library, in quotation marks. It is required only if the name specified after Sub or Function is not the actual name of the routine. Note that routine names are case sensitive in Windows 95 and Windows NT.
As Type | Declares the data type of the value returned by a function. The type is one of the following: As Integer for an integer or logical (BOOL) return type; As String for a string (LPSTR) return type; As Long for a long return type; As Double for a double return type.

The ArgumentList argument has the following syntax:

(Variable[$] [As Type] [, Variable[$] [As Type]] [, ¼])

The following table describes the parts of ArgumentList.

Part | Explanation
Variable[$] | A WordBasic variable name. For string variables, adding a dollar sign ($) to the variable name is the same as specifying As String — for example, fileName$ is the same as fileName As String. If there is no As Type, and the variable name does not end in a dollar sign, the variable defaults to a WordBasic numeric variable (double-precision floating-point number).
As Type | Declares the data type of the argument required by the routine: As Integer for integer or logical (BOOL) arguments; As String (or simply $ at the end of the variable name) for string (LPSTR) arguments; As Long for long arguments; As Double for double arguments.

Example

This Windows example uses the selection as a search keyword in Help. If there is one exact match, the macro displays the topic. If there is more than one match, the macro displays the Search dialog box (Windows 3.x Help) or the Help Topics dialog box (Windows 95 Help) with the keyword selected. If there is no match, the macro displays the Search or Help Topics dialog box, with the keyword list scrolled to the keyword closest in spelling to the selected word.

Declare Function WinHelp Lib "USER.EXE"(hWnd As Integer, lpHelpFile \
    As String, wCmd As Integer, dwData As String) As Integer
Declare Function GetActiveWindow Lib "USER.EXE"() As Integer
Sub MAIN
    hWnd = GetActiveWindow
    helpFile$ = "C:\WINWORD\WINWORD.HLP"
    wCmd = 261            'The decimal value for HELP_PARTIALKEY
    keyWord$ = Selection$()
    success = WinHelp(hWnd, helpFile$, wCmd, keyWord$)
    If success = 0 Then MsgBox "Could not start Windows Help"
End Sub

See Also

Dim


DefaultDir$()

Syntax

DefaultDir$(Type)

Remarks

Returns the path currently set for the default folder specified by Type, a number that corresponds to a default folder, as shown in the following table.

Type | Explanation
0 | DOC-PATH
1 | PICTURE-PATH
2 | USER-DOT-PATH
3 | WORKGROUP-DOT-PATH
4 | INI-PATH
5 | AUTOSAVE-PATH
6 | TOOLS-PATH
7 | CBT-PATH
8 | STARTUP-PATH
9 | The program-file path (PROGRAMDIR)
10 | The graphics-filter path (fixed; cannot be changed)
11 | The text-converter path (fixed; cannot be changed)
12 | The proofing-tool path (fixed; cannot be changed)
13 | The temporary-file path
14 | The current folder
15 | The style-gallery–template path (can be changed using ChDefaultDir)
16 | The Trash folder (Macintosh only)
17 | The Microsoft folder (Macintosh only)

Example

This example sets TOOLS-PATH to C:\TOOLS if it is not set already. On the Macintosh, substitute a folder name such as HD:TOOLS.

If DefaultDir$(6) = "" Then
    ChDefaultDir "C:\TOOLS", 6
End If

See Also

ChDefaultDir, ChDir


DeleteAddIn

Syntax

DeleteAddIn AddIn

DeleteAddIn AddIn$

Remarks

Removes a global template or Word add-in library (WLL) from the list of global templates and add-ins in the Templates And Add-ins dialog box (Templates command, File menu).

Argument | Explanation
AddIn | A number corresponding to the global template or add-in's position in the list, where 1 is the first template or add-in, 2 is the second, and so on.
AddIn$ | The path (if necessary) and filename of the global template or add-in.

See Also

AddAddIn, AddInState(), ClearAddIns, CountAddIns(), GetAddInId(), GetAddInName$()


DeleteBackWord

Syntax

DeleteBackWord

Remarks

Deletes the word immediately preceding the insertion point or the selection, but does not place it on the Clipboard.

If there is a selection, DeleteBackWord behaves as if there were an insertion point; the statement does not delete the selection but deletes the word immediately preceding it. If the insertion point is in the middle of a word, DeleteBackWord deletes the characters between the insertion point and the start of the word.

Note that if there is a space character between the word and the insertion point, DeleteBackWord deletes the space character as well as the word. Also, if the insertion point follows a punctuation mark, such as a comma or period, DeleteBackWord deletes the punctuation mark only.

See Also

DeleteWord, EditClear, EditCut, WordLeft


DeleteButton

Syntax

DeleteButton Toolbar$, Position [, Context]

Remarks

Removes a button, list box, or space from a toolbar.

Argument | Explanation
Toolbar$ | The name of the toolbar as listed in the Toolbars dialog box (View menu).
Position | A number corresponding to the position of the item to remove, where 1 is the first position, 2 is the second, and so on. Note that a list box or space counts as one position.
Context | Determines where the change to the toolbar is stored: 0 (zero) or omitted Normal template 1 Active template

For an example, see AddButton.

See Also

AddButton, ChooseButtonImage, CopyButtonImage, EditButtonImage, MoveButton, PasteButtonImage, ResetButtonImage


DeleteDocumentProperty

Syntax

DeleteDocumentProperty Name$

Remarks

Removes the Name$ custom property from the list of custom properties on the Custom tab in the Properties dialog box (Properties command, File menu). If the property specified by Name$ is not a custom property, an error occurs. Use the DocumentPropertyExists() function to verify that the Name$ property exists.

For a list of the built-in properties available in Word, see DocumentPropertyName$(). In Word version 6.0, DeleteDocumentProperty is unavailable and generates an error.

See Also

DocumentPropertyExists(), GetDocumentProperty(), IsCustomDocumentProperty(), SetDocumentProperty


DeleteWord

Syntax

DeleteWord

Remarks

Deletes the word immediately following the insertion point or the first word or part of a word included in the selection, but does not place it on the Clipboard. If the insertion point is in the middle of a word, DeleteWord deletes the characters following the insertion point to the end of the word.

Note that if there is a space character between the insertion point and the word, DeleteWord deletes the space character as well as the word. Also, if the insertion point precedes a punctuation mark, such as a comma or period, DeleteWord deletes the punctuation mark only.

See Also

DeleteBackWord, EditClear, EditCut, WordRight


DemoteList

Syntax

DemoteList

Remarks

Demotes the selected paragraphs by one level in a multilevel list. If the selected paragraphs are formatted as a bulleted list or as a numbered list that isn't

multilevel, DemoteList increases the indent. If the selected paragraphs are not already formatted as a numbered or bulleted list, an error occurs.

See Also

FormatBulletsAndNumbering, PromoteList


DemoteToBodyText

Syntax

DemoteToBodyText

Remarks

Demotes the selected headings to body text by applying the Normal style. DemoteToBodyText has no effect if the selected paragraphs are already formatted with Normal style.

See Also

OutlineDemote, OutlineMoveDown, OutlinePromote


Dialog, Dialog()

Syntax

Dialog DialogRecord [, DefaultButton] [, TimeOut]

Dialog(DialogRecord [, DefaultButton] [, TimeOut])

Remarks

The Dialog statement and Dialog() function are both used to display the dialog box specified by DialogRecord in a preceding Dim instruction. The dialog box displayed can be a Word dialog box or one that you define within a macro.

If you use the Dialog statement to display a dialog box and the user chooses the Cancel button, Word generates an error that an On Error instruction can trap. If you don't want or need to trap the error, you can use the Dialog() function to display the dialog box. In addition to displaying the dialog box, the Dialog() function returns a value corresponding to the button chosen. The return values are the same as those used to specify DefaultButton.

When you display a dynamic dialog box, use DisableInput to make the ESC key cancel the dialog box properly. For more information, see DisableInput.

Argument

Explanation

DialogRecord

The name given to the dialog record in the Dim instruction.

DefaultButton

The default command button:

– 2 No default command button

–1 The OK button

0 (zero) The Cancel button

> 0 (zero) A command button, where 1 is the first PushButton instruction in the definition, 2 is the second, and so on

The default command button is chosen if the user presses ENTER when a dialog box control other than a command button has the focus. Unless you specify otherwise, the OK button is the default command button.

DefaultButton is used only with custom dialog boxes. For DefaultButton to have any effect, the instruction for the specified button must be preceded in the dialog box definition by an instruction for a nonbutton dialog box control that can receive the focus, such as a list box or check box. (Note that because a text control cannot receive the focus, it does not meet this criterion.) Otherwise, the first button in the dialog box definition is the default command button. If the dialog box definition has a dialog function associated with it, DefaultButton may be overridden by a DlgFocus$ statement. For information on creating dialog functions, see Chapter 5, "Working with Custom Dialog Boxes," in Part 1, "Learning WordBasic."

TimeOut

The amount of time, in milliseconds, the dialog box is displayed. If 0 (zero) or omitted, the dialog box is displayed until the user closes it.

Note

A macro can use any number of custom dialog boxes, but WordBasic supports only one custom dialog record at a time (you can define any number of dialog records for Word dialog boxes). This means that you can't define a series of custom dialog records, intending to use them later in the macro. Each custom dialog record overwrites the previous one. If your macro uses more than one custom dialog box and you need to store the values contained in a dialog record that will be overwritten, save the values in regular variables. For more information about using custom dialog records, see Chapter 5, "Working with Custom Dialog Boxes," in Part 1, "Learning WordBasic."

Examples

This example uses the Dialog() function to display the Font dialog box (Format menu) so the user can set different character-formatting options. The instruction x = Dialog(dlg) returns a value corresponding to the button the user chooses and removes the need for error handling. If the user chooses the OK button, the last instruction in the example, If x = -1 Then FormatFont dlg, implements the options that the user selected in the dialog box; if the user chooses the Cancel button, the options chosen are ignored. Without this statement, nothing happens, even though the dialog box has been displayed and the user has chosen the OK button.

Dim dlg As FormatFont
GetCurValues dlg
x = Dialog(dlg)
If x = -1 Then FormatFont dlg

The following example is the same as the previous one, except that it uses the Dialog statement to display the dialog box and includes error handling. If the user chooses the Cancel button, the resulting error is trapped and a message is displayed.

Dim dlg As FormatFont
GetCurValues dlg
On Error Goto trap
Dialog dlg
FormatFont dlg
Goto skiptrap
trap:
MsgBox "Dialog box closed -- no changes"
skiptrap:

The following example displays a simple custom dialog box with text box and command button controls. Since the text box control is the first control defined in the dialog box definition, it has the focus when the dialog box is displayed. The x = Dialog(dlg, 1) instruction makes the Find button the default command button (instead of the OK button).

Begin Dialog UserDialog 346, 90, "Social Security Macro"
    TextBox 9, 22, 192, 18, .secnum
    Text 9, 6, 183, 13, "Social Security Number:"
    OKButton 249, 4, 88, 21
    CancelButton 249, 28, 88, 21
    PushButton 249, 52, 88, 21, "Find..."
End Dialog
Dim dlg As UserDialog
x = Dialog(dlg, 1)

See Also

Begin Dialog ¼ End Dialog, Dim, GetCurValues


DialogEditor

Syntax

DialogEditor

Remarks

Starts the Dialog Editor if it is not already running and makes it the active application. If the Dialog Editor is already running, the DialogEditor statement makes it the active application. If the Dialog Editor is shrunk to an icon, the DialogEditor statement restores and activates it. For more information about the Dialog Editor, see Chapter 5, "Working with Custom Dialog Boxes," in Part 1, "Learning WordBasic."


Dim

Syntax

Dim [Shared] Var1 [(Size1 [, Size2] [, ...])] [, Var2 [(Size1 [, Size2] [, ...])]] [, ...]

Dim DialogRecord As DialogName

Dim DialogRecord As UserDialog

Remarks

Declares variables to be shared by more than one subroutine, defines array variables, or defines a dialog record. Dim statements that declare shared variables must be placed outside the macro's subroutines — usually before the main subroutine.

Syntax | Purpose
Dim Var(Size1 [, Size2] [, ...]) | Defines an array variable. For one-dimensional arrays, Size1 is the subscript of the last element in the array. For multidimensional arrays, each Size argument is the subscript of the last element for the dimension of the array to be defined. In WordBasic, the first element in an array is always numbered 0 (zero), so to define a one-dimensional array of seven elements — for example, the days of the week — Size1 would be 6. To define a two-dimensional array of 12 rows by 31 columns — for example, the days of the year organized by month — Size1 would be 11 and Size2 would be 30.
Dim Shared Var[(Size1 [, Size2] [, ...])] | Declares a string, numeric, or array variable to be shared by more than one subroutine. The Dim statement must be placed outside any subroutine. Usually, shared variable declarations are placed at the start of a macro, before the main subroutine.

Syntax | Purpose
Dim DialogRecord As DialogName | Defines a dialog record variable for a Word dialog box. DialogName can be any WordBasic statement that corresponds to a Word command or dialog box. For example, FormatFont or FileOpen are valid as DialogName.
Dim DialogRecord As UserDialog | Defines a dialog record for a user-defined dialog box.

Examples

This example declares three variables to be shared by multiple subroutines and would typically be placed before the Sub MAIN instruction.

Dim Shared numDocs, docName$, savePath$

The following example stores the names of the days of the week in the array Days$ and displays the third element of the array, "Tuesday," in the status bar:

Dim Days$(6)
Days$(0) = "Sunday" : Days$(1) = "Monday" : Days$(2) = "Tuesday"
Days$(3) = "Wednesday" : Days$(4) = "Thursday"
Days$(5) = "Friday" : Days$(6) = "Saturday"
Print Days$(2)

The following example stores the names of the days of the week and their Spanish translations in the two-dimensional array Days$. The last instruction displays "Martes," the element in the third row of the second column of the array, in the status bar:

Dim Days$(6, 1)
Days$(0, 0) = "Sunday" : Days$(0, 1) = "Domingo" : Days$(1, 0) = "Monday"
Days$(1, 1) = "Lunes" : Days$(2, 0) = "Tuesday" : Days$(2, 1) = "Martes"
Days$(3, 0) = "Wednesday" : Days$(3, 1) = "Miércoles" : Days$(4, 0) = "Thursday"
Days$(4, 1) = "Jueves" : Days$(5, 0) = "Friday" : Days$(6, 1) = "Viernes"
Days$(5, 1) = "Saturday" : Days$(6, 0) = "Sábado"
Print Days$(2, 1)

The following example declares the variable num as shared, sets the variable to 6, and then calls the MyRoutine subroutine. The subroutine adds 10 to num, and the main subroutine displays the new value. Note that the instruction Dim Shared num must be placed outside both subroutines.

Dim Shared num                    'Declare num as shared
Sub MAIN
    num = 6                        'Set the value of num
    MyRoutine                    'Call the routine
    Print num                    'Display the new value of num
End Sub

Sub MyRoutine
    num = num + 10                'Increase the value of num
End Sub

In the following example, Dim is used to define the dialog record TOVrec in which the values of the View tab in the Options dialog box (Tools menu) are stored. This macro toggles the setting of the Paragraph Marks check box.

Dim TOVrec As ToolsOptionsView    'Define dialog record
GetCurValues TOVrec                 'Get the current state
If TOVrec.Paras = 1 Then            'If on
    TOVrec.Paras = 0             'turn off
Else                             'Else
    TOVrec.Paras = 1                'turn on
End If
ToolsOptionsView TOVrec            'Apply new setting

In the following example, Dim is used to define the dialog record Dlg for a user-defined dialog box:

Begin Dialog UserDialog 320, 57, "A Simple Dialog Box"
    Text 5, 16, 205, 18, "This is a simple dialog box."
    OKButton 220, 4, 88, 21
    CancelButton 220, 29, 88, 21
End Dialog
Dim Dlg As UserDialog            'Define the dialog record
Dialog Dlg                        'Display the dialog box

See Also

Declare, Dialog, Let, Redim


DisableAutoMacros

Syntax

DisableAutoMacros [Disable]

Remarks

Disables AutoOpen, AutoClose, AutoNew, and AutoExit macros until they are re-enabled with the instruction DisableAutoMacros 0 or until Word is started again. You can place a DisableAutoMacros statement before the line in your macro that triggers an auto macro — for example, a FileNew instruction that creates a document based on a template containing an AutoNew macro.

Argument | Explanation
Disable | Specifies whether to disable auto macros: 0 (zero) Enables auto macros 1 or omitted Disables auto macros

You cannot use DisableAutoMacros to disable an AutoExec macro or to disable the current macro. For example, you could not place a DisableAutoMacros statement in an AutoOpen macro to disable AutoOpen. To disable an AutoExec macro, hold down the SHIFT key while Word is loading or use the /m startup switch. For more information, see "Startup Switches" in Help.

Example

This example creates a new document based on the Memo template. Assume that the Memo template contains an AutoNew macro that presents a series of dialog boxes. The DisableAutoMacros statement prevents AutoNew from running.

DisableAutoMacros
FileNew .Template = "MEMO"


DisableInput

Syntax

DisableInput [Disable]

Remarks

Prevents the ESC key from interrupting a macro. DisableInput does not prevent ESC from canceling a dialog box.

Argument | Explanation
Disable | Determines whether or not to disable the ESC key: 0 (zero) Enables the ESC key to cancel the macro 1 or omitted Prevents the ESC key from canceling the macro

Note

If the user presses ESC while a dynamic dialog box is displayed, a message stating that the macro was interrupted appears and the dialog box remains on screen. To make ESC behave properly when you display a dynamic dialog box, precede the Dialog or Dialog() instruction with the instruction DisableInput 1; follow with DisableInput 0 to reset the original ESC key behavior.

Example

This example shows how you might use DisableInput instructions preceding and following an instruction that displays a dynamic dialog box.

DisableInput 1
button = Dialog(MyDynamicDlg)
DisableInput 0


DlgControlId()

Syntax

DlgControlId(Identifier$)

Remarks

Used within a dialog function to return the numeric identifier for the dialog box control specified by Identifier$, the string identifier of the dialog box control. Numeric identifiers are numbers, starting at 0 (zero), that correspond to the positions of dialog box control instructions within a dialog box definition. For example, consider the following instruction in a dialog box definition:

CheckBox 97, 54, 36, 12, "&Update", .MyCheckBox

The instruction DlgControlId("MyCheckBox") returns 0 (zero) if the CheckBox instruction is the first instruction in the dialog box definition, 1 if it is the second instruction, and so on.

In most cases, your dialog functions will perform actions based on the string identifier of the control that was selected. However, dialog functions can use numeric identifiers to manipulate more quickly a large number of controls (for example, the number of controls found in a multiple-panel dialog box). Note that if you change the order of instructions in a dialog box definition, the numeric identifiers for the corresponding controls will change also.

For information about using a dialog function, see Chapter 5, "Working with Custom Dialog Boxes," in Part 1, "Learning WordBasic."

Example

This macro displays a simple dialog box containing the OK and Cancel buttons and a check box labeled "Test." The dialog function checks to see if the value for action is 2, meaning a control has been selected or chosen. If so, the dialog function then checks to see if the control selected is the first one defined—in other words, if the numeric identifier returned by DlgControlId() is 0 (zero). If it is, a message box is displayed in front of the dialog box, which remains on-screen.

Sub MAIN
Begin Dialog UserDialog 320, 50, "Test", .MyDlgFunction
    CheckBox 212, 10, 88, 19, "Test", .Test            '0
    OKButton 7, 10, 88, 21                            '1
    CancelButton 109, 10, 88, 21                        '2
End Dialog
Dim dlg As UserDialog
DisableInput 1
button = Dialog(dlg)
DisableInput 0
End Sub

END BREAK

Function MyDlgFunction(identifier$, action, suppvalue)
If action = 2 Then
    If DlgControlId(identifier$) = 0 Then
        MsgBox "You selected the first control " + \
                "defined in the dialog box definition."
    End If
End If
End Function

See Also

DlgFocus, DlgValue


DlgEnable, DlgEnable()

Syntax

DlgEnable Identifier[$] [, On]

DlgEnable(Identifier[$])

Remarks

The DlgEnable statement is used within a dialog function to enable or disable the dialog box control identified by Identifier[$] while the dialog box is displayed. When a dialog box control is disabled, it is visible in the dialog box, but is dimmed and not functional.

For information about using a dialog function, see Chapter 5, "Working with Custom Dialog Boxes," in Part 1, "Learning WordBasic."

Argument | Explanation
Identifier[$] | The string or numeric identifier of the dialog box control
On | Enables or disables the dialog box control: 1 Enables the control 0 (zero) Disables the control Omitted Toggles the control

The DlgEnable() function returns the following values.

Value | Explanation
–1 | If the control is enabled
0 (zero) | If the control is disabled

Example

This example disables the dialog box control with the string identifier "Set" when the dialog box is initially displayed. (The main subroutine that contains the dialog box definition is not shown.)

Function MyDlgFunction(identifier$, action, suppvalue)
Select Case action
    Case 1                        'The dialog box is displayed
        DlgEnable "Set", 0
    Case 2                        'The user selects a control
        'Statements that perform actions based
        'on which control is selected go here
    Case 3                        'Text change (not applicable)
    Case Else
End Select
End Function

See Also

DlgVisible


DlgFilePreview, DlgFilePreview$()

Syntax

DlgFilePreview [Identifier[$]] [, Filename$]

DlgFilePreview$()

Remarks

The DlgFilePreview statement is used within a dialog function to preview the first page of the document specified by Filename$ (which does not have to be open). If you don't specify Filename$, DlgFilePreview previews the first page of the active document. The document is displayed in the box created with a FilePreview instruction in the dialog box definition. Because a custom dialog box can have only one file preview box, the use of Identifier[$] to specify the file preview box is optional.

The DlgFilePreview$() function returns the path and filename of the document displayed in the file preview box. If the active document has not been saved as a file (for example, a new document such as Document2 or a macro open for editing), DlgFilePreview$() returns the window name instead of the path and filename.

For information about using a dialog function, see Chapter 5, "Working with Custom Dialog Boxes," in Part 1, "Learning WordBasic."

Example

This example updates the file preview box according to the selection made in a list box containing filenames. (The main subroutine that contains the dialog box definition is not shown.)

Function PreviewFiles(identifier$, action, suppvalue)
If action = 1 Then                        'Preview first file in list
    previewfilename$ = DlgText$("ListBox1")
    DlgFilePreview$ previewfilename$
ElseIf action = 2 Then                    'The user selects a control
    If identifier$ = "ListBox1" Then        'Preview selected file
        previewfilename$ = DlgText$("ListBox1")
        DlgFilePreview$ previewfilename$
    End If
End If
End Function

See Also

DlgSetPicture, DlgUpdateFilePreview, FilePreview, Picture


DlgFocus, DlgFocus$()

Syntax

DlgFocus Identifier[$]

DlgFocus$()

Remarks

The DlgFocus statement is used within a dialog function to set the focus on the dialog box control identified by Identifier[$] while the dialog box is displayed. When a dialog box control has the focus, it is active and responds to keyboard input. For example, if a text box has the focus, any text you type appears in that text box.

The DlgFocus$() function returns the string identifier for the dialog box control that currently has the focus.

For information about using a dialog function, see Chapter 5, "Working with Custom Dialog Boxes," in Part 1, "Learning WordBasic."

Example

This example sets the focus on the control "MyControl1" when the dialog box is initially displayed. (The main subroutine that contains the dialog box definition is not shown.)

Function MyDlgFunction(identifier$, action, suppvalue)
Select Case action
    Case 1                    'The dialog box is displayed
        DlgFocus "MyControl1"
    Case 2                    'The user selects a control
        'Statements that perform actions based
        'on which control is selected go here
    Case 3                    'Text change (not applicable)
    Case Else
End Select
End Function

See Also

DlgEnable, DlgVisible


DlgListBoxArray, DlgListBoxArray()

Syntax

DlgListBoxArray Identifier[$], ArrayVariable$()

DlgListBoxArray(Identifier[$] [, ArrayVariable$()])

Remarks

The DlgListBoxArray statement is used within a dialog function to fill a list box, drop-down list box, or combo box with the contents of ArrayVariable$(). You can use this statement to change the contents of a list box, drop-down list box, or combo box in a custom dialog box while the dialog box is displayed.

For information about using a dialog function, see Chapter 5, "Working with Custom Dialog Boxes," in Part 1, "Learning WordBasic."

Argument | Explanation
Identifier[$] | The string or numeric identifier of the dialog box control. The control must be a list box, drop-down list box, or combo box.
ArrayVariable$() | A string array containing items to be displayed in the specified list box, drop-down list box, or combo box.

The DlgListBoxArray() function fills ArrayVariable$() with the contents of the list box, drop-down list box, or combo box specified by Identifier[$] and returns the number of entries in the list box, drop-down list box, or combo box. ArrayVariable$() is optional with the DlgListBoxArray() function; if ArrayVariable$() is omitted, DlgListBoxArray() returns the number of entries
in the specified control.

Example

This example changes the contents of a list box while the dialog box is displayed. The dialog box definition in the main subroutine (not shown) defines a dialog box containing a list box, the OK and Cancel buttons, and a Change button. When the user chooses the Change button, the If control structure in Case 2 of the dialog function takes over: A new string array is defined, DlgListBoxArray is used to replace the contents of the list box, and the Change button is disabled. By default, a custom dialog box is closed when the user chooses a command button such
as the Change button; however, in this example, the keepDisplayed = 1 and dlgTest = keepDisplayed instructions keep the dialog box displayed (when
a dialog function returns a value of 1, the dialog box remains displayed).

Function dlgTest(identifier$, action, suppvalue)
Select Case action
Case 1                    'The dialog box is displayed
Case 2                    'The user selects a control
If identifier$ = "Change" Then
    Dim MyArray2$(1)
    MyArray2$(0) = "New first item"
    MyArray2$(1) = "New second item"
    DlgListBoxArray "MyListBox", MyArray2$()
    DlgFocus "MyListBox"
    DlgEnable "Change", 0
    keepDisplayed = 1
End If
Case 3                    'Text change (not applicable)
Case Else
End Select
dlgTest = keepDisplayed
End Function

See Also

DlgEnable, DlgFocus, DlgText


DlgLoadValues, DlgLoadValues()

Syntax

DlgLoadValues ValuesFile$, Identifier$

DlgLoadValues(ValuesFile$, Identifier$)

Remarks

On the Macintosh, the DlgLoadValues statement retrieves values stored by a DlgStoreValues instruction for controls in a custom dialog box.

Argument | Explanation
ValuesFile$ | The name of the file in which the values are stored. ValuesFile$ can include a path. If a path is not included, Word looks for ValuesFile$ in the Preferences folder. If ValuesFile$ does not exist, empty strings and null values are passed to the dialog box but no error occurs.
Identifier$ | A string that identifies the set of stored values (the same string is used when storing values with DlgStoreValues).

The DlgLoadValues() behaves the same as the statement, and also returns the following values:

Value | Explanation
0 (zero) | If either ValuesFile$ or Identifier$ does not exist, or if any of the stored values cannot be loaded (this can occur if the dialog definition has changed since the values were last stored).
-1 | If the values were loaded successfully.

In Windows, DlgLoadValues and DlgLoadValues() are not available and generate errors.

Example

This Macintosh macro shows how you can use DlgStoreValues and DlgLoadValues in a dialog function to save settings for a variety of dialog box controls. During initialization of the dialog box, the DlgLoadValues instruction runs; when the user chooses OK, the DlgStoreValues instruction runs. Note that the identifier for the first check box ends in 0 (zero), preventing Word from performing its default action of saving the check box setting. The first time the dialog box is displayed, the file containing the settings (DLGVALS) does not exist. The file is created the first time the DlgStoreValues instruction runs.

Sub MAIN
Begin Dialog UserDialog 225, 167, "Test", .MyDlgFunction
    CheckBox 11, 48, 88, 19, "Test 1", .FirstBox0
    CheckBox 97, 48, 88, 19, "Test 2", .SecondBox
    OKButton 118, 124, 88, 21
    CancelButton 11, 124, 88, 21
    TextBox 11, 24, 197, 18, .TextBox1
    Text 11, 7, 46, 12, "Name:", .Text1
    GroupBox 11, 71, 197, 41, "Group Box"
    OptionGroup  .OptionGroup1
        OptionButton 17, 84, 89, 18, "Option A", .OptionA
        OptionButton 110, 84, 89, 18, "Option B", .OptionB
End Dialog
Dim dlg As UserDialog
DisableInput 1
button = Dialog(dlg)
DisableInput 0
End Sub

Function MyDlgFunction(identifier$, action, suppvalue)
Select Case action
    Case 1                'initialization
        DlgLoadValues "DLGVALS", "MyDlgFunction"
    Case 2                'button chosen or setting changed
        If identifier$ = "OK" Then
            DlgStoreValues "DLGVALS", "MyDlgFunction"
        End If
    Case Else
End Select
End Function

See Also

DlgStoreValues


DlgSetPicture

Syntax

DlgSetPicture Identifier[$], PictureName$, PictureType

Remarks

Used in a dialog function to set the graphic displayed by a Picture dialog box control whose identifier is Identifier[$].

Argument | Explanation
Identifier[$] | The string or numeric identifier of the dialog box control.
PictureName$ | The name of the graphics file, AutoText entry, or bookmark containing the graphic to be displayed. If the picture does not exist, Word displays the text "(missing picture)" within the rectangle that defines the picture area.
PictureType | A value indicating how the graphic is stored: 0 (zero) PictureName$ is a file. 1 PictureName$ is an AutoText entry. 2 PictureName$ is a bookmark. 3 PictureName$ is ignored; the graphic is retrieved from the Clipboard. 4 PictureName$ is a PICT file stored in the resource fork of the template containing the macro (Macintosh only). You can use the ResEdit program to add PICT files to the resource fork of a template.

Example

In this example, the user selects a person's name from a list box and a picture of the person is displayed in the dialog box. The instructions assume that the graphics file to display is in the C:\PHOTOS folder and that the filename is the same as the selected name, followed by a .PIC filename extension. (On the Macintosh, change the instruction that sets the pictureName$ variable to use the value "HD:PHOTOS:" + name$.) The main subroutine that contains the dialog box definition is not shown.

Function dlgTest(identifier$, action, suppvalue)
Select Case action
Case 1                        'The dialog box is displayed
Case 2                        'The user selects a control
If identifier$ = "Name" Then
    name$ = DlgText$("Name")
    pictureName$ = "C:\PHOTOS\" + name$ + ".PIC"
    DlgSetPicture "Photo", pictureName$, 0
End If
Case 3                        'Text change (not applicable)
Case Else
End Select
End Function

See Also

Picture


DlgStoreValues

Syntax

DlgStoreValues ValuesFile$, Identifier$

Remarks

On the Macintosh, stores string and numeric values for controls in custom dialog boxes so they may be retrieved later by DlgLoadValues. If you create a complex wizard, using DlgStoreValues and DlgLoadValues instead of SetPrivateProfileString and GetPrivateProfileString$() for storing and retrieving values entered by the user can improve performance significantly.

Argument | Explanation
ValuesFile$ | The name of the file in which the values are stored. ValuesFile$ can include a path. If a path is not specified, Word looks for ValuesFile$ in the Preferences folder.
Identifier$ | A string that identifies the set of stored values (this string is used when retrieving values with DlgLoadValues). Note that while you can store multiple sets of values for different dialog boxes in the same file, it is recommended for future cross-platform compatibility that you use one values file per dialog box.

The following rules determine which values Word stores:

  • Values for the following items are stored by default: check boxes, option groups, text boxes, list boxes, drop-down list boxes, and combo boxes. Values for all other items are not stored by default.
  • You can reverse the default behavior for most individual items by giving the item a string identifier that ends in 0 (zero). For example, you can store the value for a Text control (such as a tip in a wizard) or prevent the value for a check box from being stored. Note that .Item0 and .Item000 are examples of identifiers that end in 0 (zero), but .Item100 is not.
  • You cannot store values for picture, file preview, option button, and push button controls.

In Windows, DlgStoreValues is unavailable and generates an error.

For an example, see DlgLoadValues.

See Also

DlgLoadValues


DlgText, DlgText$()

Syntax

DlgText Identifier[$], Text$

DlgText$(Identifier[$])

Remarks

The DlgText statement is used in a dialog function to set the text or label for the dialog box control identified by Identifier[$]. The DlgText statement does not change the string identifier of a dialog box control.

For a text box or combo box, DlgText sets the text within the text box. For dialog box controls that have labels, such as check boxes, option buttons, option groups, and command buttons, DlgText sets the label. For list boxes, DlgText sets the selection to Text$ or to the first item that begins with Text$.

For information about using a dialog function, see Chapter 5, "Working with Custom Dialog Boxes," in Part 1, "Learning WordBasic."

Argument | Explanation
Identifier[$] | The string or numeric identifier of the dialog box control
Text$ | The text or label to set

The DlgText$() function returns the text or label of the dialog box control identified by Identifier[$]. If the dialog box control is a list box, the text of the selected item is returned. If the dialog box control is a text box or combo box, DlgText$() returns the text that appears in the text box.

Example

This example hides and displays a control in a dialog box, and, accordingly, toggles the label of a command button between "Hide Control" and "Show Control." (The main subroutine that contains the dialog box definition is not shown.) By default, a custom dialog box is closed when the user chooses a command button; however, in this example, the keepDisplayed = 1 and dlgTest = keepDisplayed instructions keep the dialog box displayed (when a dialog function returns a value of 1, the dialog box remains displayed).

Function dlgTest(identifier$, action, suppvalue)
Select Case action
Case 1                        'The dialog box is displayed
Case 2                        'The user chooses a button
If identifier$ = "Hide" Then
    If DlgText$("Hide") = "Hide &Control" Then
        DlgVisible "Option1", 0
        DlgText$ "Hide", "Show &Control"
    Else
        DlgVisible "Option1", 1
        DlgText$ "Hide", "Hide &Control"
    End If
    keepDisplayed = 1
End If
Case 3                        'Text change (not applicable)
Case Else
End Select
dlgTest = keepDisplayed
End Function

See Also

DlgValue


DlgValue, DlgValue()

Syntax

DlgValue Identifier[$], Value

DlgValue(Identifier[$])

Remarks

The DlgValue statement is used in a dialog function to select or clear a dialog
box control by setting the numeric value associated with the control specified by Identifier[$]. For example, DlgValue "MyCheckBox", 1 selects a check box, DlgValue "MyCheckBox", 0 clears a check box, and DlgValue "MyCheckBox", -1 fills the check box with gray. An error occurs if Identifier[$] specifies a dialog box control such as a text box or an option button that cannot be set with a numeric value.

For information about using a dialog function, see Chapter 5, "Working with Custom Dialog Boxes," in Part 1, "Learning WordBasic."

Argument | Explanation
Identifier[$] | The string or numeric identifier of the dialog box control. The DlgValue statement and DlgValue() function can be used with identifiers created by the following statements: CheckBox, ComboBox, DropListBox, ListBox, and OptionGroup.
Value | Numeric value to set the dialog box control identified by Identifier[$]

The DlgValue() function returns the numeric value of the check box, list box, drop-down list box, combo box, or option group identified by Identifier[$]. For example, DlgValue("MyCheckBox") returns 1 if the check box is selected, 0 (zero) if it is cleared, and –1 if it is filled with gray. The instruction DlgValue("MyListBox") returns 0 (zero) if the first item in the list box is selected, 1 if the second item is selected, and so on.

Example

This example is the portion of a dialog function that runs when the check box with the identifier "MyCheckBox" is selected. DlgValue() is used to determine whether the check box was turned on or off. If it was turned on, the instructions redefine an array and fill a list box with the items in the array.

Case 2                    'The user selects a control
If identifier$ = "MyCheckBox" Then
If DlgValue("MyCheckBox") = 1 Then
    ReDim MyArray$(1)
    MyArray$(0) = "Alberto"
    MyArray$(1) = "Gina"
    DlgListBoxArray "MyListBox", MyArray$()
End If
End If

See Also

DlgText


DlgVisible, DlgVisible()

Syntax

DlgVisible Identifier[$] [, On]

DlgVisible FirstIdentifier[$] , LastIdentifier[$], On

DlgVisible(Identifier[$])

Remarks

In Windows 3.x, the DlgVisible statement is used in a dialog function to make visible or to hide the dialog box control identified by Identifier[$]. On the Macintosh and in Windows 95 and Windows NT, the DlgVisible statement can be used to make visible or to hide a range of dialog box controls. You can use DlgVisible to hide little-used options until they are needed, or to create dialog boxes with multiple panels of controls.

Argument | Explanation
Identifier[$] | The string or numeric identifier of the dialog box control
FirstIdentifier[$] | The string or numeric identifier of the first dialog box control in a range of dialog box controls
LastIdentifier[$] | The string or numeric identifier of the last dialog box control in a range of dialog box controls. LastIdentifier[$] can be the same as FirstIdentifier[$].
On | Shows or hides the dialog box control Identifier[$] or the range of dialog box controls between FirstIdentifier[$] and LastIdentifier[$] as listed in a dialog box definition. 1 Shows the control or range of controls 0 (zero) Hides the control or range of controls Omitted Toggles the control between visible and hidden Note that the On argument cannot be omitted if FirstIdentifier[$] and LastIdentifier[$] are specified.

The DlgVisible() function returns the following values:

Value | Explanation
–1 | If the control is visible
0 (zero) | If the control is hidden

For an example that uses DlgVisible, see DlgText.

See Also

DlgEnable, DlgFocus, DlgText


DocClose

Syntax

DocClose [Save]

Remarks

Closes the active document window. DocClose is not the same as FileClose: Whereas FileClose closes the active document and all associated windows, DocClose closes only the active document window. When a document is open in a single window, which is usually the case, DocClose and FileClose have the same effect.

Argument | Explanation
Save | Determines whether or not to save the document: 0 (zero) or omitted Prompts the user to save if changes have been made in the document since the last time it was saved. 1 Saves the document without prompting before closing it. 2 Closes the window but does not save the document. The Save argument also controls whether a prompt appears if the document has a routing slip. A prompt appears if Save is 0 (zero) or omitted; otherwise, the document is closed without being routed.

Example

This example closes every open document window and prompts the user to save any unsaved changes:

While Window() <> 0
    DocClose 0
Wend

See Also

ClosePane, FileClose


DocMinimize, DocMinimize()

Syntax

DocMinimize

DocMinimize()

Remarks

The DocMinimize statement shrinks the active document window to an icon.

The DocMinimize() function returns the following values.

Value | Explanation
–1 | If the active document window is minimized
0 (zero) | If the active document window is not minimized

See Also

AppMinimize, DocMaximize, DocRestore


DocMove

Syntax

DocMove HorizPos, VertPos

Remarks

Moves the active document window or icon to the specified location. If the active document is maximized, Word cannot perform this action and generates an error.

Argument | Explanation
HorizPos, VertPos | The horizontal (HorizPos) and vertical (VertPos) distance from the upper-left corner of the workspace to the upper-left corner of the document window, in points (72 points = 1 inch). Negative values are allowed.

Example

This example moves the document window to the position 20 points to the right and 40 points down from the upper-left corner of the workspace:

If DocMaximize() = 0 Then DocMove 20, 40

See Also

AppMove, DocSize, DocWindowPosLeft, DocWindowPosTop


DocRestore

Syntax

DocRestore

Remarks

Restores all document windows from a maximized state or restores a minimized document window. Unlike DocMaximize, which maximizes the document windows if restored and restores them if maximized, DocRestore only restores document windows. It generates an error if the active document is already restored.

There is no corresponding function for DocRestore. As the example for this entry demonstrates, however, you can use the DocMaximize() function to determine whether document windows are restored.

Example

This example restores document windows if they are maximized:

If DocMaximize() <> 0 Then DocRestore

See Also

AppRestore, DocMaximize, DocMinimize


DocSize

Syntax

DocSize Width, Height

Remarks

Sizes the active document window to the specified Width and Height, in points
(72 points = 1 inch). If the active document is maximized or minimized, Word cannot perform this action and generates an error. Note that this statement must have arguments for both the width and height of the window. To size only the width or height of a window, use DocWindowWidth or DocWindowHeight.

Example

This example ensures that the active document window is restored and then sizes it to half the width of the workspace:

If DocMaximize() or DocMinimize() Then DocRestore
DocSize(Val(AppInfo$(6)) / 2), Val(AppInfo$(7))

See Also

AppInfo$(), AppSize, DocWindowHeight, DocWindowWidth


DocSplit, DocSplit()

Syntax

DocSplit Percentage

DocSplit()

Remarks

The DocSplit statement splits the active document window at the given height, expressed as a percentage of the distance between the top and bottom of the document area.

The DocSplit() function returns the split position as a percentage of the active document area's height or returns 0 (zero) if the document window is not split.

The DocSplit statement accepts values between 0 (zero) and 100, but values near the ends of the range may not split the document window, depending on the screen elements that are displayed and the size of the window. Using the WindowPane() function, you can determine whether a window is split.

Example

This example splits the active document window in the middle:

DocSplit 50

See Also

ClosePane, OtherPane, WindowPane()


DocumentHasMisspellings()

Syntax

DocumentHasMisspellings()

Remarks

Returns information about the status of automatic spell checking in the active document. In Word version 6.0, DocumentHasMisspellings() is unavailable and generates an error.

The DocumentHasMisspellings() function returns the following values.

Value | Explanation
-1 | If automatic spell checking is turned off (unless the document is empty), or if checking is in progress
0 (zero) | If the document has been completely checked and contains no misspellings, or if the document is empty
1 | If the document has been completely checked and contains at least one misspelling

Example

This example enables automatic spell checking and finds the next misspelled word in the active document. (Errors are shown if the document either hasn't been checked for spelling errors or has been completely checked and contains misspellings.) When it locates the misspelled word, the example opens the shortcut menu containing spelling suggestions.

If DocumentHasMisspellings() <> 1 Then
    ToolsOptionsSpelling .AutomaticSpellChecking = 1, .HideSpellingErrors = 0
End If
NextMisspelling

See Also

NextMisspelling, ToolsGetSpelling, ToolsLanguage, ToolsOptionsSpelling


DocumentPropertyExists()

Syntax

DocumentPropertyExists(Name$)

Remarks

Returns 1 if Name$ is the name of an existing property or 0 (zero) if it is not. For a list of the built-in properties available in Word, see DocumentPropertyName$(). In Word version 6.0, DocumentPropertyExists() is unavailable and generates an error. For an example, see SetDocumentProperty.

See Also

DeleteDocumentProperty, DocumentPropertyName$(), DocumentPropertyType(), IsCustomDocumentProperty()


DocumentPropertyName$()

Syntax

DocumentPropertyName$(PropertyNumber)

Remarks

Returns the name of the document property as specified by PropertyNumber. Word lists the built-in properties first. The custom properties are appended at the end the list. Use the DocumentPropertyExists() function to verify that the property specified by PropertyNumber exists. In Word version 6.0, DocumentPropertyName$() is unavailable and generates an error.

The following table lists the built-in properties available in Word for the active document. The list indicates which of these properties are read-only.

Property name | Explanation
Title | The title of the document
Subject | The subject of the document
Author | The author of the document
Manager | The name of the manager
Company | The name of the company
Category | The category of the document
Keywords | The keywords used to identify the document
Comments | The comments about the document
Template | The document template (read-only)
CreateTime | The creation date (read-only)
LastSavedTime | The date the document was last saved (read-only)
LastPrinted | The date the document was last printed (read-only)
LastSavedBy | The name of the person who last saved the document (read-only)
RevisionNumber | The number of times that the document has been saved (read-only)
TotalEditingTime | The total time that the document has been open, in minutes, as a number (read-only)
Pages | The number of pages (read-only)
Paragraphs | The number of paragraphs (read-only)
Lines | The number of lines (read-only)
Words | The number of words (read-only)
Characters | The number of characters (read-only)

Property name | Explanation
Bytes | The size of the document, in the form "36,352 Bytes" (read-only)
NameOfApplication | The name of the associated application; for example, "Microsoft Word for Windows 95" (read-only)
Security | The level of document protection (read-only)

Example

This example inserts a list of all the document properties at the end of the current document. Property names are inserted with bold formatting, and each one is followed by its value.

EndOfDocument
InsertPara
For count = 1 To CountDocumentProperties()
    a$ = DocumentPropertyName$(count)
    Bold 1 : Insert a$
    InsertPara
    If DocumentPropertyType(a$) = 1 then
        b = GetDocumentProperty(a$)
        Bold 0 : Insert Str$(b)
        InsertPara : InsertPara
    Else
        b$ = GetDocumentProperty$(a$)
        Bold 0 : Insert b$
        InsertPara : InsertPara
    End If
Next

See Also

CountDocumentProperties(), DocumentPropertyType(), GetDocumentProperty(), IsDocumentPropertyReadOnly(), SetDocumentProperty


DocumentPropertyType()

Syntax

DocumentPropertyType(Name$)

Remarks

Returns a numeric value that indicates the type of the Name$ property. If Name$ is not a valid property, an error occurs. Use the DocumentPropertyExists() function to verify that the Name$ property exists.

For a list of the built-in properties available in Word, see DocumentPropertyName$(). In Word version 6.0, DocumentPropertyType() is unavailable and generates an error.

The DocumentPropertyType() function returns the following values.

Value | Explanation
0 | The property is a string.
1 | The property is a number.
2 | The property is a date.
3 | The property is a Yes or No value.

See Also

DocumentPropertyExists(), DocumentPropertyName$(), IsCustomDocumentProperty(), IsDocumentPropertyReadOnly()


DocumentProtection()

Syntax

DocumentProtection()

Remarks

Returns a value specifying the protection mode of the active document. To change the current protection mode, use ToolsProtectDocument. In Word version 6.0, DocumentProtection() is unavailable and generates an error.

Value | Explanation
0 (zero) | The document is not protected.
1 | Users can only select and modify text in form fields.
2 | Users can only add annotations.
3 | Users can select and edit text, but all changes are tracked with revision marks.

See Also

ToolsProtectDocument, ToolsUnprotectDocument


DocumentStatistics

Syntax

DocumentStatistics [.FileName = text] [, .Directory = text] [, .Template = text] [, .Title = text] [, .Created = text] [, .LastSaved = text] [, .LastSavedBy = text] [, .Revision = text] [, .Time = text] [, .Printed = text] [, .Pages = text] [, .Words = text] [, .Characters = text] [, .Paragraphs = text] [, .Lines = text] [, .FileSize = text]

Remarks

Used with a dialog record, DocumentStatistics returns information about the active document. In Word version 6.0, the arguments for the DocumentStatistics statement correspond to the information available in the Document Statistics dialog box (Summary Info command, File menu). Also, the arguments are read-only, which means that unlike other WordBasic statements, you cannot use DocumentStatistics to set a value. Instead, you use the DocumentStatistics dialog record in the same way you use a function: to return information.

In Word version 7.0, this statement is included for backward compatibility. You can use the document property statements and functions to access document statistics for the active document. For more information, see GetDocumentProperty().

Argument | Explanation
.FileName | The name of the document (the path is not included)
.Directory | The path in which the document is kept
.Template | The path and filename of the template attached to the document
.Title | The document's title
.Created | The date and time the document was created
.LastSaved | The date and time the document was last saved
.LastSavedBy | The author of the document
.Revision | The number of times the document has been saved
.Time | The total time spent editing the document
.Printed | The date and time the document was last printed
.Pages | The number of pages in the document
.Words | The number of words in the document
.Characters | The number of characters in the document
.Paragraphs | The number of paragraphs in the document
.Lines | The number of lines in the document
.FileSize | The size of the document in the form "36,352 Bytes"

Note

To ensure you get the most up-to-date information when using a DocumentStatistics dialog record to return document statistics, include the instruction FileSummaryInfo .Update before defining the dialog record.

Example

This example uses the DocumentStatistics dialog record to obtain the number of words in the active document. You can use this example as a model for how to obtain the value of any DocumentStatistics argument.

FileSummaryInfo .Update                        'Update document statistics
Dim dlg As DocumentStatistics                'Create a dialog record
GetCurValues dlg                                'Fill record with values
MsgBox "Number of words: " + dlg.Words

See Also

FileSummaryInfo, SelInfo()


DocWindowHeight, DocWindowHeight()

Syntax

DocWindowHeight Height

DocWindowHeight()

Remarks

The DocWindowHeight statement sets the active document window to the specified Height, in points (72 points = 1 inch), without affecting its width. If the active document is maximized or minimized, Word cannot perform this action and generates an error. The DocWindowHeight() function returns the height of the active document window in points.

Example

This example restores the active document window if it is maximized or minimized, moves it to the upper-left corner of the workspace, and then sizes the window to 267 points high:

If DocMaximize() or DocMinimize() Then DocRestore
DocMove 0, 0
DocWindowHeight 267

See Also

AppWindowHeight, DocSize, DocWindowWidth


DocWindowPosLeft, DocWindowPosLeft()

Syntax

DocWindowPosLeft Position

DocWindowPosLeft()

Remarks

The DocWindowPosLeft statement positions the active document window or icon so that it is Position points from the left border of the workspace. If the active document is maximized, Word cannot perform this action and generates
an error. The DocWindowPosLeft() function returns the horizontal position in points.

Example

This example displays the horizontal and vertical positions of the active document window relative to the border of the workspace:

horizpos = DocWindowPosLeft()
vertpos = DocWindowPosTop()
MsgBox "Points from left:" + Str$(horizpos) + Chr$(13) + \
    "Points from top:" + Str$(vertpos), "Doc Window Position"

See Also

AppWindowPosLeft, DocMove, DocSize, DocWindowHeight, DocWindowPosTop, DocWindowWidth


DocWindowPosTop, DocWindowPosTop()

Syntax

DocWindowPosTop Position

DocWindowPosTop()

Remarks

The DocWindowPosTop statement positions the active document window or icon so that it is Position points from the upper border of the workspace. If the active document is maximized, Word cannot perform this action and generates an error. The DocWindowPosTop() function returns the vertical position in points. For an example, see DocWindowPosLeft.

See Also

AppWindowPosTop, DocMove, DocSize, DocWindowHeight, DocWindowPosTop, DocWindowWidth


DocWindowWidth, DocWindowWidth()

Syntax

DocWindowWidth Width

DocWindowWidth()

Remarks

The DocWindowWidth statement sets the active document window to the specified Width, in points (72 points = 1 inch), without affecting its height. If the active document is maximized or minimized, Word cannot perform this action and generates an error. The DocWindowWidth() function returns the width of the active document window in points.

Example

This example maximizes the Word window (Windows) and restores document windows. If there are two open document windows, the windows are each sized to 240 points in width and are placed side by side.

If InStr(AppInfo$(1), "Macintosh") = 0 Then
    If AppMaximize() = 0 Then AppMaximize
End If
If CountWindows() = 2 Then
    If DocMaximize() Or DocMinimize() Then DocRestore
    DocMove 0, 0
    DocWindowWidth 240
    NextWindow
    If DocMinimize() Or DocMinimize() Then DocRestore
    DocMove 240, 0
    DocWindowWidth 240
End If

See Also

AppWindowWidth, DocSize, DocWindowHeight


DoFieldClick

Syntax

DoFieldClick

Remarks

Moves the insertion point to the location specified by the selected GOTOBUTTON field, or runs the macro specified by the selected MACROBUTTON field (the same as double-clicking the field or pressing ALT+SHIFT+F9 (Windows) or OPTION+SHIFT+F9 (Macintosh) within the result of the field).


DOSToWin$()

Syntax

DOSToWin$(StringToTranslate$)

Remarks

In Windows, translates a string from the original equipment manufacturer (OEM) character set to the Windows character set. On the Macintosh, DOSToWin$() performs no translation and returns the specified string unchanged.

The OEM character set is typically used by MS-DOS applications. Characters 32 through 127 are usually the same in the OEM and Windows character sets. The other characters in the OEM character set (0 (zero) through 31 and 128 through 255) are generally different from the Windows characters.

Example

This example opens a sequential file created by an MS-DOS application, translates each line to the Windows character set, and places the result in a new sequential file:

ChDir "C:\TMP"
Open "DOS.TXT" For Input As #1
Open "WINDOWS.TXT" For Output As #2
While Not Eof(1)
    Line Input #1, temp$
    Print #2, DOSToWin$(temp$)
Wend
Close

See Also

WinToDOS$()


DottedUnderline, DottedUnderline()

Syntax

DottedUnderline [On]

DottedUnderline()

Remarks

The DottedUnderline statement adds or removes the dotted-underline character format for the selected text, or controls dotted-underline formatting for characters to be inserted at the insertion point.

Argument | Explanation
On | Specifies whether to add or remove the dotted-underline format: 1 Formats the selection with the dotted-underline format 0 (zero) Removes the dotted-underline format Omitted Toggles the dotted-underline format

The DottedUnderline() function returns the following values.

Value | Explanation
0 (zero) | If none of the selection is in the dotted-underline format
–1 | If part of the selection is in the dotted-underline format
1 | If all the selection is in the dotted-underline format

See Also

DoubleUnderline, FormatBordersAndShading, FormatFont, Underline


DoubleUnderline, DoubleUnderline()

Syntax

DoubleUnderline [On]

DoubleUnderline()

Remarks

The DoubleUnderline statement adds or removes the double-underline character format for the selected text, or controls double-underline formatting for characters to be inserted at the insertion point.

Argument | Explanation
On | Specifies whether to add or remove the double-underline format: 1 Formats the selection with the double-underline format 0 (zero) Removes the double-underline format Omitted Toggles the double-underline format

The DoubleUnderline() function returns the following values.

Value | Explanation
0 (zero) | If none of the selection is in the double-underline format
–1 | If part of the selection is in the double-underline format
1 | If all the selection is in the double-underline format

See Also

DottedUnderline, FormatBordersAndShading, FormatFont, Underline


DrawAlign

Syntax

DrawAlign [.Horizontal = number] [, .Vertical = number] [, .RelativeTo = number]

Remarks

Aligns the selected drawing objects. The arguments for the Align statement correspond to the options in the Align dialog box (Align Drawing Objects button, Drawing toolbar).

Argument | Explanation
.Horizontal | Specifies a horizontal alignment: 0 (zero) None; existing horizontal positions are preserved 1 Left 2 Center 3 Right
.Vertical | Specifies a vertical alignment: 0 (zero) None; existing vertical positions are preserved 1 Top 2 Center 3 Bottom
.RelativeTo | Specifies what the objects are aligned with: 0 (zero) Each other 1 Page

Example

This example left-aligns all drawing objects within the current paragraph. Using the predefined bookmark "\Para," DrawSetRange sets the drawing object range to the paragraph containing the insertion point. For more information about predefined bookmarks, see "Operators and Predefined Bookmarks" later in this part.

DrawSetRange "\Para"
For count = 1 To DrawCount()
    DrawExtendSelect count
Next count
DrawAlign .Horizontal = 1, .Vertical = 0, .RelativeTo = 0

See Also

DrawCount(), DrawExtendSelect, DrawSelect, DrawSetRange, FormatDrawingObject


DrawArc

Syntax

DrawArc

Remarks

Switches to page layout view and adds a default arc drawing object in front of the current text layer. A default arc is shaped and oriented like the lower-left portion of a circle and is inserted at the upper-left corner of the current page.

See Also

DrawEllipse, DrawFlipHorizontal, DrawFlipVertical, DrawGetType(), DrawLine, DrawRotateLeft, DrawRotateRight, FormatDrawingObject


DrawBringForward

Syntax

DrawBringForward

Remarks

Moves the selected drawing object in front of the next one in a stack of drawing objects. DrawBringForward does not move a drawing object from the layer behind text to the layer in front of text. An error occurs if the selection is not a drawing object.

See Also

DrawBringInFrontOfText, DrawBringToFront, DrawSendBackward, DrawSendBehindText, DrawSendToBack


DrawBringInFrontOfText

Syntax

DrawBringInFrontOfText

Remarks

Moves the selected drawing object from the layer behind text to the layer in front of text. The object is placed behind any other drawing objects already in front of the text layer. An error occurs if the object is already part of the drawing layer above text or if the selection is not a drawing object.

See Also

DrawBringForward, DrawBringToFront, DrawSendBackward, DrawSendBehindText, DrawSendToBack


DrawBringToFront

Syntax

DrawBringToFront

Remarks

Moves the selected drawing object to the topmost position in a stack of drawing objects. BringToFront does not move a drawing object from the layer behind text to the layer in front of text. An error occurs if the selection is not a drawing object.

See Also

DrawBringForward, DrawBringInFrontOfText, DrawSendBackward, DrawSendBehindText, DrawSendToBack


DrawCallout

Syntax

DrawCallout

Remarks

Inserts a callout drawing object in front of the current text layer at the upper-left corner of the document. A callout consists of a text box and a line segment within a bounding rectangle. When you first insert a callout, the text box is the same size as the bounding rectangle, so the line segment does not appear. You change the size of the text box with the DrawSetCalloutTextbox statement.

To change the size and position of the rectangle bounding the callout, as well as the fill color and line style, use FormatDrawingObject. You can change other options for the callout with FormatCallout.

Example

This example inserts and formats a callout that points to the left. The DrawCallout instruction inserts a default callout whose type is set by the FormatCallout instruction. The FormatDrawingObject instruction then positions and sizes the callout and adds a fill color. Coordinates for the text box within the callout are defined in the two-dimensional array calloutpts$() and then applied using DrawSetCalloutTextbox. Finally, text is inserted into the callout.

DrawCallout
FormatCallout .Type = 1, .Gap = "10 pt", .Angle = 4, \
    .Drop = "Center", .Length = "100 pt", .Border = 1, \
    .AutoAttach = 0, .Accent = 0
FormatDrawingObject .FillColor = 0, .FillPatternColor = 7, \
    .FillPattern = 5, .ArrowStyle = 2, \
    .HorizontalPos = "173 pt", .HorizontalFrom = 1, \
    .VerticalPos = "100 pt", .VerticalFrom = 1, \
    .Height = "42 pt", .Width = "161 pt"
Dim calloutpts$(2, 2)
calloutpts$(1, 1) = "63 pt"
calloutpts$(1, 2) = "0 pt"
calloutpts$(2, 1) = "97 pt"
calloutpts$(2, 2) = "42 pt"
DrawSetCalloutTextbox calloutpts$()
Insert "This callout points to the left."

See Also

DrawGetCalloutTextbox, DrawSetCalloutTextbox, DrawTextBox, FormatCallout, FormatDrawingObject


DrawClearRange

Syntax

DrawClearRange

Remarks

Clears a drawing range. For more information about drawing ranges, see DrawSetRange.

See Also

DrawSetRange


DrawCount()

Syntax

DrawCount()

Remarks

Returns the number of drawing objects whose anchors are in the range set by DrawSetRange.

Example

This example displays a message box showing the number of drawing objects in the active document:

DrawSetRange "\Doc"
numobjects = DrawCount()
MsgBox "There are" + Str$(numobjects) + " drawing objects" + \
        " in the document."

See Also

DrawGetType(), DrawSetRange


DrawCountPolyPoints()

Syntax

DrawCountPolyPoints([Object])

Remarks

Returns the number of points in a freeform drawing object. If the specified object is not a freeform shape, an error occurs.

Argument | Explanation
Object | Specifies a drawing object: Omitted The selected drawing object > 0 (zero) An object whose anchor is in a range set by the DrawSetRange statement, where 1 is the first object in the range, 2 is the second object, and so on. If the number is not in the range 1 to DrawCount(), an error occurs.

Example

This example determines whether the first two drawing objects in the document are freeform shapes. If they are, the points of the first freeform drawing object are loaded into the array pointsArray() and applied to the second freeform drawing object.

DrawSetRange "\Doc"
If DrawGetType(1) = 7 And DrawGetType(2) = 7 Then
    size = DrawCountPolyPoints(1)
    Dim pointsArray(size, 2)
    DrawGetPolyPoints pointsArray(), 1
    DrawSetPolyPoints size, pointsArray(), 2
Else
    MsgBox "The first or second drawing object is " + \
        "not a freeform shape."
End If

See Also

DrawFreeformPolygon, DrawGetPolyPoints, DrawSetPolyPoints


DrawDisassemblePicture

Syntax

DrawDisassemblePicture

Remarks

Converts the selected graphic into a group of drawing objects. If the selected graphic cannot be disassembled, Word inserts it into a text box drawing object. If a graphic is not selected, an error occurs.

See Also

DrawGroup, DrawUngroup


DrawEllipse

Syntax

DrawEllipse

Remarks

Switches to page layout view and adds a default elliptical drawing object in front of the current text layer. A default elliptical drawing object is a circle and is inserted at the upper-left corner of the current page.

See Also

DrawGetType(), DrawRoundRectangle, FormatDrawingObject


DrawExtendSelect

Syntax

DrawExtendSelect Count

Remarks

Selects the drawing object specified by Count, whose anchor is within the drawing range set by the DrawSetRange statement. Count is the position of the drawing object relative to the text layer: 1 corresponds to the object closest to the text layer, 2 to the next object, and so on. If one or more drawing objects are already selected, the drawing object specified by Count is added to the group of selected objects. If no drawing range has been set, or if Count is greater than the number of objects whose anchors are within the range, an error occurs.

See Also

DrawGroup, DrawSelect


DrawFlipHorizontal

Syntax

DrawFlipHorizontal

Remarks

Flips the selected drawing object from left to right. DrawFlipHorizontal works only on objects drawn using the Drawing toolbar; an error occurs if the selected object is an embedded object.

See Also

DrawFlipVertical, DrawRotateLeft, DrawRotateRight


DrawFlipVertical

Syntax

DrawFlipVertical

Remarks

Flips the selected drawing object from top to bottom. DrawFlipVertical works only on objects drawn using the Drawing toolbar; an error occurs if the selected object is an embedded object.

See Also

DrawFlipHorizontal, DrawRotateLeft, DrawRotateRight


DrawFreeformPolygon

Syntax

DrawFreeformPolygon

Remarks

Switches to page layout view and adds a default freeform drawing object in front of the text layer. A default freeform shape consists of a single line segment and is inserted at the upper-left corner of the current page. To change the freeform shape, you use the DrawSetPolyPoints statement.

Example

This example adds an N-shaped drawing object in front of the text layer by inserting a default freeform drawing object and then using DrawSetPolyPoints to change it. Because the lines in an N shape have four end points, eight elements must be assigned to the pointsArray$() array (four pairs of two values). End points are measured relative to the upper-left corner of the current page.

DrawFreeformPolygon
Dim pointsArray$(4, 2)
pointsArray$(1, 1) = "150 pt"
pointsArray$(1, 2) = "200 pt"
pointsArray$(2, 1) = "150 pt"
pointsArray$(2, 2) = "100 pt"
pointsArray$(3, 1) = "200 pt"
pointsArray$(3, 2) = "200 pt"
pointsArray$(4, 1) = "200 pt"
pointsArray$(4, 2) = "100 pt"
DrawSetPolyPoints 4, pointsArray$()

See Also

DrawCountPolyPoints(), DrawGetPolyPoints, DrawSetPolyPoints, FormatDrawingObject


DrawGetCalloutTextbox

Syntax

DrawGetCalloutTextbox TwoDimensionalArray[$]() [, Object]

Remarks

Fills a two-dimensional array with coordinates that describe the position and size of the text area within the bounding rectangle of the specified callout drawing object.

Argument | Explanation
TwoDimensionalArray[$]() | The predefined two-dimensional array to fill with the coordinates of the specified callout text box. TwoDimensionalArray[$]() may be a string or numeric array. A string array is filled with text measurements consisting of a number followed by the abbreviation for the default measurement unit. A numeric array is filled with the numbers only. For example, given an array pts() defined with the instruction Dim pts(2, 2), the instruction DrawGetCalloutTextbox pts() fills the array as follows: pts(1, 1) The horizontal position (the distance from the left edge of the bounding rectangle to the text area), in the default measurement unit pts(1, 2) The vertical position (the distance from the top edge of the bounding rectangle to the text area) pts(2, 1) The width of the text area pts(2, 2) The height of the text area
Object | Specifies a drawing object: Omitted The selected drawing object > 0 (zero) An object whose anchor is in a range set by the DrawSetRange statement, where 1 is the first object in the range, 2 is the second object, and so on. If the number is not in the range 1 to DrawCount(), an error occurs. If the specified drawing object is not a callout, an error occurs.

Example

This example displays a message box showing the horizontal position, vertical position, width, and height of the text area within the selected callout:

Dim pts$(2, 2)
DrawGetCalloutTextbox pts$()
msg$ = "HorizPos: " + pts$(1, 1) + Chr$(13)
msg$ = msg$ + "VertPos: " + pts$(1, 2) + Chr$(13)
msg$ = msg$ + "Width: " + pts$(2, 1) + Chr$(13)
msg$ = msg$ + "Height: " + pts$(2, 2) + Chr$(13)
MsgBox msg$, "Text Area In Callout"

See Also

DrawCallout, DrawSetCalloutTextbox, DrawSetInsertToTextbox


DrawGetPolyPoints

Syntax

DrawGetPolyPoints TwoDimensionalArray[$]() [, Object]

Remarks

Fills a two-dimensional array with coordinates of the end points in the specified freeform drawing object. If the specified object is not a freeform shape, an error occurs. You can use the array as an argument for DrawSetPolyPoints to apply the coordinates to another freeform drawing object. You must define the array before running DrawGetPolyPoints; use DrawCountPolyPoints() to determine the appropriate size for the array.

Argument | Explanation
TwoDimensionalArray[$]() | The predefined two-dimensional array to fill with the coordinates of the specified freeform drawing object. TwoDimensionalArray[$]() may be a string or numeric array. A string array is filled with text measurements consisting of a number followed by the abbreviation for the default measurement unit. A numeric array is filled with the numbers only.
Object | Specifies a drawing object: Omitted The selected drawing object > 0 (zero) An object whose anchor is in a range set by the DrawSetRange statement, where 1 is the first object in the range, 2 is the second object, and so on. If the number is not in the range 1 to DrawCount(), an error occurs.

Example

This example stores the coordinates of the selected freeform drawing object in the array pointsArray(). If a freeform drawing object is not selected, an error occurs.

If DrawGetType() = 7 Then
    size = DrawCountPolyPoints()
    Dim pointsArray(size, 2)
    DrawGetPolyPoints pointsArray()
Else
    MsgBox "The selected drawing object is not a freeform shape."
End If

For another example, see DrawCountPolyPoints().

See Also

DrawCountPolyPoints(), DrawFreeformPolygon, DrawSetPolyPoints


DrawGetType()

Syntax

DrawGetType([Count])

Remarks

Returns a number corresponding to the type of the drawing object specified by Count. Count is in the range 1 to DrawCount(), the number of objects within a range specified by DrawSetRange. If Count is omitted, the type of the selected drawing object is returned.

DrawGetType() returns the following values.

Value | Explanation
0 (zero) | Count is not specified and a drawing object is not selected.
1 | Count is not specified and more than one drawing object is selected.
2 | The drawing object is a line.
3 | The drawing object is a text box.
4 | The drawing object is a rectangle.
5 | The drawing object is an ellipse.
6 | The drawing object is an arc.
7 | The drawing object is a freeform shape.
8 | The drawing object is a callout.

Example

This example sets the drawing range to the entire document using the predefined bookmark " \ Doc," counts the number of arcs in the document, and then displays the result in a message box:

DrawSetRange "\Doc"
numarcs = 0
For i = 1 To DrawCount()
    type = DrawGetType(i)
    If type = 6 Then numarcs = numarcs + 1
Next
MsgBox "The document contains" + Str$(numarcs) + " arc(s)."

See Also

DrawCount(), DrawSelect, DrawSetRange


DrawGroup

Syntax

DrawGroup

Remarks

Groups the selected drawing objects so they can be manipulated as a single object.

Example

This example sets the drawing range to the current paragraph and then selects each object whose anchor is in the range. If the number of objects in the range is greater than one, they are grouped together.

DrawSetRange "\Para"
numobjects = DrawCount()
For i = 1 To numobjects
    DrawExtendSelect i
Next i
If numobjects > 1 Then DrawGroup

See Also

DrawDisassemblePicture, DrawExtendSelect, DrawSelect, DrawSetRange, DrawUngroup


DrawInsertWordPicture

Syntax

DrawInsertWordPicture

Remarks

Opens a temporary document (a Word Picture object) and displays the Picture and Drawing toolbars. When the user closes the document or clicks Close Picture on the Picture toolbar, the object is embedded in the document that was active when DrawInsertWordPicture was run. The instruction DrawInsertWordPicture is the same as the instruction InsertObject .Class = "Word.Picture.6".

See Also

InsertDrawing, InsertObject, InsertPicture


DrawLine

Syntax

DrawLine

Remarks

Adds a default linear drawing object in front of the current text layer. The default line segment is inserted at the upper-left corner of the current page.

See Also

DrawArc, DrawFlipHorizontal, DrawFlipVertical, DrawFreeformPolygon, DrawGetType(), DrawRotateLeft, DrawRotateRight, FormatDrawingObject


DrawNudgeDown

Syntax

DrawNudgeDown

Remarks

Moves the selected drawing object or objects down 10 pixels or, if Snap To Grid is selected in the Snap To Grid dialog box (Drawing toolbar), moves the selected objects down by the measurement in the Vertical Spacing box.

See Also

DrawNudgeDownPixel, DrawNudgeLeft, DrawNudgeRight, DrawNudgeUp, DrawSnapToGrid


DrawNudgeDownPixel

Syntax

DrawNudgeDownPixel

Remarks

Moves the selected drawing object or objects down one pixel (the smallest unit on the screen).

See Also

DrawNudgeDown, DrawNudgeLeftPixel, DrawNudgeRightPixel, DrawNudgeUpPixel


DrawNudgeLeft

Syntax

DrawNudgeLeft

Remarks

Moves the selected drawing object or objects left 10 pixels or, if Snap To Grid is selected in the Snap To Grid dialog box (Drawing toolbar), moves the selected objects left by the measurement in the Horizontal Spacing box.

See Also

DrawNudgeDown, DrawNudgeLeftPixel, DrawNudgeRight, DrawNudgeUp, DrawSnapToGrid


DrawNudgeLeftPixel

Syntax

DrawNudgeLeftPixel

Remarks

Moves the selected drawing object or objects left one pixel (the smallest unit on the screen).

See Also

DrawNudgeLeft, DrawNudgeDownPixel, DrawNudgeRightPixel, DrawNudgeUpPixel


DrawNudgeRight

Syntax

DrawNudgeRight

Remarks

Moves the selected drawing object or objects right 10 pixels or, if Snap To Grid is selected in the Snap To Grid dialog box (Drawing toolbar), moves the selected objects right by the measurement in the Horizontal Spacing box.

See Also

DrawNudgeDown, DrawNudgeLeft, DrawNudgeRightPixel, DrawNudgeUp, DrawSnapToGrid


DrawNudgeRightPixel

Syntax

DrawNudgeRightPixel

Remarks

Moves the selected drawing object or objects right one pixel (the smallest unit on the screen).

See Also

DrawNudgeDownPixel, DrawNudgeLeftPixel, DrawNudgeRight, DrawNudgeUpPixel


DrawNudgeUp

Syntax

DrawNudgeUp

Remarks

Moves the selected drawing object or objects up 10 pixels or, if Snap To Grid is selected in the Snap To Grid dialog box (Drawing toolbar), moves the selected objects up by the measurement in the Vertical Spacing box.

See Also

DrawNudgeDown, DrawNudgeLeft, DrawNudgeRight, DrawNudgeUpPixel, DrawSnapToGrid


DrawNudgeUpPixel

Syntax

DrawNudgeUpPixel

Remarks

Moves the selected drawing object or objects up one pixel (the smallest unit on the screen).

See Also

DrawNudgeDownPixel, DrawNudgeLeftPixel, DrawNudgeRightPixel, DrawNudgeUp


DrawRectangle

Syntax

DrawRectangle

Remarks

Adds a default rectangular drawing object in front of the current text layer. A default rectangle is a square and is inserted at the upper-left corner of the current page.

See Also

DrawFreeformPolygon, DrawRoundRectangle, DrawTextBox, FormatDrawingObject


DrawResetWordPicture

Syntax

DrawResetWordPicture

Remarks

Resets the boundaries in a Word Picture object to include all drawing objects in the picture editing window. If the active window is not a picture editing window, an error occurs.

See Also

DrawInsertWordPicture, FileClosePicture


DrawReshape

Syntax

DrawReshape

Remarks

Toggles the handles on the selected freeform drawing object between the bounding rectangle (where you use the handles to scale or resize the object) and the vertices of the freeform shape (where you use the handles to reshape the object). You can select multiple freeform drawing objects before running DrawReshape. If a freeform drawing object is not selected, an error occurs.

See Also

DrawFreeformPolygon, DrawGetType(), DrawSelect


DrawRotateLeft

Syntax

DrawRotateLeft

Remarks

Rotates the selected drawing object counterclockwise 90 degrees. DrawRotateLeft works only on objects drawn using the Drawing toolbar; an error occurs if the selected object is an embedded object.

See Also

DrawFlipHorizontal, DrawFlipVertical, DrawRotateRight


DrawSelectNext

Syntax

DrawSelectNext

Remarks

Selects the next drawing object, where "next" means next closest to the top in
a stack of drawing objects. If the topmost object is selected, Word selects the bottommost object. If a drawing object is not selected when DrawSelectNext runs, an error occurs. Note that you do not need to set a drawing range with DrawSetRange to use DrawSelectNext.

See Also

DrawExtendSelect, DrawSelect, DrawSelectPrevious


DrawSelectPrevious

Syntax

DrawSelectPrevious

Remarks

Selects the previous drawing object, where "previous" means next closest to the bottom in a stack of drawing objects. If the bottommost object is selected, Word selects the topmost object. If a drawing object is not selected when DrawSelectPrevious runs, an error occurs. Note that you do not need to set a drawing range with DrawSetRange to use DrawSelectPrevious.

See Also

DrawExtendSelect, DrawSelect, DrawSelectNext


DrawSendBackward

Syntax

DrawSendBackward

Remarks

Moves the selected drawing object behind the previous one in a stack of drawing objects. DrawSendBackward does not move a drawing object from the layer in front of text to the layer behind text. An error occurs if a drawing object is not selected.

See Also

DrawBringForward, DrawBringInFrontOfText, DrawBringToFront, DrawSendBehindText, DrawSendToBack


DrawSendBehindText

Syntax

DrawSendBehindTextxxx

Remarks

Moves the selected drawing object from the layer in front of text to the layer behind text. The object is placed in front of any other drawing objects already behind the text layer. An error occurs if the object is already part of the drawing layer behind text or if a drawing object is not selected.

See Also

DrawBringForward, DrawBringInFrontOfText, DrawBringToFront, DrawSendBackward, DrawSendToBack


DrawSendToBack

Syntax

DrawSendToBack

Remarks

Moves the selected drawing object behind all previous ones in a stack of drawing objects. DrawSendToBack does not move a drawing object from the layer in front of text to the layer behind text. An error occurs if a drawing object is not selected.

See Also

DrawBringForward, DrawBringInFrontOfText, DrawBringToFront, DrawSendBackward, DrawSendBehindText


DrawSetCalloutTextbox

Syntax

DrawSetCalloutTextbox TwoDimensionalArray[$]() [, Object]

END BREAK

Remarks

Applies the position and size stored in a two-dimensional array to the text area of the specified callout drawing object.

Argument | Explanation
TwoDimensionalArray[$]() | A two-dimensional array containing coordinates for the position and size of the text area relative to the bounding rectangle of a callout drawing object. You can use a numeric array containing values in the default measurement unit or a string array containing text measurements. For information on how values are stored in the array, see DrawGetCalloutTextbox.

Argument | Explanation
Object | Specifies a drawing object: Omitted The selected drawing object > 0 (zero) An object whose anchor is in a range set by the DrawSetRange statement, where 1 is the first object in the range, 2 is the second object, and so on. If the number is not in the range 1 to DrawCount(), an error occurs. If the specified drawing object is not a callout, an error occurs.

For an example, see DrawCallout.

See Also

DrawCallout, DrawGetCalloutTextbox, DrawSetInsertToTextbox


DrawSetInsertToAnchor

Syntax

DrawSetInsertToAnchor [Object]

Remarks

Moves the insertion point to the beginning of the paragraph to which the specified drawing object is anchored.

Argument | Explanation
Object | Specifies a drawing object: Omitted The selected drawing object > 0 (zero) An object whose anchor is in a range set by the DrawSetRange statement, where 1 is the first object in the range, 2 is the second object, and so on. If the number is not in the range 1 to DrawCount(), an error occurs.

See Also

DrawSetInsertToTextBox


DrawSetInsertToTextbox

Syntax

DrawSetInsertToTextbox [Object]

Remarks

Moves the insertion point to the text area of the specified text box or callout drawing object. If the specified object is not a text box or callout drawing object, an error occurs.

Argument | Explanation
Object | Specifies a drawing object: Omitted The selected drawing object > 0 (zero) An object whose anchor is in a range set by the DrawSetRange statement, where 1 is the first object in the range, 2 is the second object, and so on. If the number is not in the range 1 to DrawCount(), an error occurs.

Example

This example sets the drawing range to the entire document and then selects the first drawing object. If the drawing object is a text box or callout, Word moves the insertion point to the text area and inserts some text.

DrawSetRange "\Doc"
Select Case DrawGetType(1)
    Case 3                            'Text box
        DrawSetInsertToTextbox 1
        Insert "Text box text"
    Case 8                            'Callout
        DrawSetInsertToTextbox 1
        Insert "Callout text."
    Case Else
End Select

See Also

DrawCallout, DrawSelect, DrawSetInsertToAnchor, DrawTextBox


DrawSetPolyPoints

Syntax

DrawSetPolyPoints NumPoints, TwoDimensionalArray[$]() [, Object]

Remarks

Applies the coordinates stored in a two-dimensional array to the specified freeform drawing object. If the specified object is not a freeform shape, an error occurs.

Argument | Explanation
NumPoints | The number of coordinates in TwoDimensionalArray[$]() to apply to the freeform drawing object. NumPoints cannot exceed the size of the array.
TwoDimensionalArray[$]() | A two-dimensional array containing the coordinates of the end points in the freeform drawing object. You can use a numeric array containing values in the default measurement unit or a string array containing text measurements. For information on how values are stored in the array, see DrawGetPolyPoints.

Argument | Explanation
Object | Specifies a drawing object: Omitted The selected drawing object > 0 (zero) An object whose anchor is in a range set by DrawSetRange, where 1 is the first object in the range, 2 is the second object, and so on. If the number is not in the range 1 to DrawCount(), an error occurs.

For an example, see DrawCountPolyPoints().

See Also

DrawCountPolyPoints(), DrawFreeformPolygon, DrawGetPolyPoints, DrawReshape


DrawSetRange, DrawSetRange()

Syntax

DrawSetRange Bookmark$

DrawSetRange(Bookmark$)

Remarks

The DrawSetRange statement sets the drawing range to the bookmark specified by Bookmark$. A drawing range establishes the group of drawing objects that other drawing statements and functions operate on. For example, the DrawCount() function counts the number of drawing objects whose anchors are within the drawing range.

The DrawSetRange() function behaves the same as the statement and also returns –1 if the range was set or 0 (zero) if the range was not set (for example, if the specified bookmark does not exist).

It is often convenient to use predefined bookmarks when setting a drawing range. For example, you can set the drawing range to the entire document by using the instruction DrawSetRange "\Doc". For more information on predefined bookmarks, see "Operators and Predefined Bookmarks" later in this part.

Example

This example sets the drawing range to the current page, counts the number of drawing objects within the range, and then displays a message box with the result:

DrawSetRange "\Page"
n = DrawCount()
MsgBox "The current page contains" + Str$(n) + " drawing object(s)."

See Also

DrawClearRange, DrawCount(), DrawSelect


DrawSnapToGrid

Syntax

DrawSnapToGrid .SnapToGrid = number [, .XGrid = number or text] [, .YGrid = number or text] [, .XOrigin = number or text] [, .YOrigin = number or text]

Remarks

Establishes a grid that restricts where drawing objects may be positioned and how they may be sized. A grid is useful when you want to align and connect drawing objects. The arguments for DrawSnapToGrid correspond to the options in the Snap To Grid dialog box (Snap To Grid button, Drawing toolbar).

Argument | Explanation
.SnapToGrid | If 1, activates the restriction on positioning drawing objects.
.XGrid | The distance, in points or a text measurement, between vertical gridlines (in other words, the increments in which drawing objects can be positioned horizontally).
.YGrid | The distance, in points or a text measurement, between horizontal gridlines (in other words, the increments in which drawing objects can be positioned vertically).
.XOrigin | The distance, in points or a text measurement, from the left edge of the page to the vertical gridline you want Word to use when laying out all other vertical gridlines. Specifying 0 (zero) or a multiple of the .XGrid measurement has no effect.
.YOrigin | The distance, in points or a text measurement, from the top edge of the page to the horizontal gridline you want Word to use when laying out all other horizontal gridlines. Specifying 0 (zero) or a multiple of the .YGrid measurement has no effect.

See Also

DrawAlign


DrawTextBox

Syntax

DrawTextBox

Remarks

Adds a default bounded area of text to the drawing layer in front of the current text layer. A default text box is one-inch square and is inserted at the upper-left corner of the current page.

See Also

DrawCallout, DrawRectangle, DrawSetInsertToAnchor, DrawSetInsertToTextBox, FormatDrawingObject


DrawUngroup

Syntax

DrawUngroup

Remarks

Removes the association that exists between drawing objects previously associated with the DrawGroup statement, so you can move and size each object independently. If a group of drawing objects is not selected, an error occurs.

See Also

DrawExtendSelect, DrawGroup, DrawSelect


DrawUnselect

Syntax

DrawUnselect

Remarks

Deselects the selected drawing object and moves the insertion point to the beginning of the paragraph containing the corresponding anchor. If more than one drawing object is selected, DrawUnselect moves the insertion point to the first paragraph containing an anchor for at least one of the selected objects.

See Also

DrawExtendSelect, DrawSelect, DrawSelectNext, DrawSelectPrevious


DropDownFormField

Syntax

DropDownFormField

Remarks

Inserts a drop-down form field at the insertion point. DropDownFormField corresponds to the Drop-Down Form Field button on the Forms toolbar.

See Also

AddDropDownItem, CheckBoxFormField, InsertFormField, RemoveAllDropDownItems, RemoveDropDownItem, TextFormField


DropListBox

Syntax

DropListBox HorizPos, VertPos, Width, Height, ArrayVariable$(), .Identifier

Remarks

Creates a drop-down list box from which a user can select an item within a user-defined dialog box. DropListBox has the same syntax as ListBox. When a drop-down list box is dropped down, the portion that is dropped down can cover other controls in the dialog box or fall outside the dialog box.

Argument | Explanation
HorizPos, VertPos | The horizontal and vertical distance of the upper-left corner of the drop-down list box from the upper-left corner of the dialog box in increments of 1/8 and 1/12 of the System font (Windows) or the dialog font (Macintosh).
Width, Height | The width and height of the list box, in increments of 1/8 and 1/12 of the System font (Windows) or the dialog font (Macintosh). Height is the height of the list box when it is dropped down.

Argument | Explanation
ArrayVariable$() | A string array containing the items to be listed, one list box item per array element.
.Identifier | Together with the dialog record name, creates a variable whose value corresponds to the selected list box item. The form for this variable is DialogRecord.Identifier (for example, dlg.MyList). The identifier string (.Identifier minus the period) is also used by statements in a dialog function that act on the list box, such as DlgEnable and DlgVisible.

See the ListBox entry for an example of a list box.

To modify the example so that it displays a drop-down list box instead of a list box, change the ListBox instruction to DropListBox, and change the Height argument to the height of the drop-down list box when it is dropped down.

For an example of DropListBox used in a complete dialog box definition, see Begin Dialog ¼ End Dialog.

See Also

Begin Dialog ¼ End Dialog, ComboBox, DlgListBoxArray, ListBox


EditAutoText

Syntax

EditAutoText .Name = text [, .Context = number] [, .InsertAs = number] [, .Insert] [, .Add] [, .Delete]

Remarks

Inserts, adds, or deletes an AutoText entry. The arguments for the EditAutoText statement correspond to the options in the AutoText dialog box (Edit menu).

Argument | Explanation
.Name | The name of the AutoText entry.
.Context | A context for the new AutoText entry: 0 (zero) or omitted Normal template 1 Active template Note that .Context is used only when Word adds an AutoText entry. When inserting or deleting an entry, Word automatically looks for the entry first in the active template and then in the Normal template. When inserting an entry and no match is found in the active or Normal templates, Word looks in each loaded global template in the order listed in the Templates And Add-ins dialog box (File menu). You cannot delete an AutoText entry from a loaded global template.
.InsertAs | Used with .Insert to control whether the entry is inserted with its formatting: 0 (zero) or omitted Entry is inserted with formatting. 1 Entry is inserted as plain text.

You can specify only one of the following arguments.

Argument | Explanation
.Insert | Inserts the entry into the document
.Add | Stores the entry in the template (if there is no selection, an error occurs)
.Delete | Deletes the entry from the template

If you do not specify .Insert, .Add, or .Delete, Word inserts the AutoText entry.

Examples

This example selects the text of the first paragraph (not including the paragraph mark) and then defines it as an AutoText entry named "MainHead," stored in the Normal template:

StartOfDocument
EditGoTo "\Para"
CharLeft 1, 1
EditAutoText .Name = "MainHead", .Context = 0, .Add

The following example inserts the "MainHead" AutoText entry without formatting:

EditAutoText .Name = "MainHead", .InsertAs = 1, .Insert

See Also

AutoText, AutoTextName$(), CountAutoTextEntries(), GetAutoText$(), InsertAutoText, SetAutoText


EditBookmark

Syntax

EditBookmark .Name = text [, .SortBy = number] [, .Add] [, .Delete] [, .Goto]

Remarks

Adds, deletes, or selects the specified bookmark. The arguments for the EditBookmark statement correspond to the options in the Bookmark dialog box (Edit menu).

Argument | Explanation
.Name | The name of the bookmark
.SortBy | Controls how the list of bookmarks is sorted when you display the Bookmark dialog box with a Dialog or Dialog() instruction: 0 (zero) By name 1 By location

You can specify only one of the following arguments.

Argument | Explanation
.Add | Adds a bookmark at the insertion point or selection
.Delete | Deletes the bookmark
.Goto | Moves the insertion point or selection to the bookmark

If you do not specify .Add, .Delete, or .Goto, Word adds the bookmark.

Example

This example searches for a paragraph containing only the word "Index" (that is, the heading for the index), and then, if the heading is found, adds a bookmark in front of it. You could use this bookmark in another EditBookmark instruction or with EditGoTo to move the insertion point to the index.

StartOfDocument
EditFind .Find = "^pIndex^p", .MatchCase = 1, \
    .Direction = 0, .Format = 0
If EditFindFound() Then
    CharLeft : CharRight
    EditBookmark .Name = "Index", .Add
End If

See Also

BookmarkName$(), CmpBookmarks(), CopyBookmark, CountBookmarks(), EditGoTo, EmptyBookmark(), ExistingBookmark(), GetBookmark$(), SetEndOfBookmark, SetStartOfBookmark


EditButtonImage

Syntax

EditButtonImage Toolbar$, Position [, Context]

Remarks

Runs the button image editor to modify the specified toolbar button image.

Argument | Explanation
Toolbar$ | The name of the toolbar as listed in the Toolbars dialog box (View menu).
Position | A number corresponding to the position of the button whose image you want to edit, where 1 is the first position, 2 is the second, and so on. Note that a list box or space counts as one position.
Context | Determines where the new button image is stored: 0 (zero) or omitted Normal template 1 Active template

Example

This example opens the image editor and displays the first button image on the Standard toolbar for editing:

EditButtonImage "Standard", 1, 0

See Also

ChooseButtonImage, CopyButtonImage, PasteButtonImage, ResetButtonImage


EditClear

Syntax

EditClear [Count]

Remarks

Deletes the selection or a specified number of characters. Unlike EditCut, EditClear does not change the contents of the Clipboard.

Argument | Explanation
Count | Specifies the number and location of characters to delete: > 0 (zero) Deletes characters to the right of the insertion point. Omitted Deletes the selection or the character to the right of the insertion point. < 0 (zero) Deletes characters to the left of the insertion point. If Count is nonzero and there is a selection, Word deletes the selection and counts it as one character against Count. Note that EditClear 0 has no effect.

Note

In Word version 6.0, if EditClear deletes a paragraph mark, the combined paragraphs are formatted with the style of the remaining paragraph mark. In Word version 7.0, the combined paragraphs are formatted with the style of the deleted paragraph mark. For compatibility, in Word version 6.0 macros converted to Word version 7.0, the EditClear statement is changed to WW6_EditClear, which maintains the Word version 6.0 behavior.

Example

This example deletes five characters to the right of the insertion point or, if there is a selection, deletes the selection plus four characters:

EditClear 5

See Also

EditCut


EditConvertAllEndnotes

Syntax

EditConvertAllEndnotes

Remarks

Converts all endnotes in the active document to footnotes. An error occurs if there are no endnotes.

Example

This example converts all endnotes to footnotes. If WordBasic error 509 ("This command is not available") occurs, the error handler displays the message "No endnotes to convert" instead of the standard WordBasic error message. Other error conditions generate standard messages.

On Error Goto trap
EditConvertAllEndnotes
trap:
Select Case Err
    Case 509 : MsgBox "No endnotes to convert."
    Case Else : Error Err
End Select

See Also

EditConvertAllFootnotes, EditConvertNotes, EditSwapAllNotes


EditConvertAllFootnotes

Syntax

EditConvertAllFootnotes

Remarks

Converts all footnotes in the active document to endnotes. An error occurs if there are no footnotes. For an example using a similar statement, see EditConvertAllEndnotes.

See Also

EditConvertAllEndnotes, EditConvertNotes, EditSwapAllNotes


EditConvertNotes

Syntax

EditConvertNotes

Remarks

Converts the selected footnotes to endnotes, or vice versa. An error occurs if the insertion point or selection is not in the footnote or endnote pane, or if there are no notes in the pane.

See Also

EditConvertAllEndnotes, EditConvertAllFootnotes, EditSwapAllNotes


EditCopy

Syntax

EditCopy

Remarks

Copies the selection to the Clipboard. If there is no selection, an error occurs.

See Also

EditCut, EditPaste, EditPasteSpecial


EditCopyAsPicture

Syntax

EditCopyAsPicture

Remarks

On the Macintosh, copies the selected text or object to the Clipboard as a picture. In Windows, EditCopyAsPicture is not available and generates an error.

See Also

EditCopy, EditPasteSpecial


EditCreatePublisher

Syntax

EditCreatePublisher .FileName = text [, .Appearance = number] [, .Rtf = number] [, .Pict = number]

Remarks

On the Macintosh, publishes the selected text in an edition, which you can then subscribe to in other documents. The arguments for the EditCreatePublisher statement correspond to the options in the Create Publisher dialog box (Publishing command, Edit menu). In Windows, EditCreatePublisher is not available and generates an error.

Argument | Explanation
.FileName | The path and filename for the new edition.
.Appearance | Specifies how the selection is published: 0 (zero) or omitted As shown on screen 1 As shown when printed
.Rtf | If 1, allows the publisher to export rich-text format (RTF).
.Pict | If 1, allows the publisher to export a picture format (PICT).

See Also

EditLinks, EditPasteSpecial, EditPublishOptions, EditSubscribeOptions, EditSubscribeTo


EditCut

Syntax

EditCut

Remarks

Removes the selection from the document and places it on the Clipboard. If there is no selection, an error occurs.

See Also

EditClear, EditCopy, EditPaste, EditPasteSpecial, Spike


EditFind

Syntax

EditFind [.Find = text] [, .Replace = text] [, .Direction = number] [, .WholeWord = number] [, .MatchCase = number] [, .PatternMatch = number] [, .SoundsLike = number]
[, .FindAllWordForms = number] [, .Format = number] [, .Wrap = number]

Remarks

Finds the next instance of the specified text, formatting, or both. The arguments for the EditFind statement correspond to the options in the Find dialog box (Edit menu). Used in a While ¼ Wend loop, EditFind can be extremely useful when you need to repeat a series of instructions each time a certain piece of text or formatting is found in your document. Many examples in "Statements and Functions" illustrate this common use of EditFind.

Argument | Explanation
.Find | The text to find, or, to search for formatting only, an empty string (""). You can search for special characters, such as paragraph marks, by specifying appropriate character codes. For example, "^p" corresponds to a paragraph mark and "^t" corresponds to a tab character. If .PatternMatch is set to 1, you can specify wildcard characters and other advanced search criteria. For example, "*(ing)" finds any word ending in "ing." To search for a symbol character, specify the symbol's character code following a caret (^) and a zero (0). In Windows, for example, "^0151" corresponds to an em dash ( — ).
.Replace | You may need to set .Replace to an empty string ("") to avoid an error. For example, if you set .PatternMatch to 1 and the replacement text currently in the Replace dialog box is not valid with pattern matching on, an error occurs.
.Direction | The direction to search: 0 (zero) Searches toward the end of the document. 1 Searches toward the beginning of the document. The default is the direction used in the previous search or 0 (zero) the first time the Find or Replace command is run.
.WholeWord | If 1, corresponds to selecting the Find Whole Words Only check box.
.MatchCase | If 1, corresponds to selecting the Match Case check box.
.PatternMatch | If 1, Word evaluates .Find as a string containing advanced search criteria such as the asterisk (*) and question mark (?) wildcard characters (corresponds to selecting the Use Pattern Matching check box).
.SoundsLike | If 1, corresponds to selecting the Sounds Like check box.
.FindAllWordForms | If 1, corresponds to selecting the Find All Word Forms check box.
.Format | Finds formatting in addition to, or instead of, text: 0 (zero) Ignores formatting 1 Uses the specified formatting

Argument | Explanation
.Wrap | Controls what happens if the search begins at a point other than the beginning of the document and the end of the document is reached (or vice versa if .Direction is set to 1). The .Wrap argument also controls what happens if there is a selection and the search text is not found in the selection. 0 (zero) or omitted The search operation ends and the macro continues. 1 If there is a selection, Word searches the remainder of the document. If the beginning or the end of the document is reached, Word continues the search from the opposite end. 2 If there is a selection, Word displays a message asking whether to search the remainder of the document. If the beginning or the end of the document is reached, Word displays a message asking whether to continue the search from the opposite end.

Formatting is not specified within the EditFind instruction itself. Instead, you precede EditFind with one or more EditFindBorder, EditFindFont, EditFindLang, EditFindPara, EditFindStyle, or EditFindTabs instructions. Then, in the EditFind instruction, you set .Format to 1. Note that EditFindBorder and EditFindTabs are available only on the Macintosh.

Here are some tips for using EditFind effectively:

  • EditFind retains whatever settings were used in the most recent find or replace operation. For example, if the Find Whole Words Only check box was selected in the Find dialog box in the last find operation (or if the .WholeWord argument was set to 1), .WholeWord will still be set to 1 in the new find operation — unless you explicitly set it to 0 (zero). Before beginning a find operation, make sure to specify every option that can affect the outcome of a search.
  • When you search for formatting, it's a good idea to include the statement EditFindClearFormatting before specifying the formats you want to find. That way, you clear any formats left over from previous find or replace operations.
  • When repeating an operation for each occurrence of a piece of text or formatting in the document using a While ¼ Wend loop, remember to use StartOfDocument before the first EditFind instruction. You should either omit the .Wrap argument or set it to 0 (zero). If you set .Wrap to 1, you may create an endless loop. If you set .Wrap to 2, Word displays a message asking if you'd like to continue from the beginning of the document; you must choose No to keep the macro running.

Examples

This example finds the next instance of "Trey Research" with single-underline formatting:

EditFindClearFormatting            'Clear leftover formats
EditFindFont .Underline = 1
EditFind .Find = "Trey Research", .Direction = 0, \
    .WholeWord = 0, .MatchCase = 0, .Format = 1

The following example inserts the string "Tip: " at the beginning of every Heading 6 paragraph. The instructions StartOfDocument and While EditFindFound() are key to any macro that repeats a series of actions each time the specified item is found.

StartOfDocument
EditFindClearFormatting
EditFindStyle .Style = "Heading 6"
EditFind .Find = "", .Direction = 0, .Format = 1, .Wrap = 0
While EditFindFound()
    StartOfLine
    Insert "Tip: "
    EditFindStyle .Style = "Heading 6"
    EditFind .Find = "", .Direction = 0, .Format = 1, .Wrap = 0
Wend

See Also

EditFindClearFormatting, EditFindBorder, EditFindFont, EditFindFound(), EditFindFrame, EditFindLang, EditFindPara, EditFindStyle, EditFindTabs, EditReplace


EditFindBorder

Syntax

EditFindBorder [.ApplyTo = number] [, .Shadow = number] [, .TopBorder = number] [, .LeftBorder = number] [, .BottomBorder = number] [, .RightBorder = number] [, .HorizBorder = number] [, .VertBorder = number] [, .TopColor = number] [, .LeftColor = number] [, .BottomColor = number] [, .RightColor = number] [, .HorizColor = number] [, .VertColor = number] [, .FineShading = number] [, .FromText = number or text] [, .Shading = number] [, .Foreground = number] [, .Background = number] [, .Tab = number]

Remarks

On the Macintosh, when followed by an EditFind or EditReplace instruction in which .Format is set to 1, specifies the borders or shading applied to the text you want to find. For argument descriptions, see FormatBordersAndShading. In Windows, EditFindBorder is not available and generates an error.

See Also

EditFind, EditFindClearFormatting, EditFindFrame, EditFindLang, EditFindPara, EditFindStyle, EditFindTabs, EditReplace, EditReplaceBorder, FormatBordersAndShading


EditFindClearFormatting

Syntax

EditFindClearFormatting

Remarks

Clears any formats specified for text to be found. Before specifying formats with EditFindFont, EditFindPara, and so on, it's a good idea to include the EditFindClearFormatting statement to ensure that any unwanted formats are not included in the specification.

Example

The EditFindClearFormatting statement in this example ensures that the only formats specified are bold and italic:

EditFindClearFormatting
EditFindFont .Bold = 1, .Italic = 1
EditFind .Find = "", .Format = 1

See Also

EditFind, EditFindBorder, EditFindFont, EditFindFrame, EditFindLang, EditFindPara, EditFindStyle, EditFindTabs, EditReplace, EditReplaceClearFormatting


EditFindFont

Syntax

EditFindFont [.Points = number] [, .Underline = number] [, .Color = number] [, .Strikethrough = number] [, .Superscript = number] [, .Subscript = number] [, .Shadow = number] [, .Hidden = number] [, .SmallCaps = number] [, .AllCaps = number] [, .Outline = number] [, .Spacing = number] [, .Position = number or text] [, .Kerning = number] [, .KerningMin = number or text] [, .Default] [, .Tab = number] [, .Font = text] [, .Bold = number] [, .Italic = number]

Remarks

When followed by an EditFind or EditReplace instruction in which .Format is set to 1, specifies the character formatting of the text you want to find. You can set .Strikethrough, .Superscript, .Subscript, .Shadow, .Hidden, .SmallCaps, .AllCaps, .Outline, .Kerning, .Bold, and .Italic to one of the three following values.

Use this value | To do this
–1 | Find text regardless of whether it has the format
0 (zero) | Find text that does not have the format
1 | Find text that has the format

Note that .Shadow and .Outline are available only on the Macintosh. For more information on the arguments, see FormatFont.

Examples

This example finds the next instance of any text that is bold:

EditFindClearFormatting
EditFindFont .Bold = 1
EditFind .Find = "", .Format = 1

The following example finds the next instance of the word "Note" that is not bold:

EditFindClearFormatting
EditFindFont .Bold = 0
EditFind .Find = "Note", .Format = 1

The following example finds the next instance of "Note" whether or not it is bold. Normally, you use EditFindClearFormatting to remove formatting specifications from a search operation. With the instruction EditFindFont .Bold = –1, you can remove the specification for bold without affecting other search formats set previously.

EditFindFont .Bold = –1
EditFind .Find = "Note", .Format = 1

See Also

EditFind, EditFindBorder, EditFindClearFormatting, EditFindFrame, EditFindLang, EditFindPara, EditFindStyle, EditFindTabs, EditReplace, EditReplaceFont, FormatFont


EditFindFound()

Syntax

EditFindFound()

Remarks

Returns a value indicating whether the most recent EditFind operation was successful.

Value | Explanation
–1 | The find operation was successful.
0 (zero) | The find operation was not successful.

Example

This macro counts the number of times "pillbox" occurs in a document and then displays the result in a message box. EditFindFound() is often used with a While ¼ Wend loop to repeat a series of instructions each time the specified text or formatting is found.

Sub MAIN
count = 0
StartOfDocument
EditFind .Find = "pillbox", .WholeWord = 1, .Format = 0, .Wrap = 0
While EditFindFound()
    count = count + 1
    EditFind
Wend
MsgBox "The word " + Chr$(34) + "pillbox" + Chr$(34) + \
    " was found" + Str$(count) + " times."
End Sub

See Also

EditFind, EditReplace, While ¼ Wend


EditFindFrame

Syntax

EditFindFrame [.Wrap = number] [, .WidthRule = number] [, .FixedWidth = number or text] [, .HeightRule = number] [, .FixedHeight = number or text] [, .PositionHorz = number or text] [, .PositionHorzRel = number] [, .DistFromText = number or text] [, .PositionVert = number or text] [, .PositionVertRel = number] [, .DistVertFromText = number or text] [, .MoveWithText = number] [, .LockAnchor = number]

Remarks

On the Macintosh, when followed by an EditFind or EditReplace instruction in which .Format is set to 1, specifies the frame formatting of the text you want to find. For information on the arguments, see FormatFrame. In Windows, EditFindFrame is not available and generates an error.

See Also

EditFind, EditFindBorder, EditFindFont, EditFindLang, EditFindPara, EditFindStyle, EditFindTabs, EditReplaceFrame, FormatFrame


EditFindHighlight

Syntax

EditFindHighlight

Remarks

When followed by an EditFind or EditReplace instruction in which .Format is set to 1, specifies that the text you want to find is highlighted. Word finds any text that has been highlighted, even if different colors of highlight have been used in the same document. In Word version 6.0, EditFindHighlight is unavailable and generates an error.

Example

This example finds all instances of highlighted text in the document, removes the highlight, and applies bold formatting to that text.

EditFindClearFormatting
EditReplaceClearFormatting
EditFindHighlight
EditReplaceFont .Bold = 1
EditReplaceNotHighlight
EditReplace .Find = "", .Replace = "", .Format = 1, .ReplaceAll

See Also

EditFind, EditReplaceHighlight, Highlight, HighlightColor, ToolsOptionsRevisions


EditFindLang

Syntax

EditFindLang .Language = text

Remarks

When followed by an EditFind or EditReplace instruction in which .Format is set to 1, specifies the language formatting of the text you want to find. Although the Language command (Tools menu) lists the names of languages in their English form, the text for .Language must be in the specified language and include any accented characters (for example, Italian must be specified as "Italiano" and French must be specified as "Français"). For a list of valid foreign language names, see ToolsLanguage.

Example

This example formats all occurrences of German text with italic. Note that the instruction EditReplaceLang .Language = "Deutsch" is required to preserve the language formatting of the found text.

EditFindClearFormatting
EditReplaceClearFormatting
EditFindLang .Language = "Deutsch"
EditReplaceLang .Language = "Deutsch"
EditReplaceFont .Italic = 1
EditReplace .Find = "", .Replace = "", .Format = 1, \
    .ReplaceAll, .Wrap = 1

See Also

EditFind, EditFindBorder, EditFindFont, EditFindFrame, EditFindPara, EditFindStyle, EditFindTabs, EditReplace, EditReplaceLang, Language, ToolsLanguage


EditFindNotHighlight

Syntax

EditFindNotHighlight

Remarks

When followed by an EditFind or EditReplace instruction in which .Format is set to 1, specifies that the text you want to find is not highlighted. In Word version 6.0, EditFindNotHighlight is unavailable and generates an error.

See Also

EditFind, EditFindHighlight, Highlight, HighlightColor, ToolsOptionsRevisions


EditFindPara

Syntax

EditFindPara [.LeftIndent = number or text] [, .RightIndent = number or text] [, .Before = number or text] [, .After = number or text] [, .LineSpacingRule = number] [, .LineSpacing = number or text] [, .Alignment = number] [, .WidowControl = number] [, .KeepWithNext = number] [, .KeepTogether = number] [, .PageBreak = number] [, .NoLineNum = number] [, .DontHyphen = number] [, .Tab = number] [, .FirstIndent = number or text]

Remarks

When followed by an EditFind or EditReplace instruction in which .Format is set to 1, specifies the paragraph formatting of the text you want to find. You can set .WidowControl, .KeepWithNext, .KeepTogether, .PageBreak, .NoLineNum, and .DontHyphen to one of the three following values.

Use this value | To do this
–1 | Find text regardless of whether it has the format
0 (zero) | Find text that does not have the format
1 | Find text that has the format

For more information on the arguments, see FormatParagraph. For an example, see EditReplacePara.

See Also

EditFind, EditFindBorder, EditFindFont, EditFindFrame, EditFindLang, EditFindStyle, EditFindTabs, EditReplace, EditReplacePara, FormatParagraph


EditFindStyle

Syntax

EditFindStyle .Style = text

Remarks

When followed by an EditFind or EditReplace instruction in which .Format is set to 1, specifies the style of the text you want to find. If the specified style does not exist in the active document, or if the capitalization does not match that of the actual style name, an error occurs.

Argument | Explanation
.Style | The name of the style you want to find; to remove a style from the specification, use an empty string ("").

Examples

This example finds and selects the next paragraph formatted with the Heading 2 style:

EditFindClearFormatting
EditFindStyle .Style = "Heading 2"
EditFind .Find = "", .Format = 1

The following example finds the next instance of the word "catnip" in a paragraph of any style. Normally, you use EditFindClearFormatting to remove formatting specifications from a search operation. With the instruction EditFindStyle .Style = "", you can remove the style specification without affecting other search formats set previously.

EditFindStyle .Style = ""
EditFind .Find = "catnip", .Format = 1

See Also

EditFind, EditFindBorder, EditFindFont, EditFindFrame, EditFindLang, EditFindPara, EditFindTabs, EditReplace, EditReplaceStyle, FormatStyle


EditFindTabs

Syntax

EditFindTabs [.Position = text] [, .Align = number] [, .Leader = number]

Remarks

On the Macintosh, when followed by an EditFind or EditReplace instruction in which .Format is set to 1, specifies tab setting for the text you want to find. For argument descriptions, see FormatTabs. In Windows, EditFindTabs is not available and generates an error.

See Also

EditFind, EditFindBorder, EditFindClearFormatting, EditFindFrame, EditFindLang, EditFindPara, EditFindStyle, EditReplace, EditReplaceTabs, FormatTabs


EditGoTo

Syntax

EditGoTo .Destination = text

Remarks

Moves the insertion point or selection to the specified location or item, such
as a page, bookmark, footnote, line, or field. To move the insertion point to
a destination listed in the following table, use the corresponding identifier in combination with a number, the plus sign (+) or minus sign (–), or a string.

Destination | Identifier | Example text for .Destination
Page | p (or omitted) | The text "p5" or "5" goes to the fifth page.
Section | s | The text "s" goes to the next section.
Line | l | The text "l+5" goes to the fifth line after the current insertion point. The plus sign (+) means count forward from the insertion point.
Bookmark | (none) | The text "Temp" goes to the bookmark "Temp."
Annotation | a | The text "a'Sara Levine'" goes to the next mark for an annotation by Sara Levine.
Footnote | f | The text "f-" goes to the previous footnote reference mark. The minus sign (–) means count backward from the insertion point.

Destination | Identifier | Example text for .Destination
Endnote | e | The text "e5" goes to the fifth endnote reference mark.
Field | d | The text "d'TIME'" goes to the next TIME field. The single quotation marks separate the field type from the identifier.
Table | t | The text "t" goes to the next table.
Graphic | g | The text "g10" goes to the tenth graphic in the document.
Equation | q | The text "q-" goes to the previous equation.
Object | o | The text "o-'WordArt'" goes to the previous Microsoft WordArt object. The single quotation marks separate the object type from the identifier.

The following table summarizes the use of numbers and the plus sign or minus sign with destination identifiers in EditGoTo instructions. Numbers and the plus sign or minus sign can be used with every type of destination except bookmarks.

Identifier and this | Result
Number | Goes to an item according to its location within the document. For example, EditGoto "l30" goes to the thirtieth line in a document; EditGoto "f200" goes to the two-hundredth footnote.
+[Number] or –[Number] | Goes to an item relative to the current location. For example, EditGoto "l+2" goes to the second line after the current line. Likewise, EditGoto "l-2" goes to the second line before the current line. The instruction EditGoto "l-" goes to the previous line; EditGoto "l+" goes to the next line.
Omitted | Goes to the next item specified. For example, EditGoto "s" goes to the next section in the document.

Example

This example counts the number of tables in the document. The bookmark "Temp" is defined at each successive insertion point location so CmpBookmarks() can determine whether the most recent EditGoTo (or RepeatFind) instruction has moved the insertion point. When RepeatFind no longer moves the insertion point — that is, when there are no more tables — Word exits the While ¼ Wend loop.

StartOfDocument
EditBookmark "Temp", .Add
count = 0
If SelInfo(12) = - 1 Then count = 1
EditGoTo .Destination = "t"
While CmpBookmarks("\Sel", "Temp") <> 0
    EditBookmark "Temp", .Add
    count = count + 1
    RepeatFind
Wend
EditBookmark "Temp", .Delete
MsgBox "There are" + Str$(count) + " tables in the document"

See Also

EditFind, GoBack, GoToNext Item, GoToPrevious Item, NextField, NextObject, NextPage, PrevField, PrevObject, PrevPage, RepeatFind


EditLinks

Syntax

EditLinks [.UpdateMode = number,] [.Locked = number,] [.SavePictureInDoc = number,] [.UpdateNow,] [.OpenSource,] [.KillLink,] .Link = text, .Application = text, .Item = text, .FileName = text

Remarks

Sets options for the specified link. The arguments for the Link statement correspond to the options in the Links dialog box (Edit menu).

Argument | Explanation
.UpdateMode | Specifies how the link is updated: 0 (zero) Automatically 1 Manually
.Locked | Specifies whether to lock or unlock the link: 0 (zero) Unlock the link 1 Lock the link
.SavePictureInDoc | If 1, saves a copy of the linked object in the Word document
.UpdateNow | Updates the specified link
.OpenSource | Opens the source of the specified link (for example, a Microsoft Excel worksheet)
.KillLink | Replaces the specified link with its most recent result
.Link | Specifies the link listed in the Links dialog box whose options are to be set: "1" corresponds to the first link in the list, "2" corresponds to the second, and so on. Note that the number must be enclosed in quotation marks. You can also use the "\ Sel" predefined bookmark to specify the currently selected link.
.Application | The type of document supplying the link, as it appears in the LINK field codes — for example, "Word.Document.6" for a Word document or "Excel.Sheet.5" for a Microsoft Excel 5.0 worksheet.
.Item | Text that identifies the linked information (for example, a bookmark name such as "INTERN_LINK2" in a Word document, or a range of cells such as R1C1:R5C3 in a Microsoft Excel worksheet)
.FileName | The path and filename of the source document containing the linked item

The last three arguments correspond to choosing the Change Source button and setting options in the Change Source dialog box.

Examples

This example unlocks an existing link to a Microsoft Excel 5.0 worksheet and makes updating automatic. On the Macintosh, substitute a path and filename such as HD:WORKSHEETS:SALES.

EditLinks .UpdateMode = 0, .Locked = 0, .Link = "\Sel", \
    .Application = "Excel.Sheet.5", .Item = "Sales Report!R1C1:R5C3", \
    .FileName = "C:\EXCEL5\EXAMPLES\SALES.XLS"

The following example selects each link between the active document and a Microsoft Excel 5.0 worksheet and makes updating manual:

StartOfDocument
ViewFieldCodes 1
EditFind "^d LINK Excel.Sheet.5", .Format = 0, .Wrap = 0
While EditFindFound()
    Dim dlg As EditLinks
    GetCurValues dlg
    dlg.UpdateMode = 1
    EditLinks dlg
    CharRight
    RepeatFind
Wend

See Also

EditPasteSpecial, EditPublishOptions, EditSubscribeOptions, InsertField, LockFields, UnlinkFields, UnlockFields


EditObject

Syntax

EditObject

Remarks

Opens the selected object linking and embedding (OLE) object for editing in the application associated with the object. OLE objects include Equation Editor equations, font effects created with WordArt, Microsoft Excel charts, and so on.

Example

This example selects the next equation in the active document and opens it for editing in the Equation Editor:

EditGoTo .Destination = "o'Equation.2'"
EditObject

See Also

ActivateObject, EditGoTo, InsertObject


EditPaste

Syntax

EditPaste

Remarks

Inserts the contents of the Clipboard at the insertion point. EditPaste replaces the selection if you select the Typing Replaces Selection check box on the Edit tab in the Options dialog box (Tools menu).

See Also

CopyText, EditCopy, EditCut, EditPasteSpecial, MoveText


EditPasteSpecial

Syntax

EditPasteSpecial [.IconNumber = number] [, .Link = number] [, .DisplayIcon = number] [, .Class = text] [, .DataType = text] [, .IconFilename = text] [, .Caption = text]

Remarks

Inserts the contents of the Clipboard at the insertion point. The arguments for the EditPasteSpecial statement correspond to the options in the Paste Special dialog box (Edit menu). Unlike EditPaste, EditPasteSpecial allows you to control the format of the pasted information and to establish a link with the information source (for example, a Microsoft Excel worksheet).

Argument | Explanation
.IconNumber | If .DisplayIcon is set to 1, a number corresponding to the icon you want to use in the program file specified by .IconFilename. Icons appear in the Change Icon dialog box (Object command, Insert menu): 0 (zero) corresponds to the first icon, 1 to the second icon, and so on. If omitted, the first (default) icon is used. On the Macintosh, icons for embedded objects cannot be changed; this argument is ignored.
.Link | Specifies whether or not to create a link: 0 (zero) or omitted No link is created. 1 A link is created.
.DisplayIcon | Specifies whether or not to display a link as an icon: 0 (zero) or omitted Link is not displayed as an icon. 1 Link is displayed as an icon.
.Class | The object class of the Clipboard contents. This argument cannot be set. However, you can define a dialog record as EditPasteSpecial and then use the dialog record to return the current value of .Class.

Argument | Explanation
.DataType | Specifies a format for the pasted contents: Bitmap Bitmap (Windows only) DIB Device Independent Bitmap (Windows only) Object Object linking and embedding (OLE) object PICT Metafile (Windows) or Word Picture (Macintosh) RTF Rich-text format Text Unformatted text Styled Formatted text that preserves font formatting (Macintosh only)
.IconFilename | If .DisplayIcon is set to 1, the path and filename of the program file in which the icon to be displayed is stored. On the Macintosh, icons for embedded objects cannot be changed; this argument is ignored.
.Caption | If .DisplayIcon is set to 1, the caption of the icon to be displayed; if omitted, Word inserts the name of the object.

Note

Not all data types are available for each Clipboard item. For example, in Windows, if the Clipboard contains a text selection from a Word document, the available data types are "Object," "PICT, "RTF," and "Text." For a selection from a Microsoft Excel worksheet, the available formats are "Bitmap," "Object," "PICT," "RTF," and "Text." If you specify an unavailable data type, an error occurs.

See Also

EditCopy, EditCreatePublisher, EditCut, EditLinks, EditPaste, EditSubscribeTo, InsertField


EditPicture

Syntax

EditPicture

Remarks

Opens the selected graphic for editing.

Example

This example goes to the next graphic and opens it for editing.

ViewFieldCodes 0
EditGoTo "g"
CharRight 1,1
EditPicture

See Also

EditObject, FormatPicture, InsertPicture, Picture


EditPublishOptions

Syntax

EditPublishOptions [.SendManually = number] [, .SendEditionNow = number] [, .SendEditionWhenEdited = number] [, .Delete] [, .Appearance = number] [, .Rtf = number] [, .Pict = number]

Remarks

On the Macintosh, sets options for the selected publisher. The arguments for the EditPublishOptions statement correspond to the options in the Publisher Options dialog box (Publishing command, Edit menu). In Windows, EditPublishOptions is not available and generates an error.

Argument | Explanation
.SendManually | Specifies how the edition is updated: 0 (zero) or omitted On Save (the edition is updated whenever a change is made to the publisher) 1 Manually (the edition is updated on demand)
.SendEditionNow | If 1, immediately updates the edition with changes in the publisher.
.SendEditionWhenEdited | If 1, updates the edition whenever changes are made to the publisher; .SendManually must be 0 (zero).
.Delete | Cancels the publisher.
.Appearance | Specifies how the publisher is published: 0 (zero) or omitted As shown on screen 1 As shown when printed
.Rtf | If 1, allows the publisher to export rich-text format (RTF).
.Pict | If 1, allows the publisher to export a picture format (PICT).

See Also

EditCreatePublisher, EditLinks, EditSubscribeOptions, EditSubscribeTo


EditRedo

Syntax

EditRedo

Remarks

Redoes the last action that was undone (reverses EditUndo).

See Also

EditRepeat, EditUndo


EditRepeat

Syntax

EditRepeat

Remarks

Repeats the most recent editing action, if possible.

See Also

EditRedo, EditUndo


EditReplace

Syntax

EditReplace [.Find = text] [, .Replace = text] [, .Direction = number] [, .MatchCase = number] [, .WholeWord = number] [, .PatternMatch = number] [, .SoundsLike = number] [, .FindAllWordForms = number] [, .FindNext] [, .ReplaceOne] [, .ReplaceAll] [, .Format = number] [, .Wrap = number]

Remarks

Replaces one or all instances of the specified text or formatting (or both) with different text or formatting. If there is a selection and .Wrap is omitted or set to 0 (zero), the .Find text is replaced only within the selection. The arguments for the EditReplace statement correspond to the options in the Replace dialog box.

Argument | Explanation
.Find | The text to find, or, to search for formatting only, an empty string (""). You can search for special characters, such as paragraph marks, by specifying appropriate character codes. For example, "^p" corresponds to a paragraph mark and "^t" corresponds to a tab character. If .PatternMatch is set to 1, you can specify wildcard characters and other advanced search criteria. For example, "*(ing)" finds any word ending in "ing." To search for a symbol character, specify the symbol's character code following a caret (^) and a zero (0). In Windows, for example, "^0151" corresponds to an em dash ( — ).
.Replace | The replacement text, or, to delete the text specified with .Find, an empty string (""). You specify special characters and advanced search criteria just as you do for .Find. To specify a graphic or other nontext item as the replacement, put the item on the Clipboard and specify "^c" for .Replace.
.Direction | The direction to search: 0 (zero) Searches toward the end of the document 1 Searches toward the beginning of the document The default is the direction used in the previous search or 0 (zero) the first time the Find or Replace command is run.
.MatchCase | If 1, corresponds to selecting the Match Case check box
.WholeWord | If 1, corresponds to selecting the Find Whole Words Only check box
.PatternMatch | If 1, Word evaluates .Find as a string containing advanced search criteria such as the asterisk (*) and question mark (?) wildcard characters (corresponds to selecting the Use Pattern Matching check box)

Argument | Explanation
.SoundsLike |  | If 1, corresponds to selecting the Sounds Like check box
.FindAllWordForms |  | If 1, corresponds to selecting the Find All Word Forms check box.
.FindNext |  | Finds the next instance of the text specified by .Find
.ReplaceOne |  | Replaces the first instance of the text specified by .Find
.ReplaceAll |  | Replaces all instances of the .Find text
.Format |  | Finds and replaces formatting in addition to, or instead of, text: 0 (zero) Ignores formatting 1 Uses the specified formatting
.Wrap |  | Controls what happens if the search begins at a point other than the beginning of the document and the end of the document is reached (or vice versa if .Direction is set to 1). The .Wrap argument also controls what happens if there is a selection and the search text is not found in the selection. 0 (zero) The replace operation ends and the macro continues. 1 If there is a selection, the replace operation continues in the remainder of the document. If the beginning or end of the document is reached, the replace operation continues from the opposite end. 2 If there is a selection, Word displays a message asking whether to continue the replace operation in the remainder of the document. If the beginning or end of the document is reached, Word displays a message asking whether to continue the replace operation from the opposite end.

Formatting is not specified within the EditReplace instruction itself. Instead, you precede EditReplace with one or more of the following statements: EditFindBorder, EditFindFont, EditFindLang, EditFindPara, EditFindStyle, EditFindTabs, EditReplaceBorder, EditReplaceFont, EditReplaceLang, EditReplacePara, EditReplaceStyle, or EditReplaceTabs. Then, in the EditReplace instruction, you set .Format to 1. Note that EditFindBorder, EditFindTabs, EditReplaceBorder, and EditReplaceTabs are available only on the Macintosh.

Here are some tips for using EditReplace effectively:

  • EditReplace retains whatever settings were used in the most recent find or replace operation. For example, if the Find Whole Words Only check box was selected in the Replace dialog box in the last replace operation (or if the .WholeWord argument was set to 1), .WholeWord will automatically be set to 1 in the new replace operation—unless you explicitly set it to 0 (zero). Before beginning a replace operation, make sure to specify every option that can affect the outcome of a search.
  • When you search for and replace formatting, it's a good idea to include the statements EditFindClearFormatting and EditReplaceClearFormatting before specifying the formats you want to find and replace. That way, you clear any formats left over from previous find or replace operations.

Example

This example finds all instances of underlined text in the document and replaces the format with italic. Note that the instruction .Wrap = 1 means no StartOfDocument statement is required; instances both before and after the insertion point are replaced.

EditFindClearFormatting
EditReplaceClearFormatting
EditFindFont .Underline = 1
EditReplaceFont .Italic = 1, .Underline = 0
EditReplace .Find = "", .Replace = "", .Format = 1, \
    .ReplaceAll, .Wrap = 1

See Also

EditFind, EditReplaceBorder, EditReplaceClearFormatting, EditReplaceFont, EditReplaceFrame, EditReplaceLang, EditReplacePara, EditReplaceStyle, EditReplaceTabs


EditReplaceBorder

Syntax

EditReplaceBorder [.ApplyTo = number] [, .Shadow = number] [, .TopBorder = number] [, .LeftBorder = number] [, .BottomBorder = number] [, .RightBorder = number] [, .HorizBorder = number] [, .VertBorder = number] [, .TopColor = number] [, .LeftColor = number] [, .BottomColor = number] [, .RightColor = number] [, .HorizColor = number] [, .VertColor = number] [, .FineShading = number] [, .FromText = number or text] [, .Shading = number] [, .Foreground = number] [, .Background = number] [, .Tab = number]

Remarks

On the Macintosh, when followed by an EditReplace instruction in which .Format is set to 1, specifies border and shading formats for the replacement text. For argument descriptions, see FormatBordersAndShading. In Windows, EditReplaceBorder is not available and generates an error.

See Also

EditFind, EditFindBorder, EditReplace, EditReplaceClearFormatting, EditReplaceFrame, EditReplaceLang, EditReplacePara, EditReplaceStyle, EditReplaceTabs, FormatBordersAndShading


EditReplaceClearFormatting

Syntax

EditReplaceClearFormatting

Remarks

Clears any formats specified for replacement text. Before specifying replacement formats with EditReplaceFont, EditReplacePara, and so on, it's a good idea to include the EditReplaceClearFormatting statement to ensure that any unwanted formats are not included in the replacement formatting. For an example, see EditReplace.

See Also

EditFindClearFormatting, EditReplace, EditReplaceBorder, EditReplaceFont, EditReplaceFrame, EditReplaceLang, EditReplacePara, EditReplaceStyle, EditReplaceTabs


EditReplaceFont

Syntax

EditReplaceFont [.Points = number] [, .Underline = number] [, .Color = number] [, .Strikethrough = number] [, .Superscript = number] [, .Subscript = number] [, .Shadow = number] [, .Hidden = number] [, .SmallCaps = number] [, .AllCaps = number] [, .Outline = number] [, .Spacing = number] [, .Position = number or text] [, .Kerning = number] [, .KerningMin = number or text] [, .Default] [, .Tab = number] [, .Font = text] [, .Bold = number] [, .Italic = number]

Remarks

When followed by an EditReplace instruction in which .Format is set to 1, specifies the character formatting of the replacement text. You can set .Strikethrough, .Superscript, .Shadow, .Subscript, .Hidden, .SmallCaps, .AllCaps, .Outline, .Kerning, .Bold, and .Italic to one of the three following values.

Use this value | To do this
–1 | Preserve the state of a given format in the found text
0 (zero) | Remove the given format from the found text
1 | Apply the given format to the found text

Note that .Shadow and .Outline are available only on the Macintosh. For more information on the arguments, see FormatFont. For an example, see EditFindLang.

See Also

EditFindFont, EditReplace, EditReplaceBorder, EditReplaceClearFormatting, EditReplaceLang, EditReplacePara, EditReplaceStyle, EditReplaceTabs, FormatFont


EditReplaceFrame

Syntax

EditReplaceFrame [.Wrap = number] [, .WidthRule = number] [, .FixedWidth = number or text] [, .HeightRule = number] [, .FixedHeight = number or text] [, .PositionHorz = number or text] [, .PositionHorzRel = number] [, .DistFromText = number or text] [, .PositionVert = number or text] [, .PositionVertRel = number] [, .DistVertFromText = number or text] [, .MoveWithText = number] [, .LockAnchor = number]

Remarks

On the Macintosh, when followed by an EditFind or EditReplace instruction in which .Format is set to 1, specifies the frame formatting of the replacement text. For information on the arguments, see FormatFrame. In Windows, EditReplaceFrame is not available and generates an error.

See Also

EditFindFrame, EditReplace, EditReplaceBorder, EditReplaceFont, EditReplaceLang, EditReplacePara, EditReplaceStyle, EditReplaceTabs, FormatFrame


EditReplaceHighlight

Syntax

EditReplaceHighlight

Remarks

When followed by an EditReplace instruction in which .Format is set to 1, specifies that the replacement text is highlighted. In Word version 6.0, EditReplaceHighlight is unavailable and generates an error.

Example

This example highlights all instances of bold text in the document.

EditFindClearFormatting
EditReplaceClearFormatting
EditFindFont .Bold = 1
EditReplaceHighlight
EditReplace .Find = "", .Replace = "", .Format = 1 .ReplaceAll

See Also

EditFindHighlight, EditReplace, Highlight, HighlightColor, ToolsOptionsRevisions


EditReplaceLang

Syntax

EditReplaceLang .Language = text

Remarks

When followed by an EditReplace instruction in which .Format is set to 1, specifies the language formatting of the replacement text. Although the Language command (Tools menu) lists the names of languages in their English form, the text for .Language must be in the specified language and include any accented characters (for example, Italian must be specified as "Italiano" and French must be specified as "Français"). For a list of valid foreign language names, see ToolsLanguage. For an example, see EditFindLang.

See Also

EditFindLang, EditReplace, EditReplaceBorder, EditReplaceClearFormatting, EditReplaceFont, EditReplaceFrame, EditReplacePara, EditReplaceStyle, EditReplaceTabs, ToolsLanguage


EditReplaceNotHighlight

Syntax

EditReplaceNotHighlight

Remarks

When followed by an EditReplace instruction in which .Format is set to 1, specifies that the replacement text is not highlighted. In Word version 6.0, EditReplaceNotHighlight is unavailable and generates an error.

See Also

EditFindNotHighlight, EditReplace, Highlight, HighlightColor, ToolsOptionsRevisions


EditReplacePara

Syntax

EditReplacePara [.LeftIndent = number or text] [, .RightIndent = number or text] [, .Before = number or text] [, .After = number or text] [, .LineSpacingRule = number] [, .LineSpacing = number or text] [, .Alignment = number] [, .WidowControl = number] [, .KeepWithNext = number] [, .KeepTogether = number] [, .PageBreak = number] [, .NoLineNum = number] [, .DontHyphen = number] [, .Tab = number] [, .FirstIndent = number or text]

Remarks

When followed by an EditReplace instruction in which .Format is set to 1, specifies paragraph formatting for the replacement text. You can set .WidowControl, .KeepWithNext, .KeepTogether, .PageBreak, .NoLineNum, and .DontHyphen to one of the three following values.

Use this value | To do this
–1 | Preserve the state of a given format in the found text
0 (zero) | Remove the given format from the found text
1 | Apply the given format to the found text

For more information on the arguments, see FormatParagraph.

Example

This example applies a 2-inch left indent to all paragraphs in the active document that currently have a 1-inch left indent:

StartOfDocument
EditFindClearFormatting
EditReplaceClearFormatting
EditFindPara .LeftIndent = "1 in"
EditReplacePara .LeftIndent = "2 in"
EditReplace .Find = "", .Replace = "", .ReplaceAll, \
    .Format = 1, .Wrap = 0

See Also

EditFindPara, EditReplace, EditReplaceBorder, EditReplaceClearFormatting, EditReplaceFont, EditReplaceFrame, EditReplaceLang, EditReplaceStyle, EditReplaceTabs, FormatParagraph


EditReplaceStyle

Syntax

EditReplaceStyle .Style = text

Remarks

When followed by an EditReplace instruction in which .Format is set to 1, specifies a style for the replacement text. If the specified style does not exist in the active document, or if the capitalization does not match that of the actual style name, an error occurs.

Argument | Explanation
.Style | The name of the style for the replacement text; to remove a style from the replacement formatting, use an empty string ("").

Example

This example changes all Heading 4 paragraphs to Heading 3 paragraphs:

StartOfDocument
EditFindClearFormatting
EditReplaceClearFormatting
EditFindStyle .Style = "Heading 4"
EditReplaceStyle .Style = "Heading 3"
EditReplace .Find = "", .Replace = "", .ReplaceAll, \
    .Format = 1, .Wrap = 0

See Also

EditFindStyle, EditReplace, EditReplaceBorder, EditReplaceClearFormatting, EditReplaceFont, EditReplaceFrame, EditReplaceLang, EditReplacePara, EditReplaceTabs, FormatStyle


EditReplaceTabs

Syntax

EditReplaceTabs [.Position = text] [, .Align = number] [, .Leader = number]

Remarks

On the Macintosh, when followed by an EditReplace instruction in which .Format is set to 1, specifies tab setting for the replacement text. For argument descriptions, see FormatTabs. In Windows, EditReplaceTabs is not available and generates an error.

See Also

EditFindTabs, EditReplace, EditReplaceBorder, EditReplaceClearFormatting, EditReplaceFrame, EditReplaceLang, EditReplacePara, EditReplaceStyle, FormatTabs


EditSelectAll

Syntax

EditSelectAll

Remarks

Selects the entire document.


EditSubscribeOptions

Syntax

EditSubscribeOptions [.GetManually = number] [, .GetEditionNow = number] [, .Format = number] [, .KeepFormatting = number]

Remarks

On the Macintosh, sets options for the selected subscriber. The arguments for the EditSubscribeOptions statement correspond to the options in the Subscriber Options dialog box (Publishing command, Edit menu). In Windows, EditSubscribeOptions is not available and generates an error.

Argument | Explanation
.GetManually | Specifies how the subscriber is updated: 0 (zero) or omitted Automatically (the subscriber is updated whenever a change is made to the edition) 1 Manually (the subscriber is updated on demand)
.GetEditionNow | If 1, immediately updates the subscriber with changes in the current edition.
.Format | Specifies a format for subscribing to the edition: 0 (zero) or omitted Best 1 Formatted text (RTF) 2 Unformatted text 3 Picture
.KeepFormatting | If 1, preserves formatting changes made in the subscriber.

See Also

EditCreatePublisher, EditLinks, EditPublishOptions, EditSubscribeTo


EditSubscribeTo

Syntax

EditSubscribeTo .FileName = text [, .Format = number] [, .GetManually = number]

Remarks

On the Macintosh, subscribes to a published edition. In Windows, EditSubscribeTo is not available and generates an error.

Argument | Explanation
.FileName | The path and filename of the edition.
.Format | Specifies a format for subscribing to the edition: 0 (zero) or omitted Best 1 Formatted text (RTF) 2 Unformatted text 3 Picture
.GetManually | Specifies how the subscriber is updated: 0 (zero) or omitted Automatically (the subscriber is updated whenever a change is made to the edition) 1 Manually (the edition is updated on demand)

See Also

EditCreatePublisher, EditLinks, EditPasteSpecial, EditPublishOptions, EditSubscribeOptions


EditSwapAllNotes

Syntax

EditSwapAllNotes

Remarks

Converts all footnotes in the document to endnotes and all endnotes to footnotes. The insertion point may be in either the document window or the footnote or endnote pane. If there are no footnotes or endnotes, an error occurs.

See Also

EditConvertAllEndnotes, EditConvertAllFootnotes, EditConvertNotes


EditTOACategory

Syntax

EditTOACategory .Category = number, .CategoryName = text

Remarks

Modifies the name of a category of citations for a table of authorities. The arguments for the EditTOACategory command correspond to the options in the Edit Category dialog box (Mark Citations dialog box, Index And Tables command, Insert menu).

Argument | Explanation
.Category | The category you want to modify: 1 corresponds to the first name in the list, 2 to the second name, and so on.
.CategoryName | The new name for the category of citations.

Example

This example changes the ninth item in the list of categories to "Case Histories":

EditTOACategory .Category = 8, .CategoryName = "Case Histories"

See Also

InsertTableOfAuthorities, MarkCitation


EditUndo

Syntax

EditUndo

Remarks

Undoes the last action, if possible. Most editing and formatting actions can be undone. Some actions, such as modifying a style, cannot be undone.

See Also

EditRedo, EditRepeat


EmptyBookmark()

Syntax

EmptyBookmark(Name$)

Remarks

Determines whether Name$ is an "empty" bookmark. An empty bookmark marks only a location for the insertion point in a document; it does not mark any text. You can use EmptyBookmark() to verify that a bookmark (for example, a bookmark referred to in a REF field) does indeed mark text.

This function returns the following values.

Value | Explanation
–1 | If the bookmark is empty (that is, it marks no text)
0 (zero) | If the bookmark is not empty or does not exist

Example

This example verifies that the bookmark referred to in each REF field both exists and is not empty. If a reference to a nonexistent or empty bookmark is encountered, an appropriate message box is displayed.

StartOfDocument
ViewFieldCodes 1
EditFind .Find = "^d REF", .Format = 0, .Wrap = 0
While EditFindFound()
    CharLeft
    WordRight 2
    WordRight 1, 1
    mark$ = RTrim$(Selection$())
    If Not ExistingBookmark(mark$) Then
        MsgBox mark$ + " is not a bookmark."
    ElseIf EmptyBookmark(mark$) Then
        MsgBox mark$ + " is an empty bookmark."
    End If
    CharRight
    EditFind .Find = "^d REF", .Format = 0, .Wrap = 0
Wend

See Also

BookmarkName$(), CmpBookmarks(), CountBookmarks(), EditBookmark, ExistingBookmark(), GetBookmark$()


EnableFormField

Syntax

EnableFormField BookmarkName$, Enable

Remarks

Allows or prevents changes to the specified form field while the form is being filled in.

Argument | Explanation
BookmarkName$ | The name of the bookmark that marks the form field.
Enable | Specifies whether the form field can be filled in or otherwise changed: 0 (zero) The form field cannot be changed. 1 The form field can be changed.

Example

This example allows or prevents changes to a form field based on the user name specified on the User Info tab in the Options dialog box (Tools menu). This macro could be part of an AutoNew macro that runs each time a document based on the form template is created.

Dim dlg As ToolsOptionsUserInfo
GetCurValues dlg
If dlg.Name = "Stella Richards" Then
    EnableFormField "TotalSales", 1
Else
    EnableFormField "TotalSales", 0
End If

See Also

InsertFormField


EndOfColumn, EndofColumn()

Syntax

EndOfColumn [Select]

EndOfColumn ([Select])

Remarks

The EndOfColumn statement moves the insertion point or extends the selection (if Select is nonzero) to the bottom of the table column containing the insertion point or selection. If the selection extends over more than one column, the insertion point moves or the selection is extended to the bottom of the rightmost column in the selection. If the insertion point or selection is not in a table, an error occurs.

Note

If the last row in the table does not have a cell that corresponds to the column that contains the current selection — for example, if you have deleted or merged cells in the last row — EndOfColumn moves the insertion point or extends the selection to the end of the last row in the table.

The EndOfColumn() function behaves the same as the statement and also returns one of the following values.

Value | Explanation
0 (zero) | If the insertion point was not moved or the selection was not extended (that is, if it was already at the bottom of the column)
–1 | If the insertion point was moved or the selection was extended

Example

This example moves the insertion point from anywhere in the table to the beginning of the last cell in the last row:

EndOfRow
EndOfColumn

See Also

EndOfRow, StartOfColumn


EndOfDocument, EndOfDocument()

Syntax

EndOfDocument [Select]

EndOfDocument([Select])

Remarks

The EndOfDocument statement moves the insertion point or, if Select is nonzero, the active end of the selection (the end that moves when you press CTRL+SHIFT+END) to the end of the document.

The EndOfDocument() function behaves the same as the statement and also returns one of the following values.

Value | Explanation
0 (zero) | If the insertion point or the active end of the selection was not moved (for example, if it was already at the end of the document)
–1 | If the insertion point or the active end of the selection was moved

See Also

AtEndOfDocument(), StartOfDocument


EndOfLine, EndOfLine()

Syntax

EndOfLine [Select]

EndOfLine ([Select])

Remarks

The EndOfLine statement moves the insertion point or, if Select is nonzero, the active end of the selection (the end that moves when you press SHIFT+END) to the end of the current line or the line that contains the active end of the selection. If there is a paragraph mark at the end of the line, EndOfLine positions the insertion point to the left of the paragraph mark; EndOfLine 1 moves the active end of the selection over the paragraph mark.

The EndOfLine() function behaves the same as the statement and also returns one of the following values.

Value | Explanation
0 (zero) | If the insertion point or the active end of the selection was not moved (that is, if it was already at the end of the line)
–1 | If the insertion point or the active end of the selection was moved

Avoid using EndOfLine by itself to go to the end of a paragraph unless you are sure that the paragraph is a single line (for example, a word in a list of words). Instead, use the following instructions:

ParaDown        'Go to start of next paragraph
CharLeft        'Go back one character

Examples

This example selects the current line and the paragraph mark (if there is one at the end of the line). The instruction EditGoTo "\Line" has the same effect.

StartOfLine
EndOfLine 1

The following example selects the current line but not the paragraph mark (if there is one at the end of the line):

EndOfLine
StartOfLine 1

See Also

EndOfRow, ParaDown, StartOfLine


EndOfRow, EndOfRow()

Syntax

EndOfRow [Select]

EndOfRow ([Select])

Remarks

The EndOfRow statement moves the insertion point or extends the selection (if Select is nonzero) to the last cell of the table row containing the insertion point or selection. If the selection extends over more than one row, the insertion point moves or the selection is extended to the last cell of the last row in the selection. If the insertion point or selection is not in a table, an error occurs.

The EndOfRow() function behaves the same as the statement and also returns one of the following values.

Value | Explanation
0 (zero) | If the insertion point was not moved or the selection was not extended (that is, if it was already at the end of the row)
–1 | If the insertion point was moved or the selection was extended

Example

This example deletes the selected cells or the cell containing the insertion point and all cells to the right:

EndOfRow 1
TableDeleteCells

See Also

EndOfColumn, EndOfLine, StartOfRow


EndOfWindow, EndOfWindow()

Syntax

EndOfWindow [Select]

EndOfWindow([Select])

Remarks

The EndOfWindow statement moves the insertion point or, if Select is nonzero, the active end of the selection (the end that moves when you press CTRL+SHIFT+
PAGE DOWN) to the lower-right corner of the contents currently visible in the document window.

The EndOfWindow() function behaves the same as the statement and also returns one of the following values.

Value | Explanation
0 (zero) | If the insertion point or the active end of the selection was not moved (that is, if it was already at the lower-right corner of the window)
–1 | If the insertion point or the active end of the selection was moved

For an example, see StartOfWindow.

See Also

EndOfDocument, StartOfWindow


Environ$()

Syntax

Environ$(EnvironmentVariable$)

Remarks

In Windows 3.x and Windows 95, returns a string associated with EnvironmentVariable$. For example, tempdir$ = Environ$("TEMP") returns the folder associated with the TEMP environment variable. On the Macintosh, Environ$() is not available and generates an error.

Environment variables are normally set using MS-DOS® batch files (such as AUTOEXEC.BAT) or the System option in Control Panel in Windows NT. For more information about environment variables, see your system documentation.

Example

This Windows example checks the PATH environment variable and displays one of two message boxes based on the number of characters in the path. (The limit is 127 characters.)

path$ = Environ$("PATH")
length = Len(path$)
avail = 127 - length
Select Case avail
    Case 127
        MsgBox "The PATH is empty."
    Case 0 To 126
        MsgBox "You can add" + Str$(avail) + \
                " character(s) to the PATH."
    Case Else
End Select

See Also

AppInfo$(), GetProfileString$(), GetSystemInfo


Eof()

Syntax

Eof([#]FileNumber)

Remarks

Determines whether the end of an open sequential file has been reached. FileNumber is the number specified in the Open instruction that opened the file for input. For more information about sequential files, see Chapter 9, "More WordBasic Techniques," in Part 1, "Learning WordBasic."

You cannot use this function to check for the end of a Word document open in a document window. To check for the end of a Word document, use the predefined bookmark "\EndOfDoc" with CmpBookmarks(). For more information about predefined bookmarks, see "Operators and Predefined Bookmarks" later in this part.

Eof() returns the following values.

Value | Explanation
–1 | The end of the file specified by FileNumber has been reached.
0 (zero) | The end of the file has not been reached.

For an example, see Read.

See Also

Close, Input, Input$(), Line Input, Lof(), Open, Print, Read, Seek, Write


Err

Syntax

Err = 0

Error Err

ErrorNum = Err

Remarks

Err is a special variable whose value is the error code for the most recent error condition.

  • Err = 0 is ued to reset error trapping after an error has occurred, normally at the end of an error trap.
  • Error Err displays the message associated with the most recent error condition and stops the macro.
  • ErrorNum = Err assigns the value of Err to the variable ErrorNum.

For more information on trapping errors, see On Error.

Example

This macro prompts the user to type a style name that is then applied to the selected paragraphs. The macro contains an error handler that illustrates the use
of Err within a Select Case control structure. The Select Case control structure
in this macro can be described as follows:

  • If the error code is 102 (which occurs if the InputBox$ dialog box is canceled), the macro prevents the "Command failed" error message from being displayed.
  • If the error code is 24 (which occurs if the style name does not exist), Word displays a custom message box in place of the "Bad parameter" error message, error trapping is reset with the instruction Err = 0, and the InputBox$ dialog box is displayed again so the user can type another style name. Note that Case 24 is the only case in which error trapping needs to be reset. In the other cases, the macro ends and there is no need for further error trapping.
  • If the error code is neither 102 nor 24, the instruction Error Err displays the error.

Sub MAIN
On Error Goto trap
start:
apply$ = InputBox$("Type a style name:", "Apply Style")
Style apply$
trap:
Select Case Err
    Case 102                'Input box was canceled
    Case 24                'Bad parameter
        MsgBox "No such style; try another name."
        Err = 0
        Goto start
    Case Else            'Any other error condition
        Error Err
End Select
End Sub

See Also

Error, Goto, On Error


Error

Syntax

Error Err

Error ErrorNumber

Remarks

Error Err generates the most recent error condition and stops the macro. Error ErrorNumber generates the error condition associated with ErrorNumber. For WordBasic error conditions, which have numbers of less than 1000, Error displays an error message. For Word errors, which have numbers of 1000 or greater, Error generates an error condition, but does not display an error message. Error can be used to test an error trap.

For a list of errors and their numbers, see "Error Messages," later in this part. For more information on error trapping, see On Error and Err.

Example

This example generates WordBasic error condition 53 in order to test the handling of this error. When error condition 53 occurs, Word displays a custom message box; any other error runs the instruction Error Err, which displays the built-in message associated with the error number.

On Error Goto trap
Error 53                'Generate error condition
trap:
If Err = 53 Then
    MsgBox "Error 53 successfully trapped"
    Err = 0
Else
    Error Err
End If

See Also

Err, Goto, On Error


ExistingBookmark()

Syntax

ExistingBookmark(Name$)

Remarks

Indicates whether the bookmark specified by Name$ exists in the active document. This function returns the following values.

Value | Explanation
–1 | If the bookmark exists
0 (zero) | If the bookmark does not exist

Example

This macro displays a prompt in the status bar for the name of a bookmark to add. If the bookmark does not yet exist, it is added. If the bookmark already exists, Word displays a message box that asks whether to reset the bookmark. If the user answers No, the macro ends. Otherwise, the bookmark is reset.

Sub MAIN
Input "Bookmark to add", myMark$
If ExistingBookmark(myMark$) Then
    ans = MsgBox(myMark$ + " already exists; reset?", 36)
    If ans = 0 Then Goto bye
End If
EditBookmark myMark$, .Add
bye:
End Sub

See Also

BookmarkName$(), CmpBookmarks(), CountBookmarks(), EditBookmark, EmptyBookmark(), GetBookmark$()


ExitWindows

Syntax

ExitWindows

Remarks

In Windows 3.x, closes all open applications and quits Windows. In Windows 95 and Windows NT, ExitWindows logs the current user off. ExitWindows does not save changes or prompt you to save changes in Word documents; it does prompt you to save changes in other open Windows-based applications.

ExitWindows can be useful if you have an MS-DOS batch file that starts Word and runs a macro using the /m macroname startup switch. By including ExitWindows as the final instruction in the macro, you restore control to the MS-DOS batch file. If you are running a batch file that starts Word from a command prompt running within Windows 3.x, Windows 95, or Windows NT, use FileExit 2 instead of ExitWindows.

On the Macintosh, ExitWindows is not available and generates an error.

See Also

FileExit, FileQuit


ExtendMode()

Syntax

ExtendMode()

Remarks

Returns –1 if extend mode is on. In extend mode, actions that normally move the insertion point extend the selection. ExtendMode() does not indicate whether column selection mode is on.

Example

This example toggles the state of extend mode:

If ExtendMode() = 0 Then ExtendSelection Else Cancel

See Also

Cancel, ColumnSelect, ExtendSelection


ExtendSelection

Syntax

ExtendSelection [Character$]

Remarks

Performs one of the following actions:

  • If extend mode is off, activates extend mode (in extend mode, actions that normally move the insertion point move the active end of the selection).
  • If extend mode is already on, extends the selection to the next unit of text
    (the progression is as follows: word, sentence, paragraph, section, entire document).
  • If Character$ is specified, extends the selection from the insertion point or the fixed end of the current selection (the end of the selection that does not move when you press SHIFT+an arrow key) to the next instance of that character without activating or deactivating extend mode.

You can use ExtendSelection with EditGoTo and EditFind to extend the selection to a specific location or piece of text. Use the Cancel statement to deactivate extend mode.

Example

This example selects all text from the insertion point to and including the bookmark "MyMark":

ExtendSelection
EditGoTo "MyMark"
Cancel

See Also

Cancel, ColumnSelect, ExtendMode(), ShrinkSelection


FieldSeparator$, FieldSeparator$()

Syntax

FieldSeparator$ Separator$

FieldSeparator$()

Remarks

The FieldSeparator$ statement sets the separator character, Separator$, that Word recognizes when dividing text among cells in a TextToTable operation. For example, if you have data in which the items of information are delimited by percent signs (%), you can use the instruction FieldSeparator "%" before converting the data to a table. The FieldSeparator$() function returns the current separator character.

See Also

TextToTable


FileAOCEAddMailer

Syntax

FileAOCEAddMailer

Remarks

Adds a mailer to the active document. FileAOCEAddMailer is available only on the Macintosh and only if PowerTalk is installed.

See Also

AOCEAddRecipient, AOCESetSubject, FileAOCEDeleteMailer, FileAOCEExpandMailer


FileAOCEDeleteMailer

Syntax

FileAOCEDeleteMailer

Remarks

Removes the mailer from the active document. FileAOCEDeleteMailer is available only on the Macintosh and only if PowerTalk is installed.

See Also

AOCEClearMailerField, FileAOCEAddMailer, FileAOCEExpandMailer


FileAOCEExpandMailer

Syntax

FileAOCEExpandMailer

Remarks

Toggles the display of the mailer attached to the active document between the full mailer and a bar showing just the sender and subject. FileAOCEExpandMailer is available only on the Macintosh and only if PowerTalk is installed.

See Also

FileAOCEAddMailer, FileAOCEDeleteMailer


FileAOCEForwardMail

Syntax

FileAOCEForwardMail

Remarks

Adds a mailer for forwarding the active letter. The subject text is copied to the new mailer and prefixed by "Fwd> ". FileAOCEForwardMail is available only on the Macintosh and only if PowerTalk is installed.

See Also

AOCESendMail, FileAOCEReplyMail, FileAOCESendMail


FileAOCENextLetter

Syntax

FileAOCENextLetter

Remarks

Opens the next available letter in the In Tray. If there are no more letters to open, a message appears. FileAOCENextLetter is available only on the Macintosh and only if PowerTalk is installed.


FileAOCEReplyAllMail

Syntax

FileAOCEReplyAllMail

Remarks

Adds a mailer for replying to the active letter and specifies the sender and all recipients of the original letter as recipients. The subject text is copied from the original letter and prefixed with "Re> ". FileAOCEReplyAllMail is available only on the Macintosh and only if PowerTalk is installed.

See Also

FileAOCEReplyMail


FileAOCEReplyMail

Syntax

FileAOCEReplyMail

Remarks

Adds a mailer for replying to the active letter and specifies the sender of the original letter as the recipient. The subject text is copied from the original letter and prefixed with "Re> ". FileAOCEReplyMail is available only on the Macintosh and only if PowerTalk is installed.

See Also

FileAOCEForwardMail, FileAOCEReplyAllMail


FileAOCESendMail

Syntax

FileAOCESendMail

Remarks

Displays a dialog box in which you can set options for sending the active document to the the recipients specified in the attached mailer. Use AOCESendMail to set options and send the document without displaying a dialog box. FileAOCESendMail is available only on the Macintosh and only if PowerTalk is installed.

See Also

AOCESendMail, FileAOCEForwardMail


FileClose

Syntax

FileClose [Save]

Remarks

Closes the active document. All document windows containing the active document are closed. If the document is open in more than one window and you want to close only the active window, use DocClose.

Argument | Explanation
Save | Determines whether or not Word saves the document before closing it if the document is "dirty" — that is, if changes have been made since the last time the file was saved: 0 (zero) or omitted Prompts the user to save the document. 1 Saves the document before closing it. 2 Closes the document without saving it. The Save argument also controls whether a prompt appears if the document has a routing slip. A prompt appears if Save is 0 (zero) or omitted; otherwise, the document is closed without being routed.

See Also

ClosePane, DocClose, FileCloseAll, FileExit, IsDocumentDirty()


FileCloseAll

Syntax

FileCloseAll [Save]

Remarks

Closes all open document windows.

Argument | Explanation
Save | Determines whether or not Word saves each document before closing it if it is "dirty" — that is, if changes have been made since the last time the file was saved: 0 (zero) or omitted Prompts the user to save each changed document. 1 Saves each changed document before closing it. 2 Closes all documents without saving changed documents. The Save argument also controls whether a prompt appears if a document has a routing slip. A prompt appears if Save is 0 (zero) or omitted; otherwise, the document is closed without being routed.

See Also

DocClose, FileClose, FileExit, FileQuit


FileClosePicture

Syntax

FileClosePicture

Remarks

Closes the picture editing window and embeds a Word Picture object in the document.

See Also

DrawResetWordPicture


FileConfirmConversions, FileConfirmConversions()

Syntax

FileConfirmConversions [On]

FileConfirmConversions()

Remarks

The FileConfirmConversions statement controls whether Word displays a confirmation dialog box when a file in a format other than Word Document or Document Template is opened. In Word version 6.0, FileConfirmConversions selects or clears the Confirm Conversions check box in the Open dialog box (File menu). In Word version 7.0, FileConfirmConversions selects or clears the Confirm Conversions At Open check box on the General tab in the Options dialog box (Tools menu).

Argument | Explanation
On | Specifies whether Word displays the confirmation dialog box: 0 (zero) Does not display the dialog box. 1 Displays the dialog box. Omitted Toggles the Confirm Conversions check box.

The FileConfirmConversions() function returns the following values.

Value | Explanation
0 (zero) | If the Confirm Conversions check box is cleared
–1 | If the Confirm Conversions check box is selected

See Also

MailMergeAskToConvertChevrons


FileCreator$()

Syntax

FileCreator$(File$)

Remarks

On the Macintosh, returns the four-character application signature for the application that created File$, a path and filename. In Windows, FileCreator$() is not available and generates an error.

Example

This Macintosh example checks the creator before opening the file specified by openme$. If the application signature is not "MSWD," a message is displayed.

openme$ = "HD:GAMES:GAME RULES"
If FileCreator$(openme$) <> "MSWD" Then
    ans = MsgBox(openme$ + " was not created by Microsoft Word. " + \
        "Open anyway?", 4)
    If ans = 0 Then endmacro = -1
End If
If Not endmacro Then FileOpen .Name = openme$

See Also

FileType$(), MacID$(), SetFileCreatorAndType


FileDocumentLayout

Syntax

FileDocumentLayout [.Tab = number] [, .TopMargin = number or text] [, .BottomMargin = number or text] [, .LeftMargin = number or text] [, .RightMargin = number or text] [, .Gutter = number or text] [, .PageWidth = number or text] [, .PageHeight = number or text] [, .Orientation = number] [, .FirstPage = number] [, .OtherPages = number] [, .VertAlign = number] [, .ApplyPropsTo = number] [, .Default] [, .FacingPages = number] [, .HeaderDistance = number or text] [, .FooterDistance = number or text] [, .SectionStart = number] [, .OddAndEvenPages = number] [, .DifferentFirstPage = number] [, .Endnotes = number] [, .LineNum = number] [, .StartingNum = number] [, .FromText = number or text] [, .CountBy = number] [, .NumMode = number]

Remarks

On the Macintosh, sets page attributes such as margins and page width for the entire document or sections within the document. With the exception of .Tab, the arguments for FileDocumentLayout are the same as the arguments described for FilePageSetup. In Windows, use FilePageSetup.

Argument | Explanation
.Tab | Specifies which tab to select when you display the Document Layout dialog box with a Dialog or Dialog() instruction: 0 (zero) Margins 1 If QuickDraw GX is installed, Paper Size; if not, Margins 2 Margins 3 Layout

Keep the following points in mind when using FileDocumentLayout:

  • Setting page size and orientation does not override those set by the user in the Page Setup dialog box (supplied by the printer driver). For more information, see the note in FileMacPageSetup.
  • Word does not have access to Macintosh paper source settings. Although settings for .FirstPage and .OtherPages are saved with the document, they are ignored when printing. If the document is printed in Windows, however, the options take effect.

See Also

FileMacPageSetup, FileMacPageSetupGX, FileMacCustomPageSetupGX, FilePageSetup, FormatColumns


FileExit

Syntax

FileExit [Save]

Remarks

Quits Word. FileExit (Windows) is the same as FileQuit (Macintosh).

Argument | Explanation
Save | Determines whether Word saves each document before closing it if it is "dirty" — that is, if changes have been made since the last time the file was saved: 0 (zero) or omitted Prompts the user to save each changed document. 1 Saves all edited documents before quitting. 2 Quits without saving changed documents. The Save argument also controls whether a prompt appears if a document has a routing slip or if Word is printing in the background. Prompts appear if Save is 0 (zero) or omitted; otherwise, Word quits without routing documents or finishing print jobs.

See Also

AppClose, ExitWindows, FileCloseAll, FileQuit


FileFind

Syntax

FileFind [.SearchName = text] [, .SearchPath = text] [, .Name = text] [, .SubDir = number] [, .Title = text] [, .Author = text] [, .Keywords = text] [, .Subject = text] [, .Options = number] [, .MatchCase = number] [, .Text = text] [, .PatternMatch = text] [, .DateSavedFrom = text] [, .DateSavedTo = text] [, .SavedBy = text] [, .DateCreatedFrom = text] [, .DateCreatedTo = text] [, .View = number] [, .SortBy = number] [, .ListBy = number] [, .SelectedFile = number] [, .ShowFolders = number] [, .Add] [, .Delete]

Remarks

Creates a list of files based on the search criteria specified by one or more of the arguments. In Word version 6.0, the arguments for the FileFind statement correspond to the options in the Search dialog box (Find File command, File menu).

In Word version 7.0, the .SearchName, .Options, .PatternMatch, .View, .SortBy, .ListBy, .SelectedFile, .ShowFolders, .Add, and .Delete arguments are ignored, and you cannot use a Dialog or Dialog() instruction to display the Word version 6.0 Find File dialog box.

Argument | Explanation
.SearchName | A name given to a group of search criteria you want to add to or remove from the Search dialog box (using .Add or .Delete). Note that when performing the search, Word ignores .SearchName; you must specify criteria using .SearchPath, .Name, and so on.
.SearchPath | A path or list of paths in which to search for files. In Word version 6.0, you can specify more than one path by separating them with semicolons (;). In Word version 7.0, you cannot specify more than one path.
.Name | The name of the document or, in Windows, a file specification. To find document templates, for example, the file specification would be "*.DOT". On the Macintosh, use MacID$() to specify a file type (for example, MacID$("WTBN") to find document templates).
.SubDir | If 1, Word searches subfolders of the folder or folders specified by .SearchPath.
.Title | Title in the Summary Info dialog box
.Author | Author in the Summary Info dialog box
.Keywords | Keywords used to identify the document in the Summary Info dialog box
.Subject | Subject in the Summary Info dialog box
.Options | Specifies how to list the found files: 0 (zero) Create a new list 1 Add matches to the existing file list 2 Search only in the existing file list
.MatchCase | Specifies whether to match the case of each letter in .Text: 0 (zero) Do not match the case (default) 1 Match the case
.Text | The text to search for in the document
.PatternMatch | If 1, Word evaluates .Text as a string containing advanced search criteria such as the asterisk (*) and question mark (?) wildcard characters. For more information, search for "search operators" in Word Help and choose "Advanced search criteria."
.DateSavedFrom | The document save date you want to search from
.DateSavedTo | The document save date you want to search to
.SavedBy | The name of the person who last saved the document

Argument | Explanation
.DateCreatedFrom | The document creation date you want to search from. The following are examples of valid date formats: 7/8/93 8-Jul-91 July 8, 1991
.DateCreatedTo | The document creation date you want to search to
.View | Specifies what to display on the right side of the dialog box when you display the Find File dialog box with a Dialog or Dialog() instruction: 0 (zero) File information (a line for each file) 1 A preview window of the contents of the selected file 2 Summary information for the selected file
.SortBy | Specifies how documents are sorted when you display the Find File dialog box with a Dialog or Dialog() instruction: 0 (zero) Alphabetically by author 1 By creation date, with the most recently created file listed first 2 Alphabetically by the name of the person who last saved the document 3 By the date last saved, with the most recently saved file listed first 4 Alphabetically by filename 5 By size, with the smallest file listed first
.ListBy | Specifies whether to list filenames or titles on the left side of the dialog box when you display the Find File dialog box with a Dialog or Dialog() instruction: 0 (zero) Filenames 1 Titles
.SelectedFile | When you've used a Dialog or Dialog() instruction to display the Find File dialog box, returns a number when the user closes the dialog box that corresponds to the file that was last selected. To retrieve the filename, pass this value to the FoundFileName$() function (for example, FoundFileName$(dlg.SelectedFile)).
.ShowFolders | If 1, groups filenames by folder when you display the Find File dialog box with a Dialog or Dialog() instruction.
.Add | Stores the specified search criteria under the name specified by .SearchName; may be used to create or modify a group of search criteria.
.Delete | Removes the group of search criteria specified by .SearchName.

If you specify multiple words for .Title, .Subject, .Author, .Keywords, .Path, and .Text, Word interprets the entire argument as a logical expression rather than as a multiple-word phrase. A comma serves as the logical operator OR, and a space or an ampersand (&) serves as the logical operator AND.

Examples

This Windows example searches a folder for files with the .RPT filename extension, defines an array to hold their names, and then uses FoundFileName$() to fill the array with the filenames.

FileFind .SearchPath = "C:\REPORTS", .Name = "*.RPT"
size = CountFoundFiles() - 1
If size >= 0 Then
    Dim mydocs$(size)
    For count = 0 To size
        mydocs$(count) = FoundFileName$(count + 1)
    Next
End If

The following Macintosh example creates a dialog record for the Find File dialog box, sets the search path and file type criteria, specifies that summary information be displayed for the found files, and then displays the list of found files.

Dim dlg As FileFind
dlg.SearchPath = "HD:MY DOCUMENTS"
dlg.Name = MacID$("W6BN")
dlg.View = 2
x = Dialog(dlg)

See Also

CountFoundFiles(), FoundFileName$()


FileList

Syntax

FileList Number

Remarks

Opens one of the files in the list of recently used files at the bottom of the File menu. (Word defines "used" as either opened or saved.) Number corresponds to the number next to the filename listed on the File menu (from 1 through 9) you want to open. If Number is greater than the number of files listed, an error occurs. If the specified file is already open, Word activates the document.

You can control the number of filenames that appear on the File menu with the Recently Used File List option on the General tab in the Options dialog box (Tools menu).

Example

This example opens the most recently used file. You can include these instructions in an AutoExec macro so that every time you start Word, the most recently used file is opened automatically. If there is no file listed on the File menu, On Error Resume Next prevents Word from displaying an error message.

On Error Resume Next
FileList 1

See Also

CountFiles(), FileName$(), File Number, FileOpen


FileMacCustomPageSetupGX

Syntax

FileMacCustomPageSetupGX [.PageWidth = number or text] [, .PageHeight = number or text] [, .Orientation = number] [, .ApplyPropsTo = number]

Remarks

On the Macintosh with QuickDraw GX installed, sets page width, height, and orientation for the entire document or sections within the document. For argument descriptions, see FilePageSetup.

In Windows, and on the Macintosh if QuickDraw GX is not installed, FileMacCustomPageSetupGX is not available and generates an error.

See Also

FileDocumentLayout, FileMacPageSetup, FileMacPageSetupGX, FilePageSetup


FileMacPageSetup

Syntax

FileMacPageSetup [.PageWidth = number or text] [, .PageHeight = number or text] [, .Orientation = number] [, .ApplyPropsTo = number] [, .Default]

Remarks

On the Macintosh, sets page width, height, and orientation for the entire document or sections within the document. For argument descriptions, see FilePageSetup. If QuickDraw GX is installed, FileMacPageSetup generates an error; use FileMacPageSetupGX and FileMacCustomPageSetupGX instead.

Note

Changing the page size with FileMacPageSetup is equivalent to setting a custom paper size in the Custom Paper Size dialog box (Page Setup command, File menu). In both cases, the custom settings override other page size settings in the Page Setup dialog box.

See Also

FileDocumentLayout, FileMacCustomPageSetupGX, FileMacPageSetupGX, FilePageSetup


FileMacPageSetupGX

Syntax

FileMacPageSetupGX [.PageWidth = number or text] [, .PageHeight = number or text] [, .Orientation = number]

Remarks

On the Macintosh with QuickDraw GX installed, sets page width, height, and orientation for the default page setup. Note that only those sections with the default page format will be changed; sections whose page format has been changed with FileDocumentLayout or FileMacCustomPageSetupGX are unchanged. For argument descriptions, see FilePageSetup.

In Windows, and on the Macintosh if QuickDraw GX is not installed, FileMacPageSetupGX is not available and generates an error.

See Also

FileDocumentLayout, FileMacCustomPageSetupGX, FileMacPageSetup, FilePageSetup


FileName$()

Syntax

FileName$([Number])

Remarks

Returns the path and filename of the active document or of a file in the list of recently used files at the bottom of the File menu.

Argument | Explanation
Number | The number of the file in the order listed on the File menu, from 1 through 9. If the number is 0 (zero) or omitted, FileName$() returns the name of the active document; if there is no active document, it returns an empty string(""). If Number is greater than the number of files listed on the File menu, an error occurs. You can control the number of filenames that appear on the File menu with the Recently Used File List option on the General tab in the Options dialog box (Tools menu).

Example

When run, this example demonstrates the difference between FileName$() and WindowName$(). FileName$() always returns a file's path and filename. WindowName$() returns the window title, which does not include the path and may include extra text such as "(Read-Only)" or ":2" after the filename.

MsgBox "File = " + FileName$() + Chr$(13) + \
    "Window = " + WindowName$()

See Also

CountFiles(), FileList, FileNameFromWindow$(), File Number, Files$(), WindowName$()


FileNameFromWindow$()

Syntax

FileNameFromWindow$([WindowNumber])

Remarks

Returns the path and filename of the document in the specified window.

Argument | Explanation
WindowNumber | The position of the window on the Window menu, where 1 is the first position, 2 is the second position, and so on. If WindowNumber is 0 (zero) or omitted, FileNameFromWindow$() returns the path and filename of the active document; if the active document has never been saved, it returns an empty string ("").

See Also

CountWindows(), FileName$(), WindowName$()


FileNameInfo$()

Syntax

FileNameInfo$(Filename$, InfoType)

Remarks

Returns the part of Filename$ specified by InfoType.

Argument | Explanation
Filename$ | The path, if specified, and filename of a document. Though the path must exist, the filename does not have to be the name of an existing document. If the path does not exist, an error occurs.

Argument

Explanation

InfoType

The part of Filename$ to return:

1 The full path and filename. In Windows, for example, FileNameInfo$(FileName$(), 1) might return "C:\DOCUMENT\TEST.DOC." If Filename$ does not include a path, FileNameInfo$() returns a path made up of the current folder and Filename$, even if such a file does not yet exist.

2 The filename only, if Filename$ is located in the current folder; otherwise, the full path and filename.

3 The filename. On the Macintosh, for example, FileNameInfo$("HD:DOCUMENTS:TEST DOC", 3) returns "TEST DOC."

4 The filename without a filename extension. In Windows, for example, FileNameInfo$("C:\DOCUMENT\TEST.DOC", 4) returns "TEST." On the Macintosh, setting InfoType to 4 returns the whole filename (same as setting InfoType to 3).

5 The full path, including the trailing backslash (\) (Windows) or colon (:) (Macintosh). On the Macintosh, for example, FileNameInfo$("HD:DOCUMENTS:TEST DOC", 5) returns "HD:DOCUMENTS:."

6 In Windows, returns the universal naming convention (UNC) network path and filename. For example, if TEST.DOC is located on a server with the network share name \\DOCUMENT\PUBLIC, then FileNameInfo$("D:\DOCUMENT\TEST.DOC", 6) returns "\\DOCUMENT\PUBLIC\DOCUMENT\TEST.DOC."

On the Macintosh, returns a string that begins with the zone and computer name. For example if INSTRUCTIONS is located in a shared folder named ART TOOLS, FileNameInfo$("ART TOOLS:INSTRUCTIONS") might return "PUBLIC:TOOLS:ART TOOLS:INSTRUCTIONS," where PUBLIC is the zone and TOOLS is the computer name.

If Filename$ is not located on a network share, the full path and filename are returned.

Example

This Windows example uses FileNameInfo$() to change the filename extension of all the files in the current folder with the extension .DOC to .RTF and then saves the files in rich-text format (RTF):

file$ = Files$("*.DOC")
While file$ <> ""
    FileOpen .Name = file$
    noExtension$ = FileNameInfo$(file$, 4)
    FileSaveAs .Name = noExtension$ + ".RTF" , .format = 6
    FileClose 2
    file$ = Files$()
Wend

See Also

FileName$(), FileNameFromWindow$()


FileNew

Syntax

FileNew [.Template = text] [, .NewTemplate = number]

Remarks

Creates a new document or template based on the template you specify, or runs a wizard. The arguments for the FileNew statement correspond to the options in the New dialog box (File menu).

Argument | Explanation
.Template | The name of the template or document on which to base the new document or template, or the name of the wizard to run
.NewTemplate | Specifies whether to create a new document or a new template: 0 (zero) or omitted Create a new document 1 Create a new template

Examples

These examples create a new document based on a memo template. In Windows, the .DOT filename extension is optional — you can specify either "MEMO1" or "MEMO1.DOT."

FileNew .Template = "MEMO1"        'Windows
FileNew .Template = "MEMO 1"        'Macintosh

The following examples create a new template based on the existing Letter3 template:

FileNew .NewTemplate = 1, .Template = "LETTER3.DOT"    'Windows
FileNew .NewTemplate = 1, .Template = "LETTER 3"        'Macintosh

The following examples run the Resume wizard:

FileNew .Template = "RESUME.WIZ"            'Windows
FileNew .Template = "RESUME WIZARD"        'Macintosh

See Also

FileNewDefault, FileOpen


FileNewDefault

Syntax

FileNewDefault

Remarks

Creates a new document based on the Normal template.

See Also

FileNew


FileNumber

Syntax

File Number

Remarks

Opens one of the files in the list of recently used files at the bottom of the File menu. (Word defines "used" as either opened or saved.) File1 opens the first document in the list (the most recently used), File2 opens the second document, and so on through File9. Nine is the maximum number of filenames that can be listed on the File menu. If no file is listed, or if Number is greater than the number of files listed, an error occurs. If the specified file is already open, Word activates the document.

You can control the number of files to be listed on the File menu with the Recently Used File List option on the General tab in the Options dialog box (Tools menu).

See Also

CountFiles(), FileList, FileName$(), Window Number


FileOpen

Syntax

FileOpen .Name = text [, .ConfirmConversions = number] [, .ReadOnly = number] [, .AddToMru = number] [, .PasswordDoc = text] [, .PasswordDot = text] [, .Revert = number] [, .WritePasswordDoc = text] [, .WritePasswordDot = text]

Remarks

Opens the specified document. If the document does not exist, or is not located in the specified folder, an error occurs. Most arguments for the FileOpen statement correspond to the options in the Open dialog box (File menu).

Argument | Explanation
.Name | The name of the document (paths are accepted). In Windows, you can specify multiple files by separating the filenames with spaces; on the Macintosh and in Windows NT, you can specify only one file per FileOpen instruction. If you use Dialog or Dialog() to display the Open dialog box, you can display files of a certain type by setting .Name to a file specification. To display text files, for example, the file specification would be "*.TXT" (Windows) or MacID$("TEXT") (Macintosh). For an example, see MacID$().

Argument | Explanation
.ConfirmConversions | If 1, displays the Convert File dialog box if the file is not in Word format.
.ReadOnly | If 1, opens the document as read-only.
.AddToMru | If 1, adds the filename to the list of recently used files at the bottom of the File menu. (Note that MRU is an abbreviation for "most recently used.")
.PasswordDoc | The password to open the document, if required.
.PasswordDot | The password to open the template, if required.
.Revert | Controls what happens if .Name is the filename of an open document: 0 (zero) Word activates the open document. 1 Word discards any unsaved changes to the open document and reopens the file.
.WritePasswordDoc | The password to save changes to the document, if required.
.WritePasswordDot | The password to save changes to the template, if required.

In Windows 95 and Windows NT, if any part of the path or filename for a file specified by .Name contains a space character, the entire path and filename must be enclosed by Chr$(34) characters, as shown in the following example:

FileOpen .Name = Chr$(34) + "C:\DOCUMENTS\AUGUST REPORT" + Chr$(34)

You can specify multiple files using this technique as well. Each filename must be separated by a space character, as shown in the following example:

FileOpen .Name = Chr$(34) + "JUNE REPORT" + Chr$(34) + " " + \
        Chr$(34) + "JULY REPORT" + Chr$(34) + " " + \
        Chr$(34) + "AUGUST REPORT" + Chr$(34)

On the Macintosh, paths and filenames that contain spaces should not be enclosed by Chr$(34) characters. The following Macintosh example shows the correct way to specify a path and filename with spaces in them in a Macintosh FileOpen instruction:

FileOpen .Name = "HD:MONTHLY REPORTS:AUGUST REPORT"

Examples

This Windows example changes the current folder, and then opens a read-only copy of MYDOC.DOC:

ChDir "C:\WINWORD\DOCS"
FileOpen .Name = "MYDOC.DOC", .ReadOnly = 1

The following Macintosh example also opens MY DOCUMENT, but because the full path is specified, no ChDir instruction is required before the FileOpen instruction:

FileOpen .Name = "HD:WORD:MY DOCUMENT", .ReadOnly = 1

See Also

FileConfirmConversions, FileFind, FileNew, MacID$()


FilePageSetup

Syntax

FilePageSetup [.Tab = number] [, .TopMargin = number or text] [, .BottomMargin = number or text] [, .LeftMargin = number or text] [, .RightMargin = number or text] [, .Gutter = number or text] [, .PageWidth = number or text] [, .PageHeight = number or text] [, .Orientation = number] [, .FirstPage = number] [, .OtherPages = number] [, .VertAlign = number] [, .ApplyPropsTo = number] [, .Default] [, .FacingPages = number] [, .HeaderDistance = number or text] [, .FooterDistance = number or text] [, .SectionStart = number] [, .OddAndEvenPages = number] [, .DifferentFirstPage = number] [, .Endnotes = number] [, .LineNum = number] [, .StartingNum = number] [, .FromText = number or text] [, .CountBy = number] [, .NumMode = number]

Remarks

In Windows, sets page attributes such as margins and page width for the entire document or sections within the document. The arguments for the FilePageSetup statement correspond to the options in the Page Setup dialog box (File menu). On the Macintosh, use FileDocumentLayout.

Argument | Explanation
.Tab | Specifies which tab to select when you display the Page Setup dialog box with a Dialog or Dialog() instruction: 0 (zero) Margins 1 Paper Size 2 Paper Source 3 Layout For details, see the second example in this entry.
.TopMargin | The distance between the top edge of the page and the top boundary of the body text in points or a text measurement
.BottomMargin | The distance between the bottom edge of the page and the bottom boundary of the body text in points or a text measurement
.LeftMargin | The distance between the left edge of the page and the left boundary of the body text in points or a text measurement

Argument | Explanation
.RightMargin | The distance between the right edge of the page and the right boundary of the body text in points or a text measurement
.Gutter | The extra margin space allowed for binding the document, in points or a text measurement
.PageWidth | The width of the page in points or a text measurement
.PageHeight | The height of the page in points or a text measurement
.Orientation | The orientation of the page: 0 (zero) Portrait 1 Landscape Note that unlike using the TogglePortrait statement, specifying a new orientation with FilePageSetup does not automatically adjust the page size and margins for the new orientation.
.FirstPage, .OtherPages | Selects the paper source for the first page and the other pages in the document: 0 (zero) Default Tray (determined by the printer driver) 1 Upper Tray 2 Lower Tray 4 Manual Feed (often used to override the default tray for the first page) 5 Envelope Other values may be available depending on your printer driver. To determine a value, record a macro that selects the option you want on the Paper Source tab in the Page Setup dialog box, and then review the values for .FirstPage and .OtherPages in the macro-editing window.
.VertAlign | Alignment of section on the page: 0 (zero) Top 1 Center 2 Justified
.ApplyPropsTo | The part of the document to apply the page setup properties to: 0 (zero) This Section 1 This Point Forward 2 Selected Sections 3 Selected Text 4 Whole Document
.Default | Makes the current page-setup properties the default for new documents based on the active template.

Argument | Explanation
.FacingPages | If 1, corresponds to selecting the Mirror Margins check box
.HeaderDistance | Distance of header from the top of the page
.FooterDistance | Distance of footer from the bottom of the page
.SectionStart | Determines the type of section break: 0 (zero) Continuous 1 New Column 2 New Page 3 Even Page 4 Odd Page
.OddAndEvenPages | If 1, corresponds to selecting the Different Odd And Even check box
.DifferentFirstPage | If 1, corresponds to selecting the Different First Page check box
.Endnotes | If 1, corresponds to selecting the Suppress Endnotes check box
.LineNum | If 1, corresponds to selecting the Add Line Numbering check box
.StartingNum | The number at which to begin line numbering
.FromText | The distance from text, in points or a text measurement; 0 (zero) sets automatic spacing
.CountBy | The numeric increment used to print line numbers.
.NumMode | Determines how lines are numbered: 0 (zero) Restart at each new page 1 Restart at each new section 2 Continuous

Examples

This Windows example sets the top margin to 1 inch for the entire document:

FilePageSetup .ApplyPropsTo = 4, .TopMargin = "1 in"

The following Windows example displays the Paper Source tab in the Page Setup dialog box, and then applies the settings the user selects:

Dim dlg As FilePageSetup
GetCurValues dlg
dlg.Tab = 2
Dialog dlg
FilePageSetup dlg

See Also

FileDocumentLayout, FileMacCustomPageSetupGX, FileMacPageSetup, FileMacPageSetupGX, FormatColumns, FormatSectionLayout


FilePost

Syntax

FilePost Destination$

Remarks

Posts the active document to a public folder in Microsoft Exchange. If the folder specified by Destination$ isn't a valid public folder, an error occurs.

The FilePost statement is available only in Microsoft Word for Windows 95 and only if running against Microsoft Exchange Server.

See Also

FileRoutingSlip, FileSendMail


FilePreview

Syntax

FilePreview HorizPos, VertPos, Width, Height, .Identifier

Remarks

Creates a file preview box — similar to the one in the Find File dialog box (File menu) — in a custom dialog box. A custom dialog box can have only one file preview box.

You cannot use the Dialog Editor to create a FilePreview instruction. A good workaround is to use another control as a stand-in. In the Dialog Editor, size and position the stand-in control as you want the file preview box to be sized and positioned. Then, after you paste the dialog box definition into your macro, convert the stand-in instruction to a FilePreview instruction.

The file preview box displays the first page of the document that is active when the dialog box is displayed. You can also control which document is displayed in the file preview box by using DlgFilePreview in a dialog function. For information about using a dialog function, see Chapter 5, "Working with Custom Dialog Boxes," in Part 1, "Learning WordBasic."

Argument | Explanation
HorizPos, VertPos | The horizontal and vertical distance of the upper-left corner of the file preview box from the upper-left corner of the dialog box, in increments of 1/8 and 1/12 of the System font (Windows) or the dialog font (Macintosh).
Width, Height | The width and height of the file preview box, in increments of 1/8 and 1/12 of the System font (Windows) or the dialog font (Macintosh).
.Identifier | An identifier used by a DlgFilePreview instruction in a dialog function to change the document displayed in the file preview box.

For an example, see DlgUpdateFilePreview.

See Also

DlgFilePreview, DlgUpdateFilePreview, Picture


FilePrint

Syntax

FilePrint [.Background = number] [, .AppendPrFile = number] [, .Range = number] [, .PrToFileName = text] [, .From = text] [, .To = text] [, .Type = number] [, .NumCopies = number] [, .Pages = text] [, .Order = number] [, .PrintToFile = number] [, .Collate = number] [, .FileName = text] [, .OutputPrinter = text]

Remarks

Prints all or part of the active document or a document you specify. The arguments for the FilePrint statement correspond to the options in the Print dialog box (File menu).

Argument | Explanation
.Background | If 1, the macro continues while Word prints the document. On the Macintosh, this argument is not available and generates an error.
.AppendPrFile | If you print to a file, specifies whether to overwrite or append to the file if it already exists: 0 (zero) Overwrite 1 Append On the Macintosh, this argument is ignored unless QuickDraw GX is installed.
.Range | The page range: 0 (zero) Prints the entire document 1 Prints the selection 2 Prints the current page 3 Prints the range of pages specified by .From and .To 4 Prints the range of pages specified by .Pages
.PrToFileName | If you print to a file, the path and filename of the file to print to. This argument is not available on the Macintosh unless QuickDraw GX is installed.
.From | The starting page number when .Range is 3
.To | The ending page number when .Range is 3
.Type | The item to print: 0 (zero) Document 1 Summary Info 2 Annotations 3 Styles 4 AutoText Entries 5 Key Assignments

Argument | Explanation
.NumCopies | The number of copies to print
.Pages | The page numbers and page ranges you want to print, separated by commas. For example, "2, 6-10" prints page 2 and pages 6 through 10.
.Order | Further delimits the range of pages to print: 0 (zero) Prints all pages in the range. 1 Prints only odd pages in the range. 2 Prints only even pages in the range.
.PrintToFile | If 1, sends printer instructions to a file. Make sure to specify a filename with .PrToFileName. This argument is not available on the Macintosh unless QuickDraw GX is installed.
.Collate | If 1, organizes pages when printing multiple copies of the document.
.FileName | The path and filename of the document to print. If omitted, Word prints the active document.
.OutputPrinter | On the Macintosh, if QuickDraw GX is installed, specifies the printer to print to. If the specified printer is not valid, Word prints to the printer selected in the Print dialog box or to the default desktop printer.

See Also

FilePrintDefault, FilePrintOneCopy, FilePrintSetup, ToolsOptionsPrint


FilePrintDefault

Syntax

FilePrintDefault

Remarks

Prints the active document using the current settings in the Print and Print Setup (Word version 6.0) dialog boxes (File menu) and on the Print tab in the Options dialog box (Tools menu).

See Also

FilePrint, FilePrintOneCopy, FilePrintSetup, ToolsOptionsPrint


FilePrintOneCopy

Syntax

FilePrintOneCopy

Remarks

On the Macintosh with QuickDraw GX installed, prints a single copy of the active document. This statement corresponds to the Print One Copy command that is added to the File menu if you install QuickDraw GX. In Windows, and on the Macintosh if QuickDraw GX is not installed, FilePrintOneCopy is not available and generates an error.

See Also

FilePrint, FilePrintDefault


FilePrintPreview, FilePrintPreview()

Syntax

FilePrintPreview [On]

FilePrintPreview()

Remarks

The FilePrintPreview statement switches the active document to and from print preview.

Argument | Explanation
On | Displays the document in print preview or the previous view: Omitted Toggles print preview 0 (zero) Cancels print preview 1 Switches to print preview

The FilePrintPreview() function returns the following values.

Value | Explanation
–1 | If the active document is in print preview
0 (zero) | If the active document is in some other view

See Also

ClosePreview, FilePrintPreviewFullScreen, FilePrintPreviewPages, ViewZoom


FilePrintPreviewFullScreen

Syntax

FilePrintPreviewFullScreen

Remarks

Toggles the display of rulers, scroll bars, the status bar, and the menu bar in print preview. If the active document is not in print preview, an error occurs.

See Also

ToolsOptionsView


FilePrintPreviewPages, FilePrintPreviewPages()

Syntax

FilePrintPreviewPages PagesAcross

FilePrintPreviewPages()

Remarks

The FilePrintPreviewPages statement specifies whether to display one or two columns of pages in page layout view and print preview. PagesAcross can be 1
or 2 only; for more control over the grid of page images, use ViewZoom. The FilePrintPreviewPages() function returns the number of columns of pages currently displayed. If the active document is not in either page layout view or print preview, an error occurs.

See Also

FilePrintPreview, ViewPage, ViewZoom


FilePrintSetup

Syntax

FilePrintSetup [.Printer = text] [, .Options] [, .DoNotSetAsSysDefault = number]

Remarks

Changes the active printer or a printer's options. In Word version 6.0, the arguments for the FilePrintSetup statement correspond to the options in the Print Setup dialog box (Print command, File menu). On the Macintosh, FilePrintSetup is not available and generates an error.

Argument | Explanation
.Printer | The name of the new printer to be activated. Specify this argument exactly as it appears in the Printer Setup dialog box. To activate the system default printer, specify an empty string ("").
.Options | Displays a dialog box showing the options for .Printer. You can use the SendKeys statement to select options.
.DoNotSetAsSysDefault | If 0 (zero) or omitted, makes .Printer the system default printer. In Word version 6.0, this argument is unavailable and generates an error.

Examples

This Windows example changes the system default printer to the PostScript® printer attached to the COM2 port.

FilePrintSetup .Printer = "PostScript printer on COM2:"

The following Windows example uses the SendKeys statement to send the key sequence ALT+O, ALT+L, Enter to the Options dialog box for the current printer. The instructions depend on the existence of an Orientation box whose access key is O and a Landscape button in that box whose access key is L.

SendKeys "%o%l{enter}"
FilePrintSetup .Options

See Also

FilePrint, SendKeys, ToolsOptionsPrint


FileProperties

Syntax

FileProperties

Remarks

Displays the Properties dialog box for the active document. For a list of the built-in properties available in Word, see DocumentPropertyName$(). In Word version 6.0, FileProperties is unavailable and generates an error.

Use the document properties statements and functions to define custom properties and to return and change the values for available custom and built-in properties.

See Also

DocumentPropertyName$(), GetDocumentProperty(), SetDocumentProperty


FileQuit

Syntax

FileQuit [Save]

Remarks

Quits Word. FileQuit (Macintosh) is the same as FileExit (Windows). For information on the Save argument, see FileExit.

See Also

AppClose, ExitWindows, FileCloseAll, FileExit


FileRoutingSlip

Syntax

FileRoutingSlip [.Subject = text] [, .Message = text] [, .AllAtOnce = number] [, .ReturnWhenDone = number] [, .TrackStatus = number] [, .Protect = number] [, .AddSlip] [, .RouteDocument] [, .AddRecipient] [, .OldRecipient] [, .ResetSlip] [, .ClearSlip] [, .ClearRecipients] [, .Address = text]

Remarks

Adds, removes, or changes the routing slip for the active document, or routes the active document to the recipients specified by the routing slip. FileRoutingSlip is available only if Microsoft Mail is installed. The arguments for FileRoutingSlip correspond to the options in the Routing Slip dialog box (Add Routing Slip command, File menu).

Argument | Explanation
.Subject | Text for the subject line of the electronic mail message
.Message | The message you want to precede the icon for the attached document
.AllAtOnce | Specifies how recipients receive the document: 0 (zero) Sends the document to the first recipient specified by .Address 1 Sends a copy of the document to all the recipients at the same time
.ReturnWhenDone | If 1, sends the document back to the original sender when the last recipient chooses the Send command from the File menu
.TrackStatus | If 1, sends a message back to the original sender each time the document is forwarded

Argument | Explanation
.Protect | Specifies a level of protection for the document: 0 (zero) No protection 1 All changes are tracked by revision marks. 2 Recipients can add annotations only. 3 Recipients can enter information in form fields only.
.Address | The address of a recipient for the document you are routing. To add multiple recipients, use multiple FileRoutingSlip instructions to add them one at a time. If you are routing the document to recipients one at a time, add recipient names in the order you want to route the document.

Only one of the following arguments can be specified for each FileRoutingSlip instruction.

Argument | Explanation
.AddSlip | Adds a routing slip to the active document. Note that when you close a document with an attached routing slip, Word displays a message asking if you want to route the document. To suppress this message in a macro that contains DocClose, FileClose, FileCloseAll, or FileExit instructions, set the .Save argument for those statements to 1 or 2. Word closes the document or documents without routing them.
.RouteDocument | Routes the active document.
.AddRecipient | Adds the address specified by .Address to the list of recipients.
.OldRecipient | Adds the address specified by .Address to the list of recipients only if the document has not already been routed. When you record a modification to a routing slip for a document that has already been routed, FileRoutingSlip instructions with .OldRecipient arguments are recorded for recipients who have already received the document.
.ResetSlip | Prepares the document to be rerouted to the recipients. If the document has not completed its first routing, Word displays a message.
.ClearSlip | Removes the routing slip from the active document.
.ClearRecipients | Removes all addresses from the list of recipients.

Example

This example adds a routing slip to the active document (which includes the current date in the subject line), adds two recipients, and then routes the document:

curdate$ = Date$(Now())
FileRoutingSlip .Subject = "Status Doc " + curdate$, \
    .Message = "Please fill in your status.", .AllAtOnce = 0, \
    .ReturnWhenDone = 1, .TrackStatus = 1, .Protect = 1, .AddSlip
FileRoutingSlip .Address = "Sara Levine", .AddRecipient
FileRoutingSlip .Address = "Carlos Alicea", .AddRecipient
FileRoutingSlip .RouteDocument

See Also

FileSendMail


Files$()

Syntax

Files$(FileSpec$)

Remarks

Returns the first filename that matches the file specification FileSpec$. If you specify a period (.) (Windows) or colon (:) (Macintosh) as the FileSpec$, Files$() returns the current path. In Windows, you can use the MS-DOS wildcard characters — the asterisk (*) and the question mark (?) — to specify files. On the Macintosh, you use MacID$() to specify files of a certain type.

Argument | Explanation
FileSpec$ | The file specification. If you omit the file specification, the next file that matches the most recently used FileSpec$ is returned. In Windows, you can specify a path as part of the file specification (for example, C:\DOCS\*.TXT). On the Macintosh, you produce the same result by changing the current folder with ChDir and then using MacID$() to specify files of a certain type (for example, MacID$("TEXT")).

By specifying FileSpec$ on the first iteration and omitting it thereafter, you can use Files$() to generate a list of files that match FileSpec$ (as in the final example in this reference entry). If no files match, an empty string ("") is returned.

Note that if the path or filename returned by Files$() contains one or more spaces, the entire return value is enclosed in quotation marks.

Examples

This Windows example returns the first file ending with the .DOC filename extension found in the current folder:

a$ = Files$("*.DOC")

The following is the same example, rewritten for the Macintosh. W6BN is the four-character sequence that specifies the Word Document file type.

a$ = Files$(MacID$("W6BN"))

The following examples return the current path (for example, "C:\WINWORD" or "HD:WORD 6:"):

CurDir$ = Files$(".")    'Windows example
CurDir$ = Files$(":")    'Macintosh example

If NOTE.DOC exists in the current folder, the following example opens the document. If NOTE.DOC does not exist, a message box is displayed.

If Files$("NOTE.DOC") <> "" Then
    FileOpen "NOTE.DOC"
Else
    MsgBox "File not found in current folder."
End If

The following example fills an array with the names of all files in the current folder. The instructions first count the files to determine the size of the array. Then they define the array, fill it with the filenames, and sort the elements. You could use this array to present a list of files in a user-defined dialog box or to open and perform an operation on each file in the array. On the Macintosh, substitute MacID$("****") for "*.*" in the file specifications.

temp$ = Files$("*.*")
count = - 1
While temp$ <> ""
    count = count + 1
    temp$ = Files$()
Wend
If count > -1 Then
    Dim list$(count)
    list$(0) = Files$("*.*")
    For i = 1 To count
        list$(i) = Files$()
    Next i
    SortArray list$()
    MsgBox Str$(count + 1) + " files; 1st in array is " + list$(0)
Else
    MsgBox "No files in current folder."
End If

See Also

FileFind, MacID$()


FileSave

Syntax

FileSave

Remarks

Saves the active document or template. If the document is not named, FileSave displays the Save As dialog box (File menu).

See Also

FileSaveAll, FileSaveAs, IsDocumentDirty(), IsTemplateDirty()


FileSaveAll

Syntax

FileSaveAll [Save] [, OriginalFormat]

Remarks

Saves all changed files, including the Normal template and any other templates attached to open documents that have changed. It's a good idea to include a FileSaveAll statement if your macro makes changes to AutoText entries, other macros, or keyboard, menu, and toolbar assignments.

Argument | Explanation
Save | Specifies whether or not to prompt the user to save each document or template if it is "dirty" — that is, if changes have been made since the last time the document or template was saved: 0 (zero) Prompts the user to save each changed document or template. 1 Saves all changed documents and templates automatically.
OriginalFormat | Specifies whether or not to prompt when saving a document opened from a foreign file format in which changes have been made that cannot be stored in the original format: 0 (zero) Saves the document in Word Document format. 1 Saves the document in its original format. 2 or omitted Prompts the user to save in Word Document format.

See Also

FileSave, FileSaveAs, IsDocumentDirty(), IsTemplateDirty()


FileSaveAs

Syntax

FileSaveAs [.Name = text] [, .Format = number] [, .LockAnnot = number] [, .Password = text] [, .AddToMru = number] [, .WritePassword = text] [, .RecommendReadOnly = number] [, .EmbedFonts = number] [, .NativePictureFormat = number] [, .FormsData = number] [, .SaveAsAOCELetter = number]

Remarks

Saves the active document with a new name or format. The arguments for the FileSaveAs statement correspond to the options in the Save As dialog box (File menu).

Argument | Explanation
.Name | The new name. If you don't specify .Name, the current folder and name are the defaults. If the document has never been saved, Word saves to a default name such as DOC1.DOC (Windows) or DOCUMENT1 (Macintosh). Note that if a document with the new name or a default name already exists, Word overwrites that document without prompting.
.Format | Specifies the new format: 0 (zero) Word document 1 Document template 2 Text Only (extended characters saved in ANSI character set) 3 Text Only with Line Breaks (extended characters saved in ANSI character set) 4 MS-DOS Text (extended characters saved in IBM® PC character set) (Windows only) 5 MS-DOS Text with Line Breaks (extended characters saved in IBM PC character set) (Windows only) 6 Rich-Text Format (RTF) You can return values appropriate for other formats by specifying a format name in a ConverterLookup() instruction.
.LockAnnot | If 1, locks the document for annotations. You can also lock a document with ToolsProtectDocument.
.Password | Sets a password for opening the document.
.AddToMru | If 1, places the document name first on the list of recently used files at the bottom of the File menu. (Note that MRU is an abbreviation for "most recently used.")
.WritePassword | Sets a password for saving changes to the document.
.RecommendReadOnly | If 1, displays a message upon opening the document suggesting that it be opened as read-only.
.EmbedFonts | If 1, embeds TrueType fonts in the document.
.NativePictureFormat | If 1, saves only the Windows version of imported graphics.
.FormsData | If 1, saves the data entered by a user in a form as a data record. Note the form must be unprotected or FileSaveAs generates an error.
.SaveAsAOCELetter | If the active document has an attached mailer, specifies how to save the document: 0 (zero) As a Word document (mailer is not saved) 1 or omitted As an AOCE letter (mailer is saved) This option is available only on the Macintosh and only if PowerTalk is installed.

Example

This example saves the active document in rich-text format (RTF) with the filename TEST.RTF:

FileSaveAs .Name = "TEST.RTF", .Format = 6

See Also

Converter$(), ConverterLookup(), FileSave, FileSaveAll, Name, ToolsOptionsSave, ToolsProtectDocument


FileSendMail

Syntax

FileSendMail

Remarks

Opens a message window for sending the active document through Microsoft Mail. Use the ToolsOptionsGeneral statement with the .SendMailAttach argument to control whether the document is sent as text in the message window or as an attachment. FileSendMail is available only if Microsoft Mail is installed.

See Also

AOCESendMail, FileAOCESendMail, FileRoutingSlip, ToolsOptionsGeneral


FileSummaryInfo

Syntax

FileSummaryInfo [.Title = text] [, .Subject = text] [, .Author = text] [, .Keywords = text] [, .Comments = text] [, .FileName = text] [, .Directory = text] [, .Template = text] [, .CreateDate = text] [, .LastSavedDate = text] [, .LastSavedBy = text] [, .RevisionNumber = text] [, .EditTime = text] [, .LastPrintedDate = text] [, .NumPages = text] [, .NumWords = text] [, .NumChars = text] [, .NumParas = text] [, .NumLines = text] [, .Update] [, .FileSize = text]

Remarks

Sets the summary information and allows access to document statistics for the active document. In Word version 6.0, the arguments for the FileSummaryInfo statement correspond to the options in the Summary Info dialog box (File menu) and the Document Statistics dialog box (Statistics button, Summary Info command). All the arguments corresponding to the options in the Document Statistics dialog box are read-only, with the exception of .EditTime.

In Word version 7.0, this statement is included for backward compatibility. You can use the document property statements and functions to set or access summary information for the active document. For more information, see GetDocumentProperty() and SetDocumentProperty.

Argument | Explanation
.Title | The title of the document
.Subject | The subject of the document
.Author | The author of the document
.Keywords | The keywords used to identify the document

Argument | Explanation
.Comments | The comments about the document
.FileName | When using FileSummaryInfo as a statement, the name of the file to make summary information changes to (the file must be open); when returning information from a FileSummaryInfo dialog record, the filename of the active document (path not included)
.Directory | The document's location (read-only)
.Template | The document template (read-only)
.CreateDate | The creation date (read-only)
.LastSavedDate | The date the document was last saved (read-only)
.LastSavedBy | The name of the person last saving the document (read-only)
.RevisionNumber | The number of times the document has been saved (read-only)
.EditTime | The total time the document has been open, in minutes
.LastPrintedDate | The date the document was last printed (read-only)
.NumPages | The number of pages (read-only)
.NumWords | The number of words (read-only)
.NumChars | The number of characters (read-only)
.NumParas | The number of paragraphs (read-only)
.NumLines | The number of lines (read-only)
.Update | Updates the summary information
.FileSize | The size of the document in the form "36,352 Bytes" (read-only)

Note

To ensure you get the most up-to-date information when using a FileSummaryInfo dialog record to return summary information or document statistics, include the instruction FileSummaryInfo .Update before defining the dialog record.

Examples

This example sets the title of the active document:

FileSummaryInfo .Title = "Exploration of the Upper Amazon."

The following example defines the variable author$ as the author of the active document.

Dim dlg As FileSummaryInfo
GetCurValues dlg
author$ = dlg.Author

See Also

DocumentStatistics


FileTemplates

Syntax

FileTemplates [.Template = text] [, .LinkStyles = number]

Remarks

Changes the template attached to the active document. To add or remove global templates, use AddAddIn, AddInState, and DeleteAddIn. The arguments for the FileTemplate statement correspond to the options in the Templates And Add-ins dialog box (Templates command, File menu).

Argument | Explanation
.Template | The path and filename of the template to attach.
.LinkStyles | If 1, styles in the active document are linked to the active template; Word copies styles from the attached template each time the document is opened.

If you choose Templates from the File menu while recording a macro, Word records the .Store argument in the FileTemplates statement. This argument is recognized for backward compatibility with Word version 2.x macros. In Word version 6.0 or later, the .Store argument is ignored.

See Also

AddAddIn, AddInState, DeleteAddIn, FileNew, Organizer


FileType$()

Syntax

FileType$(File$)

Remarks

On the Macintosh, returns a four-character string identifying the file type of File$ (a path and filename). In Windows, FileType$() is not available and generates an error.

Example

This Macintosh example displays a message box stating the file type of the file specified by checkfile$:

checkfile$ = "HD:WORK:TO DO LIST"
ftype$ = FileType$(checkfile$)
Select Case ftype$
    Case "W6BN" : a$ = "a Word document"
    Case "WDBN" : a$ = "a Word 5.1 document"
    Case "WTBN" : a$ = "a Word template"
    Case "TEXT" : a$ = "a text file"
    Case "XLS5" : a$ = "a Microsoft Excel worksheet"
    Case "APPL" : a$ = "an application"
    Case "WDLL" : a$ = "a Word add-in library"
    Case "WIZ!" : a$ = "a wizard"
    Case Else : a$ = ""
End Select
If a$ <> "" Then
    MsgBox checkfile$ + " is " + a$ + "."
Else
    MsgBox checkfile$ + " has file type " + ftype$ "."
End If

See Also

FileCreator$(), MacID$(), SetFileCreatorAndType


Font, Font$()

Syntax

Font Name$ [, Size]

Font$()

Font$(Count)

Remarks

The Font statement applies the specified font to the selection.

Argument | Explanation
Name$ | The name of the font to apply.
Size | The size of the font, in points. You can use this argument instead of following a Font instruction with a FontSize instruction.

The Font$() function returns the name of the font applied to the selection. If the selection contains more than one font, an empty string ("") is returned. If Count is specified, Font$() returns the name of the font at position Count in the current font list, in the range 1 to CountFonts().

Examples

This example selects the paragraph containing the insertion point (using the predefined bookmark " \ Para") and then applies 8-point Courier font:

EditGoTo "\Para"
Font "Courier", 8

The following example displays a message box if the paragraph containing the insertion point has more than one font:

EditGoTo "\Para"
If Font$() = "" Then
    MsgBox "Paragraph contains more than one font."
End If

See Also

CountFonts(), FontSize, FormatFont


FontSize, FontSize()

Syntax

FontSize Size

FontSize()

Remarks

The FontSize statement sets the font size of the selected text, in points.

The FontSize() function returns the font size of the selected text. If the selection contains more than one font size, 0 (zero) is returned.

See Also

Font, FontSizeSelect, FormatFont


FontSizeSelect

Syntax

FontSizeSelect

Remarks

If the Formatting toolbar is displayed, moves the focus to the Font Size box; otherwise, displays the Font dialog box (Format menu), selects the Font tab, and then moves the focus to the Size box.

See Also

Font, FontSize, FormatFont


FontSubstitution

Syntax

FontSubstitution .UnavailableFont = text, .SubstituteFont = text

Remarks

Sets font-mapping options for the active document. The arguments for the FontSubstitution statement correspond to the options in the Font Substitution dialog box (Compatibility tab, Options dialog box, Tools menu).

Argument | Explanation
.UnavailableFont | The name of a font not available on your computer that you want to map to a different font for display and printing
.SubstituteFont | The name of a font available on your computer that you want to substitute for the unavailable font

See Also

ToolsOptionsCompatibility


For...Next

Syntax

For CounterVariable = Start To End [Step Increment]
Series of instructions
Next [CounterVariable]

Remarks

Repeats the series of instructions between For and Next while increasing CounterVariable by 1 (default) or Increment until CounterVariable is greater than End. If Start is greater than End, Increment must be a negative value; CounterVariable decreases by Increment until it is less than End.

If you place one or more For ¼ Next loops within another, use a unique CounterVariable for each loop, as in the following instructions:

For I = 1 To 10
    For J = 1 To 10
        For K = 1 To 10
            'Series of instructions
        Next K
    Next J
Next I

For more information about For ¼ Next, see Chapter 4, "Advanced WordBasic," in Part 1, "Learning WordBasic."

Examples

This example displays five message boxes in a row, each giving the current value of count:

For count = 1 To 5
    MsgBox "Current value of count is" + Str$(count)
Next count

The following example produces exactly the same effect as the previous example by decrementing the value of count in steps of –1:

For count = 5 To 1 Step -1
    MsgBox "Current value of count is" + Str$(count)
Next

The following example demonstrates how you can use WordBasic counting functions with a For ¼ Next loop to perform an operation on all the items in a certain category. In this example, the names of all the bookmarks defined in the active document are stored in the array mark$().

numBookmarks = CountBookmarks()
arraySize = numBookmarks - 1
Dim mark$(arraySize)
For n = 0 To arraySize
    mark$(n) = BookmarkName$(n + 1)
Next

See Also

Goto, If ¼ Then ¼ Else, Select Case, While ¼ Wend


FormatAddrFonts

Syntax

FormatAddrFonts [.Points = number] [, .Underline = number] [, .Color = number] [, .Strikethrough = number] [, .Superscript = number] [, .Subscript = number] [, .Hidden = number] [, .SmallCaps = number] [, .AllCaps = number] [, .Spacing = number] [, .Position = number or text] [, .Kerning = number] [, .KerningMin = number or text] [, .Default] [, .Tab = number] [, .Font = text] [, .Bold = number] [, .Italic = number]

Remarks

Sets character formatting for the address on an envelope. Precede ToolsCreateEnvelope with FormatAddrFonts to specify options corresponding to those in the Font dialog box (Format menu). Include .Default to store the options you specify as the default character formatting for the address. For argument descriptions, see FormatFont.

See Also

FormatFont, FormatRetAddrFonts, ToolsCreateEnvelope


FormatAutoFormat

Syntax

FormatAutoFormat

Remarks

Automatically formats a document according to the options set with ToolsOptionsAutoFormat. To control the look of the document, you can use FormatStyleGallery to copy styles into the active document before or after running FormatAutoFormat.

Example

This Windows example automatically formats the active document using styles in REPORT1.DOT. On the Macintosh, substitute "REPORT 1" for "REPORT1."

FormatStyleGallery .Template = "REPORT1"
FormatAutoFormat

See Also

FormatStyleGallery, ToolsOptionsAutoFormat


FormatBordersAndShading

Syntax

FormatBordersAndShading [.ApplyTo = number] [, .Shadow = number] [, .TopBorder = number] [, .LeftBorder = number] [, .BottomBorder = number] [, .RightBorder = number] [, .HorizBorder = number] [, .VertBorder = number] [, .TopColor = number] [, .LeftColor = number] [, .BottomColor = number] [, .RightColor = number] [, .HorizColor = number] [, .VertColor = number] [, .FineShading = number] [, .FromText = number or text] [, .Shading = number] [, .Foreground = number] [, .Background = number] [, .Tab = number]

Remarks

Sets border and shading formats for the selected paragraphs, table cells, or graphic. The arguments for the FormatBordersAndShading statement correspond to the options in the Borders And Shading dialog box (Format menu).

Argument | Explanation
.ApplyTo | If the selection consists of more than one of the following items, specifies to which item or items the border format is applied: 0 (zero) Paragraphs 1 Graphic 2 Cells 3 Whole table If .ApplyTo is omitted, the default for the selection is assumed.
.Shadow | Specifies whether to apply a shadow to the border of paragraphs or a graphic: 0 (zero) Does not apply a shadow. 1 Applies a shadow. You cannot apply a shadow to a table or table cells. If you want to apply a shadow to a paragraph or graphic, the item must have — or you must specify — matching right, left, top, and bottom borders. Otherwise, an error occurs.
.VertBorder | The line style for the vertical border between table cells, in the range 0 (zero), which is no border, through 11 (or 12 on the Macintosh). The border does not appear unless the table selection is at least two cells wide. (When applied to paragraphs, .VertBorder has the same effect as .LeftBorder.)
.TopColor, .LeftColor, .BottomColor, .RightColor, .HorizColor, .VertColor | The color to be applied to the specified borders, in the range from 0 (zero), which is Auto, through 16. For a list of colors and their values, see CharColor.
.FineShading | A shading pattern in the range 0 (zero) to 40 corresponding to a shading percentage in 2.5 percent increments. If .FineShading is anything but 0 (zero), .Shading is ignored.
.FromText | The distance of the border from adjacent text, in points or a text measurement. Valid only for paragraphs; otherwise, .FromText must be an empty string ("") or omitted or an error will occur.
.Shading | The shading pattern to be applied to the selection, in the range from 0 (zero), which is Clear, through 25. For a list of shading patterns and their values, see ShadingPattern.

Argument | Explanation
.Foreground | The color to be applied to the foreground of the shading, in the range from 0 (zero), which is Auto, through 16. For a list of colors and their values, see CharColor.
.Background | The color to be applied to the background of the shading, in the range from 0 (zero), which is Auto, through 16.
.Tab | Specifies which tab to select when you display the Borders And Shading dialog box with a Dialog or Dialog() instruction: 0 (zero) Borders tab 1 Shading tab

See Also

BorderBottom, BorderInside, BorderLeft, BorderLineStyle, BorderNone, BorderOutside, BorderRight, BorderTop, EditFindBorder, EditReplaceBorder, ShadingPattern


FormatBullet

Syntax

FormatBullet [.Points = number] [, .Color = number] [, .Alignment = number] [, .Indent = number or text] [, .Space = number or text] [, .Hang = number] [, .CharNum = number] [, .Font = text]

Remarks

Adds bullets to the selected paragraphs. The arguments for the FormatBullet statement correspond to the options in the Modify Bulleted List dialog box (Bulleted tab, Bullets And Numbering command, Format menu). You cannot display this dialog box using a Dialog or Dialog() instruction.

Argument | Explanation
.Points | The size of the bullets, in points
.Color | The color of the bullets (for a list of colors, see CharColor)
.Alignment | Specifies an alignment for the bullets within the space between the left indent and the first line of text; takes effect only if .Space is 0 (zero): 0 (zero) or omitted Left 1 Centered 2 Right
.Indent | The distance between the left indent and the first line of text, in points or a text measurement
.Space | The distance between the bullet and the first line of text, in points or a text measurement

Argument | Explanation
.Hang | If 1, applies a hanging indent to the selected paragraphs
.CharNum | The sum of 31 and the number corresponding to the position of the symbol in the Symbol dialog box (Insert menu), counting from left to right. For example, to specify an omega (W), which is at position 56 on the table of symbols in the Symbol font, set .CharNum to 87.
.Font | The name of the font containing the symbol. Names of decorative fonts appear in the Font box in the Symbol dialog box.

See Also

CharColor, FormatBulletsAndNumbering, FormatHeadingNumber, FormatMultilevel, FormatNumber


FormatBulletDefault, FormatBulletDefault()

Syntax

FormatBulletDefault [Add]

FormatBulletDefault()

Remarks

The FormatBulletDefault statement adds bullets to or removes bullets from the selected paragraphs.

Argument | Explanation
Add | Specifies whether to add or remove bullets: 0 (zero) Removes bullets. If the paragraph preceding or following the selection is not formatted as a list paragraph, the list format in the selection is removed along with the bullets. 1 Adds bullets. If the paragraph preceding the selection already has bullets applied with the Bullets And Numbering command (Format menu), the selected paragraphs are formatted with matching bullets; otherwise, the default settings of the Bullets And Numbering dialog box (Format menu) are used. Omitted Toggles bullets.

The FormatBulletDefault() function returns the following values.

Value | Explanation
0 (zero) | If none of the selected paragraphs are bulleted or numbered
–1 | If the selected paragraphs are not all bulleted, all "skipped," or all formatted with the same level of numbering
1 | If all the selected paragraphs are bulleted

See Also

FormatBulletsAndNumbering, FormatNumberDefault, SkipNumbering


FormatBulletsAndNumbering

Syntax

FormatBulletsAndNumbering [.Remove] [, .Hang = number] [, .Preset = number]

Remarks

Adds bullets or numbers to the selected paragraphs based on the preset bullets or numbering scheme you specify, or removes bullets and numbers. The arguments for the FormatBulletsAndNumbering statement correspond to the options in the Bullets And Numbering dialog box (Format menu). In Windows, you cannot display this dialog box using a Dialog or Dialog() instruction. On the Macintosh, you can display this dialog box using a Dialog or Dialog() instruction; however, the Multilevel tab does not appear.

Argument | Explanation
.Remove | Removes bullets or numbering from the selection.
.Hang | If 1, applies a hanging indent to the selected paragraphs.
.Preset | A number corresponding to a bullets or numbering scheme in the Bullets And Numbering dialog box (Format menu) To determine the appropriate number, display the Bullets And Numbering dialog box and then select the tab with the scheme you want. Counting left to right, values for the preset schemes are: u 1 through 6 for the schemes on the Bulleted tab u 7 through 12 for the schemes on the Numbered tab u 13 through 18 for the schemes on the Multilevel tab

Example

This example adds diamond-shaped bullets to the selected paragraphs and formats the paragraphs with a hanging indent:

FormatBulletsAndNumbering .Hang = 1, .Preset = 3

See Also

FormatBulletDefault, FormatNumberDefault, RemoveBulletsNumbers, SkipNumbering


FormatCallout

Syntax

FormatCallout [.Type = number] [, .Gap = number or text] [, .Angle = number] [, .Drop = text] [, .Length = number or text] [, .Border = number] [, .AutoAttach = number] [, .Accent = number]

Remarks

Sets options for callout drawing objects. The arguments for the FormatCallout statement correspond to the options in the Format Callout dialog box (Format Callout button, Drawing toolbar).

Argument | Explanation
.Type | Specifies the type of callout: 0 (zero) One line segment (vertical or horizontal) 1 One line segment (vertical, horizontal, or diagonal) 2 Two line segments 3 Three line segments
.Gap | Specifies the distance between the callout line and the rectangle bounding the text area, in points or a text measurement.
.Angle | Specifies the angle for the callout line (affects the outermost line segment if .Type is set to 2 or 3): 0 (zero) Any; Word adjusts the angle automatically as you move and size the callout. 1 30 degrees 2 45 degrees 3 60 degrees 4 90 degrees
.Drop | Specifies the starting position of the callout line with respect to the rectangle bounding the text area: Top Top of the text area (or if .Type is set to 1 and the line segment is horizontal, the right edge of the text area) Center Center of the text area Bottom Bottom of the text area (or if .Type is set to 1 and the line segment is horizontal, the left edge of the text area) You can also specify a positive text measurement for the distance between the top of the text area and the starting point of the callout line.
.Length | If .Type is set to 2 or 3, the length of the first segment in the callout line in twips (20 twips = 1 point) or a text measurement, or "Best Fit" if you want Word to adjust the length automatically as you size and position the callout.
.Border | If 1, applies a border around the callout text.
.AutoAttach | If 1, changes the starting position of the callout line automatically when the callout origin or the callout text is switched from left to right.
.Accent | If 1, adds a vertical line next to the text area.

For an example, see DrawCallout.

See Also

DrawCallout, DrawGetCalloutTextBox, DrawSetCalloutTextBox, FormatDrawingObject


FormatChangeCase

Syntax

FormatChangeCase [.Type = number]

Remarks

Changes the case of the selected text according to the specified type of capitalization. The arguments for the FormatChangeCase statement correspond to the options in the Change Case dialog box (Format menu).

Argument | Explanation
.Type | The type of capitalization you want to apply: 0 (zero) or omitted Sentence case (capitalizes the first character in each selected sentence). 1 lowercase (changes selected characters to lowercase). 2 UPPERCASE (changes selected characters to uppercase). 3 Title Case (capitalizes the first letter of each selected word). 4 tOGGLE cASE (toggles the capitalization of each selected letter).

See Also

AllCaps, ChangeCase, LCase$(), SmallCaps, UCase$()


FormatColumns

Syntax

FormatColumns [.Columns = number or text] [, .ColumnNo = text] [, .ColumnWidth = text] [, .ColumnSpacing = text] [, .EvenlySpaced = number] [, .ApplyColsTo = number] [, .ColLine = number] [, .StartNewCol = number]

Remarks

Formats all or part of the document with the specified number of columns, or changes the width of and space between existing columns. The arguments for the FormatColumns statement correspond to the options in the Columns dialog box (Format menu).

Argument | Explanation
.Columns | The number of columns to apply to the portion of the document specified by .ApplyColsTo
.ColumnNo | If .EvenlySpaced is set to 0 (zero), the number of the column to format; if you are returning information from a FormatColumns dialog record, the column for which you want to return the width To set the width of any column independently of other columns, you need to include an additional FormatColumns instruction to set the width of the last column. If you include only one FormatColumns instruction, the resulting number of columns will be the same as .ColumnNo. For example, if you change the width of the first column in a section containing three columns, there will be only one column after the instruction runs. To preserve the three-column format, you need to include an additional FormatColumns instruction and set .ColumnNo to 3.

Argument | Explanation
.ColumnWidth | The width of the column specified by .ColumnNo, or if .EvenlySpaced is set to 1, the width of each column in the portion of the document specified by .ApplyColsTo
.ColumnSpacing | The space between columns
.EvenlySpaced | If 1, makes each column the same width
.ApplyColsTo | Specifies the portion of the document to apply the column format to: 0 (zero) This section 1 This Point Forward 2 Selected Sections 3 Selected Text 4 Whole Document
.ColLine | If 1, adds a line between columns
.StartNewCol | If 1, corresponds to selecting the Start New Column check box (effective only if This Point Forward is specified by .ApplyColsTo)

Example

This example formats the current section into three columns of equal width and specifies that a vertical line appear between columns:

FormatColumns .Columns = "3", .EvenlySpaced = 1, .ColLine = 1

See Also

TableColumnWidth


FormatDefineStyleBorders

Syntax

FormatDefineStyleBorders [.ApplyTo = number] [, .Shadow = number] [, .TopBorder = number] [, .LeftBorder = number] [, .BottomBorder = number] [, .RightBorder = number] [, .HorizBorder = number] [, .VertBorder = number] [, .TopColor = number] [, .LeftColor = number] [, .BottomColor = number] [, .RightColor = number] [, .HorizColor = number] [, .VertColor = number] [, .FineShading = number] [, .FromText = number or text] [, .Shading = number] [, .Foreground = number] [, .Background = number] [, .Tab = number]

Remarks

Sets border and shading formats for either the current style or the style specified in a FormatStyle instruction containing the .Define argument. Note that when modifying the style specified with FormatStyle, the FormatDefineStyleBorders instruction follows the FormatStyle instruction.

The arguments for the FormatDefineStyleBorders statement correspond to the options in the Borders And Shading dialog box (Format menu). For argument descriptions, see FormatBordersAndShading. For examples of how to use similar statements to define a style, see FormatDefineStyleFont and FormatDefineStylePara.

See Also

FormatBordersAndShading, FormatDefineStyleFont, FormatDefineStylePara, FormatStyle


FormatDefineStyleFont

Syntax

FormatDefineStyleFont [.Points = number] [, .Underline = number] [, .Color = number] [, .Strikethrough = number] [, .Superscript = value] [, .Subscript = value] [, .Hidden = number] [, .SmallCaps = number] [, .AllCaps = number] [, .Spacing = value] [, .Position = number or text] [, .Kerning = number] [, .KerningMin = number or text] [, .Default] [, .Tab = number] [, .Font = text] [, .Bold = number] [, .Italic = number]

Remarks

Sets character formats for either the current style or the style specified in a FormatStyle instruction containing the .Define argument. Note that when modifying the style specified with FormatStyle, the FormatDefineStyleFont instruction follows the FormatStyle instruction.

The arguments for the FormatDefineStyleFont statement correspond to options in the Font dialog box (Format menu). For argument descriptions, see FormatFont.

Example

This example defines the character formatting of the "TestMe" style as 10-point, bold, and small caps. Word creates the style if it does not already exist.

FormatStyle .Name = "TestMe", .Define
FormatDefineStyleFont .Points = "10", .Bold = 1, .SmallCaps = 1

See Also

FormatFont, FormatStyle


FormatDefineStyleFrame

Syntax

FormatDefineStyleFrame [.Wrap = number] [, .WidthRule = number] [, .FixedWidth = number or text] [, .HeightRule = number] [, .FixedHeight = number or text] [, .PositionHorz = number or text] [, .PositionHorzRel = number] [, .DistFromText = number or text] [, .PositionVert = number or text] [, .PositionVertRel = number] [, .DistVertFromText = number or text] [, .MoveWithText = number] [, .LockAnchor = number] [, .RemoveFrame]

Remarks

Sets frame formats for either the current style or the style specified in a FormatStyle instruction containing the .Define argument. Note that when modifying the style specified with FormatStyle, the FormatDefineStyleFrame instruction follows the FormatStyle instruction.

The arguments for the FormatDefineStyleFrame statement correspond to the options in the Frame dialog box (Format menu). For argument descriptions, see FormatFrame. For examples of how to use similar statements to define a style, see FormatDefineStyleFont and FormatDefineStylePara.

See Also

FormatDefineStyleFont, FormatDefineStylePara, FormatFrame, FormatStyle


FormatDefineStyleLang

Syntax

FormatDefineStyleLang .Language = text [, .Default]

Remarks

Sets the language format for either the current style or the style specified in
a FormatStyle instruction containing the .Define argument. Note that when modifying the style specified with FormatStyle, the FormatDefineStyleLang instruction follows the FormatStyle instruction.

The arguments for the FormatDefineStyleLang statement correspond to the options in the Language dialog box (Tools menu). For argument descriptions, see ToolsLanguage. For examples of how to use similar statements to define a style, see FormatDefineStyleFont and FormatDefineStylePara.

See Also

FormatDefineStyleFont, FormatDefineStylePara, FormatStyle, ToolsLanguage


FormatDefineStyleNumbers

Syntax

FormatDefineStyleNumbers [.Points = text] [, .Color = number] [, .Before = text] [, .Type = number] [, .After = text] [, .StartAt = text] [, .Include = number] [, .Alignment = number] [, .Indent = text] [, .Space = number or text] [, .Hang = number] [, .Level = text] [, .CharNum = text] [, .Font = text] [, .Strikethrough = number] [, .Bold = number] [, .Italic = number] [, .Underline = number]

Remarks

Sets number formats for either the current style or the style specified in a FormatStyle instruction containing the .Define argument. Note that when modifying the style specified with FormatStyle, the FormatDefineStyleNumbers instruction follows the FormatStyle instruction.

The arguments for the FormatDefineStyleNumbers statement correspond to the options in the Modify List dialog box (Bullets And Numbering command, Format menu). For argument descriptions, see FormatBullet, FormatMultilevel, and FormatNumber. For examples of how to use similar statements to define a style, see FormatDefineStyleFont and FormatDefineStylePara.

See Also

FormatBullet, FormatDefineStyleFont, FormatDefineStylePara, FormatMultilevel, FormatNumber, FormatStyle


FormatDefineStylePara

Syntax

FormatDefineStylePara [.LeftIndent = number or text] [, .RightIndent = number or text] [, .Before = number or text] [, .After = number or text] [, .LineSpacingRule = number] [, .LineSpacing = number or text] [, .Alignment = number] [, .WidowControl = number] [, .KeepWithNext = number] [, .KeepTogether = number] [, .PageBreak = number] [, .NoLineNum = number] [, .DontHyphen = number] [, .Tab = number] [, .FirstIndent = number or text]

Remarks

Sets paragraph formats for either the current style or the style specified in a FormatStyle instruction containing the .Define argument. Note that when modifying the style specified with FormatStyle, the FormatDefineStylePara instruction follows the FormatStyle instruction.

The arguments for the FormatDefineStylePara statement correspond to the options in the Paragraph dialog box (Format menu). For argument descriptions, see FormatParagraph.

Example

This example adds 4 points of Before formatting and 4 points of After formatting to the definition of the style "TestMe":

FormatStyle .Name = "TestMe", .Define
FormatDefineStylePara .Before = "4 pt", .After = "4 pt"

See Also

FormatParagraph, FormatStyle


FormatDefineStyleTabs

Syntax

FormatDefineStyleTabs [.Position = text] [, .DefTabs = number or text] [, .Align = number] [, .Leader = number] [, .Set] [, .Clear] [, .ClearAll]

Remarks

Sets tab formats for either the current style or the style specified in a FormatStyle instruction containing the .Define argument. Note that when modifying the style specified with FormatStyle, the FormatDefineStyleTabs instruction follows the FormatStyle instruction.

The arguments for the FormatDefineStyleTabs statement correspond to the options in the Tabs dialog box (Format menu). For argument descriptions, see FormatTabs. For examples of how to use similar statements to define a style, see FormatDefineStyleFont and FormatDefineStylePara.

See Also

FormatDefineStyleFont, FormatDefineStylePara, FormatStyle, FormatTabs


FormatDrawingObject

Syntax

FormatDrawingObject [.Tab = number] [, .FillColor = number or text] [, .LineColor = number or text] [, .FillPatternColor = number or text] [, .FillPattern = number or text] [, .LineType = number] [, .LineStyle = number] [, .LineWeight = number or text] [, .ArrowStyle = number] [, .ArrowWidth = number] [, .ArrowLength = number] [, .Shadow = number] [, .RoundCorners = number] [, .HorizontalPos = number or text] [, .HorizontalFrom = number] [, .VerticalPos = number or text] [, .VerticalFrom = number] [, .LockAnchor = number] [, .Height = number or text] [, .Width = number or text] [, .InternalMargin = number or text]

Remarks

Changes the fill color, line style, size, and position of the selected drawing object or objects. The arguments for the FormatDrawingObject statement correspond to the options in the Drawing Object dialog box (Format menu).

Argument | Explanation
.Tab | Specifies the tab to select when you display the Drawing Object dialog box with a Dialog or Dialog() instruction: 0 (zero) Fill tab 1 Line tab 2 Size And Position tab
.FillColor | Specifies a fill color. To specify a percentage of gray, double the percentage of gray you want and make it negative (for example, for 5 percent gray, specify –10; for 37.5 percent gray, specify –75). To specify a color, use a value between 1 and 16, as described in CharColor, where 0 (zero) indicates no color.
.LineColor | Specifies a line color. For values, see .FillColor.
.FillPatternColor | Specifies the pattern color. For values, see .FillColor.
.FillPattern | Specifies the fill pattern: 0 (zero) Sets both .FillColor and .FillPattern to "None." 1 through 25 Specifies an item in the Patterns box on the Fill tab: 1 corresponds to the first item ("None"), 2 to the second, and so on.

Argument | Explanation
.LineType | Specifies whether to show the line: 0 (zero) Hides the line; only the fill and the arrowheads (if any) show. 1 Shows the line defined by .LineColor, .LineStyle, and .LineWeight.
.LineStyle | Specifies a line style in the Style box on the Line tab, where 0 (zero) is the first item, 1 is the second item, and so on through 4.
.LineWeight | The line width, in points or a text measurement.
.ArrowStyle | Specifies the arrow style for a linear drawing object: 0 (zero) corresponds to the first item (no arrowheads) in the Style box under Arrow Head, 1 to the second item, and so on through 6.
.ArrowWidth | Specifies the width of the arrowhead for a linear drawing object: 0 (zero) Narrow 1 Medium 2 Thick
.ArrowLength | Specifies the length of the arrowhead for a linear drawing object: 0 (zero) Short 1 Medium 2 Long
.Shadow | If 1, applies a shadow effect to the drawing object.
.RoundCorners | If 1, rounds the corners of a rectangular drawing object.
.HorizontalPos | The distance, in points or a text measurement, between the reference point specified by .HorizontalFrom and the drawing object.
.HorizontalFrom | Specifies the reference point from which the horizontal position of the drawing object is measured: 0 (zero) Margin 1 Page 2 Column
.VerticalPos | The distance, in points or a text measurement, between the reference point specified by .VerticalFrom and the drawing object.
.VerticalFrom | Specifies the reference point from which the vertical position of the drawing object is measured: 0 (zero) Margin 1 Page 2 Paragraph

Argument | Explanation
.LockAnchor | If 1, the drawing-object anchor remains fixed when the associated drawing object is repositioned. A locked anchor cannot be repositioned.
.Height | The height of the drawing object, in points or a text measurement.
.Width | The width of the drawing object, in points or a text measurement.
.InternalMargin | A measurement, in twips (20 twips = 1 point) or a text measurement, for the internal margin within a text box or callout drawing object.

Example

This example moves the selected drawing object down 10 points and to the right 10 points, assuming that points is the current unit of measurement:

Dim dlg As FormatDrawingObject
GetCurValues dlg
dlg.HorizontalPos = Val(dlg.HorizontalPos) + 10
dlg.VerticalPos = Val(dlg.VerticalPos) + 10
FormatDrawingObject dlg

See Also

DrawAlign, DrawReshape, DrawSnapToGrid


FormatDropCap

Syntax

FormatDropCap [.Position = number] [, .Font = text] [, .DropHeight = number or text] [, .DistFromText = number or text]

Remarks

Inserts a frame for the first character of the current paragraph so that it becomes
a dropped capital letter. The arguments for the FormatDropCap statement correspond to the options in the Drop Cap dialog box (Format menu).

Argument | Explanation
.Position | Specifies the positioning for the dropped capital letter or removes dropped capital letter formatting. 0 (zero) or omitted No dropped capital letter formatting 1 Dropped (lines in the paragraph wrap around the dropped capital letter) 2 In Margin (lines in the paragraph remain flush)
.Font | The font you want for the dropped capital letter
.DropHeight | The height of the dropped capital letter specified in lines of surrounding text
.DistFromText | The distance between the dropped capital letter and the rest of the paragraph in points or a text measurement

Example

This example makes the first character of every section a dropped capital letter. The instruction .EditGoTo .Destination = "s" moves the insertion point to the beginning of the following section. As soon as the function CmpBookmarks("tmp", "\Sel") returns a value of 0 (zero), indicating that the insertion point did not move and that there are no more sections, the temporary bookmark is deleted and the macro ends.

StartOfDocument
FormatDropCap .Position = 1, .DropHeight = "3"
EditBookmark .Name = "temp", .Add
EditGoTo .Destination = "s"
While CmpBookmarks("temp", "\Sel") <> 0
    FormatDropCap .Position = 1, .DropHeight = "3"
    CharLeft
    EditBookmark .Name = "temp", .Add
    EditGoTo .Destination = "s"
Wend
EditBookmark .Name = "temp", .Delete

See Also

FormatFrame, InsertFrame


FormatFont

Syntax

FormatFont [.Points = number] [, .Underline = number] [, .Color = number] [, .Strikethrough = number] [, .Superscript = number] [, .Subscript = number] [, .Shadow = number] [, .Hidden = number] [, .SmallCaps = number] [, .AllCaps = number] [, .Outline = number] [, .Spacing = number] [, .Position = number or text] [, .Kerning = number] [, .KerningMin = number or text] [, .Default] [, .Tab = number] [, .Font = text] [, .Bold = number] [, .Italic = number]

Remarks

Applies character formatting to the selected text. The arguments for the FormatFont statement correspond to the options in the Font dialog box (Format menu).

Argument | Explanation
.Points | The font size, in points
.Underline | Applies a type of underlining: 0 (zero) None 1 Single 2 Words Only 3 Double 4 Dotted
.Color | Color of the text (for a list of colors, see CharColor).

Argument | Explanation
.Strikethrough | If 1, applies strikethrough formatting.
.Superscript | If 1, applies superscript formatting.
.Shadow | If 1, applies shadow formatting (Macintosh only).
.Subscript | If 1, applies subscript formatting.
.Hidden | If 1, applies hidden formatting.
.SmallCaps | If 1, applies small caps formatting.
.AllCaps | If 1, applies all caps formatting.
.Outline | If 1, applies outline formatting (Macintosh only).
.Spacing | The spacing between characters, in twips (20 twips = 1 point; 72 points = 1 inch) or a text measurement: 0 (zero) Normal >0 Expanded by the specified distance <0 Condensed by the specified distance
.Position | The character's position relative to the baseline, in units of 0.5 point or a text measurement: 0 (zero) Normal >0 Raised by the specified distance <0 Lowered by the specified distance
.Kerning | If 1, enables automatic kerning (character spacing).
.KerningMin | If .Kerning is set to 1, sets a minimum font size, in points, for automatic kerning.
.Default | Sets the character formats of the Normal style.
.Tab | Specifies which tab to select when you display the Font dialog box with a Dialog or Dialog() instruction: 0 (zero) Font tab 1 Character Spacing tab
.Font | The name of the font
.Bold | If 1, applies bold formatting.
.Italic | If 1, applies italic formatting.

Example

This example demonstrates how measurements other than twips or points may be used in FormatFont instructions by specifying a text measurement. This instruction positions the selected characters .25 centimeter above the baseline.

FormatFont .Position = ".25 cm"

See Also

AllCaps, Bold, CharColor, DoubleUnderline, EditFindFont, EditReplaceFont, Font, FontSize, FormatChangeCase, FormatDefineStyleFont, GrowFont, Hidden, Italic, Outline, ResetChar, Shadow, ShrinkFont, SmallCaps, Strikethrough, Subscript, Superscript, Underline, WordUnderline


FormatFrame

Syntax

FormatFrame [.Wrap = number] [, .WidthRule = number] [, .FixedWidth = number or text] [, .HeightRule = number] [, .FixedHeight = number or text] [, .PositionHorz = number or text] [, .PositionHorzRel = number] [, .DistFromText = number or text] [, .PositionVert = number or text] [, .PositionVertRel = number] [, .DistVertFromText = number or text] [, .MoveWithText = number] [, .LockAnchor = number] [, .RemoveFrame]

Remarks

Positions and sets options for the selected frame. If the insertion point or selection is not within a frame, an error occurs. The arguments for the FormatFrame statement correspond to the options in the Frame dialog box (Format menu).

Argument | Explanation
.Wrap | Specifies a Text Wrapping option: 0 (zero) Text does not wrap around the frame. 1 Text wraps around the frame.
.WidthRule | The rule used to determine the width of the frame: 0 (zero) Auto (determined by paragraph width). 1 Exactly (width will be exactly .FixedWidth).
.FixedWidth | If .WidthRule is 1, the width of the frame in points or a text measurement.
.HeightRule | The rule used to determine the height of the frame: 0 (zero) Auto (determined by paragraph height). 1 At Least (height will be no less than .FixedHeight). 2 Exactly (height will be exactly .FixedHeight).
.FixedHeight | If .HeightRule is 1 or 2, the height of the frame in points or a text measurement (72 points = 1 inch).
.PositionHorz | Horizontal distance, in points or a text measurement, from the edge of the item specified by .PositionHorzRel. You can also specify "Left," "Right," "Center," "Inside," and "Outside" as text arguments.

Argument | Explanation
.PositionHorzRel | Specifies that the horizontal position is relative to: 0 (zero) Margin 1 Page 2 Column
.DistFromText | Distance between the frame and the text to its left, right, or both, in points or a text measurement.
.PositionVert | Vertical distance, in points or a text measurement, from the edge of the item specified by .PositionVertRel. You can also specify "Top," "Bottom," and "Center" as text arguments.
.PositionVertRel | Specifies that the vertical position is relative to: 0 (zero) Margin 1 Page 2 Paragraph
.DistVertFromText | Distance between the frame and the text above, below, or both, in points or a text measurement.
.MoveWithText | If 1, the frame moves as text is added or removed around it.
.LockAnchor | If 1, the frame anchor (which indicates where the frame will appear in normal view) remains fixed when the associated frame is repositioned. A locked frame anchor cannot be repositioned.
.RemoveFrame | Removes the frame format from the selected text or graphic.

Example

This example selects and frames the current paragraph and then formats the frame as left-aligned, relative to the current column, with a 0.13-inch gap between the frame and text above and below:

EditGoTo "\Para"
InsertFrame
FormatFrame .PositionHorz = 0, .PositionHorzRel = 2, \
    .DistVertFromText = "0.13 in"

See Also

EditFindFrame, EditReplaceFrame, FormatDefineStyleFrame, InsertFrame, RemoveFrames


FormatHeaderFooterLink

Syntax

FormatHeaderFooterLink

Remarks

Replaces the current header or footer with the corresponding header or footer from the previous section. An error occurs if the previous section does not contain a corresponding header or footer.

See Also

ShowNextHeaderFooter, ShowPrevHeaderFooter, ToggleHeaderFooterLink, ViewHeader


FormatHeadingNumber

Syntax

FormatHeadingNumber [.Points = number] [, .Color = number] [, .Before = text] [, .Type = number] [, .After = text] [, .StartAt = number] [, .Include = number] [, .Alignment = number] [, .Indent = number or text] [, .Space = number or text] [, .Hang = number] [, .RestartNum = number] [, .Level = number] [, .Font = text] [, .Strikethrough = number] [, .Bold = number] [, .Italic = number] [, .Underline = number]

Remarks

Applies numbers to all paragraphs in the document formatted with one of the
nine built-in heading level styles, or changes numbering options for a specified heading level. The arguments for the FormatHeadingNumber statement correspond to the options in the Modify Heading Numbering dialog box (Heading Numbering command, Format menu).

Argument | Explanation
.Points, .Color, .Font, .Strikethrough, .Bold, .Italic, .Underline | Apply character formatting to numbers at the specified level. For argument descriptions, see FormatFont.
.Before, .After, .Alignment, .Indent, .Space, .Hang | Set options for numbers at the specified level. For argument descriptions, see FormatNumber.
.Type | Specifies a format for numbering headings at the specified level: 0 (zero) 1, 2, 3, 4 1 I, II, III, IV 2 i, ii, iii, iv 3 A, B, C, D 4 a, b, c, d 5 1st, 2nd, ¼ 6 One, Two, ¼ 7 First, Second, ¼
.StartAt | The number for the first heading in each sequence of headings of the specified level. If .Type is 3 or 4, .StartAt corresponds to the position in the alphabet of the starting letter.
.Include | Specifies whether to include numbers and position options from the previous headings for numbers at the specified level: 0 (zero) Includes neither numbers nor position options. 1 Includes a series of numbers from higher-level headings before the numbers at the specified level. 2 Includes both numbers from higher-level headings and position options from the previous level.

Argument | Explanation
.RestartNum | If 1, restarts heading numbering at each new section.
.Level | A number from 1 through 9 corresponding to the heading level whose numbering options you want to change.

See Also

FormatBullet, FormatHeadingNumbering, FormatMultilevel, FormatNumber


FormatHeadingNumbering

Syntax

FormatHeadingNumbering [.Remove] [, .Preset = number]

Remarks

Adds or removes numbers for the headings in the selection. A heading is a paragraph formatted with one of the nine built-in heading styles.

Argument | Explanation
.Remove | Removes numbers from the headings in the selection.
.Preset | A number corresponding to a numbering scheme in the Heading Numbering dialog box (Format menu). To determine the appropriate number, open the Heading Numbering dialog box and determine the number of the scheme. From left to right, the preset schemes are numbered 1 through 6.

See Also

FormatBulletsAndNumbering


FormatMultilevel

Syntax

FormatMultilevel [.Points = number] [, .Color = number] [, .Before = text] [, .Type = number] [, .After = text] [, .StartAt = number] [, .Include = number] [, .Alignment = number] [, .Indent = number or text] [, .Space = number or text] [, .Hang = number] [, .Level = number] [, .Font = text] [, .Strikethrough = number] [, .Bold = number] [, .Italic = number] [, .Underline = number]

Remarks

Applies multilevel list numbers to the selected paragraphs or changes numbering options for a specified level. The arguments for the FormatMultilevel statement correspond to the options in the Modify Multilevel List dialog box (Multilevel tab, Bullets And Numbering command, Format menu). You cannot display this dialog box using a Dialog or Dialog() instruction.

Argument | Explanation
.Level | A number from 1 through 9 corresponding to the heading level whose numbering options you want to change. Note that if you specify .Level, the options you set in the FormatMultilevel instruction are not applied. To apply the settings, include a second FormatMultilevel instruction in which .Level is not specified.
.Points, .Color, .Font, .Strikethrough, .Bold, .Italic, .Underline | Apply character formatting to numbers at the specified level. For individual argument descriptions, see FormatFont.
.Before, .After, .Alignment, .Indent, .Space, .Hang | Set options for numbers at the specified level. For argument descriptions, see FormatNumber.
.Type | Specifies a format for numbering headings at the specified level: 0 (zero) 1, 2, 3, 4 1 I, II, III, IV 2 i, ii, iii, iv 3 A, B, C, D 4 a, b, c, d 5 1st, 2nd, ¼ 6 One, Two, ¼ 7 First, Second, ¼
.StartAt | The number for the first heading in each sequence of headings of the specified level. If .Type is 3 or 4, .StartAt corresponds to the position in the alphabet of the starting letter.
.Include | Specifies whether to include numbers and position options from the previous headings for numbers at the specified level: 0 (zero) Includes neither numbers nor position options. 1 Includes a series of numbers from higher-level headings before the numbers at the specified level. 2 Includes both numbers from higher level-headings and position options from the previous level.

See Also

FormatBullet, FormatBulletsAndNumbering, FormatHeadingNumber, FormatNumber


FormatNumber

Syntax

FormatNumber [.Points = number] [, .Color = number] [, .Before = text] [, .Type = number] [, .After = text] [, .StartAt = number] [, .Include = number] [, .Alignment = number] [, .Indent = number or text] [, .Space = number or text] [, .Hang = number] [, .Font = text] [, .Strikethrough = number] [, .Bold = number] [, .Italic = number] [, .Underline = number]

Remarks

Numbers the selected paragraphs. The arguments for the FormatNumber statement correspond to the options in the Modify Numbered List dialog box (Numbered tab, Bullets And Numbering command, Format menu). You cannot display this dialog box using a Dialog or Dialog() instruction.

Argument | Explanation
.Points, .Color, .Font, .Strikethrough, .Bold, .Italic, .Underline | Apply character formatting to numbers at the specified level. For argument descriptions, see FormatFont.
.Before | The text, if any, you want to appear before each number.
.Type | Specifies a format for numbering lists: 0 (zero) 1, 2, 3, 4 1 I, II, III, IV 2 i, ii, iii, iv 3 A, B, C, D 4 a, b, c, d
.After | The text, if any, you want to appear after each number.
.StartAt | The number for the first selected paragraph. If .Type is 3 or 4, .StartAt corresponds to the position in the alphabet of the starting letter.
.Include | Specifies whether to include numbers and position options from the previous headings for numbers at the specified level: 0 (zero) Includes neither numbers nor position options. 1 Includes a series of numbers from higher-level headings before the numbers at the specified level. 2 Includes both numbers from higher-level headings and position options from the previous level.
.Alignment | Specifies an alignment for the numbers within the space between the left indent and the first line of text; takes effect only if .Space is 0 (zero): 0 (zero) or omitted Left 1 Centered 2 Right

Argument | Explanation
.Indent | The distance between the left indent and the first line of text, in points or a text measurement.
.Space | The distance between the number and the first line of text, in points or a text measurement.
.Hang | If 1, applies a hanging indent to the selected paragraphs.

See Also

FormatBullet, FormatBulletsAndNumbering, FormatHeadingNumber, FormatMultilevel


FormatNumberDefault, FormatNumberDefault()

Syntax

FormatNumberDefault [On]

FormatNumberDefault()

Remarks

The FormatNumberDefault statement adds numbers to or removes numbers from the selected paragraphs.

Argument | Explanation
On | Specifies whether to add or remove numbers: 0 (zero) Removes numbers. If the paragraph preceding or following the selection is not formatted as a list paragraph, the list format in the selection is removed along with the numbers. 1 Adds numbers. If the paragraph preceding or following the selection already has numbers applied with the Bullets And Numbering command (Format menu), the selected paragraphs are formatted with the same numbering scheme; otherwise, the default settings of the Bullets And Numbering dialog box are used. Omitted Toggles numbers.

The FormatNumberDefault() function returns the following values.

Value | Explanation
0 (zero) | If none of the selected paragraphs are numbered or bulleted
–1 | If the selected paragraphs are not all bulleted, all "skipped," or all formatted with the same level of numbering
1–9 | If all the selected paragraphs are numbered with the same level of numbering in a multilevel list

Value | Explanation
10 | If all the selected paragraphs are numbered with one of the six schemes on the Numbered tab in the Bullets And Numbering dialog box
11 | If all the selected paragraphs are bulleted
12 | If all the selected paragraphs are "skipped"

See Also

FormatBulletDefault, FormatBulletsAndNumbering, SkipNumbering


FormatPageNumber

Syntax

FormatPageNumber [.ChapterNumber = number] [, .NumRestart = number] [, .NumFormat = number] [, .StartingNum = number] [, .Level = number] [, .Separator = number]

Remarks

Determines the format of the page numbers used in the current section. The arguments for the FormatPageNumber statement correspond to the options in the Page Number Format dialog box (Page Numbers command, Insert menu).

Argument | Explanation
.ChapterNumber | If 1, includes the chapter number with the page number.
.NumRestart | Determines whether or not a different starting number can be set: 0 (zero) Selects the Continue From Previous Section option (the setting for .StartingNum has no effect). 1 Selects the Start At option (numbering begins at the number set for .StartingNum).
.NumFormat | The format for the page numbers: 0 (zero) 1 2 3¼ 1 a b c¼ 2 A B C¼ 3 i ii iii¼ 4 I II III¼
.StartingNum | The current section's starting page number (if .NumRestart is set to 1).

Argument | Explanation
.Level | A number corresponding to the heading level applied to the first paragraph in each chapter (for including the chapter number with the page number).
.Separator | If you specify .ChapterNumber, specifies the separator between the chapter number and the page number: 0 (zero) Hyphen 1 Period 2 Colon 3 Em dash 4 En dash

See Also

InsertPageNumbers


FormatParagraph

Syntax

FormatParagraph [.LeftIndent = number or text] [, .RightIndent = number or text] [, .Before = number or text] [, .After = number or text] [, .LineSpacingRule = number] [, .LineSpacing = number or text] [, .Alignment = number] [, .WidowControl = number] [, .KeepWithNext = number] [, .KeepTogether = number] [, .PageBreak = number] [, .NoLineNum = number] [, .DontHyphen = number] [, .Tab = number] [, .FirstIndent = number or text]

Remarks

Applies paragraph formatting to the selected paragraphs. The arguments for the FormatParagraph statement correspond to the options in the Paragraph dialog box (Format menu).

Argument | Explanation
.LeftIndent | The left indent in points or a text measurement
.RightIndent | The right indent in points or a text measurement
.Before | The space before the paragraph in points or a text measurement

Argument | Explanation
.After | The space after the paragraph in points or a text measurement
.LineSpacingRule | The rule used to determine line spacing: 0 (zero) or omitted Single 1 1.5 Lines 2 Double 3 At Least 4 Exactly 5 Multiple If you specify Single, 1.5 Lines, or Double, and also specify a value for .LineSpacing, the .LineSpacing value takes precedence.
.LineSpacing | The spacing for all lines within the paragraph (used when .LineSpacingRule is At Least, Exactly, or Multiple)
.Alignment | Sets a paragraph alignment: 0 (zero) Left 1 Centered 2 Right 3 Justified
.WidowControl | If 1, prevents a page break from leaving a single line of the paragraph at the top or bottom of a page (corresponds to selecting the Widow/Orphan Control check box)
.KeepWithNext | If 1, keeps the paragraph on the same page as the paragraph that follows (corresponds to selecting the Keep With Next check box)
.KeepTogether | If 1, keeps all lines in the paragraph on the same page (corresponds to selecting the Keep Lines Together check box)
.PageBreak | If 1, makes the paragraph always appear at the top of a new page (corresponds to selecting the Page Break Before check box)
.NoLineNum | If 1, turns off line numbering for the paragraph (corresponds to selecting the Suppress Line Numbers check box)
.DontHyphen | If 1, excludes the paragraph from automatic hyphenation (corresponds to selecting the Don't Hyphenate check box)
.Tab | Specifies which tab to select when you display the Paragraph dialog box with a Dialog or Dialog() instruction: 0 (zero) Indents And Spacing tab 1 Text Flow tab
.FirstIndent | The first-line indent in points or a text measurement

Example

This example sets justified alignment and adds 1 inch of space above and below each paragraph in the selection:

FormatParagraph .Alignment = 3, .Before = "1 in", .After = "1 in"

See Also

EditFindPara, EditReplacePara, FormatBordersAndShading, FormatDefineStylePara, FormatStyle, FormatTabs, ParaKeepLinesTogether, ParaKeepWithNext, ParaPageBreakBefore, ParaWidowOrphanControl, Style


FormatPicture

Syntax

FormatPicture [.SetSize = number] [, .CropLeft = number or text] [, .CropRight = number or text] [, .CropTop = number or text] [, .CropBottom = number or text] [, .ScaleX = number or text] [, .ScaleY = number or text] [, .SizeX = number or text] [, .SizeY = number or text]

Remarks

Applies formatting to the selected graphic. If the current selection is not a graphic or contains a mixture of text and graphics, an error occurs. The arguments for the FormatPicture statement correspond to the options in the Picture dialog box (Format menu).

Argument | Explanation
.SetSize | Indicates what arguments are used to determine the size of the graphic when both the scale and size are specified: 0 (zero) .ScaleX and .ScaleY are used to format the graphic. 1 .SizeX and .SizeY are used to format the graphic.
.CropLeft, .CropRight, .CropTop, .CropBottom | Amount to crop the graphic, in points (72 points = 1 inch) or a text measurement. If you specify a negative value, the graphic is not cropped. Instead, the amount of white space around the graphic is increased.
.ScaleX, .ScaleY | The horizontal and vertical proportions of the graphic, as percentages of the original width and height.
.SizeX, .SizeY | The horizontal and vertical dimensions of the graphic, in points or a text measurement.

Example

This example resizes the selected graphic to 75 percent of the original width and height:

FormatPicture .ScaleX = "75%", .ScaleY = "75%"

See Also

InsertPicture


FormatRetAddrFonts

Syntax

FormatRetAddrFonts [.Points = number] [, .Underline = number] [, .Color = number] [, .Strikethrough = number] [, .Superscript = number] [, .Subscript = number] [, .Hidden = number] [, .SmallCaps = number] [, .AllCaps = number] [, .Spacing = number] [, .Position = number or text] [, .Kerning = number] [, .KerningMin = number or text] [, .Default] [, .Tab = number] [, .Font = text] [, .Bold = number] [, .Italic = number]

Remarks

Sets character formatting for the return address on an envelope. Precede ToolsCreateEnvelope with FormatRetAddrFonts to specify options corresponding to those in the Font dialog box (Format menu). Include .Default to store the options you specify as the default character formatting for the return address. For argument descriptions, see FormatFont.

See Also

FormatAddrFonts, FormatFont, ToolsCreateEnvelope


FormatSectionLayout

Syntax

FormatSectionLayout [.SectionStart = number] [, .VertAlign = number] [, .Endnotes = number] [, .LineNum = number] [, .StartingNum = number] [, .FromText = text] [, .CountBy = text] [, .NumMode = number]

Remarks

Applies section formatting to the selected sections. This command exists for compatibility with earlier versions of Word. The arguments for the FormatSectionLayout statement are duplicated in FilePageSetup.

See Also

FilePageSetup


FormatStyle

Syntax

FormatStyle .Name = text [, .Delete] [, .Merge] [, .NewName = text] [, .BasedOn = text] [, .NextStyle = text] [, .Type = number] [, .FileName = text] [, .Source = number] [, .AddToTemplate = number] [, .Define] [, .Rename] [, .Apply]

Remarks

Creates, modifies, redefines, applies, or deletes the specified style. You can also use FormatStyle to merge styles into the active document from its attached template. The arguments for the FormatStyle statement correspond to the options in the Style dialog box (Format menu).

To define formats for the style, follow the FormatStyle instruction with one or more of the following instructions: FormatDefineStyleBorders, FormatDefineStyleFont, FormatDefineStyleFrame, FormatDefineStyleLang, FormatDefineStyleNumbers, FormatDefineStylePara, FormatDefineStyleTabs.

To copy styles, use Organizer.

Argument | Explanation
.Name | The name of the style.
.Delete | Deletes the specified style.
.Merge | Merges styles to or from the document or template specified by .FileName, depending on the value specified for .Source.
.NewName | Specifies a new name for the style; used with .Rename.
.BasedOn | Specifies an existing style on which to base the specified style.
.NextStyle | Specifies the style to be applied automatically to the new paragraph after pressing ENTER in a paragraph formatted with the style specified by .Name.
.Type | When creating a new style, specifies the type: 0 (zero) or omitted Paragraph 1 Character
.FileName | The document or template to merge styles to or from. If .FileName is omitted and .Source is set to 1, styles are merged from the active template to the active document.
.Source | Specifies whether to merge styles to or from the active document: 0 (zero) From the active document to the file specified by .FileName 1 From the file specified by .FileName to the active document
.AddToTemplate | If 1, corresponds to selecting the Add To Template check box.
.Define | Redefines an existing style or creates a new style with the formats specified in subsequent instructions.
.Rename | Renames the style specified by .Name to the name specified by .NewName.
.Apply | Applies the style to the selected paragraphs.

Examples

This example applies the Normal style to the selected paragraphs and is equivalent to the NormalStyle statement:

FormatStyle .Name = "Normal", .Apply

The following example defines the character formatting of the "TestMe" style as 10-point, bold, and small caps. Word creates the style if it does not already exist.

FormatStyle .Name = "TestMe", .Define
FormatDefineStyleFont .Points = "10", .Bold = 1, .SmallCaps = 1

See Also

CountStyles(), Organizer, FormatDefineStyleBorders, FormatDefineStyleFont, FormatDefineStyleFrame, FormatDefineStyleLang, FormatDefineStyleNumbers, FormatDefineStylePara, FormatDefineStyleTabs, NormalStyle, Style, StyleName$()


FormatStyleGallery

Syntax

FormatStyleGallery .Template = text [, .Preview = number]

Remarks

Copies the styles from the specified template to the active document. Existing styles are updated.

Argument | Explanation
.Template | The template containing the styles you want to use. Paths are allowed. In Windows, including the .DOT filename extension is not required.
.Preview | Specifies what to preview in the StyleGallery dialog box when you display the dialog box with a Dialog or Dialog() instruction: 0 (zero) Active document 1 Example document 2 List of styles and samples

For an example, see FormatAutoFormat.

See Also

FormatAutoFormat, FormatStyle, ToolsOptionsAutoFormat


FormatTabs

Syntax

FormatTabs [.Position = text] [, .DefTabs = number or text] [, .Align = number] [, .Leader = number] [, .Set] [, .Clear] [, .ClearAll]

Remarks

Sets and clears tab stops for the selected paragraphs. The arguments for the FormatTabs statement correspond to the options in the Tabs dialog box (Format menu).

Argument | Explanation
.Position | Position of the tab stop in a text measurement
.DefTabs | Position for default tab stops in the document in points or a text measurement

Argument | Explanation
.Align | Alignment of the tab stop: 0 (zero) Left 1 Center 2 Right 3 Decimal 4 Bar
.Leader | The leader character for the tab stop: 0 (zero) None 1 Period 2 Hyphen 3 Underscore
.Set | Sets the specified custom tab stop.
.Clear | Clears the specified custom tab stop.
.ClearAll | Clears all custom tab stops.

Examples

This example sets a right-aligned tab stop at 1.5 inches:

FormatTabs .Position = "1.5 in", .Align = 2, .Set

The following example clears all custom tab stops:

FormatTabs .ClearAll

See Also

EditFindTabs, EditReplaceTabs, FormatDefineStyleTabs, NextTab(), PrevTab(), TabLeader$(), TabType()


FormFieldOptions

Syntax

FormFieldOptions [.Entry = text] [, .Exit = text] [, .Name = text] [, .Enable = number] [, .TextType = number] [, .TextWidth = number or text] [, .TextDefault = text] [, .TextFormat = text] [, .CheckSize = number] [, .CheckWidth = number or text] [, .CheckDefault = number] [, .Type = number] [, .OwnHelp = number] [, .HelpText = text] [, .OwnStat = number] [, .StatText = text]

Remarks

Changes the properties of a selected form field. The arguments for the FormFieldOptions statement correspond to the options in the dialog box that Word displays when you select a form field and click the Form Field Options button on the Forms toolbar or choose Form Field Options from the shortcut menu. If more than one form field is selected, FormFieldOptions changes the properties of the first form field in the selection. If no form field is selected, or if you attempt to set options that are inappropriate for the selected form field, an error occurs.

Argument | Explanation
.Entry | The macro that runs when the form field receives the focus
.Exit | The macro that runs when the form field loses the focus
.Name | The name of the bookmark that will mark the form field
.Enable | If 1, allows the form field to be changed as the form is filled in
.TextType | For a text form field, specifies the type: 0 (zero) Regular Text 1 Number 2 Date 3 Current Date 4 Current Time 5 Calculation
.TextWidth | For a text form field, specifies a maximum width: 0 (zero) Unlimited > 0 A maximum width, in characters
.TextDefault | The default text for a text form field
.TextFormat | For a text form field, specifies a format appropriate for .TextType. If .TextType is set to 0 (zero) for Regular Text, the following values are available: Uppercase, Lowercase, First Capital, Title Case. For formats available to other text types, review the items in the Text Format box in the Text Form Field Options dialog box.
.CheckSize | For a check box form field, specifies whether to set a fixed size: 0 (zero) Auto (the size is determined by the font size of the surrounding text). 1 Exactly (the size is fixed to that specified by .CheckWidth).
.CheckWidth | For a check box form field, and if .CheckSize is set to 1, specifies a fixed width and height in points or a text measurement.
.CheckDefault | For a check box form field, specifies whether the check box should be cleared or selected by default: 0 (zero) Cleared 1 Selected

Argument | Explanation
.Type | Specifies the type of form field: 0 (zero) or omitted Text form field 1 Check box form field 2 Drop-down form field
.OwnHelp | If 1, allows .HelpText to be specified.
.HelpText | The text that is displayed in a message box when the form field has the focus and the user presses F1 (Windows) or COMMAND+/ or HELP (Macintosh).
.OwnStat | If 1, allows .StatText to be specified.
.StatText | The text that is displayed in the status bar when the form field has the focus.

You can use the FormFieldOptions dialog record to retrieve information about the selected form field. For details, see the second example in this entry.

Examples

This example specifies help text for the selected form field. Help text is specified for both the status bar and the box that Word displays when the user presses F1 (Windows) or COMMAND+/ or HELP (Macintosh).

FormFieldOptions .OwnHelp = 1, .HelpText = "Briefly summarize " + \
    "your favorite activity. Provide specific details.", \
    .OwnStat = 1, .StatText = "What you like to do best..."

This example uses the FormFieldOptions dialog record to define the variable curType with a number that corresponds to the .Type setting for the selected form field. You can use this example as a model for how to return information on any of the options you can set with FormFieldOptions.

Dim dlg As FormFieldOptions
GetCurValues dlg
curType = dlg.Type

See Also

EnableFormField, InsertFormField


FormShading, FormShading()

Syntax

FormShading [On]

FormShading()

Remarks

The FormShading statement controls shading for form fields in the active document.

Argument | Explanation
On | Specifies whether to display form fields with or without shading. 1 Displays form fields with shading. 0 (zero) Displays form fields without shading. Omitted Toggles form-field shading.

The Formhading() function returns 0 (zero) if form fields are not shaded and –1 if they are.

See Also

FormFieldOptions


FoundFileName$()

Syntax

FoundFileName$(Number)

Remarks

Returns the name of a file found in the most recent FileFind operation. The argument Number is a number between 1 and CountFoundFiles(). For an example, see FileFind.

See Also

CountFoundFiles(), FileFind


Function...End Function

Syntax

Function FunctionName[$][(ArgumentList)]
Series of instructions to determine a value
FunctionName[$] = value
End Function

Remarks

Defines a function — a series of instructions that returns a single value. To return
a string value, the function name must end with a dollar sign ($). Note that unlike the names of built-in WordBasic functions, the names of user-defined functions that do not specify ArgumentList do not end with empty parentheses; if you include empty parentheses, an error will occur.

ArgumentList is a list of variables, separated by commas, that are passed to the function by the statement calling the function. String variables must end with a dollar sign. ArgumentList cannot include values; constants should be declared as variables and passed to the function through variable names.

For more information about creating functions, see Chapter 4, "Advanced WordBasic," in Part 1, "Learning WordBasic."

Example

This macro prompts the user to type a number of degrees Fahrenheit, which is passed to the ConvertTemp() function through the variable fahrenheit. The function converts fahrenheit to degrees Celsius, and then the main subroutine displays this value in a message box.

Sub MAIN
    On Error Resume Next
    tmp$ = InputBox$("Type a Fahrenheit temperature:")
    fahrenheit = Val(tmp$)
    celsius = ConvertTemp(fahrenheit)
    MsgBox tmp$ + " Fahrenheit =" + Str$(celsius) + " Celsius"
End Sub
Function ConvertTemp(fahrenheit)
    tmp = fahrenheit
    tmp = ((tmp - 32) * 5) / 9
    tmp = Int(tmp)
    ConvertTemp = tmp
End Function

See Also

Sub ¼ End Sub


GetAddInID()

Syntax

GetAddInID(AddIn$)

Remarks

Returns a number corresponding to the specified global template or add-in's position in the list of global templates and add-ins in the Templates And Add-ins dialog box (Templates command, File menu): 1 corresponds to the first template or add-in, 2 to the second, and so on. If AddIn$ is not currently a global template or add-in, GetAddInID() returns 0 (zero).

Argument | Explanation
AddIn$ | The path (if necessary) and filename of the global template or Word add-in library (WLL).

Example

This example displays one of two messages, depending on whether the specified template is currently loaded. On the Macintosh, substitute a path and filename such as HD:TEMPLATES:MY TEMPLATE.

id = GetAddInID("C:\TEMPLATES\MYDOT.DOT")
If id > 0 Then
    MsgBox "MYDOT.DOT is global template number" + Str$(id) + "."
Else
    MsgBox "MYDOT.DOT is not currently a global template."
End If

See Also

AddAddIn, AddInState, ClearAddIns, CountAddIns(), DeleteAddIn, GetAddInName$()


GetAddInName$()

Syntax

GetAddInName$(AddInID)

Remarks

Returns the path and filename of the global template or add-in whose position in the list of global templates and add-ins in the Templates And Add-ins dialog box (Templates command, File menu) corresponds to AddInID: 1 corresponds to the first template or add-in, 2 to the second, and so on.

Example

This example displays a list of the current global templates and add-ins in a message box:

size = CountAddIns() - 1
Dim GlobalAddIns$(size)
For i = 0 To size
    GlobalAddIns$(i) = GetAddInName$(i + 1)
    msg$ = msg$ + GlobalAddIns$(i) + Chr$(13)
Next
MsgBox msg$, "Current Global Templates and Add-ins"

See Also

AddAddIn, AddInState, ClearAddIns, CountAddIns(), DeleteAddIn, GetAddInID()


GetAddress$()

Syntax

GetAddress$([Name$], [AddressProperties$], [UseAutoText], [DisplaySelectDialog], [SelectDialog], [CheckNamesDialog], [MRUChoice], [UpdateMRU])

Remarks

Returns an address from the default address book. GetAddress$() is available only if you have Windows 95 and either Microsoft Exchange or Schedule+ version 2.0 installed. In Word version 6.0, GetAddress$() is unavailable and generates an error.

Argument | Explanation
Name$ | The name of the addressee, as specified in the Search Name dialog box in the address book.
AddressProperties$ | If UseAutoText is set to 1, AddressProperties$ specifies the name of an AutoText entry that defines a sequence of address book properties. If UseAutoText is set to 0 (zero) or omitted, AddressProperties$ defines a custom layout. Valid address book property name or sets of property names are surrounded by angle brackets ("<" and ">") and separated by a space or a paragraph mark (for example, "<PR_GIVEN_NAME> <PR_SURNAME>" + Chr$(13) + "<PR_OFFICE_TELEPHONE_NUMBER>".) If AddressProperties$ is omitted, Word looks for the default AutoText entry, "AddressLayout". If "AddressLayout" hasn't been defined, Word uses the following layout definition for the address: "<PR_GIVEN_NAME> <PR_SURNAME>" + Chr$(13) + "<PR_STREET_ADDRESS>" + Chr$(13) + "<PR_LOCALITY>" + ", " + "<PR_STATE_OR_PROVINCE>" + " " + "<PR_POSTAL_CODE>" + Chr$(13) + "<PR_COUNTRY>". For a list of the valid address book property names, see AddAddress.

Argument | Explanation
UseAutoText | Indicates the value that AddressProperties$ specifies: 0 (zero) or omitted Defines the layout of the address book properties. 1 Specifies the name of the AutoText entry that defines the layout of the address book properties.
DisplaySelectDialog | Specifies whether the Select Name dialog box is displayed: 0 (zero) The Select Name dialog box is not displayed. 1 or omitted The Select Name dialog box is displayed. 2 The Select Name dialog box is not displayed, but no search for a specific name is performed. The address returned by GetAddress$() will be the previously selected address.
SelectDialog | Specifies how the Select Name dialog box should be displayed: 0 (zero) or omitted In Browse mode 1 In Compose mode, with only the To: box 2 In Compose mode, with both the To: and CC: boxes
CheckNamesDialog | Specifies whether to display the Check Names dialog box when the value of Name$ is not specific enough: 0 (zero) The Check Names dialog box is not displayed. 1 or omitted The Check Names dialog box is displayed. This parameter is ignored if DisplaySelectDialog is nonzero. If SelectDialog is set to 1 or 2, all names are resolved before the Select Names dialog box is closed.
MRUChoice | Specifies which list of most recently used addresses to use as the address list: 0 (zero) or omitted The list of delivery addresses 1 The list of return addresses
UpdateMRU | Specifies whether the new address is added to the list of most recently used addresses: 0 (zero) or omitted The address is not added. 1 The address is added. If SelectDialog is set to 1 or 2, UpdateMRU is ignored.

Examples

This example sets the variable letterAddress$ to John Smith's address, moves the insertion point to the beginning of the document, and inserts the address. The inserted address will include the default address book properties.

letterAddress$ = GetAddress$("John Smith", "", 0, 0)
StartOfDocument
Insert letterAddress$

The following example inserts John Smith's address, using the "My Address Layout" AutoText entry as the layout definition. "My Address Layout" is defined in the active template and contains a set of address properties assigned to the text$ variable. The example also adds John Smith's address to the list of most recently used addresses.

text$ = "<PR_GIVEN_NAME> <PR_SURNAME>" + Chr$(13) + \
    "<PR_STREET_ADDRESS>" + Chr$(13) + "<PR_LOCALITY>" + \
    ", " + "<PR_STATE_OR_PROVINCE>" + "  " + "<PR_POSTAL_CODE>" + \
    Chr$(13) + "<PR_OFFICE_TELEPHONE_NUMBER>"
SetAutoText "My Address Layout", text$, 1
letterAddress$ = GetAddress$("John Smith", "My Address Layout",
    \ 1, , , , , 1)
StartOfDocument
Insert letterAddress$

The following example inserts information from the same address at two different locations in the active document, using a different set of properties for each location. In this example, the second GetAddress$() instruction does not display the Select Name dialog box of the address book.

letterAddress$ = GetAddress$("John Smith", \
    "<PR_GIVEN_NAME> <PR_SURNAME>" + Chr$(13) + \
    "<PR_STREET_ADDRESS>" + Chr$(13) + "<PR_LOCALITY>" + \
    ", " + "<PR_STATE_OR_PROVINCE>" + "  " + "<PR_POSTAL_CODE>" + \
    Chr$(13) + "<PR_OFFICE_TELEPHONE_NUMBER>", 0, 0)
letterGivenName$ = GetAddress$( , "<PR_GIVEN_NAME>", , 2)
StartOfDocument
Insert letterAddress$
InsertPara
Insert "Dear "
Insert letterGivenName$
InsertPara

See Also

AddAddress, AutoText, InsertAddress, ToolsCreateEnvelope, ToolsCreateLabels


GetAttr()

Syntax

GetAttr(Filename$)

Remarks

Returns a number corresponding to the file attributes set for Filename$, the path and filename of the file on which you want information. In Windows, the attributes correspond to those you can set using the Properties command (File menu) in File Manager (Windows 3.x and Windows NT) or Windows Explorer (Windows 95). For definitions of the attributes, display the Properties dialog box and choose the Help button. On the Macintosh, only the Read Only and Hidden attributes are available (Read Only corresponds to the Locked check box in the Get Info dialog box (File menu) in the Finder). The values returned by GetAttr() are additive. For example, if both Read Only and Archive are selected, the return value is 33 (the sum of 1 and 32).

Value | Explanation
0 (zero) | None of the file attributes are selected.
1 | The Read Only attribute is selected.
2 | The Hidden attribute is selected.
4 | The System attribute is selected (not availble on the Macintosh).
32 | The Archive attribute is selected (not available on the Macintosh).

For an example, see SetAttr.

See Also

SetAttr


GetAutoCorrect$()

Syntax

GetAutoCorrect$(AutoCorrectEntry$)

Remarks

Returns the replacement text for the specified entry in the Replace column of the AutoCorrect dialog box (Tools menu). If AutoCorrectEntry$ doesn't exist, GetAutoCorrect$() returns an empty string ("").

Argument | Explanation
AutoCorrectEntry$ | The text specified in the Replace column for an AutoCorrect entry in the AutoCorrect dialog box. AutoCorrectEntry$ is not case-sensitive. For example, you can specify an entry "GW" as either "GW" or "gw."

Example

This example checks the replacement text for the AutoCorrect entry "uk." If the replacement text doesn't match "United Kingdom," the AutoCorrect entry is modified to do so.

If GetAutoCorrect$("uk") <> "United Kingdom" Then
    ToolsAutoCorrect .Replace = "uk", \
        .With = "United Kingdom", .Add
End If

See Also

ToolsAutoCorrect


GetAutoCorrectException$()

Syntax

GetAutoCorrectException$(Tab, EntryNumber)

Remarks

Returns the text of the exception that corresponds to EntryNumber on the specified tab in the AutoCorrect Exceptions dialog box (AutoCorrect command, Tools Menu). In Word version 6.0, GetAutoCorrectException$() is unavailable and generates an error.

Argument | Explanation
Tab | The tab where Word looks for the exception list entry: 0 (zero) First Letter 1 INitial CAps
EntryNumber | The number of the exception list entry, from 1 to the number returned by CountAutoCorrectExceptions()

Example

This example creates the array exceptions$(), which contains all the exceptions listed on the INitial CAps tab in the AutoCorrect Exceptions dialog box (AutoCorrect command, Tools Menu):

size = CountAutoCorrectExceptions(1) - 1
Dim exceptions$(size)
For count = 0 To size
    exceptions$(count) = GetAutoCorrectException$(1, count + 1)
Next

The following example deletes all the exceptions listed on the INitial CAps tab in the AutoCorrect Exceptions dialog box (AutoCorrect command, Tools Menu):

For n = 1 To CountAutoCorrectExceptions(1)
    ac$ = GetAutoCorrectException$(1, 1)
    ToolsAutoCorrectExceptions .Tab = 1, .Name = ac$, .Delete
Next

See Also

CountAutoCorrectExceptions(), IsAutoCorrectException(), ToolsAutoCorrectExceptions


GetAutoText$()

Syntax

GetAutoText$(Name$ [, Context])

Remarks

Returns the unformatted text of the specified AutoText entry.

Argument | Explanation
Name$ | The name of the AutoText entry
Context | Where the AutoText entry is stored: 0 (zero) or omitted Normal template and any loaded global templates 1 Active template Note that if Context is 1 and the active template is the Normal template, GetAutoText$() returns an empty string ("").

Example

This example displays a message box containing the text of the AutoText entry named "Welcome," which is stored in the active template:

MsgBox GetAutoText$("Welcome", 1)

See Also

AutoText, AutoTextName$(), CountAutoTextEntries(), EditAutoText, InsertAutoText, SetAutoText


GetBookmark$()

Syntax

GetBookmark$(Name$)

Remarks

Returns the text (unformatted) marked by the specified bookmark. If Name$ is not the name of a bookmark in the active document, GetBookmark$() returns an empty string ("").

Examples

This example sets the variable first$ to the text of the first bookmark in the document:

first$ = GetBookmark$(BookmarkName$(1))

The following example sets the variable paratext$ to the text of the paragraph containing the insertion point:

paratext$ = GetBookmark$("\Para")

The bookmark " \ Para" is one of several predefined bookmarks that Word defines and updates automatically. For more information, see "Operators and Predefined Bookmarks" later in this part.

See Also

BookmarkName$(), CountBookmarks(), EditBookmark


GetCurValues

Syntax

GetCurValues DialogRecord

Remarks

Stores in DialogRecord the current values for a previously defined dialog record for a Word dialog box. You use Dim to define a dialog record (for example, Dim dlg As ToolsOptionsSave), GetCurValues to store the settings (for example, GetCurValues dlg), and the syntax DialogRecord.ArgumentName to return specific settings (for example, save = dlg.FastSaves). You do not need to use GetCurValues with a dialog record for a custom dialog box; if you do, the instruction has no effect.

Example

This Word version 6.0 example uses GetCurValues to retrieve the date the active document was created from the Document Statistics dialog box (Summary Info command, File menu). The instructions then use date functions to calculate the number of days since the document was created and display a message box according to the result.

Dim dlg As DocumentStatistics
GetCurValues dlg
docdate$ = dlg.Created
age = Now() - DateValue(docdate$)
age = Int(age)
Select Case age
    Case 0
        MsgBox "This document is less than a day old."
    Case Is > 0
        MsgBox "This document was created" + Str$(age) + " day(s) ago."
    Case Else
        MsgBox "Check your computer's date and time."
End Select

For an example that uses GetCurValues and shows how to toggle any check box, see Abs().

See Also

Dialog, Dim


GetDirectory$()

Syntax

GetDirectory$([Directory$,] Count)

Remarks

Returns the name of the subfolder specified by Count in the specified folder.

Argument | Explanation
Directory$ | The path of the folder containing the subfolder; if omitted, the current folder is assumed.
Count | A number in the range 1 to CountDirectories(), where 1 corresponds to the first subfolder, 2 to the second, and so on.

Example

This example defines an array with the names of the subfolders in the current folder. In a dialog box definition, you could specify this array in a ListBox instruction to present a list of the subfolders.

Dim subdirs$(CountDirectories())
For i = 1 To CountDirectories()
    subdirs$(i) = LCase$(GetDirectory$(i))
Next

See Also

CountDirectories()


GetDocumentProperty(), GetDocumentProperty$()

Syntax

GetDocumentProperty(Name$ [, CustomOrBuiltIn])

GetDocumentProperty$(Name$ [, CustomOrBuiltIn])

Remarks

GetDocumentProperty() returns the numeric representation of the Name$ property defined in the active document. This can be a built-in property or a custom property. If the Name$ property is a string or a date, or if it is not defined, an error occurs. Yes or No properties are returned as 1 or 0 (zero), respectively.

GetDocumentProperty$() returns the string representation of the Name$ property defined in the active document. This can be a built-in property or a custom property. GetDocumentProperty$() returns an error if the Name$ property is a number or is not defined. Date properties are returned in the default date format, and Yes or No properties are returned as "Y" or "N". Use the DocumentPropertyExists() function to verify that the Name$ property exists.

For a list of the built-in properties available in Word, see DocumentPropertyName$(). In Word version 6.0, GetDocumentProperty() and GetDocumentProperty$() are unavailable and generate errors.

Argument | Explanation
Name$ | The name of the property.
CustomOrBuiltIn | Specifies whether Name$ is a built-in property or a custom property: 0 (zero) or omitted Word looks in the list of built-in and custom properties and returns the first matching value. 1 Name$ is a built-in property. 2 Name$ is a custom property.

See Also

DocumentPropertyName$(), DocumentPropertyType(), SetDocumentProperty


GetDocumentVar$()

Syntax

GetDocumentVar$(VariableName$)

Remarks

Returns the string associated with VariableName$, which was previously set for the active document with the SetDocumentVar statement. If the insertion point is not in a document — for example, if the macro-editing window is active — an error occurs.

Example

This AutoOpen macro determines whether there is a reminder note and, if so, displays it:

Sub MAIN
worknote$ = GetDocumentVar$("reminder")
If worknote$ <> "" Then
    MsgBox worknote$, "Note from last time"
End If
End Sub

For an example that prompts for a reminder note to store with a document before closing it, see SetDocumentVar.

See Also

SetDocumentVar


GetDocumentVarName$()

Syntax

GetDocumentVarName$(VariableNumber)

Remarks

Returns the name of a document variable set with SetDocumentVar or SetDocumentVar().

Argument | Explanation
VariableNumber | The number of the document variable, from 1 to the total number of document variables stored in the active document (you can obtain the total using CountDocumentVars()).

For an example, see CountDocumentVars().

See Also

CountDocumentVars(), GetDocumentVar$(), SetDocumentVar


GetFieldData$()

Syntax

GetFieldData$()

Remarks

When the insertion point is within an ADDIN field, retrieves text data stored internally within the field. Data stored within an ADDIN field is not visible, even when field codes are showing. If there is a selection, it must begin at an ADDIN field; otherwise, an error occurs.

See Also

PutFieldData


GetFormResult(), GetFormResult$()

Syntax

GetFormResult(BookmarkName$)

GetFormResult$(BookmarkName$)

Remarks

GetFormResult() returns a number corresponding to the setting of a check box form field or drop-down form field marked by the bookmark BookmarkName$. (Word adds a bookmark automatically when you insert a form field.) GetFormResult() returns values as follows:

  • For a check box form field, returns 0 (zero) if the check box is cleared or 1 if it is selected.
  • For a drop-down form field, returns 0 (zero) if the first item is selected, 1 if the second item is selected, and so on.

Note that an error occurs if you use GetFormResult() with a text form field.

GetFormResult$() returns a string corresponding to the setting of the form field marked by the bookmark BookmarkName$. GetFormResult$() returns values as follows:

  • For a check box form field, returns "0" (zero) if the check box is cleared or "1" if it is selected.
  • For a drop-down form field, returns the item that is currently selected.
  • For a text form field, returns the current text.

Example

This is an example of an "on-exit" macro that tests the item selected in a drop-down form field as soon as the user moves the focus to another form field. If the item is "Paris," a message box is displayed. The on-exit macro is assigned to the field marked by the bookmark "Dropdown1."

Sub MAIN
city$ = GetFormResult$("Dropdown1")
If city$ = "Paris" Then
MsgBox "We offer daily excursions to Versailles!"
End If
End Sub

For more information about on-exit macros, see Chapter 9, "More WordBasic Techniques," in Part 1, "Learning WordBasic."

See Also

SetFormResult


GetMergeField$()

Syntax

GetMergeField$(FieldName$)

Remarks

Returns the contents of the specified merge field in the current data record. If the main document is not the active document or FieldName$ doesn't exist, GetMergeField$() returns an empty string ("").

Example

This example displays the contents of the FirstName field for the current data record:

MsgBox GetMergeField$("FirstName")

See Also

CountMergeFields(), MergeFieldName$()


GetPrivateProfileString$()

Syntax

GetPrivateProfileString$(Section$, KeyName$, Filename$)

Remarks

Returns a setting in a settings file, a file that your macros can use to store and retrieve settings. For example, you can store the name of the active document when you quit Word so that it can be reopened automatically the next time you start Word. In Windows, a settings file is a text file such as WIN.INI. On the Macintosh, a settings file is a resource file such as Word Settings (6).

In Windows 95 and Windows NT, you can use GetPrivateProfileString$() to return a setting in the registry.

Argument | Explanation
Section$ | The name of the section in the settings file that contains KeyName$. In Windows, the section name appears between brackets before the associated keys (do not include the brackets with Section$). If you are using GetPrivateProfileString$() in Windows 95 or Windows NT to return a setting in the registry, Section$ should be the complete path to the key, including the root (for example, "HKEY_CURRENT_USER\Software\Microsoft\Word\7.0\Options").
KeyName$ | The key whose setting you want to retrieve. In a Windows settings file, the key name is followed by an equal sign (=) and the setting. If you are using GetPrivateProfileString$() in Windows 95 or Windows NT to return a value from the registry, KeyName$ should be the name of the value in the key specified by Section$ (for example, "MessageBeeps").
Filename$ | The filename for the settings file. If a path is not specified, the Windows folder (Windows) or the Preferences folder (Macintosh) is assumed. If you are using GetPrivateProfileString$() in Windows 95 or Windows NT to return a value from the registry, Filename$ must be an empty string ("").

If a specified section, key, or file does not exist, GetPrivateProfileString$() returns an empty string ("").

Example

This example sets the variable artdir$ to the path specified by the PICTURE-PATH key in the [Microsoft Word] section of WINWORD6.INI and, if the setting exists, changes the current folder accordingly. The last two instructions display the Insert Picture dialog box (Picture command, Insert menu). On the Macintosh, substitute Word Settings (6) for WINWORD6.INI. In Windows 95 and Windows NT, substitute the full path to the Options key for "Microsoft Word," and substitute an empty string ("") for WINWORD6.INI.

artdir$ = GetPrivateProfileString$("Microsoft Word", \
    "PICTURE-PATH", "WINWORD6.INI")
If artdir$ <> "" Then ChDir artdir$
Dim dlg As InsertPicture
x = Dialog(dlg)

For another example, see SetPrivateProfileString.

See Also

GetProfileString$(), SetPrivateProfileString, SetProfileString


GetProfileString$()

Syntax

GetProfileString$([Section$,] KeyName$)

Remarks

In Windows 3.x, returns a setting in WIN.INI, or if Section$ is "Microsoft Word 2.0," "Microsoft Word," "MSWord Text Converters," or "MSWord Editable Sections," returns the setting from WINWORD6.INI instead. These exceptions are made for compatibility with Word for Windows version 2.x macros. On the Macintosh, GetProfileString$() returns settings from the Word Settings (6) file. In Windows or on the Macintosh, it is generally preferable to use GetPrivateProfileString$(), which allows you to specify a settings file from which to return information.

Argument | Explanation
Section$ | The name of the section in the settings file that contains KeyName$. In Windows, the section name appears between brackets before the associated keys (do not include the brackets with Section$). If omitted, "Microsoft Word" is assumed.
KeyName$ | The key whose setting you want to retrieve. In Windows, the key name is followed by an equal sign (=) and the setting.

If a specified section or key does not exist, GetProfileString$() returns an empty string ("").

Note

In Windows 95 and Windows NT, settings are stored in the registry. You can still use SetProfileString and GetProfileString$() to set and return settings from a text file with the name WIN.INI, but neither the system nor Word uses these settings. To access and change values in the registry from within WordBasic, you need to use GetPrivateProfileString$() and SetPrivateProfileString$().

See Also

GetPrivateProfileString$(), SetPrivateProfileString, SetProfileString


GetSelEndPos()

Syntax

GetSelEndPos()

Remarks

Returns the character position of the end of the selection relative to the start of the document, which has a character position of 0 (zero). The end of the selection is defined as the end farthest from the start of the document. All characters, including nonprinting characters, are counted. Hidden characters are counted even if they are not displayed.

Example

This macro displays a message box if there is no selection. The user-defined function checksel compares the character positions at the start and end of the selection. If the positions are equal, indicating there is no selection, the function returns 0 (zero) and the message box is displayed.

Sub MAIN
    If checksel = 0 Then MsgBox "There is no selection."
End Sub

Function checksel
    If GetSelStartPos() = GetSelEndPos() Then
        checksel = 0
    Else
        checksel = 1
    End If
End Function

See Also

GetSelStartPos(), GetText$(), SetSelRange


GetSelStartPos()

Syntax

GetSelStartPos()

Remarks

Returns the character position of the start of the selection relative to the start of the document, which has a character position of 0 (zero). The start of the selection is defined as the end closest to the start of the document. All characters, including nonprinting characters, are counted. Hidden characters are counted even if they are not displayed.

For an example, see GetSelEndPos().

See Also

GetSelEndPos(), GetText$(), SetSelRange


GetSystemInfo, GetSystemInfo$()

Syntax

GetSystemInfo Array$()

GetSystemInfo$(Type)

Remarks

The GetSystemInfo statement fills a previously defined string array with information about the environment in which Word is running. In Windows, the size of the array should be 12 elements; on the Macintosh, 15 elements.

The GetSystemInfo$() function returns one piece of information about the environment in which Word is running. Type is one of the following numeric codes, specifying the type of information to return. In Windows, Type is a value from 21 to 32. Note that Type 23, 25, and 27 return meaningful values in Windows 3.x only.

Type | Explanation
21 | The environment (for example, "Windows" or "Windows NT")
22 | The type of central processing unit, or CPU (for example, "80286," "80386," "i486," or "Unknown")
23 | The MS-DOS version number
24 | The Windows version number
25 | The percent of system resources available
26 | The amount of available disk space, in bytes
27 | The mode under which Windows is running: "Standard" or "386-Enhanced"
28 | Whether a math coprocessor is installed: "Yes" or "No"
29 | The country setting
30 | The language setting
31 | The vertical display resolution, in pixels
32 | The horizontal display resolution, in pixels

On the Macintosh, Type is a value from 512 to 526.

Type | Explanation
512 | The environment ("Macintosh")
513 | The folder for storing settings files (for example, "HD:System Folder:Preferences:")
514 | Whether the current display is color: "Yes" or "No"
515 | The processor type (for example, "68000", "68040", or "PowerPC™")
516 | The computer type (for example, "Macintosh IIci" or "PowerBook™ 145")
517 | System software version (for example, "7.1")
518 | The Macintosh name as set in the Sharing Setup control panel
519 | Whether QuickDraw GX is installed: "Yes" or "No"
520 | Whether Balloon Help™ is on: "Yes" or "No"
521 | The vertical display resolution, in pixels
522 | The horizontal display resolution, in pixels
523 | The country setting
524 | Whether a math coprocessor is installed: "Yes" or "No"

Type | Explanation
525 | Total memory available for running applications, in bytes
526 | Free disk space, in bytes

If you are writing a macro to run both in Windows and on the Macintosh, use the AppInfo$() function to determine the current platform before running a GetSystemInfo$() instruction.

Examples

This Windows example creates a table of system information in a new document. First, the example defines and fills an array with labels for each type of system information. Second, the example opens a new document and defines the info$() array, which GetSystemInfo then fills with the system information. Finally, the For ¼ Next loop inserts the table of information. This example could be easily modified for the Macintosh by increasing the size of the array to 14 and changing the labels.

Dim a$(11)
a$(0) = "Environment" : a$(1) = "CPU" : a$(2) = "MS-DOS"
a$(3) = "Windows" : a$(4) = "% Resources" : a$(5) = "Disk Space"
a$(6) = "Mode" : a$(7) = "Coprocessor" : a$(8) = "Country"
a$(9) = "Language" : a$(10) = "Pixels High" : a$(11) = "Pixels Wide"
Dim info$(11)
GetSystemInfo info$()
FileNewDefault
FormatTabs .Position = "1.5 in", .Set
For i = 0 To 11
    Insert a$(i) + Chr$(9) + info$(i)
    InsertPara
Next

The following Macintosh example displays in a message box the total amount of available disk space:

space$ = GetSystemInfo$(526)
MsgBox "Available disk space: " + space$ + " bytes."

See Also

AppInfo$()


GetText$()

Syntax

GetText$(CharPos1, CharPos2)

Remarks

Returns the text (unformatted) from CharPos1 through CharPos2. Note that GetText$() does not return hidden text that is not displayed even though Word counts hidden characters when determining the range of text to return. Though GetText$() can be handy if you need to return document text without changing the selection, special document elements such as fields, tables, and page breaks within the specified range can produce unpredictable results.

Argument | Explanation
CharPos1 | The character position that defines the beginning of the range, relative to the start of the document, which has a character position of 0 (zero)
CharPos2 | The character position that defines the end of the range

Example

This example sets the variable a$ to the first 10 characters in the document:

a$ = GetText$(0, 10)

See Also

GetSelEndPos(), GetSelStartPos(), SetSelRange


GoBack

Syntax

GoBack

Remarks

Moves the insertion point among the last four locations where editing occurred (the same as pressing SHIFT+F5).

Example

An AutoExec macro such as the following runs each time you start Word. If there is at least one document listed at the bottom of the File menu, this macro opens the document and moves the insertion point to the most recent editing location.

Sub MAIN
If FileName$(1) <> "" Then
    FileList 1
    GoBack
End If
End Sub

See Also

EditGoTo


Goto

Syntax

Goto Label

Remarks

Redirects a running macro from the Goto instruction to the specified Label anywhere in the same subroutine or function. The macro continues running from the instruction that follows the label. Keep the following in mind when placing a label in a macro:

  • Labels must be the first text on a line and cannot be preceded by spaces or tab characters.
  • Labels must be followed by a colon (:). (Do not include the colon in the Goto instruction.)
  • Labels that contain letters must begin with a letter and can contain letters and numbers up to a maximum length of 40 characters, not counting the colon.
  • You can use a number that appears at the beginning of a line instead of a label. Line numbers are supported primarily for compatibility with Basic programs created in older versions of the Basic programming language that required line numbers. The line number can be as high as 32,759 and does not need a colon following it.

Example

This macro displays a message box, with Yes, No, and Cancel buttons, asking if the user wants to continue the macro. If the user chooses No or Cancel, the macro branches to the label bye immediately before End Sub, and the macro ends.

Sub MAIN
ans = MsgBox("Continue macro?", 3)
If ans = 0 Or ans = 1 Then Goto bye
'Series of instructions to run if the user chooses Yes
bye:
End Sub

See Also

For ¼ Next, If ¼ Then ¼ Else, Select Case, While ¼ Wend


GroupBox

Syntax

GroupBox HorizPos, VertPos, Width, Height, Label$ [, .Identifier]

Remarks

Creates a box in a custom dialog box that you can use to enclose a group of related option buttons or check boxes.

Argument | Explanation
HorizPos, VertPos | The horizontal and vertical distance from the upper-left corner of the group box to the upper-left corner of the dialog box, in increments of 1/8 and 1/12 of the System font (Windows) or the dialog font (Macintosh).
Width, Height | The width and height of the group box, in increments of 1/8 and 1/12 of the System font (Windows) or the dialog font (Macintosh).
Label$ | The label displayed in the upper-left corner of the group box. An ampersand (&) precedes the character in Label$ that is the access key for moving to the group box.
.Identifier | An optional identifier used by statements in a dialog function that act on the group box. For example, you can use this identifier with DlgText to change Label$ while the dialog box is displayed.

For an example, see OptionGroup.

See Also

Begin Dialog ¼ End Dialog, DlgText, OptionGroup


GoToAnnotationScope

Syntax

GoToAnnotationScope

Remarks

Selects the range of document text associated with the annotation containing the insertion point. If the insertion point is not within an annotation in the annotation pane, an error occurs.

The range, or "scope," of the annotation is defined as the text that was selected when the annotation mark was inserted. This text appears shaded when the insertion point is within the annotation in the annotation pane. If no text was selected when the annotation was inserted, GoToAnnotationScope moves the insertion point to the position immediately preceding the annotation mark in the document text.

Example

This example copies to the Clipboard the document text associated with the annotation containing the insertion point. The first If instruction ensures that the annotation pane is open and the insertion point is within it. Then GoToAnnotationScope selects the associated document text. The second If instruction ensures that text is selected before running EditCopy.

If ViewAnnotations() = -1 And WindowPane() = 3 Then
    GoToAnnotationScope
    If SelType() = 2 Then
        EditCopy
    Else
        MsgBox "No text to select."
    End If
    OtherPane
Else
    MsgBox "Please place the insertion point in an annotation."
End If

See Also

GoToNext Item, GoToPrevious Item, OtherPane, ViewAnnotations(), WindowPane()


GoToNextItem

Syntax

GoToNext Item

Remarks

Moves the insertion point to the next item specified by Item.

Argument | Explanation
Item | The item you want to go to. The following statements are available: GoToNextAnnotation GoToNextEndnote GoToNextFootnote GoToNextPage GoToNextSection GoToNextSubdocument

See Also

EditGoTo, GoToHeaderFooter, GoToPrevious Item


GoToPreviousItem

Syntax

GoToPrevious Item

Remarks

Moves the insertion point to the previous item specified by Item.

Argument | Explanation
Item | The item you want to go to. The following statements are available: GoToPreviousAnnotation GoToPreviousEndnote GoToPreviousFootnote GoToPreviousPage GoToPreviousSection GoToPreviousSubdocument

See Also

EditGoTo, GoBack, GoToNext Item


GrowFont

Syntax

GrowFont

Remarks

Increases the font size of the selected text (or text to be inserted at the insertion point) to the next size supported by the selected printer. If more than one font size is included in the selection, each size is increased to the next available setting. If there is no selection, the larger font size will be applied to new text.

See Also

FontSize, FormatFont, GrowFontOnePoint, ShrinkFont, ShrinkFontOnePoint


GrowFontOnePoint

Syntax

GrowFontOnePoint

Remarks

Increases the font size of the selected text (or text to be inserted at the insertion point) by 1 point, whether or not the new size is supported by the selected printer. If more than one font size is included in the selection, each size is increased by
1 point.

See Also

FontSize, FormatFont, GrowFont, ShrinkFont, ShrinkFontOnePoint


HangingIndent

Syntax

HangingIndent

Remarks

Applies a hanging indent to the selected paragraphs, or increases the current hanging indent to the next tab stop of the first paragraph in the selection.

See Also

Indent, UnHang, UnIndent


Help

Syntax

Help

Remarks

In Word version 6.0, displays Help for the selected context. If no context is active — for example, if the insertion point is in a Word document and not in a field — Help displays the Word Help Contents screen.

In Word version 7.0, Help displays the Answer Wizard tab in the Help Topics dialog box.

See Also

HelpActiveWindow, HelpTool


HelpAbout

Syntax

HelpAbout [.AppName = text] [, .AppCopyright = text] [, .AppUserName = text] [, .AppOrganization = text] [, .AppSerialNumber = text]

Remarks

Without any arguments, displays the About Microsoft Word dialog box (Help menu), which gives the Word version number, the serial number, copyright information, and the name of the licensed user.

The arguments for the HelpAbout statement are read-only, which means that unlike other WordBasic statements, HelpAbout cannot be used to set a value. Instead, you define a dialog record as HelpAbout and then use the dialog record in the same way you use a function: to return information. In this case, the dialog record can return information from the About Microsoft Word dialog box.

Argument | Explanation
.AppName | The name and version number of Word as they appear in the About Microsoft Word dialog box
.AppCopyright | The copyright notice for Word
.AppUserName | The name of the person to whom the active copy of Word is licensed
.AppOrganization | The organization name provided when Word was installed
.AppSerialNumber | The serial number of the active copy of Word

Example

This example defines a dialog record for the About Microsoft Word dialog box, stores the current values in the dialog record, and then displays in a message box the value for the serial number:

Dim dlg As HelpAbout
GetCurValues dlg
MsgBox "Serial number: " + dlg.AppSerialNumber

See Also

AppInfo$(), DocumentStatistics, GetSystemInfo, MicrosoftSystemInfo


HelpActiveWindow

Syntax

HelpActiveWindow

Remarks

Displays a Help topic describing the command associated with the active view or pane.

See Also

Help, HelpTool


HelpContents

Syntax

HelpContents

Remarks

Displays either the Help Topics dialog box (Word version 7.0) or the contents for Help (Word version 6.0).

See Also

Help, HelpIndex


HelpExamplesAndDemos

Syntax

HelpExamplesAndDemos

Remarks

Displays a screen from which you can access all the examples and demonstrations in Help. Note that in Windows 95 and Windows NT, the examples and demonstrations are not available and HelpExamplesAndDemos generates an error.

See Also

HelpQuickPreview


HelpIndex

Syntax

HelpIndex

Remarks

Displays either the Help Topics dialog box (Word version 7.0) or the index for Help (Word version 6.0).

See Also

Help, HelpContents


HelpKeyboard

Syntax

HelpKeyboard

Remarks

Displays a list of Help topics about keyboard and mouse shortcuts.


HelpMSN

Syntax

HelpMSN

Remarks

Displays a dialog box from which users can connect to forums on The Microsoft Network for information about Microsoft Word. HelpMSN is available only in Word for Windows 95 and only if the Microsoft Network is installed.

See Also

Help


HelpPSSHelp

Syntax

HelpPSSHelp

Remarks

Displays information in Help about the support services available for Microsoft Word.


HelpQuickPreview

Syntax

HelpQuickPreview

Remarks

Starts a tutorial that introduces Microsoft Word. Note that in Windows 95 and Windows NT, the Quick Preview demos are not available and HelpQuickPreview generates an error.

See Also

HelpExamplesAndDemos


HelpSearch

Syntax

HelpSearch

Remarks

Displays either the Help Topics dialog box (Word version 7.0) or the Search dialog box for performing a keyword search in Help (Word version 6.0).


HelpTipOfTheDay

Syntax

HelpTipOfTheDay .StartupTips = number

Remarks

Controls whether the Tip Of The Day dialog box appears when you start Word. This statement is ignored in Word version 7.0.

Argument | Explanation
.StartupTips | If 1, displays the Tip Of The Day dialog box each time you start Word. This argument is not available in Word version 7.0.


HelpTool

Syntax

HelpTool

Remarks

Changes the mouse pointer to a question mark, indicating you will get context-sensitive Help on the next command you choose or the next element of the Word screen you click. If you click text, Word displays a box describing current paragraph and character formats.

See Also

Help, HelpActiveWindow


HelpUsingHelp

Syntax

HelpUsingHelp

Remarks

Displays a list of Help topics that describe how to use Help.


HelpWordPerfectHelp

Syntax

HelpWordPerfectHelp

Remarks

In Windows, used with a Dialog or Dialog() instruction to display the Help For WordPerfect® Users dialog box (Help menu), as shown in the example for this entry. On the Macintosh, HelpWordPerfectHelp is not available and generates an error.

Example

This Windows example displays the Help For WordPerfect Users dialog box:

Dim dlg As HelpWordPerfectHelp
x = Dialog (dlg)

See Also

HelpWordPerfectHelpOptions


HelpWordPerfectHelpOptions

Syntax

HelpWordPerfectHelpOptions [.CommandKeyHelp = number] [, .DocNavKeys = number] [, .MouseSimulation = number] [, .DemoGuidance = number] [, .DemoSpeed = number] [, .HelpType = number]

Remarks

In Windows, sets options in the Help for WordPerfect Users feature. The arguments for HelpWordPerfectHelpOptions correspond to the options in the Help Options dialog box (Help For WordPerfect Users command, Help menu). On the Macintosh, HelpWordPerfectHelpOptions is not available and generates an error.

Argument | Explanation
.CommandKeyHelp | If 1, Word evaluates keystrokes as WordPerfect keystrokes.
.DocNavKeys | If 1, the arrow keys and the PAGE UP, PAGE DOWN, HOME, END, and ESC keys function as they would in WordPerfect.
.MouseSimulation | If 1, the mouse pointer moves as Help for WordPerfect Users selects options during demonstrations.
.DemoGuidance | If 1, Help for WordPerfect Users displays help text when user input is required during demonstrations.
.DemoSpeed | Controls the speed of demonstrations: 0 (zero) Fast 1 Medium 2 Slow
.HelpType | Specifies whether Help for WordPerfect Users displays help text or demonstrates the WordPerfect command you choose: 0 (zero) Help text 1 Demonstration


Hidden, Hidden()

Syntax

Hidden [On]

Hidden()

Remarks

The Hidden statement adds or removes the hidden character format for the current selection, or controls hidden formatting for characters to be inserted at the insertion point. You can control the display of hidden text with the Hidden Text check box, an option on the View tab in the Options dialog box (Tools menu).

Argument | Explanation
On | Specifies whether to add or remove the hidden format: 1 Adds the hidden format. 0 (zero) Removes the hidden format. Omitted Toggles the hidden format.

The Hidden() function returns the following values.

Value | Explanation
0 (zero) | If none of the selection is formatted as hidden
–1 | If part of the selection is formatted as hidden
1 | If all the selection is formatted as hidden

See Also

FormatFont


Highlight

Syntax

Highlight

Remarks

Highlights the selected text. If the selection is already highlighted, Highlight removes the highlight formatting. If no text is selected, the Highlight statement has no effect. In Word version 6.0, Highlight is unavailable and generates an error.

Use the HighlightColor statement to change the highlight color for the selected text, or use the ToolsOptionsRevisions statement to change the default highlight color.

See Also

EditFindHighlight, EditReplaceHighlight, HighlightColor, ToolsOptionsRevisions


HighlightColor, HighlightColor()

Syntax

HighlightColor Color

HighlightColor()

Remarks

The HighlightColor statement sets the highlight color for the selected text. If no text is selected, the HighlightColor statement has no effect. Use the ToolsOptionsRevisions statement to change the default highlight color.

In Word version 6.0, HighlightColor and HighlightColor() are unavailable and generate errors.

Argument | Explanation
Color | The highlight color. For a list of colors and their values, see CharColor. If Color is set to 0 (zero), highlight formatting is removed.

The HighlightColor() function returns the following values.

Value | Explanation
-1 | If the selection contains text with different highlight colors.
0 (zero) | If the selection contains no highlight formatting.
n | A number indicating the highlight color. For a list of colors and their corresponding numeric values, see CharColor.

See Also

EditFindHighlight, EditReplaceHighlight, Highlight, ToolsOptionsRevisions


HLine

Syntax

HLine [Count]

Remarks

Scrolls the active document horizontally. A "line" corresponds to clicking a scroll arrow on the horizontal scroll bar once.

Argument | Explanation
Count | The amount to scroll, in lines: Omitted One line to the right > 0 (zero) The specified number of lines to the right < 0 (zero) The specified number of lines to the left; scrolls into the left margin only if there is text in the margin

See Also

HPage, HScroll, VLine


Hour()

Syntax

Hour(SerialNumber)

Remarks

Returns an integer between 0 (zero) and 23, inclusive, corresponding to the hours component of SerialNumber, a decimal representation of the date, time, or both. For information about serial numbers, see DateSerial().

Example

This example sets the variable thishour to the hours component of the current time:

thishour = Hour(Now())

See Also

DateSerial(), Day(), Minute(), Month(), Now(), Second(), Today(), Weekday(), Year()


HPage

Syntax

HPage [Count]

Remarks

Scrolls the active document horizontally. HPage corresponds to clicking the horizontal scroll bar to the left or right of the scroll box.

Argument | Explanation
Count | The amount to scroll, in document-window widths: Omitted One width to the right > 0 (zero) The specified number of widths to the right < 0 (zero) The specified number of widths to the left

See Also

HLine, HScroll, VPage


HScroll, HScroll()

Syntax

HScroll Percentage

HScroll()

Remarks

The HScroll statement scrolls horizontally to the specified percentage of the document width. HScroll corresponds to dragging the scroll box on the horizontal scroll bar.

The HScroll() function returns the current horizontal scroll position as a percentage of the document width. HScroll() does not return negative values; if the document is scrolled into the left margin, HScroll() returns 0 (zero).

See Also

HLine, HPage, VScroll


If...Then...Else

Syntax

If Condition Then Instruction [Else Instruction]

If Condition1 Then
Series of instructions
[ElseIf Condition2 Then
Series of instructions]
[Else
Series of instructions]
End If

Remarks

Runs instructions conditionally. In the simplest form of the If conditional — If Condition Then Instruction — the Instruction runs if Condition is true. In WordBasic, "true" means the condition evaluates to –1 and "false" means the condition evaluates to 0 (zero).

You can write an entire If conditional on one line if you specify one condition following If and one instruction following Then (and one instruction following Else, if included). Do not conclude this form of the conditional with End If. Note that it is possible to specify multiple instructions using this form if you separate the instructions with colons, as in the following conditional:

If Bold() = 1 Then Bold 0 : Italic 1

In general, if you need to specify a series of conditional instructions, the full syntax is preferable to separating instructions with colons. With the full syntax, you can use ElseIf to include a second condition nested within the If conditional. You can add as many ElseIf instructions to an If conditional as you need.

For more information about If ¼ Then ¼ Else, see Chapter 3, "WordBasic Fundamentals," in Part 1, "Learning WordBasic."

Examples

This example applies bold formatting to the entire selection if the selection is partially bold:

If Bold() = -1 Then Bold 1

The following example applies italic formatting if the selection is entirely bold; otherwise, underline formatting is applied:

If Bold() = 1 Then Italic 1 Else Underline 1

The following example shows how you can use a compound expression as the condition (in this case, whether the selection is both bold and italic):

If Bold() = 1 And Italic() = 1 Then ResetChar

The following example uses the full syntax available with the If conditional. The conditional could be described as follows: "If the selection is entirely bold, make it italic. If the selection is partially bold, reset the character formatting. Otherwise, make the selection bold."

If Bold() = 1 Then
    Italic 1
ElseIf Bold() = -1 Then
    ResetChar
Else
    Bold 1
End If

See Also

For ¼ Next, Goto, Select Case, While ¼ Wend


Indent

Syntax

Indent

Remarks

Moves the left indent of the selected paragraphs to the next tab stop of the first paragraph in the selection. Indent maintains the setting of a first-line or hanging indent.

See Also

FormatParagraph, HangingIndent, UnIndent


Input

Syntax

Input #FileNumber, Variable1[$] [, Variable2[$]] [, Variable3[$]] [, ¼]

Input [Prompt$,] Variable1[$] [, Variable2[$]] [, Variable3[$]] [, ¼]

Remarks

Retrieves string or numeric values from a sequential file, typically containing data added with the Print statement, and assigns the values to variables. FileNumber is the number specified in the Open instruction that opened the file for input. For more information about sequential files, see Chapter 9, "More WordBasic Techniques," in Part 1, "Learning WordBasic."

Input is similar to Read in that it retrieves comma-delimited values from sequential files, but unlike Read, it does not remove quotation marks from string values. Input can accept strings with as many as 65,280 characters. Longer strings are truncated. For more information, see Read.

If FileNumber is omitted, the user is prompted with a question mark (?) in the status bar to type one or more values, separated by commas. The user presses ENTER to end keyboard input. If Prompt$ is specified, the question mark follows the string.

Examples

This Windows example opens for input a list of files to save in rich-text format (RTF). Assume that FILES.TXT is a text file in which each paragraph contains two string values: the filename to open and the filename to save. The instructions open each file in turn and save it in RTF. On the Macintosh, substitute folder names such as HD:WORD DOCS: and HD:RTF DOCS:.

Open "C:\DOCS\FILES.TXT" For Input As #1
While Not Eof(#1)
    Input #1, docname$, rtfname$
    FileOpen "C:\DOCS\" + docname$
    FileSaveAs .Name =  "C:\RTF\" + rtfname$, .Format = 6
    FileClose 2
Wend
Close #1

The following example displays the prompt "RTF filename?" in the status bar and defines the variable rtfname$ with the text the user types:

Input "RTF filename", rtfname$

See Also

Close, Eof(), Input$(), InputBox$(), Line Input, Lof(), Open, Read, Print, Seek, Write


Input$()

Syntax

Input$(NumChars, [#]FileNumber)

Remarks

Reads NumChars characters (as many as 32,767) from an open sequential file. FileNumber is the number specified in the Open instruction that opened the file for input.

Example

This example defines the variable filecode$ with the first 10 characters in the text file INFO.TXT:

Open "INFO.TXT" For Input As #1
filecode$ = Input$(10, #1)
Close #1

See Also

Close, Eof(), Input, InputBox$(), Line Input, Lof(), Open, Print, Read, Seek, Write


InputBox$()

Syntax

InputBox$(Prompt$ [, Title$] [, Default$])

Remarks

Displays a dialog box requesting a single piece of information and returns the text entered in the dialog box when the user chooses the OK button. If the user chooses the Cancel button, an error occurs. You can use the On Error statement to trap the error.

Argument | Explanation
Prompt$ | Text displayed in the dialog box indicating the kind of information requested. If Prompt$ is longer than 255 characters, an error occurs.
Title$ | Text displayed in the title bar of the dialog box (if omitted, Word uses the title "Microsoft Word").
Default$ | Text that initially appears in the text box of the dialog box. This value is returned if the user types nothing before choosing OK. If Default$ is longer than 255 characters, an error occurs.

In Windows, if the user presses enter to start a new line while the dialog box is displayed, InputBox$() returns text containing Chr$(11) + Chr$(10) (a newline character followed by a paragraph mark) where the line break was made. For a method of removing the newline character, see the third example for this entry. On the Macintosh, if the user presses RETURN to start a new line, Chr$(13) is returned.

To choose the OK button in an input box using keys, press ENTER (Macintosh), or press TAB to move to the OK button, and then press ENTER (Windows).

Examples

This example asks the user to type a word, which is assigned to the variable word$. You could use this variable in a macro that counts the occurrences of a given word in the active document (as in the example for EditFindFound()).

word$ = InputBox$("Count instances of:", "WordCounter")

The following example prompts the user to type a number from 1 to 10. InputBox$() returns what the user types as a string, which the Val() function converts to a number to assign to the numeric variable num. Note that if the user spells out "Ten" instead of typing "10," Val() returns 0.

num = Val(InputBox$("Type a number from 1 to 10:"))

This example asks the user to type multiple lines, which are assigned to the variable a$. The CleanString$() function removes any extra newline characters (returned in Windows) so that line breaks are preserved as entered by the user.

a$ = InputBox$("Type multiple lines:")
a$ = CleanString$(a$)

See Also

Input, MsgBox, On Error, Val()


Insert

Syntax

Insert Text$

Remarks

Inserts the specified text at the insertion point. You can insert characters such as quotation marks, tab characters, nonbreaking hyphens, and newline characters using the Chr$() function with Insert. You can insert numbers by first converting them to text with the Str$() function.

Examples

This example inserts the text "Hamlet" (without quotation marks) at the insertion point:

Insert "Hamlet"

The following example inserts the text "Hamlet" enclosed in quotation marks at the insertion point:

Insert Chr$(34) + "Hamlet" + Chr$(34)

This example inserts the text "GroupA:35" at the insertion point. To create the number portion of the string, Str$() converts a numeric variable to a string, and LTrim$() removes the leading space that is automatically added by Str$().

num = 35
num$ = LTrim$(Str$(num))
Insert "GroupA:" + num$

See Also

Chr$(), InsertPara, LTrim$(), Str$()


InsertAddCaption

Syntax

InsertAddCaption [.Name = text]

Remarks

Adds a new item to the Label box in the Caption dialog box (Insert menu). The new item becomes a valid string for the .Label argument in an InsertCaption instruction.

Argument | Explanation
.Name | The name for the new caption label

Example

This example adds "Diagram" to the list of available caption labels:

InsertAddCaption .Name = "Diagram"

See Also

InsertAutoCaption, InsertCaption, InsertCaptionNumbering


InsertAddress

Syntax

InsertAddress

Remarks

Opens the Address Book window of the default Personal Address Book and inserts the selected address at the insertion point.

InsertAddress is available only if Windows 95 and either Microsoft Exchange or Schedule+ version 2.0 are installed. In Word version 6.0, InsertAddress is unavailable and generates an error.

See Also

AddAddress, GetAddress$(), ToolsCreateEnvelope, ToolsCreateLabels


InsertAnnotation

Syntax

InsertAnnotation

Remarks

Inserts an annotation mark at the insertion point, opens the annotation pane, and places the insertion point in the annotation pane. If text is selected, the annotation mark is inserted immediately after the selected text, which appears shaded when the insertion point is in the associated annotation in the annotation pane. If the document window is too small to display the annotation pane, an error occurs.

See Also

GoToAnnotationScope, InsertFootnote, ShowAnnotationBy, ViewAnnotations


InsertAutoCaption

Syntax

InsertAutoCaption [.Clear] [, .ClearAll] [, .Object = text] [, .Label = text] [, .Position = number]

Remarks

Specifies a caption to insert automatically whenever an object of the specified type is inserted. The arguments for the InsertAutoCaption statement correspond to the options in the AutoCaption dialog box (Caption command, Insert menu).

Argument | Explanation
.Clear | Cancels adding captions automatically for the type of object specified by .Object.
.ClearAll | Cancels adding captions automatically for all types of objects.
.Object | The name of the object type for which you want to establish an automatic caption, as it appears in the Add Caption When Inserting box.
.Label | The caption label to insert automatically. If the label has not yet been defined, the instruction has no effect. Use InsertAddCaption to define new labels.
.Position | The position of the caption: 0 (zero) Above Item 1 Below Item

Example

This example creates a new caption label, "Picture," and specifies that whenever a Microsoft Word Picture object is inserted, this label is automatically inserted:

InsertAddCaption .Name = "Picture"
InsertAutoCaption .Object = "Word.Picture.6", \
        .Label = "Picture"

See Also

InsertAddCaption, InsertCaption, InsertCaptionNumbering


InsertAutoText

Syntax

InsertAutoText

Remarks

Attempts to match the current selection or the text before or surrounding the insertion point with an AutoText entry and insert the entry (including its formatting, if any). Word looks for the entry first in the active template, then in the Normal template, and finally in each loaded global template in the order listed in the Templates And Add-ins dialog box (File menu). If no match can be made, an error occurs.

See Also

AutoText, AutoTextName$(), CountAutoTextEntries(), EditAutoText, GetAutoText$(), SetAutoText


InsertBreak

Syntax

InsertBreak [.Type = number]

Remarks

Inserts a page, column, or section break at the insertion point. The values available for the .Type argument correspond to the options in the Break dialog box (Insert menu).

Argument | Explanation
.Type | The type of break to insert: 0 (zero) or omitted Page break 1 Column break 2 Next Page section break 3 Continuous section break 4 Even Page section break 5 Odd Page section break 6 Line break (newline character)

Example

This example inserts a page break before each Heading 1 paragraph in the active document:

StartOfDocument
EditFindClearFormatting
EditFindStyle .Style = "Heading 1"
EditFind .Find = "", .Direction = 0, .Wrap = 0
While EditFindFound()
    CharLeft
    InsertBreak .Type = 0
    EditFind .Find = "", .Direction = 0, .Wrap = 0
Wend

See Also

InsertColumnBreak, InsertPageBreak, InsertSectionBreak, ParaPageBreakBefore, TableSplit


InsertCaption

Syntax

InsertCaption [.Label = text] [, .TitleAutoText = text] [, .Title = text] [, .Delete] [, .Position = number]

Remarks

Inserts a caption above or below a selected item. The arguments for the InsertCaption statement correspond to the options in the Caption dialog box (Insert menu).

Argument | Explanation
.Label | The caption label to insert. If the label has not yet been defined, an error occurs. Use InsertAddCaption to define new labels.
.TitleAutoText | The AutoText entry whose contents you want to insert after the label in the caption (overrides any text specified for .Title).
.Title | The text to insert after the label in the caption (ignored if .TitleAutoText is specified).
.Delete | Removes the specified Label from the label box. Built-in labels (such as "Figure") cannot be deleted; if .Label specifies a built-in label, an error occurs.
.Position | When an item is selected, specifies whether to insert the caption above or below the item: 0 (zero) Above Selected Item 1 Below Selected Item

Example

This example inserts a caption with the label "Figure" and the title ": WordArt Object" after each WordArt object in the active document. GetSelStartPos() returns the character position of the insertion point before and after the EditGoTo instruction. When the character positions are the same, indicating there are no more WordArt objects, the While ¼ Wend loop is exited.

StartOfDocument
cp1 = GetSelStartPos()
EditGoTo "o'MSWordArt.2'"
cp2 = GetSelStartPos()
While cp1 <> cp2
    CharRight 1, 1
    InsertCaption .Label = "Figure", \
            .Title = ": WordArt Object", .Position = 1
    cp1 = GetSelStartPos()
    EditGoTo "o'MSWordArt.2'"
    cp2 = GetSelStartPos()
Wend

See Also

InsertAddCaption, InsertAutoCaption, InsertCaptionNumbering


InsertCaptionNumbering

Syntax

InsertCaptionNumbering [.Label = text] [, .FormatNumber = number] [, .ChapterNumber = number] [, .Level = number] [, .Separator = text]

Remarks

Defines a format for sequence numbers in captions for a specific type of item. The arguments for the InsertCaptionNumbering statement correspond to the options in the Caption Numbering dialog box (Caption command, Insert menu).

Argument | Explanation
.Label | The label for which you want to define a sequence number format. If the label has not yet been defined, an error occurs. Use InsertAddCaption to define new labels.
.FormatNumber | Specifies a default format for the sequence number in captions containing the specified label: 0 (zero) 1, 2, 3, ¼ 1 a, b, c, ¼ 2 A, B, C, ¼ 3 i, ii, iii, ¼ 4 I, II, III, ¼
.ChapterNumber | If 1, a chapter number is included by default in captions containing the specified label. Chapters are determined by the heading style specified by .Level.
.Level | A number corresponding to the heading style used for chapter headings in the active document: 1 corresponds to Heading 1, 2 corresponds to Heading 2, and so on.
.Separator | The character to use as a separator between the chapter number and the sequence number.

Example

This example defines a number format for captions containing the "Figure" label. Chapter numbers are excluded from the sequence number.

InsertCaptionNumbering .Label = "Figure", .FormatNumber = 3, \
        .ChapterNumber = 0

See Also

InsertAddCaption, InsertAutoCaption, InsertCaption


InsertChart

Syntax

InsertChart

Remarks

Starts Microsoft Graph and displays a default chart for editing. When the user exits Microsoft Graph, the chart is embedded in the active document. The instruction InsertChart is the same as the instruction InsertObject .Class = "MSGraph".

See Also

InsertDrawing, InsertExcelTable, InsertObject


InsertColumnBreak

Syntax

InsertColumnBreak

Remarks

Inserts a column break at the insertion point. If the insertion point is in a table, InsertColumnBreak splits the table by inserting a paragraph mark above the row containing the insertion point. The instruction InsertColumnBreak is the same as the instruction InsertBreak .Type = 1.

See Also

InsertBreak, InsertPageBreak, InsertSectionBreak, TableSplit


InsertCrossReference

Syntax

InsertCrossReference [.ReferenceType = text] [, .ReferenceKind = text] [, .ReferenceItem = text]

Remarks

Inserts a cross-reference to a heading, bookmark, footnote, endnote, or an item for which a caption label is defined (for example, an equation, figure, or table). The arguments for the InsertCrossReference statement correspond to the options in the Cross-reference dialog box (Insert menu).

Argument | Explanation
.ReferenceType | The type of item to which you want to insert a cross-reference, as it appears in the Reference Type box.

Argument | Explanation
.ReferenceKind | A number specified as text corresponding to the information you want the cross-reference to include. See the following table for available values.
.ReferenceItem | If .ReferenceType is "Bookmark", a bookmark name. For all other reference types, a number specified as text corresponding to an item in the For Which [Reference Type] box: "1" corresponds to the first item, "2" corresponds to the second item, and so on.

The following table shows the values available for .ReferenceKind based on the setting for .ReferenceType.

.ReferenceType | Values available for .ReferenceKind
Heading | 0 (zero) Heading Text 7 Page Number 8 Heading Number
Bookmark | 1 Bookmark Text 7 Page Number 9 Paragraph Number
Footnote | 5 Footnote Number 7 Page Number
Endnote | 6 Endnote Number 7 Page Number
An item for which a caption label is defined | 2 Entire Caption 3 Only Label And Number 4 Only Caption Text 7 Page Number

Example

This example inserts a sentence containing two cross-references to a diagram: one to the caption and another to the page containing the diagram. A typical sentence inserted with these instructions might be, "For a diagram of a widget, see 'Figure 1: Standard Widget' on page 5."

Insert "For a diagram of a widget, see " + Chr$(34)
InsertCrossReference .ReferenceType = "Figure", \
        .ReferenceKind = "2", .ReferenceItem = "1"
Insert Chr$(34) + " on page "
InsertCrossReference .ReferenceType = "Figure", \
        .ReferenceKind = "7", .ReferenceItem = "1"
Insert "."

See Also

InsertCaption


InsertDatabase

Syntax

InsertDatabase [.Format = number] [, .Style = number] [, .LinkToSource = number] [, .Connection = text] [, .SQLStatement = text] [, .SQLStatement1 = text] [, .PasswordDoc = text] [, .PasswordDot = text] [, .DataSource = text] [, .From = text] [, .To = text] [, .IncludeFields = number]

Remarks

Retrieves data from a data source (for example, a separate Word document, a Microsoft Excel worksheet, or a Microsoft Access database) and inserts it into the active document as a table.

Argument | Explanation
.Format | Specifies a format listed under Formats in the Table AutoFormat dialog box (Table menu): 0 (zero) corresponds to the first format in the list ("none"), 1 corresponds to the second format, and so on.
.Style | Specifies which attributes of the format specified by .Format to apply to the table. Use the sum of any combination of the following values: 0 None 1 Borders 2 Shading 4 Font 8 Color 16 Auto Fit 32 Heading Rows 64 Last Row 128 First Column 256 Last Column
.LinkToSource | If 1, establishes a link between the new table and the data source.
.Connection | Specifies a range within which to perform the query. How you specify the range depends on how data is retrieved. For example: u When retrieving data using ODBC (Windows only), you specify a connection string. u When retrieving data from Microsoft Excel using dynamic data exchange (DDE), you specify a named range. u When retrieving data from Microsoft Access (Windows only), you specify the word "Table" or "Query" followed by the name of a table or query.

Argument | Explanation
.SQLStatement | An optional query string that retrieves a subset of the data in a primary data source to insert into the document (Windows only).
.SQLStatement1 | If the query string is longer than 255 characters, .SQLStatement specifies the first portion of the string and .SQLStatement1 specifies the second portion (Windows only).
.PasswordDoc | The password (if any) required to open the data source.
.PasswordDot | If the data source is a Word document, the password (if any) required to open the attached template.
.DataSource | The path and filename of the data source.
.From | The number of the first data record in the range of records you want to insert.
.To | The number of the last data record in the range of records you want to insert.
.IncludeFields | If 1, field names from the data source appear in the first row of the new table.

Note

To generate the connection and query strings automatically, record the actions you take in the Database dialog box (Insert menu) as a macro.

See Also

InsertExcelTable, MailMergeCreateDataSource


InsertDateField

Syntax

InsertDateField

Remarks

Inserts a DATE field at the insertion point. The date format matches the last format chosen using the Date And Time command (Insert Menu).

See Also

InsertDateTime, InsertField, InsertPageField, InsertTimeField


InsertDateTime

Syntax

InsertDateTime [.DateTimePic = text] [, .InsertAsField = number]

Remarks

Inserts the current date, time, or both, as either text or a TIME field.

Argument | Explanation
.DateTimePic | A string describing the format used for displaying the date, time, or both. If omitted, Word uses the format specified by the "DateFormat=" line in the [Microsoft Word] section of WINWORD6.INI (Windows 3.x), Word Settings (6) (Macintosh), or the registry (Windows 95 and Windows NT). In Windows 3.x, if there is no "DateFormat=" line, Word uses the "sShortDate" setting in the [intl] section of WIN.INI.
.InsertAsField | Specifies whether Word inserts the information as a TIME field: 0 (zero) Word inserts the information as text. 1 Word inserts the information as a TIME field. Omitted Word inserts the information according to the current setting of the Insert As Field check box in the Date And Time dialog box (Insert menu).

Example

This example inserts a TIME field for the current date in the form "3 September, 1993":

InsertDateTime .InsertAsField = 1, .DateTimePic = "d MMMM, yyyy"

See Also

InsertDateField, InsertField, InsertPageField


InsertDrawing

Syntax

InsertDrawing

Remarks

If Microsoft Draw is installed on your computer, starts Microsoft Draw and displays a blank window. When the user exits Microsoft Draw, the drawing is embedded in the active document. The instruction InsertDrawing is the same as the instruction InsertObject .Class = "MSDraw".

See Also

DrawInsertWordPicture, InsertChart, InsertEquation, InsertExcelTable, InsertObject, InsertPicture, InsertSound, InsertWordArt


InsertEquation

Syntax

InsertEquation

Remarks

If Microsoft Equation Editor is installed on your computer, starts Equation Editor. When the user exits Equation Editor, the equation is embedded in the active document. The instruction InsertEquation is the same as the instruction InsertObject .Class = "Equation.2".

See Also

ActivateObject, EditObject, InsertChart, InsertDrawing, InsertExcelTable, InsertWordArt


InsertExcelTable

Syntax

InsertExcelTable

Remarks

Starts Microsoft Excel and displays a new worksheet. When the user exits Microsoft Excel, the worksheet is embedded in the active document. The instruction InsertExcelTable is the same as the instruction InsertObject .Class = "Excel.Sheet.5".

See Also

InsertChart, InsertDatabase, InsertObject


InsertField

Syntax

InsertField .Field = text

Remarks

Inserts the specified field at the insertion point.

Argument | Explanation
.Field | The field type and instructions to insert. For information on a specific field, including syntax and examples, select the field name in the Field dialog box (Insert menu), and then press F1 (Windows) or HELP (Macintosh). The .Field argument accepts a maximum of 255 characters.

Do not include the field characters ({}), but follow all other syntax rules for field codes. To insert quotation marks in field codes, use Chr$(34).

Examples

This example inserts an AUTHOR field:

InsertField .Field = "AUTHOR"

The following example nests a FILLIN field within a COMMENTS field. The instructions display all field codes, insert a COMMENTS field using InsertField, then insert the FILLIN field using InsertFieldChars.

ToolsOptionsView .FieldCodes = 1
InsertField .Field = "COMMENTS"
CharLeft
InsertFieldChars
Insert "FILLIN " + Chr$(34) + "Type your comment" + Chr$(34)

See Also

InsertFieldChars


InsertFieldChars

Syntax

InsertFieldChars

Remarks

Inserts field characters ({}) at the insertion point and then positions the insertion point between the field characters.

See Also

InsertField


InsertFile

Syntax

InsertFile .Name = text [, .Range = text] [, .ConfirmConversions = number] [, .Link = number]

Remarks

Inserts all or part of the specified file at the insertion point.

Argument | Explanation
.Name | The path and filename of the file to insert. If the path is not specified, the current folder is assumed.
.Range | If the file specified by .Name is a Word document, .Range is a bookmark. If the file is another type (for example, a Microsoft Excel worksheet), .Range refers to a named range or cell range (for example, R1C1:R3C4). If Word cannot recognize .Range, an error occurs.
.ConfirmConversions | Specifies whether Word displays the Convert File dialog box when inserting files in formats other than Word Document format.
.Link | If 1, inserts an INCLUDETEXT field instead of the contents of the file itself.

Examples

This example inserts the contents of PRICES.DOC into the active document. On the Macintosh, substitute a path and filename such as HD:PRICES:PRICE LIST.

InsertFile .Name = "C:\PRICES\PRICES.DOC"

The following example inserts the portion of PRICES.DOC marked with the bookmark "sportscars" into the active document:

InsertFile .Name = "PRICES.DOC", .Range = "sportscars"

The following Windows example creates a new document and then inserts one INCLUDETEXT field for each file in the folder C:\TMP with the filename extension .TXT:

FileNewDefault
ChDir "C:\TMP"
name$ = Files$("*.TXT")
While name$ <> ""
    InsertFile name$, .Link = 1, .ConfirmConversions = 0
    InsertPara
    name$ = Files$()
Wend

To change the previous example for the Macintosh, substitute ChDir "HD:TEMP FILES" and name$ = Files$(MacID$("TEXT")) for the second and third instructions, respectively.

See Also

InsertDatabase, InsertField


InsertFootnote

Syntax

InsertFootnote [.Reference = text] [, .NoteType = number]

Remarks

Inserts a footnote or endnote reference mark at the insertion point, opens the footnote or endnote pane, and places the insertion point in the pane. The arguments for the InsertFootnote statement correspond to the options in the Footnote And Endnote dialog box (Footnote command, Insert menu).

Argument | Explanation
.Reference | A custom reference mark. If omitted, Word inserts an automatically numbered reference mark. To specify a symbol, use the syntax {FontName CharNum}. FontName is the name of a font containing the symbol. Names of decorative fonts appear in the Font box in the Symbol dialog box (Insert menu). CharNum is the sum of 31 and the number corresponding to the position of the symbol you want to insert, counting from left to right in the table of symbols. For example, to specify an omega (W) at position 56 in the table of symbols in the Symbol font, include the argument .Reference = "{Symbol 87}".
.NoteType | Specifies whether to insert a footnote or endnote: 0 (zero) Footnote 1 Endnote Omitted The type that was inserted most recently

Example

This example inserts an automatically numbered footnote reference mark at the insertion point, inserts a footnote, and then closes the footnote pane:

InsertFootnote .NoteType = 0
Insert "Sara Levine, "
Italic 1 : Insert "The Willow Tree"
Italic 0 : Insert " (Lone Creek Press, 1993)."
ClosePane

See Also

InsertAnnotation, NoteOptions, ViewFootnoteArea, ViewFootnotes


InsertFormField

Syntax

InsertFormField [.Entry = text] [, .Exit = text] [, .Name = text] [, .Enable = number] [, .TextType = number] [, .TextDefault = text] [, .TextWidth = number or text] [, .TextFormat = text] [, .CheckSize = number] [, .CheckWidth = number or text] [, .CheckDefault = number] [, .Type = number] [, .OwnHelp = number] [, .HelpText = text] [, .OwnStat = number] [, .StatText = text]

Remarks

Inserts a form field at the insertion point. The arguments for the InsertFormField statement correspond to the options in the Form Field (Insert menu) and Form Field Options dialog boxes.

Argument | Explanation
.Entry | The macro that runs when the form field receives the focus.
.Exit | The macro that runs when the form field loses the focus.
.Name | A name for a bookmark that will mark the form field.
.Enable | If 1, allows the form field to be changed as the form is filled in.
.TextType | When inserting a text form field, specifies the type: 0 (zero) Regular Text 1 Number 2 Date 3 Current Date 4 Current Time 5 Calculation
.TextDefault | The default text for a text form field.
.TextWidth | When inserting a text form field, specifies a maximum width: 0 (zero) Unlimited > 0 A maximum width, in characters

Argument | Explanation
.TextFormat | When inserting a text form field, specifies a format appropriate for .TextType. If .TextType is set to 0 (zero) for Regular Text, the following values are available: Uppercase, Lowercase, First Capital, Title Case. For formats available to other text types, review the items in the Text Format box in the Text Form Field Options dialog box.
.CheckSize | When inserting a check box form field, specifies whether to set a fixed size: 0 (zero) Auto (the size is determined by the font size of the surrounding text). 1 Exactly (the size is fixed to that specified by .CheckWidth).
.CheckWidth | When inserting a check box form field, and if .CheckSize is set to 1, specifies a fixed width and height in points or a text measurement.
.CheckDefault | When inserting a check box form field, specifies whether the check box should be cleared or selected by default: 0 (zero) Cleared 1 Selected
.Type | Specifies the type of form field to insert: 0 (zero) or omitted Text form field 1 Check box form field 2 Drop-down form field
.OwnHelp | Specifies the source of the text that is displayed in a message box when the form field has the focus and the user presses the F1 key (Windows) or COMMAND+/ or HELP (Macintosh): 0 (zero) None 1 The text of the AutoText entry specified by .HelpText 2 The text specified by .HelpText
.HelpText | If .OwnHelp is set to 1, the name of an AutoText entry containing help text for the form field. If .OwnHelp is set to 2, help text.
.OwnStat | Specifies the source of the text that is displayed in the status bar when the form field has the focus: 0 (zero) None 1 The text of the AutoText entry specified by .StatText 2 The text specified by .StatText
.StatText | If .OwnStat is set to 1, the name of an AutoText entry containing status bar text for the form field. If .OwnHelp is set to 2, the text to be displayed in the status bar.

Examples

This example inserts a drop-down form field for which status bar text is specified and then adds the names of three cities to the form field:

InsertFormField .Name = "Cities", .Enable = 1, .Type = 2, \
        .OwnStat = 1, .StatText = "Select a city."
AddDropDownItem "Cities", "Bonn"
AddDropDownItem "Cities", "Paris"
AddDropDownItem "Cities", "Tokyo"

The following example inserts a check box form field that is 8 points high and wide and is selected by default. WriteSettings is specified as the "on-exit" macro that runs when the check box loses the focus. In a macro, instructions following this one could use GetFormResult() and SetPrivateProfileString to record in a text file whether the user selects or clears the check box.

InsertFormField .Exit = "WriteSettings", .Name = "Check1", \
        .Enable = 1, .CheckSize = 1, .CheckWidth = "8 pt", \
        .CheckDefault = 1, .Type = 1

The following example inserts a text form field. The argument .TextType = 1 specifies that the text is a number, and .TextFormat = "0%" specifies that the number be shown as a percentage. The default percentage is 100 percent.

InsertFormField .Name = "PercentComplete", .Enable = 1, \
        .TextType = 1, .TextWidth = "4", \
        .TextDefault = "100%", .TextFormat = "0%", .Type = 0

See Also

AddDropDownItem, CheckBoxFormField, DropDownFormField, EnableFormField, FormFieldOptions, RemoveAllDropDownItems, RemoveDropDownItem, TextFormField


InsertFrame

Syntax

InsertFrame

Remarks

Inserts an empty frame, or frames the selected text, graphic, or both. If there is no selection, Word inserts a 1-inch – square frame at the insertion point (the frame appears as a square in page layout view). You can change the dimensions of the frame with FormatFrame.

Example

This example inserts a frame and then positions it in the margin to the left of the current paragraph, so the user can type a margin note in it. If the active document is not in page layout view, Word displays a message box asking if the user wants to switch to page layout view.

SelType 1
If ViewPage() = 0 Then
    ans = MsgBox("Switch to page layout view?", \
            "Insert Margin Note", 36)
    If ans = - 1 Then ViewPage
End If
InsertFrame
FormatFrame .Wrap = 1, .WidthRule = 1, .FixedWidth = ".75 in", \
        .PositionHorz = "Left", .PositionHorzRel = 1, \
        .DistFromText = "0.13 in", .PositionVert = "0", \
        .PositionVertRel = 2, .DistVertFromText = "0"
SelType 1 : FontSize 8 : Italic 1
ToolsOptionsView .HScroll = 1
HScroll 0

See Also

FormatFrame, RemoveFrames


InsertIndex

Syntax

InsertIndex [.HeadingSeparator = number] [, .Replace = number] [, .Type = number] [, .RightAlignPageNumbers = number] [, .Columns = number]

Remarks

Compiles and inserts an index at the insertion point or replaces an existing index. The index is the result of an INDEX field that you can update when index entries change.

Argument | Explanation
.HeadingSeparator | Specifies the heading separator: 0 (zero) or omitted None 1 Blank Line 2 Letter
.Replace | Specifies whether to replace the index, if it already exists: 0 (zero) or omitted The existing index is not replaced (the instruction has no effect other than to select the index). 1 The existing index is replaced.
.Type | Specifies the type of index: 0 (zero) or omitted Indented 1 Run-in
.RightAlignPageNumbers | If 1, aligns page numbers with the right edge of the column.
.Columns | The number of columns you want in the index.

Example

This example inserts a simple, indented index that replaces the current index, if one exists:

InsertIndex .Type = 0, .HeadingSeparator = 0, .Replace = 1

See Also

AutoMarkIndexEntries, MarkIndexEntry


InsertMergeField

Syntax

InsertMergeField .MergeField = text

Remarks

Inserts a MERGEFIELD field that Word updates in each merge document during a mail merge. If the active document is not a main document, an error occurs.

Argument | Explanation
.MergeField | A merge field name corresponding to the type of information you want to insert. Field names appear in the first record of the data source or in the header source (if a header source is attached to the main document).

Example

This example inserts a MERGEFIELD field that is updated with the city name from the data source during a mail merge:

InsertMergeField .MergeField = "City"

See Also

InsertField, MailMergeInsertAsk, MailMergeInsertFillIn, MailMergeInsertIf, MailMergeInsertMergeRec, MailMergeInsertMergeSeq, MailMergeInsertNext, MailMergeInsertNextIf, MailMergeInsertSet, MailMergeInsertSkipIf


InsertObject

Syntax

InsertObject [.IconNumber = number] [, .FileName = text] [, .Link = number] [, .DisplayIcon = number] [, .Tab = number] [, .Class = text] [, .IconFilename = number] [, .Caption = text]

Remarks

Starts an object linking and embedding (OLE) application in which the user creates an object, or immediately creates an embedded object using a specified file. In either case, InsertObject inserts an EMBED field at the insertion point.

Argument | Explanation
.IconNumber | If .DisplayIcon is set to 1, a number corresponding to the icon you want to use in the program file specified by .IconFilename. Icons appear in the Change Icon dialog box (Object command, Insert menu): 0 (zero) corresponds to the first icon, 1 to the second icon, and so on. If omitted, the first (default) icon is used. Note that on the Macintosh, icons for embedded objects cannot be changed and this argument is ignored.
.FileName | The path and filename of the file you want to store as an embedded object in the active document. If you specify .Filename, you must set .Tab to 1 and specify .Class. For an example of inserting an existing file as an object, see the second example in this entry.
.Link | If 1, links the embedded object to the file specified by .FileName. When the file changes, Word updates the embedded object.
.DisplayIcon | Specifies whether or not to display a link as an icon: 0 (zero) or omitted Link is not displayed as an icon. 1 Link is displayed as an icon.
.Tab | Specifies which tab to select when you display the Object dialog box with a Dialog or Dialog() instruction. 0 (zero) Create New tab 1 Create From File tab
.Class | The class name of a new object to insert. To look up class names, insert an object in a document and view the field codes; the class name of the object follows the word "EMBED."
.IconFilename | If .DisplayIcon is set to 1, the path and filename of the program file in which the icon to be displayed is stored. Note that on the Macintosh, icons for embedded objects cannot be changed and this argument is ignored.
.Caption | If .DisplayIcon is set to 1, the caption of the icon to be displayed; if omitted, Word inserts the name of the object.

Examples

This Windows example starts Paintbrush®. When the user chooses Exit & Return from the File menu, Word inserts the following field at the insertion point: {EMBED PBrush \ * MERGEFORMAT}.

InsertObject .Class = "PBrush"

The following Windows example inserts an embedded object that is linked to the file FLOCK.BMP:

InsertObject .FileName = "C:\WIN31\FLOCK.BMP", .Link = 1, \
    .Tab = 1, .Class = "Pbrush"

The following Macintosh example inserts an embedded object that is linked to the file APRIL SALES:

InsertObject .FileName = "HD1:MICROSOFT WORD:CHARTS:APRIL SALES", \
    .Link = 1, .Tab = 1, .Class = "MSGraph"

See Also

ActivateObject, EditObject, InsertChart, InsertDrawing, InsertExcelTable


InsertPageBreak

Syntax

InsertPageBreak

Remarks

Inserts a page break at the insertion point. The instruction InsertPageBreak is the same as the instruction InsertBreak .Type = 0.

See Also

InsertBreak, InsertColumnBreak, InsertSectionBreak, ParaPageBreakBefore, TableSplit


InsertPageField

Syntax

InsertPageField

Remarks

Inserts a PAGE field without any field instructions at the insertion point.

See Also

InsertDateField, InsertField, InsertPageNumbers, InsertTimeField


InsertPageNumbers

Syntax

InsertPageNumbers [.Type = number] [, .Position = number] [, .FirstPage = number]

Remarks

Inserts a PAGE field inside a frame in the header or footer and positions the frame as specified. The arguments for the InsertPageNumbers statement correspond to the options in the Page Numbers dialog box (Insert menu).

Argument | Explanation
.Type | Specifies where to add the page field: 0 (zero) Header 1 Footer
.Position | Specifies the position of the framed PAGE field: 0 (zero) Left 1 Center 2 Right 3 Inside (left on odd pages and right on even pages) 4 Outside (right on odd pages and left on even pages)
.FirstPage | If 1, the field is included in the header or footer on the first page.

Example

This example adds a right-aligned page number to the header and specifies that the page number not appear on the first page:

InsertPageNumbers .Type = 0, .Position = 2, .FirstPage = 0

See Also

FormatPageNumber, InsertPageField, ViewHeader


InsertPara

Syntax

InsertPara

Remarks

Inserts a paragraph mark at the insertion point.

See Also

Chr$(), Insert


InsertPicture

Syntax

InsertPicture .Name = text [, .LinkToFile = number] [, .New]

Remarks

Inserts a graphic at the insertion point. If .LinkToFile is set to 1 or 2, the graphic is inserted as an INCLUDEPICTURE field that you can update when the graphics file changes.

Argument | Explanation
.Name | The path and filename of the graphic to insert. If the path is omitted, the current folder is assumed.
.LinkToFile | Specifies whether to insert the graphic as a field and whether to save graphic data in the document: 0 (zero) or omitted Inserts the graphic specified in the .Name argument. 1 Inserts an INCLUDEPICTURE field at the insertion point and saves graphic data in the document. 2 Inserts an INCLUDEPICTURE field at the insertion point and prevents graphic data from being stored in the document by adding a \ d switch.
.New | Inserts a 1-inch–square empty metafile graphic, surrounded by a border.

Example

This example inserts an INCLUDEPICTURE field whose result is the Windows bitmap WINLOGO.BMP:

InsertPicture .Name = "WINLOGO.BMP", .LinkToFile = 1

The following example inserts an INCLUDEPICTURE field whose result is the PICT-format bitmap Artist:

InsertPicture .Name = "Artist", .LinkToFile = 1

See Also

InsertDrawing, InsertFile, InsertObject


InsertSectionBreak

Syntax

InsertSectionBreak

Remarks

Inserts a section break with the same formatting as the section containing the insertion point.

See Also

InsertBreak, InsertColumnBreak, InsertPageBreak


InsertSound

Syntax

InsertSound

Remarks

Starts Sound Recorder in Windows or Microsoft Voice Annotation on the Macintosh so the user can record or insert a sound. When the user exits the sound application, the sound is embedded in the active document. If the computer is not sound enabled, an error occurs.

See Also

InsertChart, InsertDrawing, InsertExcelTable, InsertObject


InsertSpike

Syntax

InsertSpike

Remarks

Empties the special AutoText entry "Spike" and inserts its contents at the insertion point. For an example, see Spike.

See Also

EditAutoText, InsertAutoText, Spike


InsertSubdocument

Syntax

InsertSubdocument .Name = text [, .ConfirmConversions = number] [, .ReadOnly = number] [, .PasswordDoc = text] [, .PasswordDot = text] [, .Revert = number] [, .WritePasswordDoc = text] [, .WritePasswordDot = text]

Remarks

Adds the specified file as a subdocument in the active master document. If the active document is not in outline or master document view, an error occurs. For argument descriptions, see FileOpen.

Example

This example adds the document SUB1.DOC to the beginning of the active document as a read-only, or locked, subdocument. On the Macintosh, substitute a path such as HD:MY DOCS:SUBDOC 1.

StartOfDocument
ViewMasterDocument
InsertSubdocument .Name = "C:\MYDOCS\SUB1.DOC", .ReadOnly = 1

See Also

CreateSubdocument, FileOpen, MergeSubdocument, OpenSubdocument, RemoveSubdocument, SplitSubdocument, ViewMasterDocument


InsertSymbol

Syntax

InsertSymbol .Font = text, .Tab = number, .CharNum = number or text

Remarks

Inserts a symbol at the insertion point. Note that InsertSymbol does not insert
a SYMBOL field as in Word for Windows version 2.x. The arguments for the InsertSymbol statement correspond to the options in the Symbol dialog box (Insert menu).

Argument | Explanation
.Font | The name of the font containing the symbol. Names of decorative fonts appear in the Font box in the Symbol dialog box.

Argument | Explanation
.Tab | Specifies which tab to select when you display the Symbol dialog box with a Dialog or Dialog() instruction: 0 (zero) Symbols tab 1 Special Characters tab
.CharNum | The sum of 31 and the number corresponding to the position of the symbol on the table of symbols, counting from left to right. For example, to specify an omega ( W) at position 56 on the table of symbols in the Symbol font, set .CharNum to 87.

Example

This example inserts a double-headed arrow at the insertion point:

InsertSymbol .Font = "Symbol", .CharNum = "171"

See Also

Chr$()


InsertTableOfAuthorities

Syntax

InsertTableOfAuthorities [.Replace = number] [, .Passim = number] [, .KeepFormatting = number] [, .Category = number]

Remarks

Collects citations from TA (Table of Authorities Entry) fields and inserts a TOA (Table of Authorities) field at the insertion point.

Argument | Explanation
.Replace | Specifies whether to replace a previously compiled table of authorities: 0 (zero) or omitted The existing table of authorities is not replaced (the instruction has no effect other than selecting the field result). 1 The existing table of authorities is replaced.
.Passim | If 1, Word replaces five or more different page references to the same authority with "passim."
.KeepFormatting | If 1, Word retains the formatting of long citations.
.Category | A number corresponding to an item in the Category box that specifies the type of citations to collect: 0 (zero) corresponds to the first item ("All"), 1 corresponds to the second item, and so on.

See Also

InsertTableOfContents, InsertTableOfFigures, MarkCitation


InsertTableOfContents

Syntax

InsertTableOfContents [.Outline = number] [, .Fields = number] [, .From = number] [, .To = number] [, .TableId = text] [, .AddedStyles = text] [, .Replace = number] [, .RightAlignPageNumbers = number]

Remarks

Collects table-of-contents entries from headings, TC (Table of Contents Entry) fields, or both, and inserts a TOC (Table of Contents) field at the insertion point.

Argument | Explanation
.Outline | If 1, collects table-of-contents entries from heading styles.
.Fields | If 1, collects table-of-contents entries from TC (Table of Contents Entry) fields.
.From | If .Outline is 1, the highest level of heading style to collect.
.To | If .Outline is 1, the lowest level of heading style to collect.
.TableId | The entry identifier specified in those TC fields you want to include in the table of contents.
.AddedStyles | Styles to collect in addition to the heading styles indicated by .From and .To. Use the following syntax when specifying .AddedStyles: StyleToCollect1,TOC#[,StyleToCollect2,TOC#][,¼] You can specify any number of styles to collect, though the length of the string value cannot be longer than 256 characters. For example, .AddedStyles = "NoteStyle,3" causes text formatted with a style called "NoteStyle" to be collected into a table of contents and formatted with the TOC 3 style.
.Replace | Specifies whether to replace a previously compiled table of contents: 0 (zero) or omitted The existing table of contents is not replaced (the instruction has no effect other than to select the table). 1 The existing table of contents is replaced.
.RightAlignPageNumbers | If 1, aligns page numbers with the right margin.

Examples

This example inserts a table of contents using Heading 1 through Heading 3 styles. TC fields, if any, are excluded.

InsertTableOfContents .Outline = 1, .From = 1, .To = 3, \
        .Fields = 0, .RightAlignPageNumbers = 1, .Replace = 1

The following example inserts a table of contents using Heading 1 through Heading 3 styles and Heading 5 styles (Heading 4 styles are skipped). Note that headings formatted with the Heading 5 style are formatted with the TOC 4 style in the table of contents.

InsertTableOfContents .Outline = 1, .From = 1, .To = 3, \
    .AddedStyles = "Heading 5,4", .RightAlignPageNumbers = 1, \
    .Replace = 0

The following example inserts a table of contents based on text formatted with the "Intro," "Main heading," "Summary," and "Subhead" styles. Text formatted with the Intro, Main heading, and Summary styles is mapped to the TOC 1 style; text formatted with the Subhead style is mapped to the TOC 2 style.

custom$ = "Intro,1,Summary,1,Main heading,1,Subhead,2"
InsertTableOfContents .Outline = 0, .AddedStyles = custom$, \
        .RightAlignPageNumbers = 1, .Replace = 0

See Also

InsertTableOfAuthorities, InsertTableOfFigures, MarkTableOfContentsEntry


InsertTimeField

Syntax

InsertTimeField

Remarks

Inserts a TIME field without any field instructions at the insertion point.

See Also

InsertDateField, InsertDateTime, InsertField, InsertPageField


InsertWordArt

Syntax

InsertWordArt

Remarks

If Microsoft WordArt is installed on your computer, starts WordArt. When the user exits WordArt, the WordArt object is embedded in the active document. The instruction InsertWordArt is the same as the instruction InsertObject .Class = "MSWordArt.2".

See Also

ActivateObject, EditObject, InsertChart, InsertDrawing, InsertEquation, InsertExcelTable


InStr()

Syntax

InStr([Index,] Source$, Search$)

Remarks

Returns the character position in Source$ at which Search$ begins, where 1 corresponds to the first character, 2 to the second character, and so on. If Source$ does not contain Search$, InStr() returns 0 (zero).

Argument | Explanation
Index | The character position in Source$ at which to begin the search
Source$ | The text to be searched
Search$ | The text to search for

Examples

This example sets the variable pos to 7:

list$ = "Bonn, Paris, Tokyo"
city$ = "Paris"
pos = InStr(list$, city$)

The following example sets pos to 15. Note that if Index were not specified, pos would be 2.

pos = InStr(3, "Bonn, Paris, Tokyo", "o")

The following example, which assigns an MS-DOS filename with a filename extension to name$, defines prefix$ as the filename without the extension:

name$ = "SUMMARY.DOC"
dot = InStr(name$, ".")
If dot > 1 Then prefix$ = Left$(name$, dot - 1)

See Also

Left$(), Len(), LTrim$(), Mid$(), Right$(), RTrim$()


Int()

Syntax

Int(n)

Remarks

Returns the integer part of a decimal number n. If n is greater than or equal to 32,768 or less than or equal to –32,769, an error occurs.

Examples

This example sets the variable x to 98:

x = Int(98.6)

The following example sets x to –9.

x = Int(-9.6)

The following function rounds a decimal number to the nearest whole number.

Function fRoundOff(x)
    fRoundOff = Int(x + 0.5 * Sgn(x))
End Function

See Also

Abs(), Rnd(), Sgn()


IsAutoCorrectException()

Syntax

IsAutoCorrectException(Tab, Exception$)

Remarks

Returns a value indicating whether Exception$ appears in the list of of AutoCorrect exceptions on the specified tab in the AutoCorrect Exceptions dialog box (AutoCorrect command, Tools Menu). In Word version 6.0, IsAutoCorrectException() is unavailable and generates an error.

Argument | Explanation
Tab | The tab where Word looks for Exception$: 0 (zero) First Letter 1 INitial CAps
Exception$ | The text to find as an entry on the specified tab.

The IsAutoCorrectException() function returns the following values.

Value | Explanation
-1 | Exception$ is an exception list entry.
0 | Exception$ is not an exception list entry.

See Also

CountAutoCorrectExceptions(), GetAutoCorrectException$(), ToolsAutoCorrectExceptions


IsCustomDocumentProperty()

Syntax

IsCustomDocumentProperty(Name$)

Remarks

Returns 1 if the Name$ property is a custom property, or returns 0 (zero) if it is not a custom property or is not valid. Use the DocumentPropertyExists() function to verify that the Name$ property exists.

For a list of the built-in properties available in Word, see DocumentPropertyName$(). In Word version 6.0, IsCustomDocumentProperty() is unavailable and generates an error.

See Also

CountDocumentProperties(), DocumentPropertyExists(), DocumentPropertyType(), IsDocumentPropertyReadOnly()


IsDocumentDirty()

Syntax

IsDocumentDirty()

Remarks

Returns a value indicating whether the active document has changed since it was last saved (that is, if it is "dirty"). Whether a document is dirty determines if Word displays a prompt to save changes when the document is closed.

Value | Explanation
0 (zero) | If the document has not changed since it was last saved
–1 | If the document has changed since it was last saved

Example

This example saves the active document if there are unsaved changes:

If IsDocumentDirty() = -1 Then FileSave

See Also

IsTemplateDirty(), SetDocumentDirty, SetTemplateDirty


IsDocumentPropertyReadOnly()

Syntax

IsDocumentPropertyReadOnly(Name$ [, CustomOrBuiltIn ])

Remarks

Returns 1 if the Name$ property is read-only. If Name$ is not a valid property, an error occurs. Use the DocumentPropertyExists() function to verify that the Name$ property exists.

For a list of the built-in properties available in Word, see DocumentPropertyName$(). In Word version 6.0, IsDocumentPropertyReadOnly() is unavailable and generates an error.

Argument | Explanation
Name$ | The name of the property.
CustomOrBuiltIn | Specifies whether Name$ is a custom property or a built-in property: 0 (zero) or omitted Name$ is a custom property unless it appears in the list of built-in properties. 1 Name$ is a built-in property. If it is not one of the built-in properties, an error occurs. 2 Name$ is a custom property, regardless of whether a built-in property with the same name already exists.

See Also

DocumentPropertyExists(), DocumentPropertyName$(), DocumentPropertyType(), IsCustomDocumentProperty()


IsExecuteOnly()

Syntax

IsExecuteOnly([Macro$])

Remarks

Returns 0 (zero) if the specified macro can be edited or –1 if the macro is execute-only. Macros that cannot be edited are sometimes referred to as encrypted. You can make a macro execute-only using MacroCopy.

Argument | Explanation
Macro$ | The name of a macro. Use the following syntax: [TemplateName:]MacroName$ If TemplateName is omitted, Word looks for the macro in the Normal template and loaded global templates. If TemplateName is specified, the template must be open in a document window, attached to an open document, or loaded as a global template; otherwise IsExecuteOnly() generates an error. If both TemplateName and MacroName$ are omitted, the macro containing the IsExecuteOnly() instruction is assumed.

Example

This example determines whether the global macro Test is execute-only. If it isn't, Word displays the macro in the macro-editing window.

encrypted = IsExecuteOnly("NORMAL:Test")
If encrypted = 0 Then ToolsMacro .Name = "Test", .Show = 1, .Edit

See Also

IsMacro(), MacroCopy


IsMacro()

Syntax

IsMacro([WindowNumber])

Remarks

Returns –1 if the window specified by WindowNumber is a macro-editing window and 0 (zero) if it is not.

Argument | Explanation
WindowNumber | Specifies a window on the Window menu: 1 corresponds to the first window, 2 to the second window, and so on. If WindowNumber is 0 (zero) or omitted, the active window is assumed. If WindowNumber does not correspond to a number on the Window menu, an error occurs.

Example

This example creates a new document if the active window is a macro-editing window:

If IsMacro() = -1 Then FileNewDefault

See Also

MacroFileName$(), MacroNameFromWindow$(), SelInfo()


IsTemplateDirty()

Syntax

IsTemplateDirty()

Remarks

Returns a value indicating whether the active template has changed since it was last saved (that is, if it is "dirty"). Whether a template is dirty determines if Word displays a prompt to save changes when the template is closed.

Value | Explanation
0 (zero) | If the template has not changed since it was last saved
–1 | If the template has changed since it was last saved

Example

This example saves the active template if there are unsaved changes:

If IsTemplateDirty() = -1 Then SaveTemplate

See Also

IsDocumentDirty, SaveTemplate, SetDocumentDirty(), SetTemplateDirty


Italic, Italic()

Syntax

Italic [On]

Italic()

Remarks

The Italic statement adds or removes the italic character format for the selected text, or controls italic formatting for characters to be inserted at the insertion point.

Argument | Explanation
On | Specifies whether to add or remove the italic format: 1 Formats the selection as italic. 0 (zero) Removes the italic format. Omitted Toggles the italic format.

The Italic() function returns the following values.

Value | Explanation
0 (zero) | If none of the selection is formatted as italic
–1 | If part of the selection is formatted as italic
1 | If all the selection is formatted as italic

See Also

FormatFont


JustifyPara, JustifyPara()

Syntax

JustifyPara

JustifyPara()

Remarks

The JustifyPara statement justifies the selected paragraphs. The JustifyPara() function returns the following values.

Value | Explanation
0 (zero) | If none of the selection is justified
–1 | If part of the selection is justified or there is a mix of alignments
1 | If all the selection is justified

See Also

CenterPara, FormatParagraph, LeftPara, RightPara


KeyCode()

Syntax

KeyCode(Count [, Context] [, FirstOrSecond])

Remarks

Returns a number representing a key assignment that differs from the default assignment. For tables of key codes and the keys they represent, see ToolsCustomizeKeyboard.

Argument | Explanation
Count | A number in the range 1 to CountKeys() specifying the custom key assignment for which you want to return a key code
Context | The template containing the custom key assignment: 0 (zero) or omitted Normal template 1 Active template
FirstOrSecond | If the key assignment is a sequence of two key combinations (for example, if you've assigned CTRL+S, N to NormalStyle), specifies which key combination to return a code for: 1 The first key combination in the sequence 2 The second key combination in the sequence If you specify 2 and the key assignment is not a key sequence, KeyCode() returns 255 (the null key code).

Example

This example inserts a table of key codes and macro names for key assignments in the active template that differ from the default assignments:

If CountKeys(1) = 0 Then
    MsgBox "No custom key assignments in active template."
    Goto bye
End If
FormatTabs .ClearAll
FormatTabs .Position = "1in", .Set
Bold 1 : Underline 1
Insert "Key Code" + Chr$(9) + "Macro"
Bold 0 : Underline 0
For i = 1 To CountKeys(1)
    Insert Chr$(13) + Str$(KeyCode(i, 1))
    combo2 = KeyCode(i, 1, 2)
    If combo2 <> 255 Then Insert "," + Str$(combo2)
    Insert Chr$(9) + KeyMacro$(i, 1)
Next i
bye:

See Also

CountKeys(), KeyMacro$()


KeyMacro$()

Syntax

KeyMacro$(Count [, Context])

Remarks

Returns the name of a macro or built-in command with a key assignment that differs from the default assignment.

Argument | Explanation
Count | A number in the range 1 to CountKeys() specifying the custom key assignment for which you want to return the command or macro name
Context | The template containing the custom key assignment: 0 (zero) or omitted Normal template 1 Active template

For an example, see KeyCode().

See Also

CountKeys(), KeyCode(), MenuItemMacro$()


Kill

Syntax

Kill FileSpec$

Remarks

Deletes the specified file or files. If FileSpec$ specifies an open document, an error occurs.

Argument | Explanation
FileSpec$ | The file specification. In Windows, you can use the MS-DOS wildcard characters — the asterisk (*) and the question mark (?) — to specify files. You can also specify a path as part of the file specification (for example, C:\DOCS\*.TXT). On the Macintosh, you can use MacID$() to specify files of a certain type (for example, MacID$("TEXT")); to specify a path, precede the Kill instruction with a ChDir instruction.

Examples

This example deletes a file in C:\WORD\ LETTERS. On the Macintosh, substitute a path and filename such as HD:WORD:LETTERS:DRAFT.

Kill "C:\WORD\LETTERS\DRAFT.DOC"

The following Windows example deletes all the files in the C:\DELETE folder:

Kill "C:\DELETE\*.*"

The previous example could be rewritten for the Macintosh as follows:

ChDir "HD:DELETE"
Kill MacID$("****")

See Also

CopyFile, MacID$(), RmDir


Language, Language$()

Syntax

Language Language$

Language$([Count])

Remarks

The Language statement identifies the selected text as being in a specific language. The proofing tools use dictionaries of the specified language on this text. Although the Language dialog box (Tools menu) lists language names in their English form, Language$ must be in the specified language and include any accented characters. For example, Italian must be specified as "Italiano" and French must be specified as "Français." For a list of valid foreign language names, see ToolsLanguage.

If Count is 0 (zero) or omitted, the Language$() function returns the language format of the first character of the selected text. If there is no selection, Language$() returns the language format of the character to the left of the insertion point.

If Count is greater than 0 (zero), Language$() returns the name of the language Count, where Count is the position of the language in an internal list of untranslated language names. Note that the list of untranslated language names does not match the list in the Language dialog box (Tools menu) because in the dialog box, language names are translated into English and sorted alphabetically. The Count argument is in the range 1 to CountLanguages().

Examples

These instructions show three different uses for the Language statement. The first marks the selection as British English, the second as whatever language is twelfth, and the third as No Proofing. The proofing tools skip over text marked as No Proofing.

Language "English (UK)"
Language Language$(12)
Language "0"

The following macro creates a two-column list in the active document showing all valid Language$(Count) instructions and the corresponding language names that each value of Count returns. The returned language names are all valid arguments for the Language statement.

Sub MAIN
For i = 1 To CountLanguages()
    If i > 1 Then InsertPara
    Insert "Language$(" + Right$(Str$(i), Len(Str$(i))-1) + ")" \
        + Chr$(9) + Language$(i)
Next
End Sub

See Also

CountLanguages(), ToolsLanguage


LCase$()

Syntax

LCase$(Source$)

Remarks

Returns a string in which all letters of Source$ have been converted to lowercase.

Example

This example displays the string assigned to the name$ variable in lowercase:

name$ = "Stella Richards"
MsgBox LCase$(name$)

See Also

ChangeCase, UCase$()


Left$()

Syntax

Left$(Source$, Count)

Remarks

Returns the leftmost Count characters of Source$.

Examples

This example displays the text "Legal" in the status bar:

a$ = "Legal File List"
Print Left$(a$, 5)

The following example uses Left$() to return the first part of a hyphenated word. InStr() is used to determine the position of the hyphen (-) character. Left$() is then used to return all the characters to the left of the hyphen.

wholeWord$ = "fade-out"
hyphen = InStr(wholeWord$, "-")
firstWord$ = Left$(wholeWord$, (hyphen - 1))
MsgBox "First part of word: " + firstWord$

A similar set of instructions can be used to return the characters before the filename extension in an MS-DOS filename. Instead of determining the position of the hyphen, you would use InStr() to return the position of the period (.) character. This can be useful if you want to save a copy of the active document with a different filename extension. For an example, see InStr().

See Also

InStr(), Len(), LTrim$(), Mid$(), Right$(), RTrim$()


LeftPara, LeftPara()

Syntax

LeftPara

LeftPara()

Remarks

The LeftPara statement aligns the selected paragraphs with the left indent.

The LeftPara() function returns the following values.

Value | Explanation
0 (zero) | If none of the selection is left-aligned
–1 | If part of the selection is left-aligned
1 | If all the selection is left-aligned

See Also

CenterPara, FormatParagraph, JustifyPara, RightPara


Len()

Syntax

Len(Source$)

Remarks

Returns the number of characters in Source$.

Example

This example prompts the user to type a name for an AutoText entry and then uses Len() to determine whether the name exceeds the 32-character limit. The On Error instruction prevents the "Command failed" message from appearing if the user cancels the InputBox$() dialog box.

On Error Goto Finish
Start:
a$ = InputBox$("Type a name for the AutoText entry.")
If Len(a$) > 32 Then
    MsgBox "Please type no more than 32 characters."
    Goto Start
End If
Finish:

See Also

InStr(), Left$(), LTrim$(), Mid$(), Right$(), RTrim$()


Let

Syntax

[Let] Var = Expression

Remarks

Assigns the value of an expression to a variable. The use of Let is optional.

Example

Each of the following instructions assigns the value 100 to the variable A:

Let A = 100
A = 100

See Also

Dim


Line Input

Syntax

Line Input #FileNumber, Variable$

Line Input [Prompt$,] Variable$

Remarks

Reads an entire line from an open sequential file and places it into a string variable. In a sequential file, a line is terminated by the carriage-return (ANSI 13) and linefeed (ANSI 10) characters. FileNumber is the number specified by the Open instruction that opened the file for input. For more information about sequential files, see Chapter 9, "More WordBasic Techniques," in Part 1, "Learning WordBasic."

Line Input is similar to the Input and Read statements, but Line Input does not break the line into separate values at commas. It places the entire line into a single string variable. Line Input can accept lines as long as 65,280 characters. Longer lines are truncated. Unlike Read, which takes only the text within quotation marks, Line Input does not distinguish between quotation marks and other characters.

If #FileNumber is omitted, the user is prompted with a question mark (?) in the status bar to type a value. The user presses ENTER to end keyboard input. If Prompt$ is specified, the question mark is not displayed.

Examples

This example places one line from the file designated as #1 into the variable sample$:

Line Input #1, sample$

The following example displays the default prompt (a question mark) in the status bar. The variable key$ is defined as the text entered after the question mark.

Line Input key$

The following example displays the prompt "Search text: " in the status bar. The variable target$ is defined as the text entered after the prompt.

Line Input "Search text: ", target$

See Also

Close, Eof(), Input, Input$(), Lof(), Open, Print, Read, Seek, Write


LineDown, LineDown()

Syntax

LineDown [Count] [, Select]

LineDown([Count] [, Select])

Remarks

The LineDown statement moves the insertion point or the active end of the selection (the end that moves when you press SHIFT+DOWN ARROW) down by the specified number of lines.

Argument | Explanation
Count | The number of lines to move down; if omitted, 1 is assumed. Negative values move the insertion point or the active end of the selection up.
Select | Specifies whether to select text: 0 (zero) or omitted Text is not selected. If there is already a selection, LineDown moves the insertion point Count lines below the selection. Nonzero Text is selected. If there is already a selection, LineDown moves the active end of the selection toward the end of the document. In a typical selection made from left to right, where the active end of the selection is closer to the end of the document, LineDown extends the selection. In a selection made from right to left, it shrinks the selection.

The LineDown() function behaves the same as the statement and also returns the following values.

Value | Explanation
0 (zero) | If the insertion point or the active end of the selection cannot be moved down.
–1 | If the insertion point or the active end of the selection is moved down by any number of lines, even if less than Count. For example, LineDown(10) returns –1 even if the insertion point is only three lines above the end of the document.

Examples

This example moves the insertion point down five lines:

LineDown 5

The following example uses LineDown() to count the lines in a document:

StartOfDocument
lines = 1
While LineDown()
    lines = lines + 1
Wend
MsgBox "There are" + Str$(lines) + " lines in the document."

See Also

LineUp, ParaDown, ParaUp


LineUp, LineUp()

Syntax

LineUp [Count] [, Select]

LineUp([Count] [, Select])

Remarks

The LineUp statement moves the insertion point or the active end of the selection (the end that moves when you press SHIFT+UP ARROW) up by the specified number of lines.

Argument | Explanation
Count | The number of lines to move up; if omitted, 1 is assumed. Negative values move the insertion point or the active end of the selection down.
Select | Specifies whether to select text: 0 (zero) or omitted Text is not selected. If there is already a selection, LineUp moves the insertion point Count lines above the selection. Nonzero Text is selected. If there is already a selection, LineUp moves the active end of the selection toward the beginning of the document. In a typical selection made from left to right, where the active end of the selection is closer to the end of the document, LineUp shrinks the selection. In a selection made from right to left, it extends the selection.

The LineUp() function behaves the same as the statement and also returns the following values.

Value | Explanation
0 (zero) | If the insertion point or the active end of the selection cannot be moved up.
–1 | If the insertion point or the active end of the selection is moved up by any number of lines, even if less than Count. For example, LineUp(10) returns –1 even if the insertion point is three lines below the start of the document.

Examples

This example moves the insertion point up 20 lines:

LineUp 20

The following example displays a message box if the insertion point is in the first line of the document:

If LineUp() = 0 Then MsgBox "No lines above here."

See Also

LineDown, ParaDown, ParaUp


ListBox

Syntax

ListBox HorizPos, VertPos, Width, Height, ArrayVariable$(), .Identifier

Remarks

Creates a list box from which a user can select an item in a custom dialog box.

Argument | Explanation
HorizPos, VertPos | The horizontal and vertical distance from the upper-left corner of the list box to the upper-left corner of the dialog box, in increments of 1/8 and 1/12 of the System font (Windows) or the dialog font (Macintosh).
Width, Height | The width and height of the list box, in increments of 1/8 and 1/12 of the System font (Windows) or the dialog font (Macintosh).
ArrayVariable$() | A string array containing the list, one list box item per array element.
.Identifier | Together with the dialog record name, .Identifier creates a variable whose value corresponds to the number of the selected list box item. The form for this variable is DialogRecord.Identifier (for example, dlg.MyList). The identifier string (.Identifier minus the period) is also used by statements in a dialog function that act on the list box, such as DlgEnable and DlgVisible.

Example

This macro displays a list of menu names. First, it creates an array of menu names to be presented in a list box, then it defines a dialog box containing the list box, and finally it displays the dialog box.

Sub MAIN
Dim MyList$(CountMenus(1) - 1)
For i = 1 To CountMenus(1)
    MyList$(i - 1) = MenuText$(1, i)
Next i
Begin Dialog UserDialog 320, 118, "List Box Example"
Text 27, 8, 129, 13, "This is a list box:"
ListBox 29, 25, 160, 84, MyList$(), .MyList
OKButton 226, 5, 88, 21
CancelButton 226, 29, 88, 21
End Dialog
Dim dlg As UserDialog
x = Dialog(dlg)
End Sub

See Also

Begin Dialog ¼ End Dialog, ComboBox, DlgListBoxArray, DropListBox


ListCommands

Syntax

ListCommands

Remarks

Creates a new document and inserts a table of built-in Word commands that also shows shortcut keys and menu assignments. In Word version 6.0c for Windows, ListCommands is not available and generates an error.

See Also

CountMacros(), MacroName$()


LockDocument, LockDocument()

Syntax

LockDocument [Lock]

LockDocument()

Remarks

The LockDocument statement adds or removes read-only protection for an entire master document or one of its subdocuments. If the insertion point is within a master document but not within a subdocument, LockDocument locks or unlocks the entire document. If the insertion point is within a subdocument, LockDocument locks or unlocks the subdocument only.

Argument | Explanation
Lock | Specifies whether to add or remove read-only protection for the subdocument or master document: 0 (zero) Removes read-only protection. Note that if you unlock an entire master document, Word unlocks all subdocuments that were previously locked. 1 Adds read-only protection. Omitted Toggles read-only protection.

The LockDocument() function returns –1 if the subdocument or master document is read-only and 0 (zero) if it is not. Note that when the insertion point is in a subdocument, LockDocument() returns information about the read-only state of the subdocument only, not of the entire master document.

See Also

ToolsProtectDocument, ToolsProtectSection, ToolsUnprotectDocument


LockFields

Syntax

LockFields

Remarks

Prevents the fields within the selection from being updated.

Example

This example inserts a DATE field and then immediately locks the field. This is useful if you want Word to insert the date for you, but you don't want the date to be updated each time you print the document.

InsertDateField
PrevField
LockFields

See Also

UnlinkFields, UnlockFields, UpdateFields


Lof()

Syntax

Lof([#]FileNumber)

Remarks

Returns the length of an open sequential file, in bytes. FileNumber is the number specified in the Open instruction that opened the file for input. For more information about sequential files, see Chapter 9, "More WordBasic Techniques," in Part 1, "Learning WordBasic."

Example

This example uses Open to prepare the file MYDATA.TXT for sequential input and then displays the size of the file MYDATA.TXT in the status bar:

Open "MYDATA.TXT" For Input As #1
    Size = Lof(1)
    Print Size; " bytes"
Close #1

See Also

Close, Eof(), Input, Input$(), Line Input, Open, Print, Read, Seek, Write


LTrim$()

Syntax

LTrim$(Source$)

Remarks

Returns Source$ minus any leading spaces (spaces to the left of the first character). LTrim$() is especially useful for removing the leading space from numeric values that have been converted to strings and for cleaning up user input.

Example

This example converts the numeric variable code to a string and then removes the leading space that was automatically added by Str$(). The variable lastName$ is then joined with code$ and stored in the variable license$.

lastName$ = "Peterson"
code = 1234
code$ = Str$(code)
code$ = LTrim$(code$)
license$ = lastName$ + code$

See Also

InStr(), Left$(), Mid$(), Right$(), RTrim$()


MacID$()

Syntax

MacID$(Identifier$)

Remarks

On the Macintosh, converts an application signature or a file type to a value that can be used with instructions (such as AppClose, Files$(), or Shell) that require either an application filename or a file type. In Windows, MacID$() is not available and generates an error.

MacID$() provides a way to specify an application without specifying the application filename, which the user can change. MacID$() can be used to specify an application with the following instructions: AppActivate, AppClose, AppCount, AppGetNames, AppGetNames(), AppIsRunning(), Shell.

MacID$() can be used with Files$(), FileOpen, and Kill to specify a Macintosh file type. Because the Macintosh does not support the MS-DOS asterisk (*) and question mark (?) wildcard characters, you use a file type to identify groups of files. For example, the following statement returns a text filename from the current folder:

textfile1$ = Files$(MacID$("TEXT"))

Note

You cannot specify multiple files in a specific folder by concatenating a path and a MacID$() file type. For example, the following instruction produces unexpected results:

textfile1$ = Files$("HD:TEXT FILES:" + MacID$("TEXT"))

Instead, you use a ChDir instruction to change the current folder, and then use MacID$() in an instruction to specify a file type.

Argument | Explanation
Identifier$ | An application signature or file type. An application signature is a four-character sequence that uniquely identifies an application. For example, MSWD is the application signature for Word; XCEL is the application signature for Microsoft Excel. A file type is a four-character sequence that identifies a file format. For example, W6BN is the file type for files created by Microsoft Word 6.0 for the Macintosh and TEXT is the file type for text files (and files created in Windows, such as Word 6.0 for Windows files). You can use "****" to indicate all files in a folder. Note that application signatures and file types are case sensitive. For example, "MSWD" is the application signature for Word, but "Mswd" is not. For a given filename, you can use FileCreator$() to determine the signature of the application that created the file, and you can use FileType$() to determine the file type.

Examples

This example uses MacID$() with AppIsRunning() and Shell to determine whether Microsoft Excel is running and to start Microsoft Excel if it is not running.

If AppIsRunning(MacID$("XCEL")) = 0 Then Shell MacID$("XCEL")

The following example uses MacID$() with FileOpen to display the Open dialog box and list the Word templates in the current folder.

Dim FOdlg as FileOpen
GetCurValues FOdlg
FOdlg.Name = MacID$("WTBN")
choice= Dialog(FOdlg)
If choice = -1 Then FileOpen FOdlg

The following example uses MacID$() with Files$() to insert a list of text files in the current folder into the active window:

textfilename$ = Files$(MacID$("TEXT"))
While textfilename$ <> ""
    Insert textfilename$
    textfilename$ = Files$()
    InsertPara
Wend

See Also

AppActivate, AppClose, AppCount(), AppGetNames, AppIsRunning(), FileCreator$(), FileOpen, Files$(), FileType$(), Kill, SetFileCreatorAndType, Shell


MacroCopy

Syntax

MacroCopy [Template1:]Macro1$, [Template2:]Macro2$ [, ExecuteOnly]

Remarks

Copies a macro from one open template to another. MacroCopy cannot replace an open macro. A template is open if it is attached to an open document, open in a document window, or loaded as a global template. If you make the new macro execute-only, it cannot be edited.

Argument | Explanation
Template1, Template2 | The open template containing the macro you want to copy and the open template to which you want to copy the macro, respectively. In Windows, if you do not include the filename extension in the template name, .DOT is assumed. Include paths if the templates are not in the folder specified by User Templates in the File Types box on the File Locations tab in the Options dialog box (Tools menu).
Macro1$, Macro2$ | The name of the macro to copy and the name of the new macro, respectively.
ExecuteOnly | If nonzero, makes the destination macro execute-only. Note that this action cannot be reversed. It is a good idea to make a copy of a macro before making the original execute-only.

If you don't specify a source or destination template, the Normal template is assumed. You can use the syntax Global:MacroName$ to specify the Normal template as the source or destination in a MacroCopy instruction. For example:

MacroCopy "MyTemp:DelStylesTest", "Global:DelStyles"

Though not required, including "Global:" can make MacroCopy instructions affecting the Normal template easier to read.

Example

This example copies the MyTest macro from the MYTEMP template to the Normal template. The new macro is given the name MyFinal.

MacroCopy "MYTEMP:MyTest", "Global:MyFinal"

See Also

IsExecuteOnly()


MacroDesc$()

Syntax

MacroDesc$(Name$)

Remarks

Returns the description associated with the macro Name$. The same text is displayed in the Description box when you select the macro in the Macro dialog box (Tools menu) and in the status bar when you select a macro assigned to a menu or toolbar. You can set macro descriptions with ToolsMacro.

If Name$ does not exist in the active template or the Normal template, an error occurs. If Name$ exists in both the active template and the Normal template, the description for the macro in the active template is returned.

Example

This example prints a list of macros in the Normal template and their descriptions. To print a similar list for the active template, substitute CountMacros(1) and MacroName$(count, 1) in the first and second instructions, respectively.

For count = 1 To CountMacros(0)
    name$ = MacroName$(count, 0)
    Bold 1
    Insert name$ + Chr$(9)
    Bold 0
    Insert MacroDesc$(name$)
    InsertPara
Next count

See Also

CountMacros(), KeyMacro$(), MacroName$(), MenuItemMacro$(), ToolsMacro


MacroFileName$()

Syntax

MacroFileName$([MacroName$])

Remarks

Returns the path and filename of the template containing the macro specified by MacroName$. Word first looks for the macro in the active template (if different from Normal), then in the Normal template, then in any loaded global templates (in alphabetic order), and finally in built-in commands (the same order Word would look for the macro when running it). If MacroName$ is omitted, MacroFileName$() returns the path and filename of the template containing the macro that is running. If MacroName$ does not exist, MacroFileName$() returns an empty string ("").

See Also

MacroDesc$(), MacroName$(), MacroNameFromWindow$()


MacroName$()

Syntax

MacroName$(Count [, Context] [, All] [, Global])

Remarks

Returns the name of the macro defined in the specified context.

Argument | Explanation
Count | A number representing a position in the internal list of macros in the given context. Unlike lists in the Macro dialog box (Tools menu), the order is not alphabetic. The number can range from 1 to the number returned by CountMacros() in the given context. If you specify 0 (zero) for Count, MacroName$() returns the name of the macro in the active (or most recently active) macro-editing window.
Context | Specifies the template from which the internal list of macros is generated: 0 (zero) Normal template 1 Active template Note that if you specify 1 when Normal is the active template and Count is greater than 0, an error occurs.
All | If 1, all available macros, add-in commands, and built-in commands are listed in the following order: macros stored in the active template, macros stored in the Normal template, macros stored in loaded global templates, add-in commands, and built-in commands.
Global | If 1, only macros stored in loaded global templates and add-in commands are listed.

For an example that uses MacroName$(), see MacroDesc$().

See Also

CountMacros(), ListCommands


MacroNameFromWindow$()

Syntax

MacroNameFromWindow$([WindowNumber])

Remarks

Returns the name of the macro in the specified macro-editing window. If the specified window is not a macro-editing window, MacroNameFromWindow$() returns an empty string ("").

Argument | Explanation
WindowNumber | Specifies a window on the Window menu: 1 corresponds to the first window, 2 to the second window, and so on. If WindowNumber is 0 (zero) or omitted, the active window is assumed. If WindowNumber does not correspond to a number on the Window menu, an error occurs.

See Also

IsMacro(), MacroFileName$(), MacroName$()


MacScript, MacScript$()

Syntax

MacScript Script$

MacScript$(Script$)

Remarks

The MacScript statement runs an existing AppleScript script resource, or passes the specified string to the default scripting language to compile and run.

Argument | Explanation
Script$ | The path and filename of a script file, or a string to compile and run. If you specify a script file, Word loads the file and runs the first script resource.

The MacScript$() function behaves the same as the statement and also returns a string that corresponds to the value returned by the specified script. If the script returns a number, it is converted to a string. If the script does not return a value, MacScript$() returns an empty string ("").

In Windows, MacScript and MacScript$() are not available and generate errors.

Example

The following macro refers to a script called CalculateString. Suppose that this script takes the selected string in a Word document and sends it to Microsoft Excel, where Microsoft Excel attempts to evaluate the string as a formula. If Microsoft Excel can evaluate the formula, the script returns the value to Word as a string. Word can then replace the selection with the result.

Sub MAIN
result$ = MacScript$("HD:APPLESCRIPT:SCRIPTS:CALCULATESTRING")
If result$ <> "" Then
    EditCut
    Insert result$
End If
End Sub

For more information on extending Word and WordBasic with AppleScript script resources, see Appendix D, "AppleScript," in Part 3, "Appendixes."

See Also

Call, Declare


Magnifier, Magnifier()

Syntax

Magnifier [On]

Magnifier()

Remarks

The Magnifier statement changes the mouse pointer from the standard pointer to a pointer resembling a magnifying glass, or vice versa, in print preview. When the mouse pointer is a magnifying glass, the user can zoom in on a particular area of the page or zoom out to see an entire page or pages.

Argument | Explanation
On | Specifies the mouse pointer to display in print preview: 0 (zero) Displays the standard pointer. 1 Displays the magnifying glass pointer. Omitted Toggles the mouse pointer.

The Magnifier() function returns –1 if the mouse pointer is a magnifying glass and 0 (zero) if it is the standard pointer.

See Also

FilePrintPreview, ViewZoom


MailCheckNames

Syntax

MailCheckNames

Remarks

Validates the addresses that appear in the To:, Cc:, and Bcc: lines in the active WordMail message. MailCheckNames is available only in Word for Windows 95 and only if Microsoft Exchange is installed.

See Also

MailHideMessageHeader, MailSelectNames


MailHideMessageHeader

Syntax

MailHideMessageHeader

Remarks

Toggles the display of the header of the active WordMail message. MailHideMessageHeader is available only in Word for Windows 95 and only if Microsoft Exchange is installed.

See Also

MailCheckNames, MailSelectNames


MailMerge

Syntax

MailMerge [.CheckErrors = number] [, .Destination = number] [, .MergeRecords = number] [, .From = number] [, .To = number] [, .Suppression = number] [, .MailMerge] [, .MailSubject = text] [, .MailAsAttachment = number] [, .MailAddress = text]

Remarks

Sets options for a mail merge, merges the main document with the specified data records, or both. If the active document is not a main document, an error occurs.

Argument | Explanation
.CheckErrors | Specifies how to check and report mail-merge errors: 0 (zero) Simulates the mail merge and reports errors in a new document. 1 Performs a mail merge, pausing to report each error as it occurs. 2 Performs a mail merge and reports any errors in a new document.
.Destination | Specifies where to send the merge documents: 0 (zero) New document 1 Printer 2 Electronic mail; messaging application programming interface (MAPI), vendor independent messaging (VIM), and Apple Open Collaboration Environment (AOCE) are supported. 3 Fax
.MergeRecords | Specifies whether or not to merge a subset of the data records: 0 (zero) Merges all data records. 1 Merges the range of data records specified by .From and .To.
.From | The number of the first data record to merge.
.To | The number of the last data record to merge.
.Suppression | Specifies whether or not to print blank lines for empty merge fields: 0 (zero) Does not print blank lines. 1 Prints blank lines.
.MailMerge | Performs the mail merge (omit .MailMerge if you want to set options only).

Argument | Explanation
.MailSubject | If the destination is electronic mail, specifies the subject text.
.MailAsAttachment | If 1, and if the destination is electronic mail or fax, sends the merge documents as attachments.
.MailAddress | If the destination is electronic mail or fax, specifies the name of the merge field that contains the electronic mail address or fax number.

Example

This example merges the main document with data records 50 to 100 and sends the merge documents to a new document:

MailMerge .CheckErrors = 2, .Destination = 0, .MergeRecords = 1, \
    .From = 50, .To = 100, .MailMerge

See Also

MailMergeCheck, MailMergeQueryOptions, MailMergeToDoc, MailMergeToPrinter


MailMergeAskToConvertChevrons, MailMergeAskToConvertChevrons()

Syntax

MailMergeAskToConvertChevrons [Prompt]

MailMergeAskToConvertChevrons()

Remarks

When you open a document created in Word for the Macintosh version 5.x or 4.0 that contains chevrons (« »), the MailMergeAskToConvertChevrons statement controls whether or not Word displays a prompt asking if you want to convert text enclosed by chevrons to merge fields.

Argument | Explanation
Prompt | Specifies whether or not to display a prompt: 0 (zero) Does not display the prompt; whether Word converts merge fields is controlled by MailMergeConvertChevrons. 1 Displays the prompt. Omitted Toggles the option to display the prompt.

The MailMergeAskToConvertChevrons() function returns –1 if Word will display the prompt and 0 (zero) if it will not.

See Also

MailMergeConvertChevrons


MailMergeCheck

Syntax

MailMergeCheck .CheckErrors = number

Remarks

Checks for errors and reports any that are found. You can check for errors with or without performing a mail merge.

Argument | Explanation
.CheckErrors | Specifies whether or not to perform a mail merge when checking for errors: 0 (zero) Simulates the mail merge and reports errors in a new document. 1 Performs a mail merge, pausing to report each error as it occurs. 2 Performs a mail merge and reports any errors in a new document.

See Also

MailMerge


MailMergeConvertChevrons, MailMergeConvertChevrons()

Syntax

MailMergeConvertChevrons [Convert]

MailMergeConvertChevrons()

Remarks

When you open a document created in Word for the Macintosh version 5.x or 4.0 that contains chevrons (« ») and MailMergeAskToConvertChevrons() returns 0 (zero), MailMergeConvertChevrons controls whether or not Word converts text enclosed by chevrons to merge fields. If MailMergeAskToConvertChevrons() returns 1, MailMergeConvertChevrons controls which button is the default when Word displays a prompt asking if you want to convert chevrons.

Argument | Explanation
Convert | Controls whether or not to convert chevrons (or which button is the default if the prompt appears): 0 (zero) Does not convert chevrons (or sets the default button in the prompt to No). 1 Converts chevrons (or sets the default button in the prompt to Yes). Omitted Toggles the setting that determines whether chevrons are converted (or toggles the default button in the prompt).

The MailMergeConvertChevrons() function returns 0 (zero) if the default button is No and –1 if the default button is Yes.

See Also

MailMergeAskToConvertChevrons


MailMergeCreateDataSource

Syntax

MailMergeCreateDataSource .FileName = text [, .PasswordDoc = text] [, .HeaderRecord = text] [, .MSQuery] [, .SQLStatement = text] [, .SQLStatement1 = text] [, .Connection = text] [, .LinkToSource = number]

Remarks

Creates a Word document that stores data for a mail merge. MailMergeCreateDataSource attaches the new data source to the active document, which becomes a main document if it is not one already.

To create a new data source with a table you can fill in later, specify only .FileName and .HeaderRecord (and .PasswordDoc if you want to protect the new data source).

Argument | Explanation
.FileName | The path and filename for the new data source
.PasswordDoc | A password to protect the new data source
.HeaderRecord | Field names for the header record. If omitted, the standard header record is used: "Title, FirstName, LastName, JobTitle, Company, Address1, Address2, City, State, PostalCode, Country, HomePhone, WorkPhone." To separate field names in Windows, use the character specified by the "sList" setting in the [intl] section of your WIN.INI file. (In Windows 95 and Windows NT, this setting is stored in the registry.)
.MSQuery | Launches Microsoft Query, if installed (Windows only). The .FileName, .PasswordDoc, and .HeaderRecord arguments a re ignored.

The .SQLStatement, .SQLStatement1, and .Connection arguments have no effect in MailMergeCreateDataSource instructions. If you display the Create Data Source dialog box using a dialog record and a Dialog or Dialog() instruction, you can return the values of these arguments. For more information about returning these values, see MailMergeDataSource$(). The .LinkToSource argument is ignored.

See Also

MailMergeCreateHeaderSource, MailMergeDataSource$(), MailMergeEditDataSource, MailMergeOpenDataSource


MailMergeCreateHeaderSource

Syntax

MailMergeCreateHeaderSource [.FileName = text] [.PasswordDoc = text] [, .HeaderRecord = text]

Remarks

Creates a Word document that stores a header record that is used in place of the data source header record in a mail merge. MailMergeCreateHeaderSource attaches the new header source to the active document, which becomes a main document if it is not one already.

Argument | Explanation
.FileName | The path and filename for the new header source
.PasswordDoc | A password to protect the new header source
.HeaderRecord | Field names for the header record. If omitted, the standard header record is used: "Title, FirstName, LastName, JobTitle, Company, Address1, Address2, City, State, PostalCode, Country, HomePhone, WorkPhone." To separate field names in Windows, use the character specified by the "sList" setting in the [intl] section of your WIN.INI file. (In Windows 95 and Windows NT, this setting is stored in the registry.)

See Also

MailMergeCreateDataSource, MailMergeEditHeaderSource, MailMergeOpenHeaderSource


MailMergeDataForm

Syntax

MailMergeDataForm

Remarks

Displays the Data Form dialog box for entering a new data record. You can use MailMergeDataForm in a main document, a data source, or any document containing data delimited by table cells or separator characters.

See Also

MailMergeEditDataSource


MailMergeDataSource$()

Syntax

MailMergeDataSource$(Type)

Remarks

Returns information about the data or header source, the means of data retrieval, or the current connection or query string.

Type | Values and descriptions
0 | The path and filename of the data source
1 | The path and filename of the header source
2 | A number, returned as text, indicating how data is being supplied for the mail-merge operation: 0 From a Word document or through a Word file converter 1 Dynamic data exchange (DDE) from Microsoft Access (Windows only) 2 DDE from Microsoft Excel 3 DDE from Microsoft Query (Windows only) 4 Open database connectivity (ODBC) (Windows only)
3 | A number, returned as text, indicating how the header source is being supplied for the mail-merge operation. See values and descriptions for Type 2.

Type | Values and descriptions
4 | The connection string for the data source
5 | The query string (SQL statement)

See Also

MailMergeCreateDataSource, MailMergeEditDataSource, MailMergeOpenDataSource


MailMergeEditDataSource

Syntax

MailMergeEditDataSource

Remarks

Performs one of the following when a main document is active:

  • If the data source is a Word document, opens the data source (or activates the data source if it is already open).
  • If Word is accessing the data through dynamic data exchange (DDE) — using an application such as Microsoft Excel or Microsoft Access — displays the data source in that application.
  • If Word is accessing the data through open database connectivity (ODBC) (Windows only), displays the data in a Word document. Note that if Microsoft Query is installed, a message appears providing the option to display Microsoft Query instead of converting data.

See Also

MailMergeCreateDataSource, MailMergeEditMainDocument, MailMergeOpenDataSource


MailMergeEditHeaderSource

Syntax

MailMergeEditHeaderSource

Remarks

Opens the header source attached to the active main document or activates the header source if it is already open. If the active document is not a main document, or if a header source is not attached, an error occurs.

See Also

MailMergeCreateHeaderSource, MailMergeEditDataSource, MailMergeOpenHeaderSource


MailMergeEditMainDocument

Syntax

MailMergeEditMainDocument

Remarks

Activates the mail-merge main document associated with the active header source or data source. If there is no main document associated with the active header or data source, or if the main document is not open, an error occurs.

See Also

MailMergeEditDataSource


MailMergeFindRecord

Syntax

MailMergeFindRecord .Find = text, .Field = text

Remarks

If a main document is active and merged data is visible, displays a merge document for the first data record containing the specified text in the given field. If a data source is active and is a Word document, MailMergeFindRecord selects the first row that matches the specified criteria. You can use MailMergeFindRecord in a main document, a data source, or any document containing data delimited by table cells or separator characters.

Argument | Explanation
.Find | Text you want to find in the specified field.
.Field | Limits the search to the specified field name.

Example

This example displays a merge document for the first data record in which the last name is "Perez." If the data record is found, the number of the record is stored in the variable numRecord.

MailMergeFindRecord .Find = "Perez", .Field = "LastName"
If MailMergeFoundRecord() Then
    numRecord = MailMergeGotoRecord()
End If

See Also

MailMergeFirstRecord, MailMergeFoundRecord(), MailMergeGotoRecord, MailMergeLastRecord, MailMergeNextRecord, MailMergePrevRecord, MailMergeViewData


MailMergeFirstRecord

Syntax

MailMergeFirstRecord

Remarks

If merged data is visible in the main document, displays a merge document for the first data record in the query result (or the first record in the data source if no query options are in effect). This statement is valid only when a main document is active.

See Also

MailMergeFindRecord, MailMergeGotoRecord, MailMergeLastRecord, MailMergeNextRecord, MailMergePrevRecord, MailMergeViewData


MailMergeFoundRecord()

Syntax

MailMergeFoundRecord()

Remarks

Returns a value indicating whether the most recent MailMergeFindRecord operation was successful.

Value | Explanation
–1 | The find operation was successful.
0 (zero) | The find operation was not successful.

For an example, see MailMergeFindRecord.

See Also

MailMergeFindRecord


MailMergeGotoRecord, MailMergeGotoRecord()

Syntax

MailMergeGotoRecord RecordNumber

MailMergeGotoRecord()

Remarks

If merged data is visible in the main document, the MailMergeGotoRecord statement displays a merge document for the data record corresponding to RecordNumber. Note that RecordNumber is the position of the record in the query result produced by the current query options, and is therefore not necessarily the position of the record in the data source.

The MailMergeGotoRecord() function returns the number of the data record currently displayed. If the active document is not a main document, both the statement and the function generate an error. For an example using MailMergeGotoRecord(), see MailMergeFindRecord.

See Also

MailMergeFindRecord, MailMergeFirstRecord, MailMergeLastRecord, MailMergeNextRecord, MailMergePrevRecord, MailMergeViewData


MailMergeHelper

Syntax

MailMergeHelper

Remarks

Used with a Dialog or Dialog() instruction to display the Mail Merge Helper dialog box (Mail Merge command, Tools menu), with which you can set up a main document, create and edit a data source, and perform a mail merge.

Example

This example displays the Mail Merge Helper dialog box.

Dim dlg As MailMergeHelper
GetCurValues dlg
x = Dialog(dlg)

See Also

MailMerge


MailMergeInsertAsk

Syntax

MailMergeInsertAsk .Name = text [, .Prompt = text] [, .DefaultBookmarkText = text] [, .AskOnce = number]

Remarks

Inserts an ASK field into a main document at the insertion point. When updated, an ASK field displays a dialog box that prompts for text to assign to the specified bookmark.

Argument | Explanation
.Name | The name of the bookmark to which you want to assign the text typed in the dialog box.
.Prompt | A prompt that appears in the dialog box (for example, "Your Initials:").
.DefaultBookmarkText | Default text to assign to the bookmark.
.AskOnce | If 1, Word displays the prompt once at the beginning of the merge instead of once for each data record.

See Also

InsertField, MailMergeInsertFillIn, MailMergeInsertSet


MailMergeInsertFillIn

Syntax

MailMergeInsertFillIn [.Prompt = text] [, .DefaultFillInText = text] [, .AskOnce = number]

Remarks

Inserts a FILLIN field into a main document at the insertion point. When updated, a FILLIN field displays a dialog box that prompts for text to insert into the document at the location of the field.

Argument | Explanation
.Prompt | A prompt that appears in the dialog box (for example, "Your Initials:").
.DefaultFillInText | Default text to insert at the field location.
.AskOnce | If 1, Word displays the prompt once at the beginning of the merge operation instead of once for each data record.

See Also

InsertField, MailMergeInsertAsk, MailMergeInsertSet


MailMergeInsertIf

Syntax

MailMergeInsertIf .MergeField = text, .Comparison = number [, .CompareTo = text] [, .TrueAutoText = text] [, .TrueText = text] [, .FalseAutoText = text] [, .FalseText = text]

Remarks

Inserts an IF field into a main document at the insertion point. When updated, an IF field compares a field in a data record to a specified value, and then inserts the appropriate text according to the result of the comparison.

Argument | Explanation
.MergeField | The name of the merge field you want to compare to the text specified by .CompareTo.
.Comparison | Specifies the operator for the comparison: 0 (zero) = (equal to) 1 <> (not equal to) 2 < (less than) 3 > (greater than) 4 <= (less than or equal to) 5 >= (greater than or equal to) 6 = " " (is blank) 7 <> " " (is not blank)
.CompareTo | Text to compare to the merge field. This argument is required unless .Comparison is set to 6 (is blank) or 7 (is not blank).
.TrueAutoText | An AutoText entry containing the text to insert if the comparison is true (.TrueText is ignored).
.TrueText | Text to insert if the comparison is true.
.FalseAutoText | An AutoText entry containing the text to insert if the comparison is false (.FalseText is ignored).
.FalseText | Text to insert if the comparison is false.

See Also

InsertField, MailMergeInsertNext, MailMergeInsertNextIf, MailMergeInsertSkipIf


MailMergeInsertMergeRec

Syntax

MailMergeInsertMergeRec

Remarks

Inserts a MERGEREC field into a main document at the insertion point. A MERGEREC field inserts the number of the current data record (the position of the data record in the current query result) during a mail merge.

See Also

InsertField, MailMergeInsertMergeSeq


MailMergeInsertMergeSeq

Syntax

MailMergeInsertMergeSeq

Remarks

Inserts a MERGESEQ field into a main document at the insertion point. A MERGESEQ field inserts a number based on the sequence in which data records are merged (for example, when merging records 50 to 100, inserts 1 when merging record number 50).

See Also

InsertField, MailMergeInsertMergeRec


MailMergeInsertNext

Syntax

MailMergeInsertNext

Remarks

Inserts a NEXT field into a main document at the insertion point. A NEXT field advances to the next data record so that data from more than one record can be merged into the same merge document (for example, a sheet of mailing labels).

See Also

InsertField, MailMergeInsertNextIf


MailMergeInsertNextIf

Syntax

MailMergeInsertNextIf .MergeField = text, .Comparison = number, .CompareTo = text

Remarks

Inserts a NEXTIF field into a main document at the insertion point. If the comparison in the NEXTIF field is true, Word merges the next data record into those merge fields in the current merge document that follow the NEXTIF field. Otherwise, Word merges the next data record into a new merge document. In general, it is preferable to specify query options instead of using NEXTIF fields. For argument descriptions, see MailMergeInsertIf.

See Also

InsertField, MailMergeInsertIf, MailMergeInsertNext, MailMergeInsertSkipIf


MailMergeInsertSet

Syntax

MailMergeInsertSet .Name = text [, .ValueText = text] [, .ValueAutoText = text]

Remarks

Inserts a SET field into a main document at the insertion point. A SET field defines the text of the specified bookmark.

Argument | Explanation
.Name | The name of the bookmark to define
.ValueText | Text to assign the bookmark to
.ValueAutoText | The AutoText entry whose text you want to assign the bookmark to (.ValueText is ignored)

See Also

InsertField, MailMergeInsertAsk, MailMergeInsertFillIn


MailMergeInsertSkipIf

Syntax

MailMergeInsertSkipIf .MergeField = text , .Comparison = number [, .CompareTo = text]

Remarks

Inserts a SKIPIF field into a main document at the insertion point. If the comparison in the SKIPIF field is true, Word cancels the current merge document and skips to the next data record. In general, it is preferable to specify query options instead of using SKIPIF fields. For argument descriptions, see MailMergeInsertIf.

See Also

InsertField, MailMergeInsertIf, MailMergeInsertNext, MailMergeInsertNextIf


MailMergeLastRecord

Syntax

MailMergeLastRecord

Remarks

If merged data is visible in the main document, displays a merge document for the last data record in the current query result (or the last record in the data source if no query options are in effect). This statement is valid only when a main document is active.

See Also

MailMergeFindRecord, MailMergeFirstRecord, MailMergeGotoRecord, MailMergeNextRecord, MailMergePrevRecord, MailMergeViewData


MailMergeMainDocumentType, MailMergeMainDocumentType()

Syntax

MailMergeMainDocumentType Type

MailMergeMainDocumentType()

Remarks

The MailMergeMainDocumentType statement makes the active window a main document. Note that if the active document is already a main document, Word removes the attached data source, if any.

Argument | Explanation
Type | The type of merge documents you will create with the main document: 0 (zero) or omitted Form letters 1 Mailing labels 2 Envelopes 3 Catalog documents

The MailMergeMainDocumentType() function returns one of the Type values if the active document is a main document, or –1 if it is a regular Word document.

See Also

MailMergeCreateDataSource, MailMergeOpenDataSource, MailMergeReset


MailMergeNextRecord

Syntax

MailMergeNextRecord

Remarks

If merged data is visible in the main document, displays a merge document for the next record in the current reply (or the next record in the data source if no query options are in effect). This statement is valid only when a main document is active.

See Also

MailMergeFindRecord, MailMergeFirstRecord, MailMergeGotoRecord, MailMergeLastRecord, MailMergePrevRecord, MailMergeViewData


MailMergeOpenDataSource

Syntax

MailMergeOpenDataSource .Name = text [, .ConfirmConversions = number] [, .ReadOnly = number] [, .LinkToSource = number] [, .AddToMru = number] [, .PasswordDoc = text] [, .PasswordDot = text] [, .Revert = number] [, .WritePasswordDoc = text] [, .WritePasswordDot = text] [, .Connection = text] [, .SQLStatement = text] [, .SQLStatement1 = text]

Remarks

Attaches the specified data source to the active document, which becomes a main document if it is not one already.

Argument | Explanation
.Name | The name of the data source. In Windows, you can specify a Microsoft Query (.QRY) file instead of a specifying a data source, a connection string, and a query string.
.LinkToSource | If 1, the query specified by .Connection and .SQLStatement is performed each time the main document is opened.

Argument | Explanation
.Connection | Specifies a range within which to perform the query specified by .SQLStatement. How you specify the range depends on how data is retrieved. For example: u When retrieving data through ODBC (Windows only), you specify a connection string. u When retrieving data from Microsoft Excel using dynamic data exchange (DDE), you specify a named range. u When retrieving data from Microsoft Access (Windows only), you specify the word "Table" or "Query" followed by the name of a table or query.
.SQLStatement | Defines query options for retrieving data.
.SQLStatement1 |  | If the query string is longer than 255 characters, .SQLStatement specifies the first portion of the string and .SQLStatement1 specifies the second portion.

Note

To determine the connection and query strings, set query options manually, and then use MailMergeDataSource$() to return the strings.

For descriptions of other arguments, see FileOpen.

See Also

FileOpen, MailMergeCreateDataSource, MailMergeEditDataSource, MailMergeOpenHeaderSource


MailMergeOpenHeaderSource

Syntax

MailMergeOpenHeaderSource .Name = text [, .ConfirmConversions = number] [, .ReadOnly = number] [, .AddToMru = number] [, .PasswordDoc = text] [, .PasswordDot = text] [, .Revert = number] [, .WritePasswordDoc = text] [, .WritePasswordDot = text]

Remarks

Attaches the specified header source to the active document, which becomes a main document if it is not one already. The header record in the header source is used in place of the header record in the data source. For argument descriptions, see FileOpen.

See Also

MailMergeCreateHeaderSource, MailMergeEditHeaderSource, MailMergeOpenDataSource


MailMergePrevRecord

Syntax

MailMergePrevRecord

Remarks

If merged data is visible in the main document, displays a merge document for the previous record in the current query result (or the previous record in the data source if no query options are in effect). This statement is valid only when a main document is active.

See Also

MailMergeFindRecord, MailMergeFirstRecord, MailMergeGotoRecord, MailMergeLastRecord, MailMergeNextRecord


MailMergeQueryOptions

Syntax

MailMergeQueryOptions .SQLStatement = text [, .SQLStatement1 = text]

Remarks

Specifies the query options for a mail merge. You can use MailMergeQueryOptions to change the query options established with a MailMergeCreateDataSource or MailMergeOpenDataSource instruction. If the active document is not a main document, an error occurs.

Argument | Explanation
.SQLStatement | An optional query string that retrieves a subset of the data in a primary data source.
.SQLStatement1 | If the string is longer than 255 characters, .SQLStatement specifies the first portion of the string and .SQLStatement1 specifies the second portion.

Note

To determine the query string, set query options manually, and then use MailMergeDataSource$() to return the string.

See Also

MailMergeCreateDataSource, MailMergeDataSource$(), MailMergeOpenDataSource


MailMergeReset

Syntax

MailMergeReset

Remarks

Detaches the data and header sources from the main document and resets it to a regular Word document. If the active document is not a main document, an error occurs.

See Also

MailMergeMainDocumentType


MailMergeState()

Syntax

MailMergeState(Type)

Remarks

Returns one of four different types of information about the current state of a mail-merge setup. Type 1, Type 2, and Type 3 return –1 if the active document is not a main document, data source, or header source.

Type | Values and descriptions
0 (zero) | Returns information about the active document: 0 (zero) Regular Word document 1 Main document with no data or header source attached 2 Main document with an attached data source 3 Main document with an attached header source 4 Main document with both a data and header source attached 5 Data source or header source; associated main document is open
1 | Returns the kind of main document: 0 (zero) Form letters 1 Mailing labels 2 Envelopes 3 Catalog
2 | Returns information about the selected mail-merge options: 0 (zero) Neither blank-line suppression nor query options are enabled. 1 Blank-line suppression is enabled. 2 Query options are enabled. 3 Both blank-line suppression and query options are enabled.
3 | Returns the mail-merge destination: 0 (zero) New document 1 Printer 2 Electronic mail 3 Fax

Example

This example checks the state of the active document before performing a mail merge. If the active document is not a main document, Word displays a message box. If the document is a main document but has no attached data source, a data source is attached. In any other case, the mail merge begins immediately.

Select Case MailMergeState(0)
    Case 0
        MsgBox "Not a mail merge main document."
        quitmacro = 1
    Case 1, 3
        MailMergeOpenDataSource .Name = "C:\DATA\DATA.DOC"
    Case Else
End Select
If quitmacro = 1 Then Goto bye
MailMergeToPrinter
bye:

See Also

MailMergeMainDocumentType


MailMergeToDoc

Syntax

MailMergeToDoc

Remarks

Merges data records with the main document and sends the resulting merge documents to a new document. If the most recent mail merge specified a range of data records to merge, only those records are merged.

See Also

MailMerge, MailMergeToPrinter


MailMergeToPrinter

Syntax

MailMergeToPrinter

Remarks

Merges data records with the main document and prints the resulting merge documents. If the most recent mail merge specified a range of data records to merge, only those records are merged.

See Also

MailMerge, MailMergeToDoc


MailMergeUseAddressBook

Syntax

MailMergeUseAddressBook .AddressBookType = text

Remarks

Selects the address book to be used as the data source for a mail merge.

MailMergeUseAddressBook is available only if Windows 95 and either Microsoft Exchange or Schedule+ version 2.0 are installed. In Word version 6.0, MailMergeUseAddressBook is unavailable and generates an error.

Argument | Explanation
.AddressBookType | Specifies the address book to be used as the data source: scd Schedule+ Contact List pab Microsoft Exchange Personal Address Book

See Also

AddAddress, GetAddress$()


MailMergeViewData, MailMergeViewData()

Syntax

MailMergeViewData [DisplayResults]

MailMergeViewData()

Remarks

The MailMergeViewData statement controls the display of merge fields in a main document. If the active document is not a main document, an error occurs.

Argument | Explanation
DisplayResults | Specifies whether to display merge field names in chevrons (« ») or information from the current data record in place of the merge fields: 0 (zero) Merge field names 1 Information from the current data record

The MailMergeViewData() function returns 0 (zero) if merge field names are displayed and 1 if information from the current data record is displayed.

See Also

MailMergeEditDataSource


MailMessageDelete

Syntax

MailMessageDelete

Remarks

Deletes the active WordMail message. MailMessageDelete is available only in Word for Windows 95 and only if Microsoft Exchange is installed.

See Also

MailMessageMove, MailMessageNext, MailMessagePrevious


MailMessageForward

Syntax

MailMessageForward

Remarks

Opens a new WordMail message with an empty To: line for forwarding the active message. MailMessageForward is available only in Word for Windows 95 and only if Microsoft Exchange is installed.

See Also

MailMessageReply, MailMessageReplyAll


MailMessageMove

Syntax

MailMessageMove

Remarks

Displays the Move dialog box in which the user can specify a new location for the active WordMail message in an available message store. MailMessageMove is available only in Word for Windows 95 and only if Microsoft Exchange is installed.

See Also

MailMessageDelete, MailMessageNext, MailMessagePrevious


MailMessageNext

Syntax

MailMessageNext

Remarks

Closes the active WordMail message and displays the next message, if available. MailMessageNext is available only in Word for Windows 95 and only if Microsoft Exchange is installed.

See Also

MailMessageDelete, MailMessageMove, MailMessagePrevious


MailMessagePrevious

Syntax

MailMessagePrevious

Remarks

Closes the active WordMail message and displays the previous message, if available. MailMessagePrevious is available only in Word for Windows 95 and only if Microsoft Exchange is installed.

See Also

MailMessageDelete, MailMessageMove, MailMessageNext


MailMessageProperties

Syntax

MailMessageProperties

Remarks

Displays the Properties dialog box for the active WordMail message. MailMessageProperties is available only in Word for Windows 95 and only if Microsoft Exchange is installed.

See Also

FileProperties


MailMessageReply

Syntax

MailMessageReply

Remarks

Opens a new WordMail message with the sender's address on the To: line for replying to the active message. MailMessageReply is available only in Word for Windows 95 and only if Microsoft Exchange is installed.

See Also

MailMessageForward, MailMessageReplyAll


MailMessageReplyAll

Syntax

MailMessageReplyAll

Remarks

Opens a new WordMail message with the sender and all other recipients' addresses on the To: and Cc: lines, as appropriate, for replying to the active message. MailMessageReplyAll is available only in Word for Windows 95 and only if Microsoft Exchange is installed.

See Also

MailMessageForward, MailMessageReply


MailSelectNames

Syntax

MailSelectNames

Remarks

Displays the Select Names dialog box in which the user can add addresses to the To:, Cc:, and Bcc: lines of the active unsent WordMail message. MailSelectNames is available only in Word for Windows 95 and only if Microsoft Exchange is installed

See Also

MailCheckNames, MailHideMessageHeader


MarkCitation

Syntax

MarkCitation [.LongCitation = text] [, .LongCitationAutoText = text] [, .Category = number] [, .ShortCitation = text] [, .NextCitation] [, .Mark] [, .MarkAll]

Remarks

Inserts a TA (Table of Authorities Entry) field next to the text you select or next to every instance of the selected text.

The arguments for the MarkCitation statement correspond to the options in the Mark Citation dialog box (Table Of Authorities tab, Index And Tables command, Insert menu).

Argument | Explanation
.LongCitation | The long citation for the entry as it will appear in the table of authorities.
.LongCitationAutoText | The name of an AutoText entry containing the long citation text you want to appear in the table of authorities (.LongCitation is ignored).
.Category | The number of the category (in the order of the list of categories in the Mark Citation dialog box) to associate with the entry: 1 corresponds to the first category in the list, 2 to the second category, and so on.
.ShortCitation | The short citation for the entry as it will appear in the list under Short Citation in the Mark Citation dialog box.
.NextCitation | Finds the next instance of the text specified by .ShortCitation.
.Mark | Inserts a TA (Table of Authorities Entry) field to the right of the selected text.
.MarkAll | Inserts a TA (Table of Authorities Entry) field to the right of all instances of the selected text.

If you don't specify .NextCitation, .Mark, or .MarkAll, Word inserts a TA field to the right of the selected text.

See Also

InsertTableOfAuthorities, MarkIndexEntry, MarkTableOfContentsEntry


MarkIndexEntry

Syntax

MarkIndexEntry [.MarkAll] [, .Entry = text] [, .Range = text] [, .Bold = number] [, .Italic = number] [, .CrossReference = text] [, .EntryAutoText = text] [, .CrossReferenceAutoText = text]

Remarks

Inserts an XE (Index Entry) field next to the text you select or next to every instance of the selected text. The arguments for the MarkIndexEntry statement correspond to the options in the Mark Index Entry dialog box (Index tab, Index And Tables command, Insert menu).

Argument | Explanation
.MarkAll | Inserts an XE field after each instance of the selected text.
.Entry | The text you want to appear in the index in the form MainEntry[:Subentry].
.Range | The name of a bookmark marking the range of pages you want to appear in the index. If you don't specify .Range, the number of the page containing the XE field appears in the index.

Argument | Explanation
.Bold | If 1, page numbers for the entry are bold in the index.
.Italic | If 1, page numbers for the entry are italic in the index.
.CrossReference | A cross-reference that will appear in the index.
.EntryAutoText | The name of an AutoText entry containing the text you want to appear in the index (.Entry is ignored).
.CrossReferenceAutoText | The name of an AutoText entry containing the text for a cross-reference (.CrossReference is ignored).

See Also

InsertIndex, MarkCitation, MarkTableOfContentsEntry


MarkTableOfContentsEntry

Syntax

MarkTableOfContentsEntry [.Entry = text] [, .EntryAutoText = text] [, .TableId = text] [, .Level = text]

Remarks

Inserts a TC (Table of Contents Entry) field next to the selected text.

Argument | Explanation
.Entry | The text you want to appear in the table of contents
.EntryAutoText | The name of an AutoText entry containing the text you want to appear in the table of contents (.Entry is ignored)
.TableId | A one-letter identifier for the type of item (for example, "i" for an illustration)
.Level | A level for the entry in the table of contents

See Also

InsertTableOfContents, MarkCitation, MarkIndexEntry


MenuItemMacro$()

Syntax

MenuItemMacro$(Menu$, Type, Item [, Context])

Remarks

Returns the name of the macro or built-in command associated with the specified menu item.

Argument | Explanation
Menu$ | The name of a menu or shortcut menu. Menu names are listed in the Change What Menu box on the Menus tab in the Customize dialog box (Tools menu). Including an ampersand (&) before the underlined letter in the menu name is optional (for example, you can specify either "File" or "&File"). Do not include the parenthetical phrases "(No Document)" and "(Shortcut)", even though that text appears in the Customize dialog box.

Argument | Explanation
Type | The type of menu: 0 Menus on the menu bar when a document is open 1 Menus on the menu bar when no document is open 2 Shortcut menus
Item | A number representing the item's position on the menu. The number can range from 1 to the number returned by CountMenuItems(). Separators between commands are considered items, and if Item represents the position of a separator, MenuItemMacro$() returns the string "(Separator)." Note that lists such as the list of recently used files on the File menu or proofing tools on the Tools menu correspond to a single item. If you specify the position of a list, MenuItemMacro$() returns an empty string ("").
Context | Specifies the menu assignment for which you want to return the macro or command name: 0 (zero) or omitted The assignment that is available when a document based on the Normal template is active 1 The assignment that is currently available Note that the assignment that is available depends on the custom settings, if any, of the active template, any loaded global templates, and the Normal template.

Example

This example defines an array variable containing the names of commands and macros assigned to the File menu in the current working environment. To define
a similar array for the File menu of the active template, substitute CountMenuItems("File", 0, 1) in the first instruction and MenuItemMacro$("File", 0, count, 1) in the fourth instruction.

numItems = CountMenuItems("File", 0, 0)
Dim fileItem$(numItems - 1)
For count = 1 To numItems
    fileItem$(count - 1) = MenuItemMacro$("File", 0, count, 0)
Next count

See Also

CountMacros(), KeyMacro$(), MacroDesc$(), MacroName$(), MenuItemText$(), ToolsCustomizeMenus


MenuItemText$()

Syntax

MenuItemText$(Menu$, Type, Item [, Context])

Remarks

Returns the menu text associated with a macro or built-in command assigned to the specified menu. You can change the menu text with ToolsCustomizeMenus.

Note

The menu text for a subset of built-in commands changes depending on the current conditions of the Word environment. For these commands, MenuItemText$() returns the command name instead of the menu text. The commands include EditCopy, EditPaste, EditRedoOrRepeat, EditUndo, FileClose, FileCloseAll, FileCloseOrCloseAll, FileExit, FileQuit, FileSave, FileSaveAll, FileSaveAs, FormatFrameOrFramePicture, TableDeleteGeneral, TableInsertGeneral, TableSort, TableToOrFromText, and ToolsProtectUnprotectDocument.

Argument | Explanation
Menu$ | The name of a menu or shortcut menu. Menu names are listed in the Change What Menu box on the Menus tab in the Customize dialog box (Tools menu). Including an ampersand (&) before the underlined letter in the menu name is optional (for example, you can specify either "File" or "&File"). Do not include the parenthetical phrases "(No Document)" and "(Shortcut)", even though that text appears in the Customize dialog box.
Type | The type of menu: 0 (zero) Menus on the menu bar when a document is open 1 Menus on the menu bar when no document is open 2 Shortcut menus
Item | A number representing the item's position on the menu. The number can range from 1 to the number returned by CountMenuItems(). Separators between commands are considered items, and if Item represents the position of a separator, MenuItemText$() returns the string "(Separator)." Note that lists such as the list of recently used files on the File menu or proofing tools on the Tools menu correspond to a single item. If you specify the position of a list, MenuItemText$() returns a parenthetical phrase describing the list — for example, "(List of Recently Used Files") or "(List of Proofing Tools)".

Argument | Explanation
Context | Specifies the menu assignments for which you want to return the menu text: 0 (zero) or omitted The assignments that are available when a document based on the Normal template is active 1 The assignments that are currently available Note that the assignments that are available depend on the custom settings, if any, of the active template, any loaded global templates, and the Normal template.

Example

This example displays a message box with the menu text of the first Word-related item on the Help menu when no document is open (on the Macintosh, this is the first item after the Show Balloons command):

MsgBox MenuItemText$("Help", 1, 1, 0)

See Also

CountMenuItems(), CountMenus(), MenuItemMacro$(), MenuText$(), ToolsCustomizeMenus


MenuMode

Syntax

MenuMode

Remarks

Activates the menu bar. MenuMode corresponds to pressing the alt key (Windows) or the Decimal (.) key on the numeric keypad when Num Lock is off (Macintosh).


MenuText$()

Syntax

MenuText$(Type, MenuNumber [, Context])

Remarks

Returns the name of a shortcut menu or a menu on the menu bar. If there is an underlined letter in the menu name, MenuText$() includes an ampersand (&) before the letter in the returned text. (On the Macintosh, the underlined letters in menu and command names appear only in menu mode.)

Argument | Explanation
Type | The type of menu: 0 (zero) Menus on the menu bar when a document is open 1 Menus on the menu bar when no document is open 2 Shortcut menus
MenuNumber | A number in the range 1 to CountMenus() for the specified type. If Type is 0 (zero) or 1, MenuNumber represents a position on the menu bar from left to right (where 1 corresponds to the File menu). If Type is 2, MenuNumber represents a position in the series of shortcut menus in the Change What Menu box on the Menus tab in the Customize dialog box (Tools menu): The first shortcut menu in the series is 1, the second is 2, and so on.
Context | Specifies the template that contains the name of menu MenuNumber you want to return: 0 (zero) or omitted Normal template 1 Active template

Example

This example defines an array to fill with the names of the shortcut menus available in the Normal template and then fills the array:

size = CountMenus(2, 0) - 1
Dim shortcutMenus$(size)
For count = 0 To size
    shortcutMenus$(count) = MenuText$(2, count + 1, 0)
Next count

See Also

CountMenuItems(), CountMenus(), MenuItemMacro$(), MenuItemText$(), ToolsCustomizeMenus


MergeFieldName$()

Syntax

MergeFieldName$(Count)

Remarks

Returns a field name in a data source or header source. In a data source set up as
a Word table, the field names are in the first row as column headings. In a data source set up as delimited lists, the field names are in the first paragraph. An error occurs if you run MergeFieldName$() when the active document is not a main document.

Argument | Explanation
Count | The number corresponding to the field name in the data source or header source, where 1 is the first field name, 2 is the second, and so on.

Example

This example defines an array containing the field names available to a main document (which must be active when the example is run):

numFields = CountMergeFields()
Dim mmFields$(numFields - 1)
For count = 1 To numFields
    mmFields$(count - 1) = MergeFieldName$(count)
Next count

See Also

CountMergeFields(), InsertMergeField


MergeSubdocument

Syntax

MergeSubdocument

Remarks

Merges the selected subdocuments of a master document into one subdocument. If only one subdocument is selected, or if the active document is not in master document or outline view, an error occurs.

See Also

CreateSubdocument, InsertSubdocument, OpenSubdocument, RemoveSubdocument, SplitSubdocument, ViewMasterDocument


MicrosoftApplication

Syntax

Microsoft Application

Remarks

Starts the specified Microsoft application if it is not running or switches to the application if it is already running.

Argument | Explanation
Application | The application you want to go to. The following statements are available: MicrosoftAccess (not available on the Macintosh) MicrosoftExcel MicrosoftFoxPro MicrosoftMail MicrosoftPowerPoint MicrosoftProject MicrosoftPublisher (not available on the Macintosh) MicrosoftSchedule (not available on the Macintosh) MicrosoftSystemInfo

See Also

AppActivate, AppIsRunning()


Mid$()

Syntax

Mid$(Source$, Start [, Count])

Remarks

Returns a portion of Source$ starting at a given character position.

Argument | Explanation
Source$ | The original string.
Start | The character position in Source$ where the string you want to return begins.
Count | The number of characters in the string you want to return. If you do not specify Count, the number of characters to the end of the string is assumed.

Example

This example returns the second word of a two-word string:

wholeName$ = "Sanjeev Reddy"
space = InStr(wholeName$, " ")
lastName$ = Mid$(wholeName$, space + 1)

See Also

InStr(), Left$(), Len(), LTrim$(), Right$(), RTrim$()


Minute()

Syntax

Minute(SerialNumber)

Remarks

Returns an integer between 0 (zero) and 59, inclusive, corresponding to the minutes component of SerialNumber, a decimal representation of the date, time, or both. For information about serial numbers, see DateSerial().

Example

This example displays the minutes component of the current time:

mins = Minute(Now())
MsgBox "It is" + Str$(mins) + " minute(s) after the hour."

See Also

DateSerial(), Day(), Hour(), Month(), Now(), Second(), Today(), Weekday(), Year()


MkDir

Syntax

MkDir Name$

Remarks

Creates the folder specified by Name$. An error occurs if the folder already exists. If you don't specify a path, Name$ is interpreted relative to the current folder. On the Macintosh, note that if Name$ begins with a colon, Name$ is a relative path; if Name$ contains a colon elsewhere in the folder specification, Name$ is an absolute path.

Examples

This example creates the folder "OUTPUT" by specifying a path. Note that the TEST folder must already exist; MkDir cannot create both folders at the same time. On the Macintosh, substitute a folder name such as HD:TEST:OUTPUT.

MkDir "C:\TEST\OUTPUT"

Each of the following examples creates a subfolder within the current folder:

MkDir "OUTPUT"        'Windows or Macintosh
MkDir ".\OUTPUT"        'Windows
MkDir ":OUTPUT"        'Macintosh

The following Windows example creates a folder at the same level as the current folder:

MkDir "..\OUTPUT"

The following is the Macintosh equivalent of the previous example:

MkDir "::OUTPUT"

See Also

ChDir, CountDirectories(), Files$(), GetDirectory$(), Name, RmDir


Month()

Syntax

Month(SerialNumber)

Remarks

Returns an integer between 1 and 12, inclusive, corresponding to the month component of SerialNumber, a decimal representation of the date, time, or both. For information about serial numbers, see DateSerial().

Example

This example displays the number of full months between the current month and the new year:

months = Month(Now())
MsgBox Str$(12 - months) + " full month(s) left in the year."

See Also

DateSerial(), Day(), Hour(), Minute(), Now(), Second(), Today(), Weekday(), Year()


MountVolume, MountVolume()

Syntax

MountVolume Zone$, Server$, Volume$ [, User$] [, UserPassword$]
[, VolumePassword$]

MountVolume(Zone$, Server$, Volume$ [, User$] [, UserPassword$]
[, VolumePassword$])

Remarks

On the Macintosh, the MountVolume statement connects to a disk or folder shared across the network.

Argument | Explanation
Zone$ | The zone that the computer you want to connect to is in.
Server$ | The name of the computer.
Volume$ | The name of the shared disk or folder.
User$ | Your user name, as registered by the shared computer. If you do not specify a user name, you are connected as a guest.
UserPassword$ | The password, if any, required to connect to the specified computer.
VolumePassword$ | The password, if any, required to access the specified disk or folder.

The MountVolume() function behaves the same as the statement, and also returns one of the following values.

Value | Explanation
0 (zero) | The instruction was successful or the connection already exists.
–28 | AppleTalk is not available (for example, your computer is not connected to a network).
–35 | The specified volume was not found.
–50 | The instruction contains and invalid argument (for example, the zone, server, or volume name is missing, or the user name is not recognized).
–58 | An external file system error occurred.
–108 | There was not enough memory to make the connection.
–5000 | Access was denied.
–5002 | The method used to authenticate the user is unknown.
–5003 | The AppleTalk Filing Protocol (AFP) on the server is incompatible with MountVolume.
–5016 | The specified server is not responding.
–5023 | The user was not authenticated; this usually occurs because the password is incorrect.
–5042 | The password has expired.
–5061 | The computer is already connected to the maximum number of volumes.
–5063 | The specified server is the same as the computer running the instruction.

Note

MountVolume cannot connect to volumes that the Finder cannot connect to using an alias.

In Windows, MountVolume and MountVolume() are not available and generate errors; use Connect instead.

Example

This example connects to a shared folder as a guest:

MountVolume "Public", "Tools", "Art Tools"

See Also

Connect


MoveButton

Syntax

MoveButton SourceToolbar$, SourcePosition, TargetToolbar$, TargetPosition [, Copy] [, Context]

Remarks

Moves or copies a toolbar button, list box, or space to another toolbar or to another position on the same toolbar.

Argument | Explanation
SourceToolbar$ | The name of the toolbar containing the item you want to move or copy, as listed in the Toolbars dialog box (View menu).
SourcePosition | The position of the item you want to move or copy, where 1 is the first position, 2 is the second, and so on. Note that a list box or space counts as one position.
TargetToolbar$ | The name of the toolbar to which you want to move or copy the item.
TargetPosition | The position to which you want to move or copy the item.
Copy | If 1, copies instead of moves the toolbar item.
Context | Determines where the change to the toolbar or toolbars is stored: 0 (zero) or omitted Normal template 1 Active template

Example

This example copies the Show/Hide ¶ button from the Standard toolbar to the end of the Macro toolbar (assuming these toolbars have not been customized already):

MoveButton "Standard", 26, "Macro", 18, 1, 0

See Also

AddButton, ChooseButtonImage, CopyButtonImage, DeleteButton, EditButtonImage, PasteButtonImage, ResetButtonImage


MoveText

Syntax

MoveText

Remarks

Moves text without changing the contents of the Clipboard (the same as pressing the F2 key in Windows). For MoveText to work, macro instructions must make a selection immediately before the MoveText instruction, make a new selection immediately after MoveText, and then use the OK statement to move the text.

Example

This example moves the line containing the insertion point to the beginning of the document:

StartOfLine
EndOfLine 1
MoveText
StartOfDocument
OK

See Also

CopyFormat, CopyText, OK


MoveToolbar

Syntax

MoveToolbar Toolbar$, Dock, HorizPos, VertPos

Remarks

Moves the specified toolbar. If the specified toolbar is not displayed, an error occurs.

Argument | Explanation
Toolbar$ | The name of the toolbar to move, as it is listed in the Toolbars dialog box (View menu).
Dock | Specifies whether to anchor the toolbar at the top, bottom, or either side of the Word window or to set it as a floating toolbar over the document window: 0 (zero) The toolbar floats over the document window. 1 The toolbar is anchored at the top of the Word window. 2 The toolbar is anchored at the left of the Word window. 3 The toolbar is anchored at the right of the Word window. 4 The toolbar is anchored at the bottom of the Word window.
HorizPos, VertPos | If Dock is 0 (zero), the horizontal (HorizPos) and vertical (VertPos) distance from the upper-left corner of the Word window to the upper-left corner of the toolbar, in pixels. If Dock is nonzero, you must still specify HorizPos and VertPos. Word moves the toolbar to the nearest available position in the series of docked toolbars.

Example

This example displays the Forms toolbar and moves it to the lower-right corner of the Word window. The If conditional prevents the AppMaximize instruction from running and generating an error on the Macintosh.

If InStr(AppInfo$(1), "Macintosh") = 0 Then AppMaximize 1
ViewToolbars .Toolbar = "Forms", .Show
MoveToolbar "Forms", 0, 520, 410

See Also

ToolbarName$(), ToolbarState(), ViewToolbars


MsgBox, MsgBox()

Syntax

MsgBox Message$ [, Title$] [, Type]

MsgBox(Message$ [, Title$] [, Type])

Remarks

The MsgBox statement displays a message in a message box. You can also display a message with the MsgBox() function, which returns a value according to the command button the user chooses in the message box. Use MsgBox() if you need your macro to take action based on the user's response.

Argument | Explanation
Message$ | The message to be displayed in the message box. If Message$ is longer than 255 characters, an error occurs.
Title$ | The title of the message box. In Windows, if Title$ is omitted or is an empty string (""), "Microsoft Word" is the default title. On the Macintosh, if Title$ is an empty string (""), a title bar does not appear in the message box.
Type | A value representing the symbol and buttons displayed in the box.

Type is the sum of three values, one from each of the following groups.

Group | Value | Meaning
Button | 0 (zero) | OK button (default)
 | 1 | OK and Cancel buttons
 | 2 | Abort, Retry, and Ignore buttons
 | 3 | Yes, No, and Cancel buttons
 | 4 | Yes and No buttons
 | 5 | Retry and Cancel buttons
Symbol | 0 (zero) | No symbol (default)
 | 16 | Stop symbol
 | 32 | Question symbol (Windows) or attention symbol (Macintosh)
 | 48 | Attention symbol
 | 64 | Information symbol
Button action | 0 (zero) | First button is the default
 | 256 | Second button is the default
 | 512 | Third button is the default

By specifying Type as –1, –2, or –8, you can display the message in the status bar instead of a message box. This is similar to using the Print statement, but gives you more control over how long the message is displayed. Specifying Type as –1 displays the message until another message replaces it; specifying –2 displays the message until a mouse or keyboard action occurs; and specifying –8 displays the message in the entire status bar width until a mouse or keyboard action occurs.

Because the MsgBox statement does not return a value, the use of button values other than 0 (zero) is not recommended. To make use of buttons other than the OK button, use the MsgBox() function. MsgBox() returns the following values.

Return value | Button chosen | Button text
–1 | First (leftmost) button | OK
 |  | Yes
 |  | Abort
0 (zero) | Second button | Cancel
 |  | No
 |  | Retry
1 | Third button | Cancel
 |  | Ignore

If Type is a negative value—that is, if you use MsgBox() to display a message in the status bar—MsgBox() always returns 0 (zero).

Examples

In this example, the MsgBox instruction displays a message box containing the message "Unable to find file," the title "MyTest Macro," an OK button, and a Stop symbol (0 + 16 + 0 = 16):

MsgBox "Unable to find file.", "MyTest Macro", 16

In the following macro, the If conditional checks whether or not there is a selection before proceeding. If there is no selected text, the MsgBox() function displays a message box asking if the user wants to continue anyway. The second If conditional tests the return value. If it's 0 (zero), which means the second button (No) was chosen, the macro ends without running subsequent instructions.

Sub MAIN
'Series of instructions that select text
If SelType() <> 2 Then
button = MsgBox("There is no selection. Continue anyway?", 36)
If button = 0 Then Goto bye
End If
'Series of instructions that act on the selection
bye:
End Sub

See Also

InputBox$(), Print


Name

Syntax

Name OldName$ As NewName$

Remarks

Renames a file. If you do not include paths with the OldName$ and NewName$ arguments, Name assumes the current folder — the one selected in the Open dialog box (File menu). In Windows, you can move a file to a different folder by including a different path for NewName$; however, you cannot use Name to move folders or to move a file to a different drive. On the Macintosh, the path for OldName$ must match the path for NewName$ or an error occurs.

Argument | Explanation
OldName$ | The previous name of the file. If the filename specified by OldName$ does not exist or is open, an error occurs.
NewName$ | The new name of the file. If the filename specified by NewName$ already exists, an error occurs.

The OldName$ and NewName$ arguments do not accept wildcard characters — the asterisk (*) and question mark (?).

Examples

This example uses ChDir to set the current folder, and then renames the file COGS.DOC as COGS88.DOC in that folder. Without the ChDir instruction preceding it, the Name instruction would need to specify the complete path for each filename. On the Macintosh, substitute a folder name such as HD:DOCS:MEMOS:JULY in the ChDir instruction.

ChDir "C:\MYDOCS\MEMOS\JULY"
Name "COGS.DOC" As "COGS88.DOC"

The following Windows example moves the file COGS.DOC to a different folder and leaves the filename unchanged:

Name "C:\TMP\COGS.DOC" As "C:\DOCS\COGS.DOC"

See Also

ChDir, CopyFile, FileSaveAs, Kill, MkDir, RmDir


NewToolbar

Syntax

NewToolbar .Name = text [, .Context = number]

Remarks

Creates a new toolbar to which you can add buttons using the AddButton and MoveButton statements.

Argument | Explanation
.Name | A name for the new toolbar (spaces are allowed).
.Context | The template in which you want to store the toolbar: 0 (zero) or omitted Normal template; the toolbar always appears in the Toolbars dialog box (View menu). 1 Active template; the toolbar only appears in the Toolbars dialog box when the template is active.

See Also

AddButton, CountToolbars(), MoveButton, ToolbarName$(), ViewToolbars


NextCell, NextCell()

Syntax

NextCell

NextCell()

Remarks

The NextCell statement selects the contents of the next table cell (the same as pressing TAB in a table). If more than one cell is selected, NextCell selects the contents of the first cell in the selection. If the insertion point or selection is in the last cell of the table, NextCell adds a new row.

The NextCell() function behaves the same as the statement except when the insertion point or selection is completely within the last cell. In that case, the function returns 0 (zero) without enlarging the section, whereas the statement adds a new row.

Note

You can use EditGoTo .Destination = "\Cell" to select the contents of the current cell. The predefined bookmark " \ Cell" and a number of others are set and updated automatically. For information on predefined bookmarks, see "Operators and Predefined Bookmarks" later in this part.

Examples

This example moves the selection to the next cell, and then uses SelType() to determine if the cell is empty. If SelType() returns 1 (the value for the insertion point, indicating the cell is empty), a message box appears.

NextCell
If SelType() = 1 Then MsgBox "Empty cell!"

The following example uses the NextCell() function to determine if the insertion point is in the last cell. If the current cell is the last cell, the entire table is selected. If the current cell is not the last cell, the next cell is selected.

If NextCell() = 0 Then TableSelectTable

See Also

PrevCell


NextField, NextField()

Syntax

NextField

NextField()

Remarks

The NextField statement selects the next field, regardless of whether the field is showing its codes or results. NextField skips over the following fields, which are formatted as hidden text: XE (Index Entry), TA (Table of Authorities Entry),
TC (Table of Contents Entry), and RD (Referenced Document).

The NextField() function behaves the same as the statement and also returns the following values.

Value | Explanation
0 (zero) | If there is no next field (in other words, if the selection is not moved)
1 | If the selection is moved

With field codes displayed, you can use EditFind to go to the next field of any type, including XE, TA, TC, and RD fields, provided that hidden text is displayed. Specify "^d" (the code for a field character) as the text for the .Find argument, as shown in the following instructions:

ViewFieldCodes 1
EditFind .Find = "^d", .Direction = 0, .Format = 0

To find only XE fields, specify "^d XE" as the text to find.

Example

This example counts the number of fields in the document (excluding XE, TA, TC, and RD fields) and displays the result in a message box. Note that the
While ¼ Wend loop does not include a NextField statement because the While NextField() instruction also moves the selection.

StartOfDocument
count = 0
While NextField()
    count = count + 1
Wend
MsgBox "Number of fields in the document:" + Str$(Count)

See Also

PrevField


NextMisspelling

Syntax

NextMisspelling

Remarks

Finds the next misspelled word. If automatic spell checking is turned on, NextMisspelling opens the shortcut menu containing spelling suggestions. For an example, see DocumentHasMisspellings(). In Word version 6.0, NextMisspelling is unavailable and generates an error.

See Also

DocumentHasMisspellings(), ToolsGetSpelling, ToolsLanguage, ToolsOptionsSpelling


NextObject

Syntax

NextObject

Remarks

Moves the insertion point to the next document object on the current page in page layout view (the same as pressing ALT+DOWN ARROW (Windows) or OPTION+DOWN ARROW (Macintosh)). Document objects include text columns, table cells, footnotes, and frames.

From the top of the first text column on a page, the NextObject statement moves through document objects in the following order:

  • Each text column, in order from first to last (if there is more than one), moving through all table cells and then all footnotes that appear within the text column
  • Frames, if any appear, in the order that they appear in normal view, from the previous page break to the following page break

NextObject finally moves to the top of the first text column before cycling through the document objects again.

Keep the following points in mind when using NextObject:

  • You can identify document objects by selecting the Text Boundaries check box, on the View tab in the Options dialog box (Tools menu), when the active document is in page layout view.
  • Word does not consider OLE objects, such as embedded drawings and charts, to be document objects unless they are framed.
  • If the insertion point is in a header or footer, NextObject moves between the header and footer.
  • Make sure to switch to page layout view before using NextObject.

Example

This example moves the insertion point to the first document object on the current page. The EditGoTo "\Page" instruction selects the current page, and SelType 1 cancels the selection, leaving the insertion point at the top of the page. The NextObject instruction moves the insertion point to the first document object.

ViewPage
EditGoTo "\Page"
SelType 1
NextObject

See Also

PrevObject


NextPage, NextPage()

Syntax

NextPage

NextPage()

Remarks

The NextPage statement scrolls forward one page in page layout view without moving the insertion point (the same as clicking the Page Forward button at the bottom of the vertical scroll bar in page layout view). If you want to move the insertion point after scrolling, include a StartOfWindow statement following NextPage in your macro.

NextPage scrolls from the current location on one page to the same relative location on the next page. To scroll to the beginning of the next page regardless
of what portion of the current page appears, use the instruction EditGoTo .Destination = "p" instead of NextPage. Note, however, that EditGoTo also moves the insertion point.

The NextPage() function behaves the same as the statement and also returns the following values.

Value | Explanation
0 (zero) | If there is no next page (in other words, if the document doesn't scroll)
1 | If the document scrolls

Note

NextPage and NextPage() are available only in page layout view and generate an error if run in another view.

Example

This example scrolls forward one page and positions the insertion point at the top of the document window. If the document has scrolled as far as possible, a message box is displayed.

ViewPage
If NextPage() = 0 Then
    MsgBox "Can't scroll!"
Else
    StartOfWindow
End If

See Also

EditGoTo, PageDown, PrevPage, ViewPage, VPage


NextTab()

Syntax

NextTab(Position)

Remarks

Returns the position of the next tab stop to the right of Position, in points, for the first paragraph of the selection.

Use the following list of conversions as an aid in converting from points to other measurements:

  • 1 inch = 72 points
  • 1 centimeter = 28.35 points
  • 1 pica = 12 points

Example

This example uses NextTab() with TabType() to return a value corresponding to the alignment of the first tab stop in the selection:

firstTabType = TabType(NextTab(0))

See Also

FormatTabs, PrevTab(), TabLeader$(), TabType()


NextWindow

Syntax

NextWindow

Remarks

Moves the window at the front of the internal order of open windows to the back. This statement does nothing if there is only one open window.

See Also

Activate, ChDir, PrevWindow, Window(), WindowList, WindowName$(), Window Number


NormalFontPosition

Syntax

NormalFontPosition

Remarks

Restores the selected characters to the baseline if they have been raised or lowered.

See Also

FormatFont, NormalFontSpacing


NormalFontSpacing

Syntax

NormalFontSpacing

Remarks

Restores the selected characters to Normal character spacing if their current spacing is expanded or condensed.

See Also

FormatFont, NormalFontPosition


NormalStyle

Syntax

NormalStyle

Remarks

Applies the Normal style to the selected paragraphs. There is not a corresponding function for NormalStyle; however, you can use the StyleName$() function to determine the current style. For example, the instruction If StyleName$() = "Normal" Then MsgBox "Normal paragraph" displays a message box if the current paragraph is in the Normal style.

Example

This example selects the current paragraph, and if it contains the string "Comments:", applies the Normal style. The bookmark " \ Para" is one of several predefined bookmarks that Word sets and updates automatically. For information on predefined bookmarks, see "Operators and Predefined Bookmarks" later in this part.

EditGoTo .Destination = "\Para"
If InStr(Selection$(), "Comments:") Then NormalStyle

See Also

FormatStyle, ResetPara, Style, StyleName$()


NormalViewHeaderArea

Syntax

NormalViewHeaderArea [.Type = number] [, .FirstPage = number] [, .OddAndEvenPages = number] [, .HeaderDistance = text] [, .FooterDistance = text]

Remarks

Opens the header/footer pane (normal and outline views) or displays the header
or footer area (page layout view) and sets options for headers and footers. You can display the header/footer pane to edit any type of header or footer, regardless of the number of pages in the document.

The arguments for the NormalViewHeaderArea statement correspond to the options in the Header/Footer dialog box in Word version 2.x. Note that these options are usually set using FilePageSetup in Word version 6.0 and 7.0. Although you can retrieve information from the NormalViewHeaderArea dialog record, you cannot use this statement to display the Word version 2.x dialog box.

Argument | Explanation
.Type | Specifies whether to display the header or footer area. The possible values of .Type depend on the settings of .FirstPage and .OddAndEvenPages. If both .FirstPage and .OddAndEvenPages are set to 0 (zero): 0 (zero) Header 1 Footer If .FirstPage is set to 1 and .OddAndEvenPages is set to 0 (zero): 0 (zero) Header 1 Footer 2 First header 3 First footer If .FirstPage is set to 0 (zero) and .OddAndEvenPages is set to 1: 0 (zero) Even header 1 Even footer 2 Odd header 3 Odd footer If both .FirstPage and .OddAndEvenPages are set to 1: 0 (zero) First header 1 First footer 2 Even header 3 Even footer 4 Odd header 5 Odd footer
.FirstPage | If 1, allows a header or footer for the first page that differs from the rest of the pages in the section.
.OddAndEvenPages | If 1, allows one header or footer for even-numbered pages and a different header or footer for odd-numbered pages.
.HeaderDistance | The distance from the top of the page to the header.
.FooterDistance | The distance from the bottom of the page to the footer.

See Also

FilePageSetup, ViewFooter, ViewHeader


NoteOptions

Syntax

NoteOptions [.FootnotesAt = number] [, .FootNumberAs = number] [, .FootStartingNum = text] [, .FootRestartNum = number] [, .EndnotesAt = number] [, .EndNumberAs = number] [, .EndStartingNum = text] [, .EndRestartNum = number]

Remarks

Specifies the placement and formatting of footnotes and endnotes. The arguments for the NoteOptions statement correspond to the options in the Note Options dialog box (Footnote command, Insert menu).

Argument | Explanation
.FootnotesAt | Specifies where to place footnotes: 0 (zero) Bottom Of Page 1 Beneath Text
.FootNumberAs | Specifies the format for footnote reference marks: 0 (zero) 1, 2, 3,¼ 1 a, b, c,¼ 2 A, B, C,¼ 3 i, ii, iii,¼ 4 I, II, III,¼ 5 *, †, ‡, §,¼
.FootStartingNum | The starting number for footnotes; if .FootStartingNum is not 1, .FootRestartNum must be set to 0 (zero).
.FootRestartNum | Specifies how to number footnotes after page breaks or section breaks: 0 (zero) Continuous 1 Restart Each Section 2 Restart Each Page
.EndnotesAt | Specifies where to place endnotes: 0 (zero) End Of Section 1 End Of Document
.EndNumberAs | Specifies the format for endnote reference marks. For values, see the .FootNumberAs argument.
.EndStartingNum | The starting number for endnotes; if .EndStartingNum is not 1, .EndRestartNum must be set to 0 (zero).
.EndRestartNum | Specifies how to number endnotes after section breaks: 0 (zero) Continuous 1 Restart Each Section

Example

This example places footnotes beneath text, using the "A, B, C" format and starting with "A"; footnote numbers restart with each new section:

NoteOptions .FootnotesAt = 1, .FootNumberAs = 2, \
        .FootStartingNum = "1", .FootRestartNum = 1

See Also

InsertFootnote


Now()

Syntax

Now()

Remarks

Returns a serial number that represents the current date and time according to
the computer's system date and time. Numbers to the left of the decimal point represent the number of days between December 30, 1899 and the current date; numbers to the right represent the time as a fraction of a day. For more information about serial numbers, see DateSerial().

Example

This example displays a message box stating the number of days until the new year. The number of days is calculated by subtracting the serial number for the current date and time from the serial number for January 1 of the following year.

yr = Year(Now())
rightNow = Now()
jan1 = DateSerial(yr + 1, 1, 1)
MsgBox "Days until the new year:" + Str$(jan1 - rightNow)

Fractions of a day appear in the result after the decimal point. To return strictly the number of days with no decimal fraction, substitute Today() in place of Now() in the preceding example.

See Also

DateSerial(), Date$(), DateValue(), Today()


PrintOK

Syntax

OK

Remarks

Completes a CopyText or MoveText operation (the same as pressing ENTER while the operation is in progress).

Example

This example copies the line containing the insertion point to the beginning of the document without changing the contents of the Clipboard:

StartOfLine
EndOfLine 1
CopyText
StartOfDocument
OK

See Also

Cancel, CopyText, MoveText


OKButton

Syntax

OKButton HorizPos, VertPos, Width, Height [, .Identifier]

Remarks

Creates an OK button in a custom dialog box. If the user chooses the OK button, the dialog box closes and its settings are applied.

Argument | Explanation
HorizPos, VertPos | The horizontal and vertical distance of the upper-left corner of the OK button from the upper-left corner of the dialog box, in increments of 1/8 and 1/12 of the System font (Windows) or the dialog font (Macintosh).
Width, Height | The width and height of the OK button, in increments of 1/8 and 1/12 of the System font (Windows) or the dialog font (Macintosh).
.Identifier | An optional identifier used by statements in a dialog function that act on the OK button, such as DlgEnable and DlgVisible. If omitted, "OK" is the default identifier.

Note that choosing the OK button in a custom dialog box always returns –1 and choosing the Cancel button always returns 0 (zero). For example, in a dialog box displayed with the instruction x = Dialog(dlg), choosing OK sets the value of x to –1. The return value of other buttons is determined by the relative order of the PushButton statements in the dialog box definition.

For an example of OKButton used in a complete dialog box definition, see Begin Dialog ¼ End Dialog.

See Also

Begin Dialog ¼ End Dialog, CancelButton, PushButton


On Error

Syntax

On Error Goto Label

On Error Resume Next

On Error Goto 0

Remarks

Establishes an "error handler" — typically, a series of instructions that takes over when an error occurs. When an error occurs in a macro that does not contain the On Error statement, an error message is displayed and the macro quits.

This form | Performs this action
On Error Goto Label | Jumps from the line where the error occurred to the specified label. The instructions following this label can then determine the nature of the error (using the special variable Err) and take some appropriate action to correct or resolve the problem. For more information, see Err.
On Error Resume Next | Continues running the macro from the line that follows the line where the error occurred and resets Err to 0 (zero). In effect, the error is ignored.
On Error Goto 0 | Disables the error trapping established by an earlier On Error Goto or On Error Resume Next statement and sets Err to 0 (zero).

Once an error triggers an error handler, no further error handling occurs until Err is reset to 0 (zero). Usually, you should place an Err = 0 instruction at the end of your error handler. Do not include Err = 0 in the middle of an error handler or you risk creating an endless loop if an error occurs within the handler.

Note that an error handler established in the main subroutine is not in effect when control passes to another subroutine. To trap all errors, each subroutine must have its own On Error statement and error handler. After control is returned to the main subroutine, the main On Error instruction is again in effect.

WordBasic generates errors with numbers less than 1000; Word itself generates errors with numbers 1000 or greater. Error handlers can trap both WordBasic and Word errors. However, if a Word error occurs, an error message is displayed, and the user must respond before the macro can continue. When the user chooses the OK button, control passes to the error handler.

For a complete list of all WordBasic and Word error messages and error numbers, see "Error Messages" later in this part.

Examples

This example shows a common use of On Error Resume Next to avoid WordBasic error number 102, "Command failed," when a user cancels a dialog box or prompt:

On Error Resume Next
A$ = InputBox$("Your name please:")

The following macro prompts the user to specify a sequential file for input (for example, a text-only file containing a list of Word documents). If the file cannot be found, the instructions following the label specified by On Error Goto Label suggest a reason corresponding to the error number.

Sub MAIN
On Error Goto ErrorHandler
DocName$ = InputBox$("Filename for input:", "", DocName$)
Open DocName$ For Input As #1
'Statements that use the input go here
Close #1
Goto Done                'If there is no error, skip the error handler
ErrorHandler:
Select Case Err
    Case 53 : MsgBox "The file " + DocName$ + " does not exist."
    Case 64 : MsgBox "The specified drive is not available."
    Case 76 : MsgBox "The specified folder does not exist."
    Case 102                'If the user cancels the dialog box
    Case Else : MsgBox "Error" + Str$(Err) + " occurred."
End Select
Err = 0
Done:
End Sub

See Also

Err, Error, Goto, Select Case


OnTime

Syntax

OnTime When[$], Name$ [, Tolerance]

Remarks

Sets up a background timer that runs a macro at the time specified by When[$]. If Word is occupied at the specified time — for example, if a dialog box is displayed or Word is performing a large sort operation — the macro runs as soon as Word is idle.

If you close Word before When[$], the timer is canceled and is not reactivated when you start Word. To reset the timer each time you start Word — for example, if you want to automatically set an alarm macro at your next Word session (see the example in this entry) — name the macro that includes the OnTime instruction "AutoExec." For information about AutoExec and other auto macros, see
Chapter 2, "Getting Started with Macros," in Part 1, "Learning WordBasic."

Argument | Explanation
When[$] | The time the macro is to be run, expressed as text in a 24-hour format (hours:minutes:seconds) or as a serial number, a decimal representation of the date, time, or both. For more information on serial numbers, see DateSerial(). When you specify the time as text, including seconds is optional. For example, 2:37 p.m. is expressed as "14:37" and 2:37 a.m. is expressed as "02:37" or "2:37." Midnight is "00:00:00." You can include a string representing the date before the time. There are several available date formats. You can control the default date format by choosing the International option in Control Panel (Windows) or by using a control panel such as Date & Time (Macintosh). If the date is not specified, the macro runs at the first occurrence of the specified time.
Name$ | The name of the macro to be run. For the macro to run, it must be available both when the OnTime instruction is run and when the specified time has arrived. For this reason, it is best to specify a macro in the global template, NORMAL.DOT. The format MacroName.SubroutineName is not allowed.
Tolerance | If Name$ has not yet started within Tolerance seconds after When, Word will not run the macro. If Tolerance is 0 (zero) or omitted, Word always runs the macro, regardless of how many seconds elapse before Word is idle and can run the macro.

Note

Word can run only one OnTime macro at a time. If you start a second, the first OnTime macro is canceled.

Example

This example sets up a simple alarm clock function in Word. The first macro in the example sets up the background timer.

'Alarm program: Prompts user to input time for alarm to sound
'Current time appears in title bar of input box
Sub MAIN
Alarm$ = InputBox$("Time? (HH:mm:ss), 24hr", "Alarm " + Time$())
'Set background timer to run macro called Beeper
'No tolerance is set, so alarm will always sound
OnTime Alarm$, "Beeper"
End Sub

The following macro sounds an alarm and displays an alert message in response to the timer set up by the preceding macro. This macro must be named "Beeper" to work properly with the preceding macro.

Sub MAIN                        'Beeper program
For count = 1 To 7
    Beep
    Beep
    For TL = 1 To 100        'Adds a delay between beeps
    Next
Next
MsgBox "Preset alarm sounded", "Beeper " + Time$(), 48
End Sub

See Also

Date$(), DateSerial(), DateValue(), Day(), Month(), Now(), TimeValue(), Today(), Year()


Open

Syntax

Open Name$ For Mode$ As [#]FileNumber

Remarks

Opens a sequential file for input or output of text. You can use sequential files to supply values for macro variables or to store data generated by macros.

Sequential files, which are opened with Open and closed with Close, are not displayed in document windows. Although you can use Open to open any file, Open and Close are intended to be used with text files. For more information about sequential files, see Chapter 9, "More WordBasic Techniques," in Part 1, "Learning WordBasic."

Argument | Explanation
Name$ | The name of the file to open
Mode$ | The mode in which the file is opened: Input Opens the text file so that data may be read from the file into the macro. When you open a file for input, you can use Read, Input, Line Input, and Input$() instructions to read from the file. If Name$ does not exist, an error occurs. Output Opens the text file so that data may be written from the macro to the file. When you open a file for output, you can use Write and Print instructions to write to the file. If Name$ does not exist, Word creates it. If Name$ already exists, Word deletes its contents. Append Opens the text file so that data may be written from the macro to the file. When you open a file to append, you can use Write and Print instructions to write to the file. The existing contents of the file remain and the information you write is added to the end of the file. If Name$ does not exist, Word creates it.
FileNumber | A number to assign the file, from 1 through 4

Example

This macro saves a rich-text format (RTF) copy of each document listed in the text file CONVERT.TXT. The Open instruction opens CONVERT.TXT for input as a sequential file. The instructions in the While ¼ Wend loop run once for each document, assigning the filename listed next in CONVERT.TXT to curdoc$, opening the document, saving an RTF copy, and then closing the document.

Sub MAIN
Open "CONVERT.TXT" For Input As #1
While Not Eof(1)
    Line Input #1, curdoc$
    FileOpen .Name = curdoc$
    FileSaveAs .Name = curdoc$, .Format = 6
    FileClose 2
Wend
Close #1
End Sub

See Also

Close, Eof(), Input, Input$(), Line Input, Lof(), Print, Read, Seek, Write


OpenSubdocument

Syntax

OpenSubdocument

Remarks

Opens the subdocument identified by the location of the insertion point or the beginning of the selection in a master document. Word opens the subdocument in a separate document window. If the active document is not a master document, or if the master document is not in master document or outline view, an error occurs.

See Also

CreateSubdocument, FileOpen, InsertSubdocument, MergeSubdocument, RemoveSubdocument, SplitSubdocument, ViewMasterDocument


OpenUpPara

Syntax

OpenUpPara

Remarks

Sets the Before option on the Indents And Spacing tab in the Paragraph dialog box (Format menu) to "12 pt."

Example

If there is no space before the current paragraph, this example sets the Before option to "12 pt":

Dim dlg As FormatParagraph
GetCurValues dlg
If dlg.Before = "0 pt" Then OpenUpPara

See Also

CloseUpPara, FormatParagraph


OptionButton

Syntax

OptionButton HorizPos, VertPos, Width, Height, Label$ [, .Identifier]

Remarks

Creates an option button in a custom dialog box. An OptionGroup instruction is required for each series of related OptionButton instructions, which must be positioned directly following the OptionGroup instruction. Within a group of option buttons, only one button can be selected at a time.

Argument | Explanation
HorizPos, VertPos | The horizontal and vertical distance of the upper-left corner of the rectangle containing both the option button and its associated text from the upper-left corner of the dialog box, in increments of 1/8 and 1/12 of the System font (Windows) or the dialog font (Macintosh).
Width, Height | The width and height of the rectangle, in increments of 1/8 and 1/12 of the System font (Windows) or the dialog font (Macintosh).
Label$ | The label associated with the option button. An ampersand (&) precedes the character in Label$ that is the access key for selecting the option button.
.Identifier | An optional identifier used by statements in a dialog function that act on the option button. If omitted, the default identifier is the first two words in Label$ (or the entire string if Label$ is only one word). You should specify .Identifier because the identifier you assign remains the same regardless of changes you make to Label$.

For an example of OptionButton used in a complete dialog box definition, see OptionGroup.

See Also

CheckBox, GroupBox, OptionGroup, PushButton


OptionGroup

Syntax

OptionGroup .Identifier

Remarks

Defines a series of related option buttons in a dialog box definition. An OptionGroup instruction is required for each series of related OptionButton instructions, which must be positioned directly following the OptionGroup instruction. Within the group, only one option button can be selected at a time. The OptionGroup identifier returns a value corresponding to the selected option button.

Argument | Explanation
.Identifier | Together with the dialog record name, .Identifier creates a variable whose value corresponds to the selected option button, where 0 (zero) is the first option button in the group, 1 is the second, and so on. The form for this variable is DialogRecord.Identifier (for example, dlg.Brk). The identifier string (.Identifier minus the period) is also used by statements in a dialog function that act on the option group, such as DlgEnable and DlgVisible.

Example

This macro creates the dialog box shown following it and then inserts either a page break or column break according to the option button the user selects. The identifier defined for the option group is .Brk. Note how the second If instruction performs an action based on the value of the dlg.Brk variable.

Sub MAIN
Begin Dialog UserDialog 292, 78, "Example"
    OKButton 188, 14, 88, 21
    CancelButton 188, 38, 88, 21
    GroupBox 12, 6, 164, 60, "Break"
    OptionGroup .Brk
        OptionButton 22, 23, 117, 16, "&Page Break"
        OptionButton 22, 41, 133, 16, "&Column Break"
End Dialog
Dim dlg As UserDialog
If Dialog(dlg) Then
    If dlg.Brk = 0 Then InsertPageBreak Else InsertBreak .Type = 1
End If
End Sub

See Also

Begin Dialog ¼ End Dialog, GroupBox, ListBox, OptionButton


Organizer

Syntax

Organizer [.Copy, ] [.Delete, ] [.Rename, ] [.Source = text, ] [.Destination = text, ] .Name = text [, .NewName = text] [, .Tab = number]

Remarks

Deletes and renames styles, AutoText entries, toolbars, and macros, and copies these elements between templates. The arguments for the Organizer statement correspond to the options in the Organizer dialog box (Macro command, Tools menu).

Argument | Explanation
.Copy | Copies the specified item from the source to the destination.
.Delete | Deletes the specified item from the source.
.Rename | Renames the specified item in the source.
.Source | The filename of the document or template containing the item you want to copy, delete, or rename. Paths are accepted.
.Destination | The filename of the document or template to which you want to copy the item. Paths are accepted.
.Name | The name of the style, AutoText entry, toolbar, or macro you want to copy, delete, or rename.
.NewName | A new name for the specified item; used with .Rename.
.Tab | The kind of item you want to copy, delete, or rename: 0 (zero) Styles 1 AutoText 2 Toolbars 3 Macros You also use these values to specify which tab to select when you display the Organizer dialog box with a Dialog or Dialog() instruction.

Note

When you use Organizer to make a change to a file that is not open, Word opens the file in the background, saves changes, and then closes the file. If you need to make a large number of changes, your macro will run faster if it opens the file first, performs the Organizer instructions, and then closes the file using the instruction FileClose 1 to save changes.

Example

This Word macro copies the AutoText entries from the active template to the Normal template. First, the name of the active template is retrieved from the Templates And Add-ins dialog box (Templates command, File menu). If the Document Template text box is blank, indicating the active document is a template, the template's filename is retrieved from the Document Statistics dialog box (Statistics button, Summary Info command, File menu). Then, the number of AutoText entries stored in the active template is returned. Finally, using a For ¼ Next loop, the Organizer instruction is repeated once for each AutoText entry.

Sub MAIN
Dim dlg As FileTemplates
GetCurValues dlg
template$ = dlg.Template
If template$ = "" Then
    Redim dlg As DocumentStatistics
    GetCurValues dlg
    template$ = dlg.Directory + "\" + dlg.FileName
End If
num = CountAutoTextEntries(1)
If num = 0 Then Goto bye
For count = 1 To num
    Organizer .Copy, .Source = template$, \
        .Destination = "C:\WINWORD\TEMPLATE\NORMAL.DOT", \
        .Name = AutoTextName$(count, 1), .Tab = 1
Next count
bye:
End Sub

See Also

EditAutoText, FileTemplates, FormatStyle, NewToolbar, ToolsMacro


OtherPane

Syntax

OtherPane

Remarks

Moves the insertion point to its most recent position in the next pane of the active window. OtherPane is often used in macros that open the annotation or footnote panes.

Example

This example inserts a footnote and then returns the insertion point to the footnote reference mark. In page layout view, where footnotes are not inserted in a separate pane, the instruction GoBack returns the insertion point to the reference mark. In normal view or outline view, the instruction OtherPane returns the insertion point.

FntText$ = "This is the footnote text"
InsertFootnote
Insert FntText$
If ViewPage() Then
    GoBack
Else
    OtherPane
End If

See Also

ClosePane, DocSplit, WindowPane()


Outline, Outline()

Syntax

Outline [On]

Outline()

Remarks

On the Macintosh, the Outline statement adds or removes the outline character format for the current selection, or controls outline formatting for characters to be inserted at the insertion point.

Argument | Explanation
On | Specifies whether to add or remove the outline format: 1 Formats the selection with outline 0 (zero) Removes the outline format Omitted Toggles the outline format

The Outline() function returns the following values.

Value | Explanation
0 (zero) | If none of the selection is formatted with outline
–1 | If part of the selection is formatted with outline
1 | If all the selection is formatted with outline

In Windows, Outline and Outline() are not available and generate errors.

See Also

FormatFont


OutlineCollapse

Syntax

OutlineCollapse

Remarks

Collapses one level of heading or body text under the selected headings. If the active document is not in outline or master document view, an error occurs.

Example

This example collapses every heading in the document by one level:

ViewOutline
EditSelectAll
OutlineCollapse

See Also

OutlineExpand, ShowAllHeadings


OutlineDemote

Syntax

OutlineDemote

Remarks

Applies the next heading level style to the selected headings (Heading 1 through Heading 8) or body text.

Example

This example demotes each paragraph in the document that follows a Heading 2:

StartOfDocument : ViewOutline
EditFindClearFormatting
EditFindStyle .Style = "Heading 2"
EditFind .Find = "", .Direction = 0, .Format = 1, .Wrap = 0
While EditFindFound()
    ParaDown
    OutlineDemote
    EditFind .Direction = 0
Wend

See Also

OutlineMoveDown, OutlinePromote


OutlineExpand

Syntax

OutlineExpand

Remarks

Expands one level of heading or body text under the selected headings. If the active document is not in outline or master document view, an error occurs.

Example

This example expands every heading in the document by one level:

ViewOutline
EditSelectAll
OutlineExpand

See Also

OutlineCollapse, ShowAllHeadings


OutlineLevel()

Syntax

OutlineLevel()

Remarks

Returns a number corresponding to the heading level of the selected paragraph. Returns 0 (zero) if the style of the selected paragraph is not a built-in heading level style. If multiple paragraphs are selected, OutlineLevel() returns the heading level of the first paragraph in the selection.

Example

This example deletes all paragraphs in a document that are not formatted with a built-in heading level style:

StartOfDocument
ViewNormal
While ParaDown()
    ParaUp                            'Go to each paragraph in turn.
    If OutlineLevel() = 0 Then        'If it's not a heading,
        ParaDown 1, 1                'select it, then
        EditClear                    'delete it.
    Else                                'If it is a heading,
        ParaDown                        'go to the next paragraph
    End If
Wend                            'and begin the process again.

See Also

FormatStyle, StyleName$()


OutlineMoveDown

Syntax

OutlineMoveDown

Remarks

Moves the selected paragraphs below the next visible paragraph. Body text moves with a heading only if the body text is selected or collapsed.

See Also

OutlineMoveUp, OutlineDemote


OutlineMoveUp

Syntax

OutlineMoveUp

Remarks

Moves the selected paragraphs above the next visible paragraph. Body text moves with a heading only if the body text is selected or collapsed.

See Also

OutlineMoveDown, OutlinePromote


OutlinePromote

Syntax

OutlinePromote

Remarks

Applies the previous heading level style to the selected headings (Heading 2 through Heading 9) or body text.

Example

This example promotes the heading level style of the current paragraph if each character in the paragraph, including the paragraph mark, is bold:

ViewOutline
EditGoTo "\Para"
If Bold() = 1 Then OutlinePromote

See Also

OutlineDemote, OutlineMoveUp


OutlineShowFirstLine, OutlineShowFirstLine()

Syntax

OutlineShowFirstLine [On]

OutlineShowFirstLine()

Remarks

The OutlineShowFirstLine statement controls the display of body text in outline view. You can use this statement to make the document easier to scan by hiding all but the first line of body text. If the active document is not in outline or master document view, an error occurs.

Argument | Explanation
On | Specifies whether or not to display the first line of body text: 0 (zero) All body text is shown. 1 or omitted Only the first line of body text is shown.

The OutlineShowFirstLine() function returns the following values.

Value | Explanation
0 (zero) | All lines of body text are displayed.
–1 | Only the first line of body text is displayed.

See Also

OutlineCollapse, OutlineShowFormat


OutlineShowFormat

Syntax

OutlineShowFormat

Remarks

Displays character formatting in outline view or, if character formatting is already displayed, hides it. If the active document is not in outline or master document view, an error occurs.

See Also

OutlineShowFirstLine, ViewDraft


Overtype, Overtype()

Syntax

Overtype [On]

Overtype()

Remarks

The Overtype statement switches between overtype and insert modes. In overtype mode, characters you type replace existing characters one by one; in insert mode, characters you type move existing text to the right.

Argument | Explanation
On | Specifies the mode: 0 (zero) Switches to insert mode. 1 Switches to overtype mode ("OVR" appears in status bar). Omitted Switches between overtype and insert modes.

The Overtype() function returns the following values.

Value | Explanation
0 (zero) | If overtype mode is off
–1 | If overtype mode is on

Note that text you insert with the Insert statement will not overwrite text in the document, regardless of whether the document is in insert or overtype mode.

Example

If overtype mode is active, this example displays a message box with Yes and No buttons asking if overtype should be deactivated. If the user chooses Yes, which returns a value of –1, overtype is deactivated.

If Overtype() = -1 Then
    Button = MsgBox("Overtype is on. Turn off?", 4)
    If button = -1 Then Overtype 0
End If

See Also

ToolsOptionsGeneral


PageDown, PageDown()

Syntax

PageDown [Count] [, Select]

PageDown([Count] [, Select])

Remarks

The PageDown statement moves the insertion point or the active end of the selection (the end that moves when you press SHIFT+PAGE DOWN) down by the specified number of screens, where one screen is equal to the height of the active window. If there is not a full screen between the insertion point or the selection and the end of the document, PageDown moves the insertion point or the active end of the selection to the end of the document.

Argument | Explanation
Count | The number of screens to move; if omitted, 1 is assumed. Negative values move the insertion point or the active end of the selection up.
Select | Specifies whether to select text: 0 (zero) or omitted Text is not selected. If there is already a selection, PageDown moves the insertion point Count–1 screens below the selection. Nonzero Text is selected. If there is already a selection, PageDown moves the active end of the selection toward the end of the document. In a typical selection made from left to right, where the active end of the selection is closer to the end of the document, PageDown extends the selection. In a selection made from right to left, it shrinks the selection.

The PageDown() function behaves the same as the statement and also returns the following values:

Value | Explanation
0 (zero) | If the insertion point or the active end of the selection cannot be moved down.
–1 | If the insertion point or the active end of the selection is moved down by any number of screens, even if less than Count. For example, PageDown(2) returns –1 even if the insertion point is only one screen from the end of the document.

Examples

This example extends the selection down two screens from the insertion point:

PageDown 2, 1

The following example counts the number of screens between the insertion point and the end of the document. The PageDown() function is used to detect when the end of the document is reached.

n = 0
While PageDown()
    n = n + 1
Wend
MsgBox "Number of screens:" + Str$(n)

See Also

EditGoTo, HPage, HScroll, NextPage, PageUp, VPage, VScroll


PageUp, PageUp()

Syntax

PageUp [Count] [, Select]

PageUp([Count] [, Select])

Remarks

The PageUp statement moves the insertion point or the active end of the selection (the end that moves when you press SHIFT+PAGE UP) up by the specified number of screens, where one screen is equal to the height of the active window. If there is not a full screen between the insertion point or the selection and the beginning of the document, PageUp moves the insertion point or the active end of the selection to the beginning of the document.

Argument | Explanation
Count | The number of screens to move; if omitted, 1 is assumed. Negative values move the insertion point or the active end of the selection down.
Select | Specifies whether to select text: 0 (zero) or omitted Text is not selected. If there is already a selection, PageUp moves the insertion point Count–1 screens above the selection. Nonzero Text is selected. If there is already a selection, PageUp moves the active end of the selection toward the beginning of the document. In a typical selection made from left to right, where the active end of the selection is closer to the end of the document, PageUp shrinks the selection. In a selection made from right to left, it extends the selection.

The PageUp() function behaves the same as the statement and also returns the following values.

Value | Explanation
0 (zero) | If the insertion point or the active end of the selection cannot be moved up.
–1 | If the insertion point or the active end of the selection is moved up by any number of screens, even if less than Count. For example, PageUp(2) returns –1 even if a single PageUp instruction brings the beginning of the document into view.

Example

This example selects one screen up from the insertion point. If there is less than one screen above the insertion point, the message "Selected to start of document" appears in the status bar.

PageUp 1, 1
If CmpBookmarks("\StartOfSel", "\StartOfDoc") = 0 Then
    Print "Selected to start of document."
End If

See Also

EditGoTo, HPage, HScroll, PageDown, PrevPage, VPage, VScroll


ParaDown, ParaDown()

Syntax

ParaDown [Count] [, Select]

ParaDown([Count] [, Select])

Remarks

The ParaDown statement moves the insertion point or the active end of the selection (the end that moves when you press CTRL+SHIFT+DOWN ARROW (Windows) or COMMAND+SHIFT+DOWN ARROW (Macintosh)) down by the specified number of paragraphs.

Regardless of the position of the insertion point within a paragraph or whether there is a selection within a paragraph, the instruction ParaDown moves the insertion point to the start of the next paragraph. The only exception is when the insertion point is in the last paragraph of the document; in that case, ParaDown moves the insertion point to the end of the paragraph. If the current selection extends over multiple paragraphs, the instruction ParaDown moves the insertion point to the beginning of the first paragraph following the end of the selection.

Argument | Explanation
Count | The number of paragraphs to move; if omitted, 1 is assumed. Negative values move the insertion point or the active end of the selection up.
Select | Specifies whether to select text: 0 (zero) or omitted Text is not selected. If there is already a selection, ParaDown moves the insertion point Count paragraphs below the selection. Nonzero Text is selected. If there is already a selection, ParaDown moves the active end of the selection toward the end of the document. In a typical selection made from left to right, where the active end of the selection is closer to the end of the document, ParaDown extends the selection. In a selection made from right to left, it shrinks the selection.

The ParaDown() function behaves the same as the statement and also returns the following values.

Value | Explanation
0 (zero) | If the insertion point or the active end of the selection cannot be moved down.
–1 | If the insertion point or the active end of the selection is moved down by any number of paragraphs, even if less than Count. For example, ParaDown(2) returns –1 even if the insertion point is at the beginning of the last paragraph in the document.

Example

This example inserts three asterisks (***) before each paragraph in the document. Because the While ParaDown() instruction eventually moves the insertion point to the end of the last paragraph, where the asterisks are not appropriate, the If control structure uses CmpBookmarks() to detect that condition and exit the While ¼ Wend loop.

StartOfDocument
Insert "***"
While ParaDown()
    If CmpBookmarks("\Sel", "\EndOfDoc") <> 0 Then
        Insert "***"
    End If
Wend

See Also

LineDown, PageDown, ParaUp


ParaKeepWithNext, ParaKeepWithNext()

Syntax

ParaKeepWithNext [On]

ParaKeepWithNext()

Remarks

The ParaKeepWithNext statement adds or removes the Keep With Next paragraph format for the selected paragraphs. A paragraph formatted with Keep With Next remains on the same page as the paragraph it follows when Word repaginates the document.

Argument | Explanation
On | Specifies whether to add or remove the Keep With Next format: 1 Adds the Keep With Next format. 0 (zero) Removes the Keep With Next format. Omitted Toggles the Keep With Next format.

The ParaKeepWithNext() function returns the following values.

Value | Explanation
0 (zero) | If none of the selected paragraphs are formatted with Keep With Next
–1 | If some of the selected paragraphs are formatted with Keep With Next
1 | If all the selected paragraphs are formatted with Keep With Next

See Also

FormatParagraph, ParaKeepLinesTogether, ParaPageBreakBefore


ParaPageBreakBefore, ParaPageBreakBefore()

Syntax

ParaPageBreakBefore [On]

ParaPageBreakBefore()

Remarks

The ParaPageBreakBefore statement adds or removes the Page Break Before paragraph format for the selected paragraphs. A paragraph formatted with Page Break Before appears at the top of a new page whenever the document is printed.

Argument | Explanation
On | Specifies whether to add or remove the Page Break Before format: 1 Adds the Page Break Before format. 0 (zero) Removes the Page Break Before format. Omitted Toggles the Page Break Before format.

The ParaPageBreakBefore() function returns the following values.

Value | Explanation
0 (zero) | If none of the selected paragraphs are formatted with Page Break Before
–1 | If some of the selected paragraphs are formatted with Page Break Before
1 | If all the selected paragraphs are formatted with Page Break Before

See Also

FormatParagraph, ParaKeepLinesTogether, ParaKeepWithNext


ParaUp, ParaUp()

Syntax

ParaUp [Count] [, Select]

ParaUp([Count] [, Select])

Remarks

The ParaUp statement moves the insertion point or the active end of the selection (the end that moves when you press CTRL+SHIFT+UP ARROW (Windows) or COMMAND+SHIFT+UP ARROW (Macintosh)) up by the specified number of paragraphs.

If the insertion point is at the beginning of a paragraph, the instruction ParaUp moves the insertion point to the beginning of the previous paragraph. If the insertion point is not at the beginning of the paragraph, or if there is a selection, ParaUp moves the insertion point to the beginning of the current paragraph. If the current selection extends over multiple paragraphs, the instruction ParaUp moves the insertion point to the beginning of the first selected paragraph.

Argument | Explanation
Count | The number of paragraphs to move; if omitted, 1 is assumed. Negative values move the insertion point or the active end of the selection down.
Select | Specifies whether to select text: 0 (zero) or omitted Text is not selected. If there is already a selection, ParaUp moves the insertion point Count–1 paragraphs above the selection. Nonzero Text is selected. If there is already a selection, ParaUp moves the active end of the selection toward the beginning of the document. In a typical selection made from left to right, where the active end of the selection is closer to the end of the document, ParaUp shrinks the selection. In a selection made from right to left, it extends the selection.

The ParaUp() function behaves the same as the statement and also returns the following values.

Value | Explanation
0 (zero) | If the insertion point or the active end of the selection cannot be moved up.
–1 | If the insertion point or the active end of the selection is moved up by any number of paragraphs, even if less than Count. For example, ParaUp(2) returns –1 even if the insertion point is at the end of the first paragraph in the document.

Example

This example finds the next occurrence of the phrase "Press F1 for Help" and then selects the entire text of the surrounding paragraph:

EditFind .Find = "Press F1 for Help"
ParaUp
ParaDown 1, 1

Note that you can also use the predefined bookmark "\Para" in the instruction EditGoTo "\Para" to select the paragraph containing the insertion point or selection. For more information on predefined bookmarks, see "Operators and Predefined Bookmarks" later in this part.

See Also

LineUp, PageUp, ParaDown


ParaWidowOrphanControl, ParaWidowOrphanControl()

Syntax

ParaWidowOrphanControl [On]

ParaWidowOrphanControl()

Remarks

The ParaWidowOrphanControl statement adds or removes the Widow/Orphan Control paragraph format for the selected paragraphs. A paragraph formatted with Widow/Orphan Control prevents a page break from leaving a single line of the paragraph at the top or bottom of a page.

Argument | Explanation
On | Specifies whether to add or remove the Widow/Orphan Control format: 1 Adds the Widow/Orphan Control format. 0 (zero) Removes the Widow/Orphan Control format. Omitted Toggles the Widow/Orphan Control format.

The ParaWidowOrphanControl() function returns the following values.

Value | Explanation
0 (zero) | If none of the selected paragraphs are formatted with Widow/Orphan Control
–1 | If some of the selected paragraphs are formatted with Widow/Orphan Control
1 | If all the selected paragraphs are formatted with Widow/Orphan Control

See Also

FormatParagraph, ParaKeepLinesTogether, ParaKeepWithNext, ParaPageBreakBefore


PasteButtonImage

Syntax

PasteButtonImage Toolbar$, Tool [, Context]

Remarks

Sets the face of the specified toolbar button to the graphic on the Clipboard.

Argument | Explanation
Toolbar$ | The name of the toolbar, as it appears in the Toolbars dialog box (View menu).
Tool | A number corresponding to the button face to change, where 0 (zero) is the first button on the specified toolbar, 1 is the second, and so on.
Context | Determines where the change is stored: 0 (zero) or omitted Normal template 1 Active template

For an example that uses PasteButtonImage, see CopyButtonImage.

See Also

ChooseButtonImage, CopyButtonImage, EditButtonImage, ResetButtonImage


PasteFormat

Syntax

PasteFormat

Remarks

Applies formatting copied with CopyFormat to the selection. If a paragraph mark was selected when CopyFormat was run, Word applies paragraph formatting in addition to character formatting.

Example

This example copies both character and paragraph formats from the current paragraph (selected using the predefined bookmark " \ Para"), and then applies only the paragraph formats to the next paragraph. Character formats are not applied because no text is selected when PasteFormat runs. ResetChar ensures that any new text typed at the insertion point has the font characteristics of the current style.

SelType 1                'Cancel selection, if any
EditGoTo "\Para"
CopyFormat
ParaDown
PasteFormat
ResetChar

See Also

CopyFormat, ResetChar, ResetPara


PathFromWinPath$()

Syntax

PathFromWinPath$(Path$)

Remarks

Converts the Windows path and filename specified by Path$ to a valid path and filename for the current operating system.

On the Macintosh, drive names, folder names, and filenames are separated by colons (:) instead of backslashes. When converting a Windows path to a valid Macintosh path, Word does the following:

  • Substitutes colons for backslashes.
  • Substitutes Macintosh drive names for drive letters or root folder specifications: "C:" is replaced by the name of the startup disk; "A:" and "B:" are replaced by the names of the disks in the first and second floppy disk drives, respectively; "D:", "E:", "F:", and so on are replaced by the names of other hard drives. For example, C:\DOCS\STORY.DOC or \DOCS\STORY.DOC might become HD:DOCS:STORY.DOC.
  • Removes server names. For example, \\COMMON\TOOLS\ART becomes TOOLS:ART.
  • Substitutes colons (:) to represent relative paths (for example, LETTERS\ALICE.DOC becomes :LETTERS:ALICE.DOC and ..\LETTERS\ALICE.DOC becomes ::LETTERS:ALICE.DOC).

Because all Windows filenames are valid on the Macintosh, PathFromWinPath$() does not change the filenames themselves.

See Also

PathFromMacPath$()


PauseRecorder

Syntax

PauseRecorder

Remarks

Stops and restarts macro recording. PauseRecorder is the built-in Word command that runs when the user chooses the Pause Recorder button on the Macro toolbar; this statement would not typically appear in a macro.


Picture

Syntax

Picture HorizPos, VertPos, Width, Height, PictureName$, Type, .Identifier

Remarks

Displays a graphic in a custom dialog box. Word automatically sizes the graphic to fit within the Width and Height you have specified.

Argument | Explanation
HorizPos, VertPos | The horizontal and vertical distance of the upper-left corner of the rectangle containing the graphic from the upper-left corner of the dialog box, in increments of 1/8 and 1/12 of the System font (Windows) or the dialog font (Macintosh).
Width, Height | The width and height of the rectangle, in increments of 1/8 and 1/12 of the System font (Windows) or the dialog font (Macintosh).
PictureName$ | The name of the graphics file, AutoText entry, or bookmark containing the graphic that is initially displayed. You can reset PictureName$ with DlgSetPicture in a dialog function when the dialog box is displayed.

Argument | Explanation
Type | A value indicating how the graphic is stored: 0 (zero) PictureName$ is a graphics file. Paths are allowed. 1 PictureName$ is an AutoText entry. The AutoText entry must contain a single graphic only (no text or paragraph marks) and must be stored either in the Normal template or the template attached to the active document. 2 PictureName$ is a bookmark in the active document. The bookmark must mark a single graphic only (no text or paragraph marks). 3 PictureName$ is ignored and the graphic is retrieved from the Clipboard. Include empty quotation marks ("") in place of PictureName$. The Clipboard must contain a single graphic only. If the Clipboard contains any text from a Word document, the Microsoft Word icon is displayed in the dialog box. 4 PictureName$ is a PICT file stored in the resource fork of the template containing the macro (Macintosh only). You can use the ResEdit program to add PICT files to the resource fork of a template.
.Identifier | An identifier used by statements in a dialog function that act on the graphic. For example, you can use this identifier with DlgSetPicture to display a different graphic.

Note

If the specified picture does not exist, Word displays the text "(missing picture)" within the rectangle that defines the picture area. You can change this behavior by adding 16 to the value for Type. If Type is 16, 17, 18, or 19 and the specified picture does not exist, Word displays an error (which may be trapped with On Error) and displays neither the text "(missing picture)" nor a rectangle in the dialog box.

Example

This example defines a square area at the upper-left corner of the dialog box and inserts the graphic stored in the AutoText entry "Smiley." The dialog box control is identified as .Graphic. For an example of a complete dialog box definition, see Begin Dialog ¼ End Dialog.

Picture 7, 7, 50, 50, "Smiley", 1, .Graphic

See Also

DlgSetPicture


PrevCell, PrevCell()

Syntax

PrevCell

PrevCell()

Remarks

The PrevCell statement selects the contents of the previous cell (the same as pressing SHIFT+TAB in a table). If there is already a selection including multiple cells, PrevCell selects the first cell in the selection.

The PrevCell() function behaves the same as the statement and also returns the following values.

Value | Explanation
0 (zero) | If the selection is wholly contained in the leftmost cell of the first row (in other words, if the selection is not moved)
–1 | If the selection is moved

Example

This example moves the selection to the previous cell; if the selection is in the first cell, the entire table is selected.

If PrevCell() = 0 Then TableSelectTable

See Also

NextCell


PrevField, PrevField()

Syntax

PrevField

PrevField()

Remarks

The PrevField statement selects the previous field, regardless of whether the field is showing its codes or result. PrevField skips over the following fields, which are formatted as hidden text: XE (Index Entry), TA (Table of Authorities Entry), TC (Table of Contents Entry), and RD (Referenced Document).

The PrevField() function behaves the same as the statement and also returns the following values.

Value | Explanation
0 (zero) | If there is no previous field (in other words, if the selection is not moved)
1 | If the selection is moved

With field codes displayed, you can use EditFind to go to the previous field of any type, including XE, TA, TC, and RD fields, provided that hidden text is displayed. Simply specify "^d" (the code for a field character) as the text for the .Find argument and 1 for the .Direction argument, as shown in the following instructions:

ViewFieldCodes 1
EditFind .Find = "^d", .Direction = 1, .Format = 1

To find only XE fields, specify "^d XE" as the text to find.

Example

This macro counts the number of fields above the insertion point (excluding XE, TA, TC, and RD fields) and displays the result in a message box:

Sub MAIN
    count = 0
    While PrevField()
        count = count + 1
    Wend
    MsgBox "Fields above the insertion point:" + Str$(count)
End Sub

See Also

NextField


PrevObject

Syntax

PrevObject

Remarks

Moves the insertion point to the previous document object on the current page in page layout view (the same as pressing ALT+UP ARROW (Windows) or OPTION+UP ARROW (Macintosh)). Document objects include frames, footnotes, table cells, and text columns.

From the top of the first text column on a page, the PrevObject statement moves through document objects in the following order:

  • Frames, if any appear, in the order that they appear in normal view, from the following page break to the previous page break
  • Each text column, in order from last to first (if there is more than one), moving through all footnotes and then all table cells that appear within the text column

PrevObject finally moves to the top of the first text column before cycling through the document objects again.

Keep the following points in mind when using PrevObject:

  • You can identify document objects by selecting the Text Boundaries check box on the View tab in the Options dialog box (Tools menu).
  • Word does not consider OLE objects, such as embedded drawings and charts, to be document objects unless they are framed.
  • If the insertion point is in a header or footer, PrevObject moves between the header and footer.
  • Make sure to switch to page layout view before using PrevObject.

See Also

NextObject


PrevPage, PrevPage()

Syntax

PrevPage

PrevPage()

Remarks

The PrevPage statement scrolls back one page in page layout view without moving the insertion point (the same as clicking the Page Back button at the bottom of the vertical scroll bar in page layout view). If you want to move the insertion point after scrolling, include a StartOfWindow statement following PrevPage in your macro.

PrevPage scrolls from the current location on one page to the same relative location on the previous page. To scroll to the beginning of the previous page regardless of what portion of the current page appears, use the instruction EditGoTo .Destination = "p-1" instead of PrevPage. Note, however, that EditGoTo also moves the insertion point.

The PrevPage() function behaves the same as the statement and also returns the following values.

Value | Explanation
0 (zero) | If there is no previous page (in other words, if the document doesn't scroll)
1 | If the document scrolls

Note

PrevPage and PrevPage() are available only in page layout view and generate an error if run in another view.

Example

This example ensures the document is in page layout view, scrolls to the previous page, and moves the insertion point to the top of the window:

ViewPage
PrevPage
StartOfWindow

See Also

EditGoTo, NextPage, PageUp, ViewPage, VPage


PrevTab()

Syntax

PrevTab(Position)

Remarks

Returns the position of the next tab stop to the left of Position, in points, for the first paragraph in the selection.

Use the following list of conversions as an aid in converting from points to other measurements:

  • 1 inch = 72 points
  • 1 centimeter = 28.35 points
  • 1 pica = 12 points

Example

This example displays a message box stating the position, in inches, of the last tab stop in the current paragraph. In the first instruction, PrevTab(8.5 * 72) returns the position of the last tab in points, given a page width of 8.5 inches and 72 points per inch. The value is divided by 72 to give the position in inches. The next three instructions prepare the number for display in a message box, with a maximum of two digits after the decimal point.

LastPos = PrevTab(8.5 * 72) / 72
LastPos$ = Str$(LastPos)
dot = InStr(LastPos$, ".")
LastPos$ = Left$(LastPos$, dot + 2)
MsgBox "Position of last tab stop: " + LastPos$ + " inches"

See Also

FormatTabs, NextTab(), TabLeader$(), TabType()


PrevWindow

Syntax

PrevWindow

Remarks

Moves the window at the back of the internal order of open windows to the front. This statement does nothing if there is only one open window.

See Also

Activate, ChDir, NextWindow, Window(), WindowList, WindowName$(), Window Number


Print

Syntax

Print [#FileNumber,] Expression1[$] [; or , Expression2[$] [; or , ¼]

Remarks

Displays the specified expressions in the status bar, or if you specify FileNumber, sends the expressions to the sequential file associated with that number. Unlike MsgBox, which accepts only strings, Print accepts strings, string variables, numbers, and numeric variables, and allows you to mix all these types.

You can join strings and string variables with the plus sign (+). You can join strings and numbers with a semicolon (;) or a comma (,). A comma inserts a tab between values.

Note

Print automatically adds a space before positive numeric values; there is no need to include an extra space in a string that precedes one. Print does not add a space before negative numeric values.

Like Write, the Print statement can send expressions to a sequential file. However, the expressions are formatted differently in the file, as illustrated in the following table. Note that Print separates the expressions with a tab character.

WordBasic instruction | Line created in sequential file #1
Print #1, "Phil", "Teacher" | Phil Teacher
Write #1, "Phil", "Teacher" | "Phil","Teacher"

Examples

This example displays the following sentence in the status bar: "March sales were 2500 and May sales were 3600 for a total of 6100."

mar = 2500
may = 3600
Print "March sales were"; mar ; " and May sales were" \
    ; may ; " for a total of" ; mar + may ; "."

The following example displays this line on the status bar: "Juan Garcia 32 1234".

name$ = "Juan Garcia"
age = 32
employeeNum = 1234
Print name$; age; employeeNum

The following example sets up a sequential file for use as a text-only data source in a mail-merge operation. The first Print instruction inserts column headings; the second adds a data record. Items in a given Print instruction are inserted into a single paragraph and are separated by tabs. Note that WordBasic doesn't have a sequential-file-access instruction that can read tab-delimited data. To see the results, you must open the sequential file as you would any Word document.

Open "DATA.TXT" For Output As #1
Print #1, "Name", "Address", "Occupation"
Print #1, "Juan Garcia", "123 Main St", "Accountant"
Close #1

See Also

Close, Eof(), Input, Input$(), Line Input, Lof(), MsgBox, Open, Read, Seek, Write


PromoteList

Syntax

PromoteList

Remarks

Promotes the selected paragraphs by one level in a multilevel list. If the selected paragraphs are formatted as a bulleted list or as a numbered list that isn't multilevel, PromoteList decreases the indent. If the selected paragraphs are not already formatted as a numbered or bulleted list, an error occurs.

See Also

DemoteList, FormatBulletsAndNumbering


PushButton

Syntax

PushButton HorizPos, VertPos, Width, Height, Label$ [, .Identifier]

Remarks

Creates a command button in a custom dialog box. When the command button is chosen, the Dialog() instruction that displays the dialog box (for example, button = Dialog(dlg)) returns a value corresponding to the relative order of that PushButton instruction among the other PushButton instructions: 1 for the first command button, 2 for the second, and so on.

Argument | Explanation
HorizPos, VertPos | The horizontal and vertical distance of the upper-left corner of the command button from the upper-left corner of the dialog box, in increments of 1/8 and 1/12 of the System font (Windows) or the dialog font (Macintosh).
Width, Height | The width and height of the command button, in increments of 1/8 and 1/12 of the System font (Windows) or the dialog font (Macintosh).
Label$ | The label associated with the command button. An ampersand (&) precedes the character in Label$ that is the access key for choosing the command button.
.Identifier | An optional identifier used by statements in a dialog function that act on the command button. If omitted, the default identifier is the first two words in Label$ (or the entire string if Label$ is only one word). You should specify .Identifier because the identifier you assign remains the same regardless of changes you make to Label$.

Example

This example creates a command button with the text "Create Link," whose identifier is "Link." For an example of PushButton used in a complete dialog box definition, see Begin Dialog ¼ End Dialog.

PushButton 10, 54, 108, 21, "&Create Link", .Link

See Also

Begin Dialog ¼ End Dialog, CancelButton, OKButton, OptionButton


PutFieldData

Syntax

PutFieldData FieldData$

Remarks

When the insertion point is within an ADDIN field, stores the text data specified by FieldData$ in the field. The data is stored internally in the field and is not visible, even when field codes are showing. If there is a selection, it must begin
at an ADDIN field; otherwise, an error occurs.

See Also

GetFieldData$()


Read

Syntax

Read #FileNumber, Variable1[$] [, Variable2[$]] [, Variable3[$]] [, ¼]

Remarks

Retrieves string or numeric values from an open sequential file, typically containing data added with the Write statement, and assigns the values to variables. FileNumber is the number specified in the Open instruction that opened the file for output. For more information about sequential files, see Chapter 9, "More WordBasic Techniques," in Part 1, "Learning WordBasic."

Read is similar to Input, but removes quotation marks from strings. For example, a text-only paragraph created with a Write instruction might appear as follows:

"Michelle Levine", 26,"Dancer"

Whereas Input interprets the first value as "Michelle Levine", Read takes only the text within the quotation marks: Michelle Levine.

Example

This example reads each paragraph in the sequential file in turn and defines name$ as the first item and age as the second item. For each paragraph, the values are displayed in a message box.

Open "DATA.TXT" For Input As #1
While Not Eof(1)
Read #1, name$, age
MsgBox name$ + " is" + Str$(age) + " years old."
Wend
Close #1

See Also

Close, Eof(), Input, Input$(), Line Input, Lof(), Open, Print, Seek, Write


Redim

Syntax

Redim [Shared] Var1[(Size1 [, Size2] [, ...])] [, Var2[(Size1 [, Size2] [, ...])]]

Redim Var As DialogName

Redim Var As UserDialog

Remarks

Empties array variables so that the array elements can be redefined. Redim stands for "redimension" — you can specify new Size values when redefining array variables. Note that whenever you use Redim, existing array contents are lost. Redim can also redefine a dialog record for a Word dialog box or a custom dialog box. For descriptions of arguments used with Redim, see Dim.

Examples

This example illustrates how you might use Redim to recycle the storage space in an array variable when you have finished using the first set of values. This helps conserve system resources.

Dim BigArray$(100)
BigArray$(0) = "A long text string"
'Series of statements that define array elements 1 through 99
BigArray$(100) = "Another long text string"
'Series of statements that make use of the values in BigArray$()
Redim BigArray$(100)
'Series of statements that define and make use of new array elements

The following macro retrieves the author name from the Summary Info dialog box (File menu) and the user name from the User Info tab in the Options dialog box (Tools menu), and then compares the two values. If they are different, a message box is displayed.

The Dim statement stores the array of values from the Summary Info dialog box in the dialog record dlg. After the author name is retrieved, these values are no longer needed. Redim can therefore recycle the dialog record dlg to store the values from the User Info tab (Options dialog box).

Sub MAIN
Dim dlg As FileSummaryInfo
GetCurValues dlg
Author$ = dlg.Author
Redim dlg As ToolsOptionsUserInfo
GetCurValues dlg
UserName$ = dlg.Name
If Author$ <> UserName$ Then
    MsgBox "Author does not match user."
End If
End Sub

See Also

Dim, Let


REM

Syntax

REM Comments

'Comments

Remarks

Designates explanatory text, which Word ignores when the macro is run. You can use an apostrophe (') instead of REM. Each notation has its advantages and disadvantages: REM makes it easier to distinguish comments from WordBasic instructions, but requires more space than an apostrophe.

Example

This example demonstrates four ways to include a comment in a macro:

REM MyMacro Title -- MyName Here
'More about MyMacro
ParaDown        'Move to start of next paragraph
ParaUp            REM Moves to start of previous paragraph


RemoveAllDropDownItems

Syntax

RemoveAllDropDownItems BookmarkName$

Remarks

Removes all items from a drop-down form field.

Argument | Explanation
BookmarkName$ | The name of the bookmark that marks the drop-down form field. If you specify a bookmark that does not mark a drop-down form field, an error occurs.

See Also

AddDropDownItem, DropDownFormField, RemoveDropDownItem


RemoveBulletsNumbers

Syntax

RemoveBulletsNumbers

Remarks

Removes bullets or numbers as well as list formatting from the selected paragraphs in a bulleted or numbered list created with the Bullets And Numbering command (Format menu). Subsequent bulleted or numbered paragraphs start a new list and restart the numbering in the case of a numbered list. RemoveBulletsNumbers corresponds to the Remove button in the Bullets And Numbering dialog box (Format menu).

See Also

FormatBulletsAndNumbering, SkipNumbering


RemoveDropDownItem

Syntax

RemoveDropDownItem BookmarkName$, ItemText$

Remarks

Removes an item from a drop-down form field.

Argument | Explanation
BookmarkName$ | The name of the bookmark that marks the drop-down form field. If you specify a bookmark that does not mark a drop-down form field, an error occurs.
ItemText$ | The item to remove from the drop-down form field.

Example

This example removes three items from the drop-down form field marked by the bookmark "Dropdown1":

RemoveDropDownItem "Dropdown1", "Red"
RemoveDropDownItem "Dropdown1", "Blue"
RemoveDropDownItem "Dropdown1", "Green"

See Also

AddDropDownItem, DropDownFormField, RemoveAllDropDownItems


RemoveFrames

Syntax

RemoveFrames

Remarks

Removes all frames in the selection. Note that borders, applied automatically when you insert a frame around text, are not removed.

Example

This example removes all frames from the entire document:

EditSelectAll
RemoveFrames

See Also

FormatBordersAndShading, FormatFrame, InsertFrame


RemoveSubdocument

Syntax

RemoveSubdocument

Remarks

Merges the contents of the selected subdocuments into the master document and removes the subdocuments. RemoveSubdocument does not delete subdocument files. If the active document is not in master document or outline view, or the insertion point is not in a subdocument, an error occurs.

See Also

CreateSubdocument, InsertSubdocument, MergeSubdocument, OpenSubdocument, SplitSubdocument, ViewMasterDocument


RenameMenu

Syntax

RenameMenu Menu$, NewName$, Type [, Context]

Remarks

Renames the specified menu. If Menu$ is not one of the menus of the given Type, an error occurs.

Argument | Explanation
Menu$ | The name of a menu as it appears on the menu bar. Including an ampersand (&) before the access key in the menu name is optional (for example, you can specify either "File" or "&File").
NewName$ | The new menu name. An ampersand (&) before a character in the menu name sets the access key for displaying the menu.

Argument | Explanation
Type | The type of menu: 0 (zero) Menus on the menu bar when a document is open. 1 Menus on the menu bar when no document is open. Note that you cannot rename shortcut menus.
Context | Specifies where the new menu name is stored: 0 (zero) or omitted Normal template (the new menu name appears regardless of which template is active). 1 Active template (the new menu name appears only when the template is active).

Example

This example renames the Tools menu "Other Tasks" and makes Alt, T (Windows) or COMMAND+TAB, T (Macintosh) the key sequence that activates the menu:

RenameMenu "Tools", "Other &Tasks", 0

See Also

MenuText$(), ToolsCustomizeMenus


RepeatFind

Syntax

RepeatFind

Remarks

Repeats the most recent EditFind or EditGoTo operation. Note that when an EditFind instruction is repeated, settings for .Direction, .WholeWord, .MatchCase, .PatternMatch, .Format, and .Wrap are all repeated.

Example

This example counts the number of times the word "success" occurs in the active document and then displays the result in a message box:

StartOfDocument
EditFind .Find = "success", .Direction = 0, .WholeWord = 1, \
    .MatchCase = 0, .Format = 0, .Wrap = 0
While EditFindFound()
    count = count + 1
    RepeatFind
Wend
MsgBox "The word " + Chr$(34) + "success" + Chr$(34) \
    + " occurs" + Str$(Count) + " times."

See Also

EditFind, EditGoTo, EditRepeat


ResetButtonImage

Syntax

ResetButtonImage Toolbar$, Tool [, Context]

Remarks

Resets the face of the specified toolbar button to the graphic originally associated with the command the button runs.

Argument | Explanation
Toolbar$ | The name of the toolbar, as it appears in the Toolbars dialog box (View menu)
Tool | A number corresponding to the button face to reset, where 1 is the first button on the specified toolbar, 2 is the second, and so on
Context | Determines where the change is stored: 0 (zero) or omitted Normal template 1 Active template

See Also

ChooseButtonImage, CopyButtonImage, EditButtonImage, PasteButtonImage, ViewToolbars


ResetChar, ResetChar()

Syntax

ResetChar

ResetChar()

Remarks

The ResetChar statement removes manual character formatting (formatting not defined in the selected paragraph styles) from the selected text. For example, if you manually format a word or phrase in a paragraph as bold text and the paragraph style is plain text, ResetChar would remove the bold format.

The ResetChar() function returns the following values without resetting character formats.

Value | Explanation
0 (zero) | If the selected text contains any manual character formatting
1 | If the selected text contains no manual character formatting

Example

If the current paragraph is formatted as Normal, this example selects the entire paragraph (using the predefined bookmark " \ Para") and removes any character formatting not defined as part of the style:

If StyleName$() = "Normal" Then
    EditGoTo "\Para"
    ResetChar
End If

See Also

FormatFont, ResetPara


ResetNoteSepOrNotice

Syntax

ResetNoteSepOrNotice

Remarks

Resets the separator, the continuation notice, or the continuation separator for footnotes or endnotes to the default. ResetNoteSepOrNotice generates an error unless you first open a separator pane.

Example

This example opens the footnote continuation notice pane and then determines if there is a continuation notice. If the pane contains anything more than a paragraph mark, ResetNoteSepOrNotice removes the notice. Without the If conditional, the example would generate an error if the notice were already set to the default.

ViewFootnoteContNotice
EditSelectAll
paraMark$ = Chr$(13)
If Selection$() <> paraMark$ Then ResetNoteSepOrNotice
ClosePane

See Also

NoteOptions, ViewEndnoteContNotice, ViewEndnoteContSeparator, ViewEndnoteSeparator, ViewFootnoteContNotice, ViewFootnoteContSeparator, ViewFootnoteSeparator


ResetPara, ResetPara()

Syntax

ResetPara

ResetPara()

Remarks

The ResetPara statement removes paragraph formatting not defined in the current paragraph style from the selected text. For example, if you format a paragraph with a half-inch left indent and the style applied to the paragraph has no left indent, ResetPara would remove the indent.

The ResetPara() function returns the following values without removing paragraph formatting.

Value | Explanation
0 (zero) | If the first paragraph in the selection contains formatting that differs from the formatting defined for the applied paragraph style
–1 | If the first paragraph in the selection contains no formatting that differs from the formatting defined for the applied paragraph style

Example

If the current paragraph is formatted as Normal, this example removes any paragraph formatting not defined as part of the style:

If StyleName$() = "Normal" Then ResetPara

See Also

FormatParagraph, NormalStyle, ResetChar


Right$()

Syntax

Right$(Source$, Count)

Remarks

Returns the rightmost Count characters of Source$.

Example

This example prompts the user to enter his or her first and last name in an InputBox$() dialog box. By subtracting the position of the space (located between the first and last name) from the length of the full name, the instructions determine the number of characters after the space. Right$() is then able to retrieve the last name from the single string.

fullName$ = InputBox$("Please type your first and last name.")
length = Len(fullName$)
space = InStr(fullName$, " ")
lastName$ = Right$(fullName$, length - space)
MsgBox "Last name is " + lastName$ + "."

See Also

InStr(), Left$(), Len(), LTrim$(), Mid$(), RTrim$()


RightPara, RightPara()

Syntax

RightPara

RightPara()

Remarks

The RightPara statement aligns the selected paragraphs with the right indent.

The RightPara() function returns the following values.

Value | Explanation
0 (zero) | If none of the selection is right-aligned
–1 | If part of the selection is right-aligned
1 | If all the selection is right-aligned

Example

This example formats each right-aligned paragraph with a left indent of 2 inches:

StartOfDocument
While ParaDown()                    'Check each paragraph one by one,
    ParaUp                            'including the first paragraph
    If RightPara() = 1 Then            'If right-aligned, then indent left
        FormatParagraph .LeftIndent = "2 in"
    End If
    ParaDown
Wend

See Also

CenterPara, FormatParagraph, JustifyPara, LeftPara


RmDir

Syntax

RmDir Name$

Remarks

Removes the specified folder. Name$ can be a full or relative path. For this statement to work, the folder must contain no files or subfolders. RmDir cannot remove the current folder.

Examples

This Windows example deletes all files from a folder and then deletes the folder:

Kill "C:\WORD\FCCPROJ\*.*"
RmDir "C:\WORD\FCCPROJ"

The following is the same example, rewritten for the Macintosh:

curfolder$ = Files$(":")
ChDir "HD:WORD:FCC PROJECT"
Kill MacID$("****")
ChDir curfolder$
RmDir "HD:WORD:FCC PROJECT"

The following example deletes a subfolder within the current folder:

RmDir "FCCPROJ"

The following examples delete a folder at the same level as the current folder:

RmDir "..\FCCPROJ"        'Windows example
RmDir "::FCC PROJECT"    'Macintosh example

See Also

ChDir, Files$(), Kill, MacID$(), MkDir


Rnd()

Syntax

Rnd()

Remarks

Returns a random real number greater than or equal to 0 (zero) and less than 1.
To generate a random integer between a and b, use the following syntax:

Int(Rnd() * ((b + 1) – a) + a)

Example

This example defines the variable num as a random integer between 50 and 100 and then displays the number in a message box:

a = 50
b = 100
num = Int(Rnd() * (b - a) + a)
MsgBox "The random number is" + Str$(num)

See Also

Abs(), Int(), Sgn()


RTrim$()

Syntax

RTrim$(Source$)

Remarks

Returns Source$ minus any trailing spaces (spaces to the right of the last character). RTrim$() is especially useful for cleaning up user-defined variables before passing them to other parts of a macro.

Example

This example prompts the user for his or her last name and then removes extra spaces the user may have typed at the end of the name:

lastName$ = InputBox$("Please enter your last name.")
lastName$ = RTrim$(lastName$)

See Also

InStr(), Left$(), LTrim$(), Mid$(), Right$()


RunPrintManager

Syntax

RunPrintManager

Remarks

In Windows, starts Print Manager if it is not running or switches to Print Manager if it is already running. On the Macintosh, RunPrintManager is not available and generates an error.

See Also

AppActivate, AppIsRunning(), ControlRun


SaveTemplate

Syntax

SaveTemplate

Remarks

Saves changes to the active template unless the active template is the Normal template. If your macro includes changes to items such as AutoText entries or keyboard, toolbar, and menu assignments for a template other than Normal, it's a good idea to include a SaveTemplate instruction to preserve the changes. To save changes to all documents and templates, including the Normal template, use FileSaveAll.

SaveTemplate does not request confirmation before saving changes. You may want to use MsgBox() to confirm that changes should be saved before running SaveTemplate.

See Also

FileSave, FileSaveAll


ScreenRefresh

Syntax

ScreenRefresh

Remarks

Updates the display on your monitor to show the current screen display. You can use ScreenRefresh in a macro after a ScreenUpdating instruction has turned off screen updating. ScreenRefresh turns on screen updating for just one instruction and then immediately turns it off. Subsequent instructions do not update the screen until screen updating is turned on again with another ScreenUpdating instruction. You can use ScreenRefresh and ScreenUpdating to create a series of screen "snapshots." During a long process, the screen can be updated from time to time to indicate the macro's progress.

Note

On the Macintosh, document windows are hidden when screen updating is turned off. A ScreenRefresh instruction displays updated document windows for an instant, but then the document windows are hidden again. Therefore, on the Macintosh, you may want to use ScreenUpdating instead of ScreenRefresh to turn screen updating on and off.

For an example, see ScreenUpdating.

See Also

ScreenUpdating


ScreenUpdating, ScreenUpdating()

Syntax

ScreenUpdating [On]

ScreenUpdating()

Remarks

The ScreenUpdating statement controls most display changes on the monitor while a macro is running. When screen updating is turned off, toolbars remain visible and Word still allows the macro to display or retrieve information using status bar prompts, input boxes, dialog boxes, or message boxes. You can increase the speed of some macros by preventing screen updates. Screen updating is restored when the macro finishes or when it stops after an error.

Argument | Explanation
On | Specifies whether to show screen updates: 0 (zero) The screen does not update while the macro is running. 1 The screen updates normally while the macro is running. Omitted Toggles screen updating.

The ScreenUpdating() function returns the following values.

Value | Explanation
0 (zero) | Screen updating is turned off.
1 | Screen updating is turned on.

Example

This example arranges document windows in three different ways. A ScreenUpdating statement is used to turn off screen updating while the windows are being arranged. When the windows are arranged, a ScreenRefresh statement displays them. Note that the instructions TileDocWindowsVertically and CascadeDocWindows call subroutines (not shown here) that tile and cascade document windows.

ScreenUpdating 0
TileDocWindowsVertically
ScreenRefresh
MsgBox "Windows are tiled vertically."
CascadeDocWindows
ScreenRefresh
MsgBox "Windows are cascaded."
WindowArrangeAll
ScreenUpdating 1
MsgBox "Windows are tiled horizontally."

See Also

ScreenRefresh


Second()

Syntax

Second(SerialNumber)

Remarks

Returns an integer between 0 (zero) and 59, inclusive, corresponding to the seconds component of SerialNumber, a decimal representation of the date, time, or both. For information about serial numbers, see DateSerial().

Example

This example produces a beep five seconds after the macro is started. Note that Second(Now()) returns the seconds component of the current time according to your computer's built-in clock.

n = Second(Now())
beepTime = n + 5
If beepTime > 59 Then beepTime = beepTime - 60
While Second(Now()) <> beepTime
Wend
Beep

See Also

DateSerial(), Day(), Hour(), Minute(), Month(), Now(), Today(), Weekday(), Year()


Seek, Seek()

Syntax

Seek [#]FileNumber, Count

Seek([#]FileNumber)

Remarks

The Seek statement controls where data is retrieved from a sequential file open for input, or where data is inserted into a file open for output or appending. For more information about sequential files, see Chapter 9, "More WordBasic Techniques," in Part 1, "Learning WordBasic."

Argument | Explanation
FileNumber | The number specified in the Open instruction that opened the file for input, output, or appending.
Count | The character position where data retrieval or insertion occurs. Note that line breaks and other delimiters, such as commas, are counted as characters.

The Seek() function returns the current character position in the sequential file. You can use the Seek() function to store the current character position before you close a sequential file, and the Seek statement to return to that position when you reopen the file.

Example

This example finds the first line beginning with the letter "P" in DATA.TXT and then displays a message box showing the entry and its character position in the file:

Open "DATA.TXT" For Input As #1
Input #1, name$
While Left$(name$, 1) <> "P"
    If Eof(1) Then
        MsgBox "No P names in the file."
        Goto finish
    End If
    n = Seek(#1)
    Input #1, name$
Wend
MsgBox "First P name is " + name$ + " at position" + Str$(n)
finish:
Close #1

See Also

Close, Eof(), Input, Input$(), Line Input, Lof(), Open, Print, Read, Write


Select Case

Syntax

Select Case Expression
Case CaseExpression
Series of instruction(s)
[Case Else
Series of instruction(s)]
End Select

Remarks

Runs one of several series of instructions according to the value of Expression. Expression is compared with each CaseExpression in turn. When a match is found, the instructions following that Case CaseExpression are run, and then control passes to the instruction following End Select. If there is no match, the instructions following Case Else are run. If there is no match and there is no Case Else instruction, an error occurs.

The Select Case control structure is an important part of most dialog functions. For more information about dialog functions, see Chapter 5, "Working with Custom Dialog Boxes," in Part 1, "Learning WordBasic."

Keep the following points in mind when using Select Case:

  • Use the Is keyword to compare CaseExpression with Expression using a relational operator. For example, the instruction Case Is > 8 tests for any value greater than 8. Do not use the Is keyword without a relational operator
    or an error will occur; for example, Case Is 8 generates an error.
  • Use the To keyword to test for a value that falls within a specified range. For example, the instruction Case 4 To 8 tests for any value greater than or equal to 4 and less than or equal to 8.
  • If you include a Goto instruction to go to a label outside the Select Case control structure, an error will occur.

Examples

This example goes to each paragraph in the document and inserts either a bullet
or a hyphen, depending on whether the paragraph's style is "ListItem1" or "ListItem2." If a paragraph that is not formatted with either of these styles is found, the instruction following Case Else displays a message box.

StartOfDocument
While CmpBookmarks("\Sel", "\EndOfDoc") <> 0
    Select Case StyleName$()
        Case "ListItem1"
            ToolsBulletsNumbers .Type = 0
        Case "ListItem2"
            Insert "-" + Chr$(9)
        Case Else
            MsgBox "Not a list style"
    End Select
    ParaDown
Wend

The following example illustrates how Select Case may be used to evaluate numeric expressions. The Select Case instruction generates a random number between –5 and 5, and the subsequent Case instructions run depending on the value of that numeric expression.

Select Case Int(Rnd() * 10) - 5
    Case 1,3
        Print "One or three"
    Case Is > 3
        Print "Greater than three"
    Case -5 To 0
        Print "Between -5 and 0 (inclusive)"
    Case Else
        Print "Must be 2"
End Select

See Also

For ¼ Next, Goto, If ¼ Then ¼ Else, While ¼ Wend


SelectCurAlignment

Syntax

SelectCurAlignment

Remarks

Extends the selection forward until text with a different paragraph alignment is encountered. There are four types of paragraph alignment: left, centered, right, and justified.

Example

This example positions the insertion point at the beginning of the first subsequent paragraph that does not have the same alignment as the current paragraph. If the alignment is the same to the end of the document, Word displays a message box.

SelectCurAlignment
CharRight
If CmpBookmarks("\Sel", "\EndOfDoc") = 0 Then
    MsgBox "No variation in alignment found."
End If

See Also

CenterPara, FormatParagraph, JustifyPara, LeftPara, RightPara, SelectCurIndent, SelectCurSpacing, SelectCurTabs


SelectCurColor

Syntax

SelectCurColor

Remarks

Extends the selection forward until text with a different color is encountered.

Example

This example extends the selection from the beginning of the document to the first character formatted with a different color and then displays the number of characters in the selection:

StartOfDocument
SelectCurColor
n = Len(Selection$())
MsgBox "Contiguous characters with the same color:" + Str$(n)

See Also

CharColor, FormatFont, SelectCurFont


SelectCurFont

Syntax

SelectCurFont

Remarks

Extends the selection forward until text in a different font or font size is encountered.

Example

This example extends the selection to the first character in a different font or font size and then increases the font size to the next available setting:

SelectCurFont
GrowFont

See Also

Font, FontSize, FormatFont, SelectCurColor


SelectCurIndent

Syntax

SelectCurIndent

Remarks

Extends the selection forward from the insertion point until text with different left or right paragraph indents is encountered.

Example

This example determines whether all the paragraphs in the document are formatted with the same left and right indents and then displays a message box indicating the result:

StartOfDocument
SelectCurIndent
LineDown
If LineDown() = 0 Then
    MsgBox "All paragraphs share the same left and right indents."
Else
    MsgBox "Not all paragraphs share the same left and right indents."
End If

See Also

FormatParagraph, Indent, SelectCurAlignment, SelectCurSpacing, SelectCurTabs, UnIndent


SelectCurSentence

Syntax

SelectCurSentence

Remarks

Selects the entire sentence containing the insertion point or selection, including the trailing space. If the selection is larger than a sentence when SelectCurSentence is run, an error occurs.

Example

This example defines the variable a$ as the text in the current sentence. To avoid an error if there is a selection that extends over multiple sentences, the first instruction cancels the selection if there is one.

If SelType() = 2 Then SelType 1        'Cancel selection, if any
SelectCurSentence
a$ = Selection$()

See Also

SelectCurWord, SentLeft, SentRight


SelectCurSpacing

Syntax

SelectCurSpacing

Remarks

Extends the selection from the insertion point forward until a paragraph with different line spacing is encountered.

Example

This example demonstrates a quick way to jump to the beginning of the next paragraph whose line spacing is different from that of the current paragraph. If the spacing is the same to the end of the document, Word displays a message box.

SelectCurSpacing
CharRight
If CmpBookmarks("\Sel", "\EndOfDoc") = 0 Then
    MsgBox "No variation in spacing found."
End If

See Also

FormatParagraph, SelectCurAlignment, SelectCurIndent, SelectCurTabs, SpacePara1, SpacePara15, SpacePara2


SelectCurTabs

Syntax

SelectCurTabs

Remarks

Extends the selection forward from the insertion point until a paragraph with different tab stops is encountered.

Example

This example determines the position of the first tab stop in the current paragraph, and then sets the same tab stop for the next series of paragraphs that have tab settings different from those in the original paragraph. Because NextTab() returns a position in points, points are also used in the FormatTabs instruction.

n = NextTab(0)
SelectCurTabs
CharRight
SelectCurTabs
FormatTabs .Position = Str$(n) + "pt"

See Also

FormatTabs, SelectCurAlignment, SelectCurIndent, SelectCurSpacing


SelectCurWord

Syntax

SelectCurWord

Remarks

Selects the entire word containing the insertion point or selection. Whereas double-clicking a word selects both the word and the trailing space (if any), SelectCurWord does not select the trailing space. If the selection is larger than
a word when SelectCurWord is run, an error occurs.

Example

This example defines the variable a$ as the characters in the word containing the insertion point. If there is a selection, the first instruction cancels it, so in effect, a$ is defined as the first word in the selection.

If SelType() = 2 Then SelType 1        'Cancel selection, if any
SelectCurWord
a$ = Selection$()

See Also

SelectCurSentence, WordLeft, WordRight


SelectDrawingObjects

Syntax

SelectDrawingObjects

Remarks

Toggles the mouse pointer shape between the standard mouse pointer and the pointer for selecting drawing objects. You drag a dotted rectangle to enclose the drawing objects you want to select.

See Also

DrawExtendSelect, DrawSelect


Selection$()

Syntax

Selection$()

Remarks

Returns the plain, unformatted text of the selection. Selection$() can return as many as 65,280 characters or the maximum that available memory can hold. If the selection is too large, an error occurs and no text is returned. If no text is selected, Selection$() returns the character following the insertion point.

Example

This example selects the first heading in the document and then uses the Selection$() function to define the variable heading$ with the selected text:

StartOfDocument
EditFindClearFormatting
EditFindStyle .Style = "heading 1"
EditFind .Find = "", .WholeWord = 0, .MatchCase = 0, .Direction = 0, \
    .Format = 1, .Wrap = 0
If EditFindFound() <> 0 Then
    heading$ = Selection$()
End If

See Also

ExtendSelection, SelInfo(), SelType, ShrinkSelection


SelectionFileName$()

Syntax

SelectionFileName$()

Remarks

Returns the full path and filename of the active document if it has been saved. If the document has not been saved, or if the active window is a macro-editing window, SelectionFileName$() returns the current path followed by a backslash ( \ ) (Windows) or colon (:) (Macintosh).

Example

This example checks to see if the active window is a macro-editing window. If not, the example checks the last character in the text returned by SelectionFileName$(). If the last character is a backslash ( \ ) or colon (:), indicating the document has never been saved, a message is displayed.

a$ = SelectionFileName$()
If SelInfo(27) = -1 Then
    MsgBox "A macro-editing window is active."
    Goto bye
End If
end$ = Right$(a$, 1)
If end$ = "\" Or end$ = ":" Then
    MsgBox "The active document has never been saved."
End If
bye:

See Also

FileName$(), FileNameInfo$(), GetDirectory$()


SelInfo()

Syntax

SelInfo(Type)

Remarks

Returns one of 37 types of information about the selection, where Type is one of the values described in the following tables. In the explanations, the active end of the selection refers to the end that moves when you press SHIFT+an arrow key.

Type | Explanation
1 | Number of the page containing the active end of the selection. If you set a starting page number or make other manual adjustments, returns the adjusted page number (unlike SelInfo(3)). If the selection is in a header or footer pane in normal view, returns –1. If the selection is in a footnote or annotation pane, returns the page number of the first footnote or annotation in the selection.
2 | Number of the section containing the active end of the selection.
3 | Number of the page containing the active end of the selection, counting from the beginning of the document. Any manual adjustments to page numbering are disregarded (unlike SelInfo(1)).
4 | Number of pages in the document.

Type 5 is valid only in page layout view. Type 6 is valid in page layout view or in normal view if you select the Background Repagination check box on the General tab and clear the Draft Font check box on the View tab in the Options dialog box (Tools menu).

Type | Explanation
5 | Horizontal position of the selection; distance between the left edge of the selection and the left edge of the page, in twips (20 twips = 1 point, 72 points = 1 inch). Returns –1 if the selection is not visible.
6 | Vertical position of the selection; distance between the top edge of the selection and the top edge of the page, in twips (20 twips = 1 point, 72 points = 1 inch). Returns –1 if the selection is not visible in the document window.

Types 7 and 8 are most useful in page layout view, where you can display text boundaries by selecting the Text Boundaries check box on the View tab in the Options dialog box (Tools menu). Text boundaries include table cells, frames, the edges of the page, text columns, and so on. For a complete list of text boundaries, see NextObject.

Type | Explanation
7 | Horizontal position of the selection, relative to the left edge of the nearest text boundary enclosing it, in twips (20 twips = 1 point, 72 points = 1 inch). Returns –1 if selection is not visible.
8 | Vertical position of the selection, relative to the upper edge of the nearest text boundary enclosing it, in twips (20 twips = 1 point, 72 points = 1 inch). Especially useful for determining the position of the insertion point within a frame or table cell. For a complete list of text boundaries, see NextObject. Returns –1 if the selection is not visible.
9 | Character position of the first character in the selection or, if no text is selected, the character to the right of the insertion point (same as the character column number displayed in the status bar after "Col").
10 | Line number of the first character in the selection; if Background Repagination is cleared or if Draft Font is selected, returns –1.
11 | Returns –1 if the selection is an entire frame.
12 | Returns –1 if the selection is within a table.

Types 13 through 18 apply only if the selection is within a table; if the selection is not within a table, the function returns –1.

Type | Explanation
13 | The row number containing the beginning of the selection.
14 | The row number containing the end of the selection.
15 | The number of rows in the table.

Type | Explanation
16 | The table column number containing the beginning of the selection.
17 | The table column number containing the end of the selection.
18 | The greatest number of columns within any row in the selection.

Types 19 through 37 return miscellaneous information.

Type | Explanation
19 | The current percentage of magnification as set by ViewZoom.
20 | The current selection mode: returns 0 (zero) for normal selection, 1 for extended selection, and 2 for column selection. Corresponds to the box in the status bar that reads either "EXT" or "COL."
21 | Returns –1 if Caps Lock is in effect.
22 | Returns –1 if Num Lock is in effect.
23 | Returns –1 if Word is in overtype mode.
24 | Returns –1 if revision marking is in effect.
25 | Returns –1 if the selection is in the footnote or endnote pane, or in a footnote or endnote in page layout view. See also values 35 and 36.
26 | Returns –1 if the selection is in an annotation pane.
27 | Returns –1 if the selection is in a macro-editing window.
28 | Returns –1 if the selection is in the header or footer pane or in a header or footer in page layout view.
29 | The number of the bookmark enclosing the start of the selection; 0 (zero) if none or invalid. The number corresponds to the position of the bookmark in the document — 1 for the first bookmark, 2 for the second, and so on.
30 | The number of the last bookmark that starts before or at the same place as the selection; returns 0 (zero) if none or invalid.
31 | Returns –1 if the insertion point is at the end-of-row mark in a table.
32 | Returns one of the following values, depending on where the selection is in relation to a footnote, endnote, or annotation reference: –1 If the selection includes but is not limited to a footnote, endnote, or annotation reference 0 (zero) If the selection is not in a footnote, endnote, or annotation reference 1 If the selection is in a footnote reference 2 If the selection is in an endnote reference 3 If the selection is in an annotation reference

Type | Explanation
33 | The kind of header or footer containing the selection: –1 None (the selection is not in a header or footer) 0 (zero) Even-page header 1 Odd-page header (or the only header if there are not odd and even headers) 2 Even-page footers 3 Odd-page footer (or the footer if there are not odd and even footers) 4 First-page header 5 First-page footer
34 | Returns –1 if the active document is a master document (that is, if it contains at least one subdocument)
35 | Returns –1 if the selection is in the footnote pane or in a footnote in page layout view.
36 | Same as 35, but for endnotes.
37 | Returns one of the following values, depending on whether the current selection is in a WordMail message: 0 (zero) If the selection is not in a WordMail message 1 If the selection is in a WordMail send note 2 If the selection is in a WordMail read note

Examples

This example determines whether the current selection extends over a page break, either manual or automatic. Note that SelInfo(3) is used twice: once to return the page number of the end of the selection, and again to return the page number of the beginning of the selection. The macro is then able to compare these values to determine how many page breaks are in the selection.

ToolsRepaginate
EditBookmark .Name = "Tmp"
endPage = SelInfo(3)
SelType 1
startPage = SelInfo(3)
EditGoTo .Destination = "Tmp"
numBreaks = endPage - startPage
If numBreaks = 1 Then
    MsgBox "Selection extends over one page break."
ElseIf numBreaks > 1 Then
    MsgBox "Selection extends over" + Str$(numBreaks) + \
        " page breaks."
End If
EditBookmark .Name = "Tmp", .Delete

The following example increases the view magnification by 10 percent:

n = SelInfo(19)
If n < 190 Then
    ViewZoom .ZoomPercent = n + 10
ElseIf n = 200 Then
    MsgBox "Already zoomed to maximum."
Else
    ViewZoom .ZoomPercent = 200
End If

See Also

Selection$(), SelType


SelType, SelType()

Syntax

SelType Type

SelType()

Remarks

The SelType statement specifies how the insertion point or selected text is indicated in your document. For example, you can specify that selected text appear with a dotted underline instead of in reverse video, which may be preferable on some video displays.

SelType is more commonly used to position the insertion point at the beginning of the current selection. For this result, SelType has advantages over CharLeft because if there is no current selection, the insertion point does not move left.

Argument | Explanation
Type | The type of highlight: 1 Solid insertion point (default) 2 Solid selection (default) 4 Dotted selection or insertion point (whichever is current) Note that the SelType() function never returns this value because 5 and 6 provide more specific information. 5 Dotted insertion point (visible in CopyText and MoveText modes) 6 Dotted selection (visible in CopyText and MoveText modes)

The SelType() function returns a number corresponding to the type of highlight.

Example

This example selects the next occurrence of the word "background" and then cancels the selection, leaving the insertion point at the beginning of the word:

EditFind .Find = "background", .Direction = 0
If EditFindFound() Then SelType 1

See Also

Selection$(), SelInfo()


SendKeys

Syntax

SendKeys Keys$, Wait

Remarks

Sends the keystrokes specified by Keys$ to the active application, just as if they were typed at the keyboard. To send keys to a Word dialog box, SendKeys must precede instructions that display the dialog box so that those keystrokes are in memory when the macro pauses.

On the Macintosh, a SendKeys instruction can send no more than 10 keystrokes, and can send them only to Word; SendKeys cannot be used with another application.

Note

Use SendKeys to operate other applications only when there is no alternative, and then use it with caution. In general, dynamic data exchange (DDE) is a better way for Word to interact with other applications because DDE provides a channel for two-way communication between applications and provides a path for detecting and dealing with errors in the other application. You should test even the simplest use of SendKeys under a variety of conditions to avoid unpredictable results, data loss, or both.

When stepping through a macro (using the Step or Step Subs button on the Macro toolbar) that contains a SendKeys instruction, note that the macro may not perform as expected unless the SendKeys instruction and the instruction that activates the target application or dialog box are on the same line, separated by a colon.

Argument | Explanation
Keys$ | A key or key sequence, such as "a" for the letter a, or "{enter}{tab}" for the ENTER key followed by the tab key.
Wait | If Word is not the active application and Wait is –1, Word waits for all keys to be processed before proceeding. For example, in Windows, if you run the following instructions to send Keys$ to Microsoft Excel, a beep occurs in Word only after text is inserted into all 10 cells. If Wait were 0 (zero), the beep would occur as text was inserted into the first cell. AppActivate "Microsoft Excel" For i = 1 To 10 SendKeys "Testing{down}", -1 Next i Beep

The following table lists non-character keys available to send in Windows and on the Macintosh.

Key | Code
ENTER | {enter} or ~
ESC | {escape} or {esc}
SPACE | { }
TAB | {tab}

The following table lists non-character keys available to send only in Windows.

Key | Code
BACKSPACE | {backspace} or {bs} or {bksp}
BREAK | {break}
CAPS LOCK | {capslock}
CLEAR | {clear}
DEL | {delete} or {del}
DOWN ARROW | {down}
END | {end}
HELP | {help}
HOME | {home}
INS | {insert}
LEFT ARROW | {left}
NUM LOCK | {numlock}
PAGE DOWN | {pgdn}
PAGE UP | {pgup}
RIGHT ARROW | {right}
UP ARROW | {up}
F1, F2, F3,¼F16 | {F1}, {F2}, {F3},¼{F16}

In addition to the key codes listed above, you can specify any key code listed in ToolsCustomizeKeyboard. To do so, use the syntax {Code}. For example, the instruction SendKeys "{13}" sends the key code for ENTER and SendKeys "{32}" sends the key code for SPACE.

To repeat a character, use the syntax {Character Number}. For example, SendKeys "{s 10}" repeats the letter s 10 times. Remember to put a space between the key and the number. To repeat a key whose code already includes braces, add a space and a number within the braces, for example: SendKeys "{enter 10}". (You cannot repeat ToolsCustomizeKeyboard key codes in this way.)

In Windows, to send a key combination that includes SHIFT, ALT, or CTRL, use the following symbols. (On the Macintosh, you can send a SHIFT key combination using the plus sign (+), but you cannot send key combinations including OPTION or COMMAND.)

To combine with | Precede the key code by
SHIFT | + (plus sign)
ALT (Windows) or COMMAND (Macintosh) | % (percent sign)
CTRL (Windows) or CONTROL (Macintosh) | ^ (caret)
OPTION (Macintosh) | # (pound sign)

For example, in Windows, "%{enter}" sends the code for ALT+ENTER. You can group keys with parentheses and precede the group with the key code for a SHIFT, ALT, or CTRL key. For example, the code "+(wordbasic)" specifies WORDBASIC (but you can also simply use the uppercase letters WORDBASIC, without using the plus sign). To send a plus sign (+), a percent sign (%), a caret (^), or a pound sign (#) as literal text, enclose the character in braces. For example, to send a plus sign, use the instruction SendKeys "{+}". You can also use braces to send parentheses.

Note

In Windows, when sending key combinations that include the ALT key, make it a rule to send lowercase characters. For example, to open the File menu (ALT, F), use "%f." Using "%F" is equivalent to pressing ALT+SHIFT+F.

Examples

One use of SendKeys is to insert text or select items in a Word dialog box (for example, to provide default text or initially select a specific item). This Windows example displays the Open dialog box (File menu) and inserts the default text "TESTFILE" into the File Name box. You can produce the same effect with the single instruction SendKeys "%foTESTFILE".

SendKeys "TESTFILE"
Dim dlg As FileOpen
x = Dialog(dlg)

The following Windows example starts Microsoft Excel with the worksheet MARCH.XLS and then performs the equivalent to pressing the PAGE DOWN key 20 times:

SendKeys "{pgdn 20}"
Shell "C:\EXCEL\MARCH.XLS", 1

See Also

AppActivate, DDEExecute, DDEInitiate(), DDEPoke


SentLeft, SentLeft()

Syntax

SentLeft [Count,] [Select]

SentLeft([Count,] [Select])

Remarks

The SentLeft statement moves the insertion point or the active end of the selection (the end that moves when you press SHIFT+an arrow key) to the left by the specified number of sentences.

Argument | Explanation
Count | The number of sentences to move; if less than one or omitted, 1 is assumed.
Select | Specifies whether to select text: 0 (zero) or omitted Text is not selected. If there is already a selection, SentLeft moves the insertion point Count–1 sentences to the left of the selection. Nonzero Text is selected. If there is already a selection, SentLeft moves the active end of the selection toward the beginning of the document. In a typical selection made from left to right, where the active end of the selection is closer to the end of the document, SentLeft shrinks the selection. In a selection made from right to left, it extends the selection.

Note that Word counts empty table cells as "sentences," and that, regardless of length or punctuation, Word considers every paragraph to contain at least one sentence.

The SentLeft() function behaves the same as the statement and also returns the following values.

Value | Explanation
0 (zero) | If the insertion point or the active end of the selection cannot be moved to the left.
–1 | If the insertion point or the active end of the selection is moved to the left by any number of sentences, even if less than Count. For example, SentLeft(10) returns –1 even if the insertion point is only three sentences from the start of the document.

Example

This example deletes all sentences in the document containing the phrase "see page." In other words, the example deletes all cross-references to other pages. Note that you could substitute SelectCurSentence for the pair of instructions SentLeft and SentRight 1, 1.

StartOfDocument
EditFind .Find = "see page", .WholeWord = 1, .Direction = 0, .Format = 0
While EditFindFound()
    SentLeft
    SentRight 1, 1
    EditClear
    EditFind .Find = "see page", .WholeWord = 1, .Direction = 0, \
        .Format = 0
Wend

See Also

CharLeft, ParaUp, SelectCurSentence, SentRight, StartOfLine, WordLeft


SentRight, SentRight()

Syntax

SentRight [Count,] [Select]

SentRight([Count,] [Select])

Remarks

The SentRight statement moves the insertion point or the active end of the selection (the end that moves when you press SHIFT+an arrow key) to the right by the specified number of sentences.

Argument | Explanation
Count | The number of sentences to move; if less than one or omitted, 1 is assumed.
Select | Specifies whether to select text: 0 (zero) or omitted Text is not selected. If there is already a selection, SentRight moves the insertion point Count–1 sentences to the right of the selection. Nonzero Text is selected. If there is already a selection, SentRight moves the active end of the selection toward the end of the document. In a typical selection made from left to right, where the active end of the selection is closer to the end of the document, SentRight extends the selection. In a selection made from right to left, it shrinks the selection.

Note that Word counts empty table cells as "sentences," and that, regardless of length or punctuation, Word considers every paragraph to contain at least one sentence.

The SentRight() function behaves the same as the statement and also returns the following values.

Value | Explanation
0 (zero) | If the insertion point or the active end of the selection cannot be moved to the right.
–1 | If the insertion point or the active end of the selection is moved to the right by any number of sentences, even if less than Count. For example, SentRight(10) returns –1 even if the insertion point is only three sentences from the end of the document.

Example

This example counts the number of sentences in the document (excluding paragraph marks) and displays the result in a message box:

StartOfDocument
count = 0
While SentRight(1, 1) <> 0
    If Right$(Selection$(), 1) <> Chr$(13) Then count = count + 1
Wend
MsgBox "Number of sentences in document:" + Str$(count)

See Also

CharRight, EndOfLine, ParaDown, SelectCurSentence, SentLeft, WordRight


SetAttr

Syntax

SetAttr Filename$, Attribute

Remarks

Sets file attributes for Filename$. In Windows, the attributes correspond to those you can set using the Properties command (File menu) in File Manager Windows 3.x and Windows NT) or the Windows Explorer (Windows 95). For definitions of the attributes, display the Properties dialog box and choose the Help button. On the Macintosh, only the Read Only and Hidden attributes are available (Read Only corresponds to the Locked check box in the Get Info dialog box (File menu) in the Finder). The file whose attributes you want to set must be closed; an error occurs if you try to set an attribute for an open document.

Argument | Explanation
Filename$ | The path and filename of the file whose attribute you want to set
Attribute | Specifies the attribute: 0 (zero) Clears all attributes except System 1 Read Only 2 Hidden 4 System (not available on the Macintosh) 32 Archive (not available on the Macintosh)

Note

Attribute values are additive. For example, to set both the Read Only and Archive attributes, Attribute would be 33 (the sum of 1 and 32). For a way to set the Read Only attribute independently, see the example for this entry. You cannot set the System attribute in combination with the Archive attribute.

Example

This example makes the file C:\TEST\TEST.DOC read-only without affecting the file's other attributes. First, GetAttr() returns the current Attribute value. Then the If conditional uses the MOD operator to determine whether the Attribute value is odd, which means the file's Read Only attribute is already selected. In that case, Word displays a message box. If Attribute is an even value or 0 (zero), the SetAttr instruction sets the Read Only attribute. On the Macintosh, substitute a path and filename such as HD:TEST:TEST DOCUMENT.

attribs = GetAttr("C:\TEST\TEST.DOC")
Print attribs
If attribs MOD 2 Then
        MsgBox "File is already read-only."
Else
        SetAttr "C:\TEST\TEST.DOC", 1
End If

See Also

GetAttr()


SetAutoText

Syntax

SetAutoText Name$, Text$ [, Context]

Remarks

Defines a text-only AutoText entry. Unlike an EditAutoText instruction that uses .Add, SetAutoText does not require a selection.

Argument | Explanation
Name$ | The name of the new entry
Text$ | The text to be associated with the entry
Context | Specifies the availability of the entry: 0 (zero) or omitted Normal template (available to all documents) 1 Active template (available only to documents based on the active template) Note that if Context is 1 and the active template is the Normal template, SetAutoText generates an error.

Example

This example defines the AutoText entry "Disclaim" in the active template; "Disclaim" contains the text assigned to text$:

text$ = "No warranty is either expressed or implied."
SetAutoText "Disclaim", text$, 1

See Also

AutoText, AutoTextName$(), CountAutoTextEntries(), EditAutoText, GetAutoText$(), InsertAutoText


SetDocumentDirty

Syntax

SetDocumentDirty [Dirty]

Remarks

Controls whether Word recognizes a document as "dirty" — that is, changed since the last time the document was saved. When a dirty document is closed, Word displays a prompt asking if changes should be saved.

If you change a document and then set Dirty to 0 (zero), Word recognizes the document as unchanged, or "clean." When you close the document, Word neither displays a prompt nor saves changes.

Argument | Explanation
Dirty | Specifies whether to make the active document dirty: 0 (zero) The document is treated as clean. 1 or omitted The document is recognized as dirty.

Example

This example assumes that a main document for a mail merge is active. The instructions print form letters to a document, which is then made clean. When the document is closed, Word will not display a prompt or save changes.

MailMergeToDoc
SetDocumentDirty 0

See Also

IsDocumentDirty(), IsTemplateDirty(), SetTemplateDirty


SetDocumentProperty

Syntax

SetDocumentProperty Name$, Type, Value[$], CustomOrBuiltIn

Remarks

Defines a document property for the active document. If Name$ is a built-in property that doesn't match the type specified by Type, or if it is a read-only property, an error occurs. Use the DocumentPropertyExists() function to determine whether a property called Name$ already exists.

For a list of the built-in properties available in Word, see DocumentPropertyName$(). In Word version 6.0, SetDocumentProperty is unavailable and generates an error.

Argument | Explanation
Name$ | The name of the property. Name$ can be a built-in property or a custom property.
Type | The type of the property to be defined: 0 (zero) String 1 Number 2 Date 3 Yes or No If Name$ is a built-in property and doesn't match the type specified by Type, an error occurs.
Value[$] | The property value. Value[$] must match the type specified by Type. If Value[$] doesn't match the type specified by Type, an error occurs.
CustomOrBuiltIn | Specifies whether Name$ is a custom property or a built-in property: 0 (zero) or omitted Name$ is a custom property unless it appears in the list of built-in properties. If Name$ is a built-in property, SetDocumentProperty will update its value. 1 Name$ is a built-in property. If it is not one of the built-in properties, an error occurs. 2 Name$ is a custom property, regardless of whether a built-in property with the same name already exists.

Example

This example asks the user to insert the name of a customer and then assigns the name to the variable customerName$. The SetDocumentProperty instruction defines the custom property "Customer" with the value of customerName$. Note that this is done only if the custom property "Customer" is not already defined.

customerName$ = InputBox$("Please type the name of the customer", "Customer Name")
If DocumentPropertyExists("Customer") = 0 Then
    SetDocumentProperty("Customer", 0, customerName$, 2)
End If

See Also

DocumentPropertyExists(), GetDocumentProperty(), IsCustomDocumentProperty(), IsDocumentPropertyReadOnly(), SetDocumentPropertyLink


SetDocumentPropertyLink

Syntax

SetDocumentPropertyLink Name$, Source$

Remarks

Defines a custom property for the active document and links it to an existing bookmark named Source$. If Source$ doesn't exist, an error occurs. Use the DocumentPropertyExists() function to verify that the Name$ property exists.

For a list of the built-in properties available in Word, see DocumentPropertyName$(). In Word version 6.0, SetDocumentPropertyLink is unavailable and generates an error.

Argument | Explanation
Name$ | The name of the property. Name$ can be a built-in property or a custom property.
Source$ | The name of the bookmark.

Example

This example inserts a DATE field at the insertion point, defines the DateOfLetter bookmark, and defines a custom property for the active document. This property is linked to the DateOfLetter bookmark.

InsertField .Field = "DATE"
EditGoto .Destination = "d- 'DATE'"
UnlinkFields
EditBookmark .Name = "DateOfLetter", .Add
SetDocumentPropertyLink("Date of letter","DateOfLetter")

See Also

GetDocumentProperty(), SetDocumentProperty


SetDocumentVar, SetDocumentVar()

Syntax

SetDocumentVar VariableName$, VariableText$

SetDocumentVar(VariableName$, VariableText$)

Remarks

The SetDocumentVar statement associates the string VariableText$ with the active document. You use the VariableName$ argument with the function GetDocumentVar$() to return the associated string when the document is active. The variable is saved with the document. You can set multiple document variables for a single document. To delete a document variable, specify an empty string ("") for VariableText$. If the insertion point is not in a document — for example, if the macro-editing window is active — an error occurs.

The SetDocumentVar() function behaves the same as the statement, and also returns –1 if the variable is set successfully.

Example

This example prompts for a reminder note to store with a document before closing it. If the macro were named FileClose, it would run each time the user chose Close from the File menu (the instruction FileClose runs the built-in command).

The instruction On Error Goto CloseNow ensures that a WordBasic error doesn't appear if the user cancels the InputBox$() dialog box. The instructions Err = 0 and On Error Resume Next reset error handling and ensure that an error doesn't appear if the user cancels the prompt to save changes.

On Error Goto CloseNow
worknote$ = InputBox$("Type a note for next time:")
SetDocumentVar "reminder", worknote$
CloseNow:
Err = 0
On Error Resume Next
FileClose

For an example of an AutoOpen macro that displays the most recent reminder note each time the document is opened, see GetDocumentVar$().

See Also

GetDocumentVar$()


SetEndOfBookmark

Syntax

SetEndOfBookmark Bookmark1$ [, Bookmark2$]

Remarks

Marks the end point of Bookmark1$ with Bookmark2$. If Bookmark2$ is omitted, Bookmark1$ is set to its own end point.

Example

This example marks the end of the current selection with the bookmark "EndPoint":

SetEndOfBookmark "\Sel", "EndPoint"

The bookmark " \ Sel" is one of several predefined bookmarks that Word defines and updates automatically. For more information, see "Operators and Predefined Bookmarks" later in this part.

See Also

CopyBookmark, EditBookmark, SetStartOfBookmark


SetFileCreatorAndType

Syntax

SetFileCreatorAndType File$, Creator$ [, Type$]

Remarks

On the Macintosh, sets the creator (application signature) and file type for the specified file.

Argument | Explanation
File$ | The path and filename of the file whose creator and type you want to set.
Creator$ | A four-character application signature (for example, MSWD for Word) or a string returned by the MacID$() function.
Type$ | A four-character string specifying a file type (for example, W6BN for a Word document) or a string returned by the MacID$() function.

In Windows, SetFileCreatorAndType is not available and generates an error.

See Also

FileCreator$(), FileType$(), MacID$()


SetFormResult

Syntax

SetFormResult BookmarkName$, Result[$] [, DefaultResult]

Remarks

Sets the result of the form field marked by the bookmark BookmarkName$ or updates any fields embedded within the specified form field. Depending on the type of form field, you specify Result[$] as a string or number, as follows:

  • For a check box form field, specify 0 (zero) to clear the check box or 1 to select it.
  • For a drop-down form field, specify 0 (zero) to select the first item, 1 to select the second item, and so on. You can also specify the item itself as a string.
  • For a text form field, specify a string.

If you do not specify Result[$], SetFormResult updates any fields within the specified form field.

If DefaultResult is 1, the result becomes the default result for the field. The default result is displayed each time the document containing the form field is protected for forms.

Examples

The following example is an AutoNew macro that runs each time a form is created. It sets the default results for the text form field "NameText," the check box form field "AgeCheck," and the drop-down form field "PreferencesList." It then protects the document for forms.

Sub MAIN
SetFormResult "NameText", "John Jones", 1
SetFormResult "AgeCheck", 1, 1
SetFormResult "PreferencesList", 2, 1
ToolsProtectDocument .Type = 2
End Sub

The following example updates a text form field identified by the bookmark "DateField." The form field contains a date field, which is updated by the SetFormResult instruction.

SetFormResult "DateField"

See Also

GetFormResult()


SetPrivateProfileString, SetPrivateProfileString()

Syntax

SetPrivateProfileString Section$, KeyName$, Setting$, Filename$

SetPrivateProfileString(Section$, KeyName$, Setting$, Filename$)

Remarks

Defines or redefines a setting in a settings file, a file that your macros can use for storing and retrieving settings. For example, you can store the name of the active document when you quit Word so that it can be reopened automatically the next time you start Word. In Windows, a settings file is a text file such as WINWORD6.INI. On the Macintosh, a settings file is a resource file such as Word Settings (6). In Windows 95 and Windows NT, you can use SetPrivateProfileString to assign a setting to a value in the registry.

Argument | Explanation
Section$ | The name of the section in the settings file that contains the key you want to set. In Windows, this is the name that appears between brackets before the associated keys (do not include the brackets with Section$). If you are using SetPrivateProfileString in Windows 95 or Windows NT to assign a setting to a value in the registry, Section$ should be the complete path to the key, including the root (for example, "HKEY_CURRENT_USER\Software\Microsoft\Word\6.0\Options".
KeyName$ | The key to set. In a Windows settings file, the key name is followed by an equal sign (=) and the setting. If you are using SetPrivateProfileString in Windows 95 or Windows NT to assign a setting to a value in the registry, KeyName$ should be the name of the value in the key specified by Section$ (for example, "MessageBeeps").
Setting$ | The new setting.
Filename$ | The filename for the settings file. If a path is not specified, the Windows folder (Windows) or the Preferences folder (Macintosh) is assumed. If the file does not already exist, Word creates it. If you are using S etPrivateProfileString in Windows 95 or Windows NT to assign a setting to a value in the registry, Filename$ must be an empty string ("").

The SetPrivateProfileString() function behaves the same as the statement and also returns a value indicating whether the action was successful: –1 means the key was set, 0 (zero) means the key was not set. Keys cannot be set if the settings file is read-only.

Example

This pair of auto macros automatically opens the document that was active the last time you quit Word. On the Macintosh, substitute a settings filename such as MY SETTINGS for MY.INI.

The following is the AutoExit macro. If the active window is a macro-editing window, the If conditional prevents Word from writing the macro name to the settings file. This prevents an error from occurring in the AutoExec macro.

Sub MAIN
If SelInfo(27) <> -1 Then a$ = FileName$()
check = SetPrivateProfileString("Word Info", "LastActive", a$, \
    "MY.INI")
If check = 0 Then MsgBox "Could not set INI option."
End Sub

The following is the AutoExec macro:

Sub MAIN
name$ = GetPrivateProfileString$("Word Info", "LastActive", \
    "MY.INI")
If name$ <> "" Then FileOpen .Name = name$
End Sub

See Also

GetProfileString$(), GetPrivateProfileString$(), SetProfileString, ToolsAdvancedSettings


SetProfileString

Syntax

SetProfileString Section$, KeyName$, Setting$

Remarks

In Windows, creates a key and defines a setting for it, or redefines the setting of an existing key in WIN.INI. If Section$ is "Microsoft Word 2.0," "Microsoft Word," "MSWord Text Converters," or "MSWord Editable Sections," SetProfileString redefines the setting in WINWORD6.INI. These exceptions are made for compatibility with Word for Windows version 2.x macros. On the Macintosh, SetProfileString defines settings in the Word Settings (6) file. It is generally preferable to use SetPrivateProfileString, which allows you to specify a settings file to modify.

Argument | Explanation
Section$ | The name of the section in the settings file that contains the key you want to set. In Windows, this is the name that appears between brackets before the associated keys (do not include the brackets with Section$).
KeyName$ | The key to set. In Windows, the key name is followed by an equal sign (=) and the setting.
Setting$ | The new setting.

Note

In Windows 95 and Windows NT, settings are stored in the registry. You can still use SetProfileString and GetProfileString$() to set and return settings from a text file with the name WIN.INI, but neither the system nor Word uses these settings. To access and change values in the registry from within WordBasic, you need to use GetPrivateProfileString$() and SetPrivateProfileString.

Example

This Windows example uses GetSystemInfo$() to determine the "sCountry" setting in the [intl] section of WIN.INI; SetProfileString changes the key's setting to "Sweden" if it does not already have that setting.

If GetSystemInfo$(29) <> "Sweden" Then
    SetProfileString "intl", "sCountry", "Sweden"
End If

See Also

GetPrivateProfileString$(), GetProfileString$(), SetPrivateProfileString, ToolsAdvancedSettings


SetSelRange

Syntax

SetSelRange Pos1, Pos2

Remarks

Selects the characters between character position Pos1 and character position Pos2. The character position at the start of the document is 0 (zero), the position after the first character is 1, the position after the second character is 2, and so on. All characters, including nonprinting characters, are counted. Hidden characters are counted even if they are not displayed. Note that the document does not scroll even if the selected characters are not visible in the document window.

Example

This example selects the first 20 characters in the document:

SetSelRange 0, 20

See Also

GetSelEndPos(), GetSelStartPos(), GetText$()


SetStartOfBookmark

Syntax

SetStartOfBookmark Bookmark1$ [, Bookmark2$]

Remarks

Marks the starting point of Bookmark1$ with Bookmark2$. If Bookmark2$ is omitted, Bookmark1$ is set to its own starting point.

Example

This example marks either end of the current paragraph with bookmarks:

SetStartOfBookmark "\Para", "BeginPara"
SetEndOfBookmark "\Para", "EndPara"

The bookmark " \ Para" is one of several predefined bookmarks that Word defines and updates automatically. For more information, see "Operators and Predefined Bookmarks" later in this part.

See Also

CopyBookmark, EditBookmark, SetEndOfBookmark


SetTemplateDirty

Syntax

SetTemplateDirty [Dirty]

Remarks

Controls whether Word recognizes a template as "dirty" — that is, changed since the last time the template was saved. When a dirty template is closed, Word displays a prompt asking if changes should be saved.

If you change a template and then set Dirty to 0 (zero), Word recognizes the template as unchanged, or "clean." When you close the template, Word neither displays a prompt nor saves changes.

Argument | Explanation
Dirty | Specifies whether to make the active template dirty: 0 (zero) The template is treated as clean. 1 or omitted The template is recognized as dirty.

Example

This example makes a temporary change in the active template's keyboard assignments (assigns the SmallCaps command to ctrl+shift+c (Windows) or COMMAND+SHIFT+C (Macintosh)) and then makes the template clean. When the template is closed, Word does not display a prompt or save changes.

ToolsCustomizeKeyboard .KeyCode = 835, .Context = 1, \
    .Name = "SmallCaps", .Add
SetTemplateDirty 0

See Also

IsDocumentDirty(), IsTemplateDirty(), SetDocumentDirty


Sgn()

Syntax

Sgn(n)

Remarks

Determines whether n is positive, negative, or 0 (zero).

Value | Explanation
0 (zero) | If n is 0 (zero)
–1 | If n is a negative number
1 | If n is a positive number

Example

This example compares two values. If the difference is negative, a message box is displayed.

maySales = 1200
juneSales = 1000
difference = juneSales - maySales
If Sgn(difference) = -1 Then
    MsgBox "Sales fell by" + Str$(Abs(difference)) + " dollars!"
End If

See Also

Abs(), Int(), Rnd()


ShadingPattern, ShadingPattern()

Syntax

ShadingPattern Type

ShadingPattern()

Remarks

The ShadingPattern statement applies a shading format to the selected paragraphs, table cells, or frame.

Argument | Explanation
Type | The shading format to apply: 0 [image] 13 1 [image] 14 2 [image] 15 3 [image] 16 4 [image] 17 5 [image] 18 6 [image] 19 7 [image] 20 8 [image] 21 9 [image] 22 10 [image] 23 11 [image] 24 12 [image] 25 On the Macintosh, formats 35 through 61 apply shading patterns in 2.5% increments: 35 2.5% 49 55% 36 7.5% 50 57.5% 37 12.5% 51 62.5% 38 15% 52 65% 39 17.5% 53 67.5% 40 22.5% 54 72.5% 41 27.5% 55 77.5% 42 32.5% 56 82.5% 43 35% 57 85% 44 37.5% 58 87.5% 45 42.5% 59 92.5% 46 45% 60 95% 47 47.5% 61 97.5% 48 52.5%

The ShadingPattern() function returns the following values.

Value | Explanation
0 (zero) | If none of the selection is shaded (the shading pattern is Clear)
–1 | If the selection contains a mixture of shading patterns
1 through 25 or 35 through 61 | If all the selection is formatted with the same shading pattern

See Also

FormatBordersAndShading


Shadow, Shadow()

Syntax

Shadow [On]

Shadow()

Remarks

On the Macintosh, the Shadow statement adds or removes the shadow character format for the current selection, or controls shadow formatting for characters to be inserted at the insertion point.

Argument | Explanation
On | Specifies whether to add or remove the shadow format: 1 Formats the selection with shadow 0 (zero) Removes the shadow format Omitted Toggles the shadow format

The Shadow() function returns the following values.

Value | Explanation
0 (zero) | If none of the selection is formatted with shadow
–1 | If part of the selection is formatted with shadow
1 | If all the selection is formatted with shadow

In Windows, Shadow and Shadow() are not available and generate errors.

See Also

FormatFont


Shell

Syntax

Shell Application$ [, WindowStyle]

Remarks

Starts another application (such as Microsoft Excel) or process (such as an MS-DOS batch file or executable file). In Windows, if the specified application is already running, Shell starts another instance of the same application; on the Macintosh, Shell activates the instance that is already running.

Note

In Word version 6.0 for Windows NT and Word version 7.0, you cannot depend on a program started with Shell to be finished loading before the instructions following the Shell statement in your macro are run. Any instructions that try to communicate with an application that has not finished loading will generate errors or unexpected results. To avoid this problem, you can use a For...Next loop to delay the instructions until the other application is loaded. For an example, see DDEInitiate.

Argument

Explanation

Application$

In Windows, the path and filename required to find the application, as well as any valid switches or arguments you choose to include, just as you would type them in the Run dialog box. To display a command window, specify Environ$("COMSPEC") (Windows 3.x), Environ$("COMMAND") (Windows 95), or Environ$("CMD") (Windows NT) as Application$.

On the Macintosh, Application$ is the application name or the signature returned by the MacID$() function. It is generally preferable to use the signature instead of the application name (for example, MacID$("XCEL") instead of "Microsoft Excel") because, unlike the application name, the signature never changes.

Application$ can be a document filename by itself, provided the file is associated with an application. (In Windows, a filename is associated with an application if its extension is registered in the [Extensions] section of the WIN.INI file (or the registry in Windows 95 and Windows NT). On the Macintosh, associations between filenames and applications are created automatically; you can use SetFileCreatorAndType to change an association.) Shell starts the associated application and opens the document.

Argument | Explanation
WindowStyle | In Windows, how the window containing the application should be displayed (some applications ignore this): 0 (zero) Minimized window (icon) 1 Normal window (current window size, or previous size if minimized) 2 Minimized window (for Microsoft Excel compatibility) 3 Maximized window 4 Deactivated window On the Macintosh, WindowStyle 0 (zero), 1, 2, and 3 are effectively the same: The application window (which has only one size) is activated. Set WindowStyle to 4 to start an application but leave Word active.

Examples

This Windows example starts Notepad and loads the document TORT.TXT:

Shell "Notepad TORT.TXT"

The following Macintosh example starts Microsoft Excel but leaves Word active:

Shell MacID$("XCEL"), 4

The following Windows example creates a text-only file (DOCLIST.TXT) that lists documents with the filename extension .DOC in the C:\WINWORD folder. You might use an instruction like this to create a file you can open later for sequential input. The "/c" switch ensures that control is returned to Word after the command line following "/c" is run.

Shell Environ$("COMSPEC") + " /c dir /b C:\WINWORD\*.DOC > DOCLIST.TXT"

See Also

AppActivate, DDEInitiate(), Environ$(), MacID$(), SetFileCreatorAndType


ShowAll, ShowAll()

Syntax

ShowAll [On]

ShowAll()

Remarks

The ShowAll statement displays all nonprinting characters, such as hidden text, tab marks, space marks, and paragraph marks. ShowAll corresponds to the All check box on the View tab in the Options dialog box (Tools menu).

Argument | Explanation
On | Specifies whether to hide or display all nonprinting characters: 1 Displays nonprinting characters. 0 (zero) Hides nonprinting characters. Omitted Toggles the display.

If your macro depends on nonprinting characters being visible in the document, it's a good idea to include ShowAll 1 as one of the first instructions.

The ShowAll() function returns the following values.

Value | Explanation
0 (zero) | The All check box is selected.
–1 | The All check box is cleared.

Example

This example displays all nonprinting characters and then searches for hidden text:

ShowAll 1
EditFindClearFormatting
EditFindFont .Hidden = 1
EditFind .Find = "", .Format = 1

See Also

ToolsOptionsView


ShowAllHeadings

Syntax

ShowAllHeadings

Remarks

In outline view, toggles between showing all text (headings and body text) and showing only headings. To be sure to display all text, include a ShowHeading9 instruction to display all headings without body text before running a ShowAllHeadings instruction.

ShowAllHeadings is available only in outline view and master document view; an error occurs if the statement is run in another view.

Example

This example switches to outline view and displays all text:

ViewOutline
ShowHeading9
ShowAllHeadings

See Also

OutlineCollapse, OutlineExpand, OutlineShowFirstLine, ShowHeading Number


ShowAnnotationBy

Syntax

ShowAnnotationBy ReviewerName$

Remarks

Displays the annotations by ReviewerName$ when the annotation pane is open. To display all annotations, specify "All Reviewers" as ReviewerName$. If ReviewerName$ does not match a reviewer in the list at the top of the annotation pane, Word displays all annotations.

Example

This example instructs Word to display annotations by Sara Levine only, and then displays the annotation pane:

ShowAnnotationBy "Sara Levine"
ViewAnnotations 1

See Also

ViewAnnotations


ShowClipboard

Syntax

ShowClipboard

Remarks

On the Macintosh, displays the Clipboard and its contents. In Windows, ShowClipboard is not available and generates an error; you can display the Clipboard with the ControlRun statement.

See Also

ControlRun


ShowHeadingNumber

Syntax

ShowHeading Number

Remarks

In outline view, shows all headings up to the specified heading level and hides subordinate headings and body text. Number is an integer from 1 to 9; you cannot use a variable in place of Number.

ShowHeading Number is available only in outline view and master document view; an error occurs if the statement is run in another view.

Example

This example takes advantage of outline view to easily reorder sections of the document. Consider an alphabetic reference whose headings, formatted as Heading 1 paragraphs, have gotten out of order; this macro can quickly alphabetize the sections. Collapsed headings and body text move with the Heading 1 paragraphs.

ViewOutline
ShowHeading1
EditSelectAll
TableSort .Order = 0

See Also

OutlineCollapse, OutlineExpand, OutlineShowFirstLine, ShowAllHeadings


ShowMe

Syntax

ShowMe

Remarks

Displays Help when there's more information available. The ShowMe statement corresponds to the Show Me button on the TipWizard® toolbar. In Word version 6.0, ShowMe is unavailable and generates an error.

See Also

AutomaticChange, Help


ShowNextHeaderFooter

Syntax

ShowNextHeaderFooter

Remarks

If the insertion point is in a header, moves to the next header within the
current section (for example, from an odd header to an even header) or to the
first header in the following section. If the insertion point is in a footer, ShowNextHeaderFooter moves to the next footer. If the insertion point is in the last header or footer in the last section of the document, or is not in a header or footer, an error occurs.

See Also

CloseViewHeaderFooter, FormatHeaderFooterLink, GoToHeaderFooter, ShowPrevHeaderFooter, ToggleHeaderFooterLink, ViewFooter, ViewHeader


ShowPrevHeaderFooter

Syntax

ShowPrevHeaderFooter

Remarks

If the insertion point is in a header, moves to the previous header within
the current section (for example, from an even header to an odd header) or
to the last header in the previous section. If the insertion point is in a footer, ShowNextHeaderFooter moves to the previous footer. If the insertion point is in the first header or footer in the first section of the document, or is not in a header or footer, an error occurs.

See Also

CloseViewHeaderFooter, FormatHeaderFooterLink, GoToHeaderFooter, ShowNextHeaderFooter, ToggleHeaderFooterLink, ViewFooter, ViewHeader


ShowVars

Syntax

ShowVars

Remarks

Displays a list of variables and their current values to help you debug the active macro. With ShowVars instructions, you can pause the macro and check the variables at exactly the points you want.

Example

This example defines the variables name$ and age as the items in the first line of the text file DATA.TXT. The variables are displayed in a dialog box where the values may be modified.

Open "DATA.TXT" For Input As #1
Input #1, Name$, Age
ShowVars

See Also

MsgBox, Print, Stop


ShrinkFont

Syntax

ShrinkFont

Remarks

Decreases the size of the selected text to the next available font size supported by the assigned printer. If the selection contains characters of varying font sizes, each size is reduced to the next available setting. If there is no selection, the smaller font size will be applied to new text.

Example

This macro inserts a line of increasingly smaller Z characters. Note how you can use a colon to place separate instructions on the same line. In this macro, ShrinkFont is executed three times in a single line.

Sub MAIN
FontSize 45
For count = 1 To 7
    Insert "Z"
    ShrinkFont : ShrinkFont : ShrinkFont
Next count
End Sub

See Also

Font, FontSize, FormatFont, GrowFont, ResetChar, ShrinkFontOnePoint


ShrinkFontOnePoint

Syntax

ShrinkFontOnePoint

Remarks

Decreases the font size of the selected text (or text to be inserted at the insertion point) by 1 point, whether or not the new size is supported by the selected printer. If more than one font size is included in the selection, each size is decreased by
1 point.

See Also

GrowFontOnePoint, ShrinkFont


ShrinkSelection

Syntax

ShrinkSelection

Remarks

Shrinks the selection to the next smaller unit of text. The progression is as follows: entire document, section, paragraph, sentence, word, insertion point.
The insertion point is the beginning of the original selection. Running ShrinkSelection when there is no selection produces a beep.

Unlike ExtendSelection, ShrinkSelection does not activate or require extend mode.

See Also

ExtendMode(), ExtendSelection


SizeToolbar

Syntax

SizeToolbar Toolbar$, Width

Remarks

Sizes a floating toolbar to the available width nearest the specified width. If the specified toolbar is anchored at the top, bottom, or either side of the Word window, SizeToolbar has no effect.

Argument | Explanation
Toolbar$ | The name of the toolbar as listed in the Toolbars dialog box (View menu)
Width | The width of the toolbar, in pixels

Example

This example sizes the Standard toolbar such that the buttons are displayed in two horizontal rows.

MoveToolbar "Standard", 0, 0, 40
SizeToolbar "Standard", 368

See Also

MoveToolbar


SkipNumbering, SkipNumbering()

Syntax

SkipNumbering

SkipNumbering()

Remarks

The SkipNumbering statement skips bullets or numbers for the selected paragraphs in a bulleted or numbered list created with the Bullets And Numbering command (Format menu). Subsequent bulleted or numbered paragraphs continue the current list, rather than starting a new list (and restarting the numbering in the case of a numbered list).

The SkipNumbering() function returns the following values.

Value | Explanation
0 (zero) | If the selected paragraphs are not skipped. The selected paragraphs may or may not be part of a bulleted or numbered list.
–1 | If some of the selected paragraphs are skipped and some are not, or the selection includes more than one level in a multilevel list.
1 | If all the selected paragraphs are skipped.

Example

This example selects the current paragraph and uses SkipNumbering() to determine whether the paragraph is skipped. If it is, numbering is reapplied to the paragraph.

EditGoTo "\Para"
If SkipNumbering() = 1 Then
    FormatBulletsAndNumbering
End If

See Also

DemoteList, FormatBulletsAndNumbering, PromoteList, RemoveBulletsNumbers


SmallCaps, SmallCaps()

Syntax

SmallCaps [On]

SmallCaps()

Remarks

The SmallCaps statement adds or removes the small caps character format for the current selection, or controls small caps formatting for characters to be inserted at the insertion point.

Argument | Explanation
On | Specifies whether to add or remove the small caps format: 1 Formats the selection as small caps. 0 (zero) Removes the small caps format. Omitted Toggles the small caps format.

The SmallCaps() function returns the following values.

Value | Explanation
0 (zero) | If none of the selection is formatted as small caps
–1 | If part of the selection is formatted as small caps
1 | If all the selection is formatted as small caps

Example

If the current paragraph (selected using the predefined bookmark " \ Para") has any small caps formatting, this example formats the entire paragraph as small caps:

SelType 1                        'Cancel selection, if any
EditGoTo "\Para"
If SmallCaps() = -1 Then SmallCaps 1

See Also

AllCaps, ChangeCase, FormatFont, UCase$()


SortArray

Syntax

SortArray ArrayName[$]() [, Order] [, From] [, To] [, SortType] [, SortKey]

Remarks

Performs an alphanumeric sort on the elements in the specified array. SortArray is especially useful for sorting arrays that fill list boxes in a custom dialog box. SortArray can sort one-dimensional or two-dimensional arrays; an error occurs
if the specified array has more than two dimensions.

Argument | Explanation
ArrayName[$]() | The one-dimensional or two-dimensional array to be sorted. Arrays with more than two dimensions are not sorted.
Order | The sorting order: 0 (zero) or omitted Ascending 1 Descending
From | Number of the first element to sort. The default is 0 (zero).
To | Number of the last element to sort (must be greater than From).
SortType | The kind of sort to perform (applies only to two-dimensional arrays): 0 (zero) or omitted Sort the "rows" in the array matrix. 1 Sort the "columns" in the array matrix.

Argument | Explanation
SortKey | The number of the row or column to sort by (applies only to two-dimensional arrays): 0 (zero) indicates the first row or column, 1 indicates the second, and so on. The default is 0 (zero). If SortType is 0 (zero), indicating a row sort, SortKey specifies the column that determines the sort. If SortType is 1, indicating a column sort, SortKey specifies the row that determines the sort.

Here are some examples of SortArray instructions, with descriptions of their effect.

Instruction | Description
SortArray ArrayTest() | Sort all the element(s) in the array ArrayTest() in ascending order, beginning with the element(s) numbered 0 (zero). If the array is two-dimensional, sort the rows of the array matrix, using the first column as the sort key.
SortArray List$(), 0, 1, 10 | Sort the elements numbered 1 through 10 in the array List$() in ascending order.
SortArray MailingList$(), 1, 1, 20, 0, 1 | Sort the elements numbered 1 through 20 in the two-dimensional array MailingList$() in descending order. Sort rows, using the second column as the sort key.
SortArray Table(), 0, 0, 10, 1, 3 | Sort the elements numbered 0 (zero) through 10 in the two-dimensional array Table() in ascending order. Sort columns, using the fourth row as the sort key.

Note

Although the SortArray arguments other than ArrayName[$]() are optional, you cannot omit arguments between arguments that you do include.
For example, SortArray Test(), 0, 0, 2, 0, 1 is a valid instruction, but SortArray Test(), 0, , , , 1 is not valid and will not sort the array.

Examples

This example creates an array containing the names of all the bookmarks in the active document and then sorts the names. When first defined, the variable marks$(0) represents the name of the first bookmark added to the document. After the array is sorted, marks$(0) represents the first name in an alphabetic list of the bookmark names.

size = CountBookmarks() - 1
Dim marks$(size)
For count = 0 To size
    marks$(count) = BookmarkName$(count + 1)
Next
SortArray(marks$())

The following example opens a text file containing a list of 100 names and addresses. There are five fields for the names and addresses: the first field is for the name, the second for the street address, the third for the city or town, the fourth for the state or province, and the fifth for the postal code. The array MailList$() is defined to accommodate the names and addresses, which are read into the array. The array is then sorted by postal code in descending order (so that rows with the highest postal code are first). The sorted names and addresses are then written back to the file. Note that you could perform the same sort by opening the file in a document window and using the TableSort statement.

Open "LIST.TXT" For Input As #1
Dim MailList$(99, 4)
For x = 0 To 99
    Read #1, MailList$(x, 0), MailList$(x, 1), MailList$(x, 2), \
        MailList$(x, 3), MailList$(x, 4)
Next
Close #1
SortArray MailList$(), 1, 0, 99, 0, 4
Open "NEWLIST.TXT" For Output As #1
For x = 0 To 99
    Write #1, MailList$(x, 0), MailList$(x, 1), MailList$(x, 2), \
            MailList$(x, 3), MailList$(x, 4)
Next
Close #1

See Also

Dim, TableSort


SpacePara1, SpacePara1()

Syntax

SpacePara1

SpacePara1()

Remarks

The SpacePara1 statement single-spaces the selected paragraphs. The exact spacing is determined by the font size of the largest characters in the paragraph.

The SpacePara1() function returns the following values.

Value | Explanation
0 (zero) | If none of the selection is single-spaced
–1 | If part of the selection is single-spaced
1 | If all the selection is single-spaced

See Also

CloseUpPara, FormatParagraph, OpenUpPara, SpacePara15, SpacePara2


SpacePara15, SpacePara15()

Syntax

SpacePara15

SpacePara15()

Remarks

The SpacePara15 statement formats the selected paragraphs with 1.5 line spacing. The exact spacing is determined by the font size of the largest characters in the paragraph plus 6 points.

The SpacePara15() function returns the following values.

Value | Explanation
0 (zero) | If none of the selection is formatted with 1.5 line spacing
–1 | If part of the selection is formatted with 1.5 line spacing
1 | If all the selection is formatted with 1.5 line spacing

See Also

CloseUpPara, FormatParagraph, OpenUpPara, SpacePara1, SpacePara2


SpacePara2, SpacePara2()

Syntax

SpacePara2

SpacePara2()

Remarks

The SpacePara2 statement double-spaces the selected paragraphs. The exact spacing is determined by the point size of the largest characters in the paragraph plus 12 points.

The SpacePara2() function returns the following values.

Value | Explanation
0 (zero) | If none of the selection is double-spaced
–1 | If part of the selection is double-spaced
1 | If all the selection is double-spaced

See Also

CloseUpPara, FormatParagraph, OpenUpPara, SpacePara1, SpacePara15


SpellChecked, SpellChecked()

Syntax

SpellChecked [On]

SpellChecked()

Remarks

The SpellChecked statement identifies the selected text as either checked for spelling errors or not checked. If no text is selected, SpellChecked and SpellChecked() have no effect.

In Word version 6.0, SpellChecked and SpellChecked() are unavailable and generate errors.

Argument | Explanation
On | Specifies whether to identify the selection as checked or not checked for spelling errors: 1 Identifies the selection as checked 0 (zero) Identifies the selection as not checked Omitted Toggles the setting

The SpellChecked() function returns the following values.

Value | Explanation
0 (zero) | If the selection is not checked for spelling
-1 | If only part of the selection is checked for spelling
1 | If all the selection is checked for spelling

See Also

ToolsSpelling, DocumentHasMisspellings()


Spike

Syntax

Spike

Remarks

Deletes the current selection and adds it to a built-in AutoText entry called the Spike. Items added to the Spike are separated by paragraph marks.

You can use the Spike to collect text and graphics from various locations in one or more documents and then insert them all together using InsertSpike, which clears the Spike. To insert the Spike contents without clearing the Spike, you use EditAutoText.

Example

This example opens RESEARCH.DOC, uses Spike to collect all the Heading 1 paragraphs, closes RESEARCH.DOC without saving changes, and then inserts the headings into the active document. On the Macintosh, substitute a path such as HD:DOCUMENTS:RSRCH PAPER.

FileOpen .Name = "C:\DOCS\RESEARCH.DOC", .ReadOnly = 1
EditFindClearFormatting
EditFindStyle .Style = "Heading 1"
EditFind .Find = "", .Direction = 0, .Format = 1
While EditFindFound()
    Spike
    ParaDown
    EditFind .Find = "", .Direction = 0, .Format = 1
Wend
FileClose 2                'Close without saving
InsertSpike                'Empty the Spike at insertion point

See Also

EditAutoText, EditCut, InsertSpike


SplitSubdocument

Syntax

SplitSubdocument

Remarks

Divides an existing subdocument into two subdocuments at the same level in master document or outline view. The division is made at the insertion point (or the beginning of the selection, if there is one). If the active document is not in master document or outline view, or the insertion point is not at the beginning of a paragraph within a subdocument, an error occurs.

See Also

CreateSubdocument, InsertSubdocument, MergeSubdocument, OpenSubdocument, RemoveSubdocument, ViewMasterDocument


StartOfColumn, StartOfColumn()

Syntax

StartOfColumn [Select]

StartOfColumn([Select])

Remarks

The StartOfColumn statement moves the insertion point or extends the selection (if Select is nonzero) to the top of the table column containing the insertion point or selection. If the selection extends over more than one column, the insertion point moves to the top of the column containing the end of the selection. If the insertion point or selection is not in a table, an error occurs.

Note

If the first row in the table does not have a cell that corresponds to the column that contains the current selection — for example, if you have deleted or merged cells in the first row — StartOfColumn moves the insertion point to the end of the first row in the table.

The StartOfColumn() function behaves the same as the statement and also returns one of the following values.

Value | Explanation
0 (zero) | If the insertion point was not moved or the selection was not extended (that is, if it was already at the top of the column)
–1 | If the insertion point was moved or the selection was extended

If the insertion point is not in a table, StartOfColumn and StartOfColumn() generate an error.

Example

This example moves the insertion point from anywhere in the table to the end of the first row:

TableSelectRow
StartOfColumn

See Also

EndOfColumn, StartOfRow


StartOfDocument, StartOfDocument()

Syntax

StartOfDocument [Select]

StartOfDocument([Select])

Remarks

The StartOfDocument statement moves the insertion point or, if Select is nonzero, the active end of the selection (the end that moves when you press CTRL+SHIFT+HOME (Windows) or COMMAND+SHIFT+HOME (Macintosh)) to the beginning of the document.

The StartOfDocument() function behaves the same as the statement and also returns one of the following values.

Value | Explanation
0 (zero) | If the insertion point or the active end of the selection was not moved (for example, if it was already at the start of the document)
–1 | If the insertion point or the active end of the selection was moved

Example

This example moves the insertion point to the start of the document and then prepares Word to begin a replace operation:

StartOfDocument
EditFindClearFormatting
EditReplaceClearFormatting
'Instructions that perform a replace operation go here

See Also

AtStartOfDocument(), EndOfDocument


StartOfLine, StartOfLine()

Syntax

StartOfLine [Select]

StartOfLine ([Select])

Remarks

The StartOfLine statement moves the insertion point or, if Select is nonzero, the active end of the selection (the end that moves when you press SHIFT+HOME) to the beginning of the current line or the line that contains the active end of the selection.

The StartOfLine() function behaves the same as the statement and also returns one of the following values.

Value | Explanation
0 (zero) | If the insertion point or the active end of the selection was not moved (that is, if it was already at the beginning of the line)
–1 | If the insertion point or the active end of the selection was moved

Avoid using StartOfLine by itself to go to the beginning of a paragraph unless you are sure that the paragraph is a single line (for example, a word in a list of words).

Example

This example moves the insertion point to the start of the current paragraph regardless of the length of the paragraph or the position of the insertion point within it. The first instruction selects the entire paragraph.

EditGoTo "\Para"
StartOfLine

The bookmark "\Para" is one of several predefined bookmarks that Word defines and updates automatically. For more information on predefined bookmarks, see "Operators and Predefined Bookmarks" later in this part.

See Also

EndOfLine, ParaUp, StartOfRow


StartOfRow, StartOfRow()

Syntax

StartOfRow [Select]

StartOfRow ([Select])

Remarks

The StartOfRow statement moves the insertion point or extends the selection (if Select is nonzero) to the beginning of the first cell in the table row containing the insertion point. If the selection extends over more than one row, the insertion point moves or the selection is extended to the first cell of the first row in the selection. If the insertion point or selection is not in a table, an error occurs.

The StartOfRow() function behaves the same as the statement and also returns one of the following values.

Value | Explanation
0 (zero) | If the insertion point was not moved or the selection was not extended (that is, if it was already at the beginning of the row)
–1 | If the insertion point was moved or the selection was extended

Example

This example moves the insertion point from anywhere in the table to the beginning of the first cell:

StartOfRow
StartOfColumn

See Also

EndOfRow, StartOfColumn, StartOfLine


StartOfWindow, StartOfWindow()

Syntax

StartOfWindow [Select]

StartOfWindow([Select])

Remarks

The StartOfWindow statement moves the insertion point or, if Select is nonzero, the active end of the selection (the end that moves when you press CTRL+SHIFT+PAGE UP (Windows) or COMMAND+SHIFT+PAGE UP (Macintosh)) to the upper-left corner of the contents currently visible in the document window.

The StartOfWindow() function behaves the same as the statement and also returns one of the following values.

Value | Explanation
0 (zero) | If the insertion point or the active end of the selection was not moved (that is, if it was already at the upper-left corner of the window)
–1 | If the insertion point or the active end of the selection was moved

Example

This example selects the visible contents of the active document window:

StartOfWindow
EndOfWindow 1

See Also

EndOfWindow, StartOfDocument


Stop

Syntax

Stop [SuppressMessage]

Remarks

Stops a running macro. If SuppressMessage is –1, no message appears. Otherwise, Word displays a message box that says the macro was interrupted. When Word encounters a Stop instruction in a macro that is open in a macro-editing window, you can click the Continue button on the Macro toolbar to continue running the macro.

See Also

ShowVars


Str$()

Syntax

Str$(n)

Remarks

Returns the string representation of the value n. If n is a positive number, Str$() returns a string with a leading space. To remove the leading space, use LTrim$().

Examples

This example uses Str$() to make a numeric variable acceptable as part of a string in a message box. Note that no space is needed after "were" because Str$() has included a space at the beginning of a$.

sales = 2400
a$ = Str$(sales)
MsgBox "Sales this week were" + a$ + " dollars."

You can use the following function to return string representations of numeric variables without the leading space:

Function MyString$(Num)
    If Num >= 0 Then
        MyString$ = LTrim$(Str$(Num))
    Else
        MyString$ = Str$(Num)
    End If
End Function

In another subroutine, String1$ = MyString$(25) is an example of an instruction that calls the preceding function.

See Also

Chr$(), InStr(), Left$(), LTrim$(), Mid$(), Right$(), RTrim$(), String$(), Val()


Strikethrough, Strikethrough()

Syntax

Strikethrough [On]

Strikethrough()

Remarks

The Strikethrough statement adds or removes the strikethrough character format for the current selection, or controls strikethrough formatting for characters to be inserted at the insertion point.

Argument | Explanation
On | Specifies whether to add or remove the strikethrough format: 1 Formats the selection as strikethrough. 0 (zero) Removes the strikethrough format. Omitted Toggles the strikethrough format.

The Strikethrough() function returns the following values.

Value | Explanation
0 (zero) | If none of the selection is formatted as strikethrough
–1 | If part of the selection is formatted as strikethrough
1 | If all the selection is formatted as strikethrough

When revision marking is activated, Word uses strikethrough to mark deleted text. However, Word does not recognize text formatted with the Strikethrough statement as deleted. If you want to mark the selected text as deleted for the purpose of revision marks, use the following instructions:

ToolsRevisions .MarkRevisions = 1
EditClear

See Also

FormatFont, ToolsRevisions


String$()

Syntax

String$(Count, Source$)

String$(Count, CharCode)

Remarks

Returns the first character in Source$ or the character corresponding to the character code CharCode, repeated Count times. Count can be as large as 65,280.

Examples

This instruction prints the text "ddddd" in the status bar:

Print String$(5, 100)

This example inserts a row of 40 characters with the character code 164 before the first selected paragraph:

SelType 1 : ParaDown : ParaUp    'Go to start of paragraph
Insert String$(40, 164)            'Insert character string
InsertPara                        'Insert a paragraph mark

See Also

Asc(), Chr$(), InStr(), Str$()


Style

Syntax

Style StyleName$

Remarks

Applies a style to the selected paragraphs. If StyleName$ does not exist, an error occurs. To create a style, use FormatStyle.

Example

This example finds the first instance of the word "Overview" followed by a paragraph mark and applies the Heading 1 style:

StartOfDocument
EditFind .Find = "Overview^p", .Direction = 0, .MatchCase = 1, \
    .Format = 0
If EditFindFound() Then Style "Heading 1"

See Also

FormatStyle, NormalStyle, StyleName$()


StyleDesc$()

Syntax

StyleDesc$(StyleName$)

Remarks

Returns the description of the specified style in the active document. For example, a typical description for the Heading 1 style is "Normal + Arial®, 14 pt, Bold, Space Before 12 pt After 3 pt." If StyleName$ does not exist, StyleDesc$() returns an empty string ("").

Example

This example displays the description of the Heading 1 style in a message box:

infostyle$ = "Heading 1"
MsgBox StyleDesc$(infostyle$), "Description for " + infostyle$

See Also

CountStyles(), FormatStyle, StyleName$()


StyleName$()

Syntax

StyleName$([Count,] [Context,] [All])

Remarks

Returns the name of the specified style or, if no style is specified, the name of the style applied to the first paragraph in the selection. Note that if the insertion point or selection is within text formatted with a character style, StyleName$() returns the name of the character style (not the paragraph style). For a method of returning the paragraph style in this case, see the second example in this reference entry.

Argument | Explanation
Count | The position of the style in an alphabetic list of styles for the document or template, according to the value of Context. The number can range from 1 to CountStyles(), which returns the total number of styles (both character and paragraph) in the specified context. If Count is 0 (zero) or omitted, the name of the current style is returned.
Context | The list of styles to use: 0 (zero) or omitted Active document 1 Active template
All | Specifies whether to include built-in styles: 0 (zero) or omitted Built-in styles are excluded. 1 Built-in styles are included. Note that Word contains 75 built-in styles, and that two of those built-in styles are defined by default: Default Paragraph Font and Normal.

Examples

This example checks to see if the first style in the list of document styles is used in the document. If the style is not used, a message box is displayed:

FirstStyle$ = StyleName$(1)
StartOfDocument
EditFindClearFormatting
EditFindStyle .Style = FirstStyle$
EditFind .Find = "", .WholeWord = 0, .MatchCase = 0, .Direction = 0, \
    .Format = 1, .Wrap = 0
If EditFindFound() = 0 Then
    MsgBox "Style " + FirstStyle$ + " is not in use."
End If

The following example ensures that StyleName$() returns the underlying paragraph style, regardless of any character styles applied to the current selection:

EditBookmark "tmp"
SelType 1
reset$ = StyleName$()
Style "Default Paragraph Font"
parastyle$ = StyleName$()
Style reset$
EditGoto "tmp"
EditBookmark "tmp", .Delete

See Also

CountStyles(), FormatStyle, StyleDesc$()


Sub...End Sub

Syntax

Sub SubName[(ArgumentList)]
Series of instructions
End Sub

Remarks

Defines a subroutine. A subroutine is a series of instructions that can be called repeatedly from the main subroutine and can make your macros shorter and easier to debug.

Argument | Explanation
SubName | The name of the subroutine.
ArgumentList | A list of arguments, separated by commas. You can then use these arguments in the subroutine. Values, string and numeric variables, and array variables are all valid arguments.

Subroutines must appear outside the main subroutine — generally, you add subroutines after the End Sub instruction that ends the main subroutine. You can call a subroutine not only from the macro's main subroutine, but also from other subroutines and even other macros. For more information about using subroutines, including how to share variables and pass arguments between subroutines, see Chapter 4, "Advanced WordBasic," in Part 1, "Learning WordBasic."

Example

In this macro, the main subroutine calls the GoBeep subroutine, passing the number of times to beep through the variable numBeeps:

Sub MAIN
    numBeeps = 3
    GoBeep(numBeeps)
End Sub

Sub GoBeep(count)
    For n = 1 To count
        Beep
        For t = 1 To 100 : Next        'Add time between beeps
    Next
End Sub

If the GoBeep subroutine were in a macro named LibMacros, the call to the subroutine would be as follows:

Sub MAIN
    numBeeps = 3
    LibMacros.GoBeep(numBeeps)
End Sub

For more information about using subroutines in different macros, see Chapter 4, "Advanced WordBasic," in Part 1, "Learning WordBasic."

See Also

Call, Function ¼ End Function


Subscript, Subscript()

Syntax

Subscript [On]

Subscript()

Remarks

The Subscript statement adds or removes the subscript character format for the current selection, or controls subscript formatting for characters to be inserted at the insertion point.

Argument | Explanation
On | Specifies whether to add or remove the subscript format: 1 Formats the selection as subscript. 0 (zero) Removes the subscript format. Omitted Toggles the subscript format.

The Subscript() function returns the following values.

Value | Explanation
0 (zero) | If none of the selection is formatted as subscript
–1 | If part of the selection is formatted as subscript
1 | If all the selection is formatted as subscript

See Also

FormatFont, Superscript


Superscript, Superscript()

Syntax

Superscript [On]

Superscript()

Remarks

The Superscript statement adds or removes the superscript character format for the current selection, or controls superscript formatting for characters to be inserted at the insertion point.

Argument | Explanation
On | Specifies whether to add or remove the superscript format: 1 Formats the selection as superscript. 0 (zero) Removes the superscript format. Omitted Toggles the superscript format.

The Superscript() function returns the following values.

Value | Explanation
0 (zero) | If none of the selection is formatted as superscript
–1 | If part of the selection is formatted as superscript
1 | If all the selection is formatted as superscript

See Also

FormatFont, Subscript


SymbolFont

Syntax

SymbolFont [TextToInsert$]

Remarks

Formats the selected text with the Symbol font or inserts the specified text formatted with the Symbol font at the insertion point. If no text is specified or selected, the SymbolFont statement has no effect.

See Also

FormatFont, InsertSymbol


TabLeader$()

Syntax

TabLeader$(Pos)

Remarks

Returns the leader character of the custom tab stop at the position Pos, which is given in points (72 points = 1 inch). If more than one paragraph is selected, TabLeader$() evaluates the settings in the first paragraph.

There are three cases in which TabLeader$() returns an empty string (""): if there is no tab stop at the position Pos, if the tab stop is a default tab stop, or if the document is in outline view. If there is a custom tab stop at Pos, TabLeader$() returns one of the following values.

Value | Explanation
(space) | No leader (corresponds to a tab leader set to "None")
. | Period
- | Hyphen
_ | Underscore

To change the tab leader, use FormatTabs.

Example

This example determines whether a tab stop at the three-fourths–inch position has an underscore leader character. If it does, the FormatTabs instruction changes the leader character to "None."

ViewNormal
If TabLeader$(54) = "_" Then
    FormatTabs .Position = "54 pt", .Leader = 0
End If

See Also

FormatTabs, NextTab(), PrevTab(), TabType()


TableAutoFormat

Syntax

TableAutoFormat [.Format = number] [, .Borders = number] [, .Shading = number] [, .Font = number] [, .Color = number] [, .AutoFit = number] [, .HeadingRows = number] [, .FirstColumn = number] [, .LastRow = number] [, .LastColumn = number]

Remarks

Applies a predefined look to a table. The arguments for the TableAutoFormat statement correspond to the options in the Table AutoFormat dialog box (Table menu).

Argument | Explanation
.Format | The format to apply: 0 (zero) corresponds to the first format listed in the Formats list box ("none"), 1 corresponds to the second format, and so on.
.Borders | If 1, applies the border properties of the specified format.
.Shading | If 1, applies the shading properties of the specified format.
.Font | If 1, applies the font properties of the specified format.
.Color | If 1, applies the color properties of the specified format.
.AutoFit | If 1, decreases the width of the table columns as much as possible without changing the way text wraps in the cells.
.HeadingRows | If 1, applies the heading-row properties of the specified format.
.FirstColumn | If 1, applies the first-column properties of the specified format.
.LastRow | If 1, applies the last-row properties of the specified format.
.LastColumn | If 1, applies the last-column properties of the specified format.

Example

This example applies all the properties of the Classic 2 table format to the table containing the insertion point. If the insertion point is not in a table, a message box is displayed.

If SelInfo(12) = -1 Then        'If insertion point is in a table
    TableAutoFormat .Format = 5, .Borders = 1, .Shading = 1, \
    .Font = 1, .Color = 1, .AutoFit = 1, .HeadingRows = 1, \
    .FirstColumn = 1, .LastRow = 0, .LastColumn = 1
Else
    MsgBox "The insertion point is not in a table."
End If

See Also

TableColumnWidth, TableHeadings, TableRowHeight, TableUpdateAutoFormat


TableAutoSum

Syntax

TableAutoSum

Remarks

Inserts an = (Formula) field that calculates and displays the sum of the values
in table cells above or to the left of the cell containing the insertion point. For information on how Word determines which values to add, see TableFormula.

See Also

TableFormula


TableColumnWidth

Syntax

TableColumnWidth [.ColumnWidth = number or text] [, .SpaceBetweenCols = number or text] [, .PrevColumn] [, .NextColumn] [, .AutoFit] [, .RulerStyle = number]

Remarks

Sets the column width and the space between columns for the selected cells. The arguments for the TableColumnWidth statement correspond to the options on the Column tab in the Cell Height And Width dialog box (Table menu).

Argument | Explanation
.ColumnWidth | The width to apply to the selected cells or columns, in points or a text measurement (.RulerStyle specifies how other columns are affected).
.SpaceBetweenCols | The distance between the text in each column, in points or a text measurement.
.PrevColumn | After the actions (if any) specified by the preceding arguments are carried out, selects the previous column.
.NextColumn | After the actions (if any) specified by the preceding arguments are carried out, selects the next column.
.AutoFit | Decreases the width of the selected cells as much as possible without changing the way text wraps in the cells.
.RulerStyle | Specifies how Word adjusts the table: 0 (zero) If there is a selection, only the selected cells are changed. Row width is not preserved. If there is no selection, Word sizes all cells in the selected column. 1 Word preserves row width by adjusting all cells to the right of the selection in proportion to their widths. 2 Word preserves row width by adjusting cells in the column immediately to the right of the selection only. 3 Word preserves row width by adjusting all cells to the right of the selection, assigning them each the same width. 4 Only the cell containing the insertion point (or the first cell in the selection) is changed. Row width is not preserved.

Example

For each table in the document, this example adjusts the width of the first column to 2 inches and the second column to 3 inches. The first TableColumnWidth instruction both formats the first column and moves the selection to the second column.

StartOfDocument
While ParaDown()
    If SelInfo(12) =  - 1 Then    'If insertion point is in a table
        StartOfRow
        TableSelectColumn
        TableColumnWidth .ColumnWidth = "2 in", .RulerStyle = 0, \
                .NextColumn
        If SelInfo(18) > 1 Then    'If more than one column
                TableColumnWidth .ColumnWidth = "3 in", .RulerStyle = 0
        End If
        LineDown
    End If
Wend

See Also

SelInfo(), TableDeleteColumn, TableRowHeight, TableSelectColumn


TableDeleteCells

Syntax

TableDeleteCells .ShiftCells = number

Remarks

Deletes the selected cells. If the insertion point or selection is not within a table, an error occurs.

Argument | Explanation
.ShiftCells | Sets the direction to shift the remaining cells: 0 (zero) or omitted Shift the cells left. 1 Shift the cells up. 2 Delete the entire row. 3 Delete the entire column.

Example

This example deletes the first cell in a table if the table contains more than two rows:

If SelInfo(15) > 2 Then
    TableSelectTable
    StartOfRow
    TableDeleteCells
End If

See Also

SelInfo(), TableDeleteColumn, TableDeleteRow


TableDeleteColumn

Syntax

TableDeleteColumn

Remarks

Deletes the table column containing the insertion point, or deletes all columns containing part of the selection. If the insertion point or selection is not within a table, an error occurs.

Example

This example deletes the first column in a table:

StartOfRow
TableDeleteColumn

See Also

SelInfo(), TableDeleteCells, TableDeleteRow


TableDeleteRow

Syntax

TableDeleteRow

Remarks

Deletes the row containing the insertion point, or deletes all rows containing part of the selection. If the insertion point or selection is not within a table, an error occurs.

Example

This example deletes the last row in a table if the table contains more than two rows:

If SelInfo(15) > 2 Then
    EndOfColumn
    TableDeleteRow
End If

See Also

SelInfo(), TableDeleteCells, TableDeleteColumn


TableFormula

Syntax

TableFormula [.Formula = text] [, .NumFormat = text]

Remarks

Inserts an = (Formula) field containing the specified formula at the insertion point. If the insertion point is in a table cell that already contains an = (Formula) field, the existing field is replaced with a field containing the specified formula.

Argument | Explanation
.Formula | The mathematical formula you want the = (Formula) field to evaluate. Spreadsheet-type references to table cells are valid. For example, "=SUM(a4:c4)" specifies the first three values in the fourth row. For more information on valid formulas, display the Formula dialog box (Table menu), and then choose the Help button.
.NumFormat | A format for the result of the = (Formula) field. For sample formats, choose Formula from the Table menu and review the list in the Number Format box.

If the insertion point is in a table, specifying .Formula is optional so long as there is at least one cell containing a value above or to the left of the cell containing the insertion point. If the cells above contain values, the inserted field is {=SUM(ABOVE)}; if the cells to the left contain values, the inserted field is {=SUM(LEFT)}. If the cells above and the cells to the left contain values, Word uses the following rules to determine which SUM function to insert:

  • If the cell immediately above the insertion point contains a value, Word inserts {=SUM(ABOVE)}.
  • If the cell immediately above does not contain a value and the cell immediately to the left does, Word inserts {=SUM(LEFT)}.
  • If neither adjoining cell contains a value, Word inserts {=SUM(ABOVE)}.

If you don't specify .Formula and all the cells above and to the left of the insertion point are empty, a field error occurs.

Example

This example adds a row to the end of the table, moves the insertion point to the last cell, and then inserts an = (Formula) field that adds the values in the last column:

TableSelectTable
EndOfRow
NextCell
EndOfRow
TableFormula .Formula = "=SUM(ABOVE)"

See Also

InsertField, TableAutoSum, ToolsCalculate


TableGridlines, TableGridlines()

Syntax

TableGridlines [On]

TableGridlines()

Remarks

The TableGridlines statement displays or hides table gridlines.

Argument | Explanation
On | Specifies whether to display or hide table gridlines: 0 (zero) Hides table gridlines. 1 Displays table gridlines. Omitted Toggles the option on or off.

The TableGridlines() function returns the following values.

Value | Explanation
0 (zero) | If table gridlines are hidden
–1 | If table gridlines are displayed

Example

This example displays table gridlines if they are not already showing. You could use this instruction as part of an AutoOpen macro, so that whenever documents based on a certain template are opened, table gridlines are displayed.

If Not TableGridlines() Then TableGridlines 1

See Also

ToolsOptionsView


TableHeadings, TableHeadings()

Syntax

TableHeadings [On]

TableHeadings()

Remarks

The TableHeadings statement adds or removes the table heading format for the selected rows. Rows formatted as table headings are repeated when a table spans more than one page.

Argument | Explanation
On | Specifies whether to add or remove the table heading format: 0 (zero) Removes the table heading format. 1 Adds the table heading format. Omitted Toggles the table heading format.

The TableHeadings() function returns the following values.

Value | Explanation
0 (zero) | If none of the selected rows are formatted as table headings
–1 | If one or more but not all of the selected rows are formatted as table headings
1 | If all the selected rows are formatted as table headings

See Also

TableRowHeight


TableInsertCells

Syntax

TableInsertCells [.ShiftCells = number]

Remarks

Inserts cells above or to the left of the selected range of cells in a table. If the insertion point or selection is not in a table, an error occurs.

Argument | Explanation
.ShiftCells | Sets the direction to shift the cells in the selected range: 0 (zero) Shift the cells right. 1 or omitted Shift the cells down. 2 Insert an entire row. 3 Insert an entire column.

Example

This example selects the current cell (using the predefined bookmark "\Cell") and the cell below it, and then inserts two new cells. The existing cells are shifted to the right. The If control structure makes sure the selection is entirely within a table before running TableInsertCells.

EditGoTo "\Cell"
LineDown 1, 1
If SelInfo(12) = -1 Then
    TableInsertCells .ShiftCells = 0
Else
    MsgBox "Selection extends outside the table."
End If

See Also

SelInfo(), TableInsertColumn, TableInsertRow


TableInsertColumn

Syntax

TableInsertColumn

Remarks

Inserts a column to the left of the column that contains the insertion point, or inserts as many columns as are selected to the left of the selection. If the insertion point or selection is not in a table, an error occurs.

Example

This example adds a column to the end of the table containing the insertion point:

TableSelectTable                'Select the entire table
StartOfColumn                'Move to the end of the first row
TableInsertColumn            'Add a new column

See Also

TableInsertCells, TableInsertRow


TableInsertRow

Syntax

TableInsertRow [.NumRows = number]

Remarks

Inserts a row above the selected rows or above the row that contains the insertion point. If the insertion point or any part of the selection is not in a table, an error occurs. If the insertion point immediately follows a table, TableInsertRow inserts a row at the end of the table.

Argument | Explanation
.NumRows | The number of rows you want to add. If .NumRows is 0 (zero) or omitted, TableInsertRow inserts above the selection as many rows as are selected.

Examples

The following example adds a row to the end of a table:

TableSelectTable
CharRight
TableInsertRow

This example adds two new rows at the top of a table:

TableSelectTable
StartOfRow
TableInsertRow .NumRows = 2

See Also

TableInsertCells, TableInsertColumn


TableInsertTable

Syntax

TableInsertTable [.ConvertFrom = number] [, .NumColumns = number] [, .NumRows = number] [, .InitialColWidth = number or text] [, .Wizard] [, .Format = number] [, .Apply = number]

Remarks

Converts a series of selected paragraphs into a table or inserts an empty table if there is no selection. If the insertion point is already in a table, an error occurs.

Argument | Explanation
.ConvertFrom | Specifies the character used to separate items of text into cell contents: 0 (zero) Paragraph marks (Word places every other paragraph in the second column) 1 Tab characters 2 Commas
.NumColumns | Number of columns in the table.

Argument | Explanation
.NumRows | Number of rows in the table.
.InitialColWidth | The initial width for each column, in points or a text measurement. If omitted, column width is calculated so that the table stretches from margin to margin.
.Wizard | Runs the Table wizard.
.Format | One of the predefined formats listed in the Table AutoFormat dialog box (Table menu): 0 (zero) corresponds to the first format listed in the Formats box ("none"), 1 corresponds to the second format, and so on.
.Apply | Specifies which attributes of the format specified by .Format to apply to the table. Use the sum of any combination of the following values: 0 None 1 Borders 2 Shading 4 Font 8 Color 16 AutoFit 32 Heading Rows 64 Last Row 128 First Column 256 Last Column

Example

This example inserts a three-column, five-row table:

TableInsertTable .NumColumns = 3, .NumRows = 5, \
        .InitialColWidth = "2 in"

See Also

TableAutoFormat, TableToText, TextToTable


TableMergeCells

Syntax

TableMergeCells

Remarks

Merges selected table cells in the same row into a single cell. Selections can extend over multiple rows; however, Word only merges cells in the same row. TableMergeCells generates an error if Word cannot merge cells — for example,
if only one cell is selected.

Example

This example either merges the currently selected cells or displays a message box if the command cannot be performed:

On Error Goto No
TableMergeCells
No:
If Err = 509 Then
    MsgBox "Sorry, can't merge."
End If

See Also

TableSplitCells


TableRowHeight

Syntax

TableRowHeight [.RulerStyle = text] [, .LineSpacingRule = number] [, .LineSpacing = number or text] [, .LeftIndent = number or text] [, .Alignment = number] [, .AllowRowSplit = number] [, .PrevRow] [, .NextRow]

Remarks

Sets formats for the selected rows in a table. The arguments for the TableRowHeight statement correspond to the options on the Row tab in the Cell Height And Width dialog box (Table menu).

Argument | Explanation
.RulerStyle | When the left indent is changed, specifies how Word adjusts the table: 0 (zero) Word moves cells to the right. 1 Word preserves the position of the right edge of the table by narrowing all cells in the selected rows in proportion to their widths. 2 Word preserves the position of the right edge of the table by narrowing cells in the first column only. 3 Word preserves the position of the right edge of the table by narrowing all cells in the selected rows, assigning them each the same width. 4 Word indents only the row containing the insertion point (or the first row in the selection). When row height is changed, specifies which rows are affected: 0 (zero), 1, 2, or 3 If there is a selection, only the selected rows are affected. If there is no selection, all rows are affected. 4 Only the row containing the insertion point or the first row in the selection is affected.

Argument | Explanation
.LineSpacingRule | The rule for determining the height of the rows: 0 (zero) Auto 1 At Least 2 Exactly
.LineSpacing | The height of the rows, in points or a text measurement.
.LeftIndent | The distance between the left edge of the text and the left margin, in points or a text measurement.
.Alignment | The alignment of the rows: 0 (zero) Left 1 Center 2 Right
.AllowRowSplit | If 1, allows text in the row to be divided at a page break.
.PrevRow | Selects the previous row for formatting.
.NextRow | Selects the next row for formatting.

Example

This example sets a minimum row height of 2 lines for the selected rows and indents them 1 inch from the left margin:

TableRowHeight .RulerStyle = "0", .LeftIndent = "1 in", \
    .LineSpacingRule = 1, .LineSpacing = "2 li", .Alignment = 0

See Also

TableColumnWidth, TableHeadings, TableSelectRow


TableSelectColumn

Syntax

TableSelectColumn

Remarks

Selects the table column containing the insertion point, or selects all columns containing the selection. If the insertion point or selection is not in a table, an error occurs.

Example

This example adds two new columns before the first column in a table:

TableSelectTable                'Select the entire table
StartOfRow                    'Go to the first cell
TableSelectColumn            'Select the first column
CharRight 1, 1                'Extend selection to the second column
TableInsertColumn            'Insert two new columns

See Also

TableSelectRow, TableSelectTable


TableSelectRow

Syntax

TableSelectRow

Remarks

Selects the table row containing the insertion point, or selects all rows containing the selection. If the insertion point or selection is not in a table, an error occurs.

See Also

TableSelectColumn, TableSelectTable


TableSelectTable

Syntax

TableSelectTable

Remarks

Selects the entire table containing the insertion point. If the insertion point
or selection is not in a table, an error occurs. As the examples in this entry demonstrate, you can use TableSelectTable in combination with other WordBasic statements to move the insertion point reliably to the first cell in
a table or to the first character after a table.

Examples

This example moves the insertion point to the first cell in a table:

TableSelectTable
StartOfRow

The following example moves the insertion point to the end-of-row mark in the first row in a table. When the insertion point is at this position, you can use TableInsertColumn to add a column to the end of a table.

TableSelectTable
StartOfColumn

The following example moves the insertion point to the first character after
a table:

TableSelectTable
CharRight

See Also

TableSelectColumn, TableSelectRow


TableSort

Syntax

TableSort [.DontSortHdr = number] [, .FieldNum = number] [, .Type = number] [.Order = number] [, .FieldNum2 = number] [, .Type2 = number] [, .Order2 = number] [, .FieldNum3 = number] [, .Type3 = number] [, .Order3 = number] [, .Separator = number] [, .SortColumn = number] [, .CaseSensitive = number]

Remarks

Sorts the selected paragraphs or table rows. If you want to sort paragraphs within a table cell, select only the paragraphs and not the end-of-cell mark; if you select the end-of-cell mark and then sort, Word displays a message stating that it found no valid records to sort. The arguments for the TableSort statement correspond to the options in the Sort dialog box (Table menu).

Argument | Explanation
.DontSortHdr | If 1, excludes the first paragraph or table row from the sort operation.
.FieldNum, .FieldNum2, .FieldNum3 | The number of the fields (text or table columns) to sort by. Word sorts by .FieldNum, then by .FieldNum2, and then by .FieldNum3.
.Type, .Type2, .Type3 | The respective sort types for .FieldNum, .FieldNum2, and .FieldNum3: 0 (zero) Alphanumeric 1 Numeric 2 Date
.Order, .Order2, .Order3 | The sorting order to use when sorting .FieldNum, .FieldNum2, and .FieldNum3: 0 (zero) Ascending 1 Descending
.Separator | The type of separator (irrelevant for table rows): 0 (zero) Comma 1 Tab 2 Other (the character that appears in the Other box in the Sort Options dialog box)
.SortColumn | If 1, sorts only the selected column (requires a column selection).
.CaseSensitive | If 1, sorts with case sensitivity.

Example

This example sorts table rows in ascending alphanumeric order, first by the first column, and then by the second column. The first row is excluded from the sort operation.

Select Case SelInfo(15)
    Case -1
        MsgBox "Please place the insertion point in a table."
    Case 1
        MsgBox "Sorry, can't sort a single-row table."
    Case Else
        TableSelectTable
        TableSort .Order = 0, .FieldNum = "1", .Type = 0, \
                .Order2 = 0, .FieldNum2 = "2", .Type2 = 0, \
                .DontSortHdr = 1
End Select

The following illustration shows a table before and after sorting by the preceding example.

See Also

TableSortAToZ, TableSortZToA


TableSortAToZ

Syntax

TableSortAToZ

Remarks

Sorts the paragraphs or table rows in the active document in ascending alphanumeric order. If the first paragraph or table row is a valid header record, it is not included in the sort. TableSortAToZ is intended for sorting mail-merge data sources.

See Also

MailMergeEditDataSource, TableSort, TableSortZToA


TableSortZToA

Syntax

TableSortZToA

Remarks

Sorts selected paragraphs or table rows in descending alphanumeric order. If the first paragraph or table row is a valid header record, it is not included in the sort. TableSortZToA is intended for sorting mail-merge data sources.

See Also

MailMergeEditDataSource, TableSort, TableSortAToZ


TableSplit

Syntax

TableSplit

Remarks

Inserts an empty paragraph above the current row in the table. In addition to splitting a table, you can use TableSplit to insert an empty paragraph above a table when the table is the first object in the document. If the insertion point or selection is not in a table, an error occurs.

Example

This example splits a table above the fourth row if the table contains more than three rows:

If SelInfo(15) > 3 Then
    StartOfColumn
    For i = 1 To 3
        TableSelectRow
        LineDown
    Next
    TableSplit
End If

See Also

TableSplitCells


TableSplitCells

Syntax

TableSplitCells [.NumColumns = text]

Remarks

Splits each selected table cell. Word generates an error if the selection or insertion point is not within a table.

Argument | Explanation
.NumColumns | Specifies the number of cells to split each selected table cell into. If omitted, Word splits each cell into two cells.

See Also

TableMergeCells, TableSplit


TableToText

Syntax

TableToText [.ConvertTo = number]

Remarks

Converts the selected rows to normal text. All the cells in the rows you want to convert must be selected; otherwise, an error occurs. The argument for the TableToText statement corresponds to the options in the Convert Table To Text dialog box (Table menu).

Argument | Explanation
.ConvertTo | Determines the character used to separate the contents of each cell: 0 (zero) Paragraph marks 1 or omitted Tab characters (each row ends with a paragraph mark) 2 Commas (each row ends with a paragraph mark) 3 Other (the character that appears in the Other box in the Convert Table To Text dialog box)

Example

This example converts the selected cells to a tabbed table:

TableToText

See Also

TableInsertTable, TextToTable


TableUpdateAutoFormat

Syntax

TableUpdateAutoFormat

Remarks

Updates the table containing the insertion point with the characteristics of
a predefined table format. For example, if you apply a table format with TableAutoFormat and then insert rows and columns, the table may no longer match the predefined look. TableUpdateAutoFormat restores the format.

See Also

TableAutoFormat


TabType()

Syntax

TabType(Pos)

Remarks

Returns the alignment of the custom or default tab stop at the position Pos, which is given in points (72 points = 1 inch). If more than one paragraph is selected, TabType() evaluates the setting in the first paragraph.

If there is no tab stop at the position Pos, TabType() returns –1. If there is a tab stop at Pos, TabType() returns one of the following values.

Value | Explanation
0 (zero) | Left-aligned or default
1 | Centered
2 | Right-aligned
3 | Decimal
4 | Bar

Example

This example determines whether a tab stop at the three-fourths – inch position
is centered. If it is, the FormatTabs instruction changes the alignment to left alignment.

If TabType(54) = 1 Then
    FormatTabs .Position = "54 pt", .Align = 0
End If

See Also

FormatTabs, NextTab(), PrevTab(), TabLeader$()


Text

Syntax

Text HorizPos, VertPos, Width, Height, Label$ [, .Identifier]

Remarks

Creates a text label in a custom dialog box. If you want to use the text control to define an access key for a list box or text box, the Text instruction must precede the instruction for the list box or text box control.

Although you cannot type multiple-line text labels in the Dialog Editor, you can size a text label to hold more than one line and use a variable for Label$ that holds more than one line of text (use Chr$(13) to indicate a line break within a string).

Argument | Explanation
HorizPos, VertPos | The horizontal and vertical distance of the upper-left corner of the text control rectangle from the upper-left corner of the dialog box, in increments of 1/8 and 1/12 of the System font (Windows) or the dialog font (Macintosh).
Width, Height | The width and height of the rectangle, in increments of 1/8 and 1/12 of the System font (Windows) or the dialog font (Macintosh).
Label$ | The label to display in the dialog box. An ampersand (&) precedes the character in Label$ that is the access key for the control following the Text instruction. If Label$ is longer than 255 characters, an error occurs.
.Identifier | An optional identifier used by statements in a dialog function that act on the text control. For example, you can use this identifier with DlgText to change Label$ while the dialog box is displayed.

Examples

In this example, the Text instruction results in the label "Sample Text," which indicates that "S" is the access key for the text box defined in the next instruction.

Begin Dialog UserDialog 320, 84, "Sample Dialog Macro"
Text 10, 6, 160, 12, "&Sample Text", .myTextControl
TextBox 10, 21, 236, 18, .TextBox1
OKButton 9, 58, 88, 21
CancelButton 115, 58, 88, 21
End Dialog

The following example displays the first 255 characters of the current selection in the text label.

textlabel$ = Left$(Selection$(), 255)
Begin Dialog UserDialog 621, 251, "Show Selection Text"
    OKButton 409, 220, 88, 21
    CancelButton 509, 220, 88, 21
    Text 10, 6, 586, 203, textlabel$, .Text1
End Dialog

See Also

Begin Dialog ¼ End Dialog, TextBox


TextBox

Syntax

TextBox HorizPos, VertPos, Width, Height, .Identifier[$] [, MultiLine]

Remarks

Creates a single-line or multiple-line text box into which the user can enter information in a custom dialog box. You can insert as many as 255 characters into a text box control.

Argument | Explanation
HorizPos, VertPos | The horizontal and vertical distance of the upper-left corner of the text box from the upper-left corner of the dialog box, in increments of 1/8 and 1/12 of the System font (Windows) or the dialog font (Macintosh).
Width, Height | The width and height of the text box, in increments of 1/8 and 1/12 of the System font (Windows) or the dialog font (Macintosh).
.Identifier[$] | Together with the dialog record name, .Identifier[$] creates a variable whose value corresponds to the text in the text box. The form for this variable is DialogRecord.Identifier[$] (for example, dlg.MyTextBox$). The dollar sign ($) is optional; you can use it to indicate that the variable is a string variable. The identifier string (.Identifier[$] minus the period) is also used by statements in a dialog function that act on the text box, such as DlgEnable and DlgVisible.
MultiLine | Specifies whether the text box is a single-line or multiple-line text box: 0 (zero) Single-line text box 1 Multiple-line text box In a multiple-line text box, the user can press ENTER or SHIFT+ENTER to begin new lines when typing text into the box. Note that multiple-line text boxes do not contain scroll bars; however, the user may scroll through text using the arrow keys. If the user presses ENTER or SHIFT+ENTER to begin a new line, the string returned by the identifier will contain a paragraph mark.

Example

In this example, text entered in the multiple-line text box created with the TextBox instruction is stored in the dlg.TextBox1 variable:

Begin Dialog UserDialog 290, 152, "Sample Dialog Macro"
Text 10, 6, 260, 12, "&Sample Text: Press ENTER"
Text 10, 22, 143, 12, "to start a new line."
TextBox 10, 43, 236, 64, .TextBox1, 1
OKButton 10, 117, 88, 21
CancelButton 117, 117, 88, 21
End Dialog
Dim dlg As UserDialog
Dialog dlg

See Also

Begin Dialog ¼ End Dialog, Text


TextFormField

Syntax

TextFormField

Remarks

Inserts a text form field at the insertion point. TextFormField corresponds to the Text Form Field button on the Forms toolbar.

See Also

CheckBoxFormField, DropDownFormField, InsertFormField


TextToTable

Syntax

TextToTable [.ConvertFrom = number] [, .NumColumns = number] [, .NumRows = number] [, .InitialColWidth = number or text] [, .Format = number] [, .Apply = number]

Remarks

Converts the selected text to a table based on the separator character you specify. If you run TextToTable without any arguments, Word uses tab characters as the separator if there are no commas, or commas if there are no tab characters, or paragraph marks if there are no tab characters or commas, or if there is a mixture of tab characters and commas. The arguments for the TextToTable statement correspond to the options in the Convert Text To Table dialog box (Table menu).

Argument | Explanation
.ConvertFrom | Specifies the character that separates text elements: 0 (zero) Paragraph marks 1 Tab characters 2 Commas 3 Other (the character that appears in the Other box in the Convert Text To Table dialog box)
.NumColumns | The number of columns to create.

Argument | Explanation
.NumRows | The number of rows to create.
.InitialColWidth | The width of the columns in points or a text measurement. If omitted, column width is calculated so that the table stretches from margin to margin.
.Format | One of the predefined formats listed in the Table AutoFormat dialog box (Table menu): 0 (zero) corresponds to the first format listed in the Formats box ("none"), 1 corresponds to the second format, and so on.
.Apply | Specifies which attributes of the format specified by .Format to apply to the table. For a list of attributes and their values, see TableInsertTable.

See Also

TableAutoFormat, TableInsertTable, TableToText


Time$()

Syntax

Time$([SerialNumber])

Remarks

Returns a time corresponding to SerialNumber, a decimal representation of the date, time, or both. If SerialNumber is omitted, Time$() returns the current time. For information about serial numbers, see DateSerial().

The time format is determined by the "TimeFormat=" line in the [Microsoft Word] section of WINWORD6.INI (Windows 3.x), Word Settings (6) (Macintosh), or the registry (Windows 95 and Windows NT). (In Windows 3.x, if there is no "TimeFormat=" line, Time$() uses the time settings in the [intl] section of WIN.INI.) Within a macro, you can use SetPrivateProfileString to change the current time format.

Example

When included at the end of a macro, this example displays a message box showing the time the macro finished running:

MsgBox "The macro finished at " + Time$()

See Also

Date$(), DateSerial(), GetPrivateProfileString$(), Hour(), Minute(), Now(), Second(), SetPrivateProfileString, TimeSerial(), TimeValue()


TimeSerial()

Syntax

TimeSerial(Hour, Minute, Second)

Remarks

Returns the serial number of the specified time. Because serial numbers are decimal numbers representing a number of days, TimeSerial() returns a decimal number from 0 to 0.99998842592593. For more information about serial numbers, see DateSerial().

Argument | Explanation
Hour | A number between 0 and 23, inclusive, or a numeric expression
Minute | A number between 0 and 59, inclusive, representing the minutes after the hour, or a numeric expression
Second | A number between 0 and 59, inclusive, representing the seconds after the minute, or a numeric expression

Example

This example displays a message box with a decimal number corresponding to the fraction of the current day that has passed:

h = Hour(Now())
m = Minute(Now())
s = Second(Now())
fraction = TimeSerial(h, m, s)
MsgBox Left$(Str$(fraction), 5) + " of this day is over."

See Also

DateSerial(), Day(), Month(), Now(), Time$(), TimeValue(), Today(), Year()


TimeValue()

Syntax

TimeValue(TimeText$)

Remarks

Returns the serial number of the time represented by TimeText$. Use TimeValue() to convert a time represented by text to a serial number. A serial number is a decimal representation of the date, time, or both. For information about serial numbers, see DateSerial().

Argument | Explanation
TimeText$ | A string representing the time. For example, the following are each valid representations of 4:30 p.m.: 16:30:00 4:30 pm 4:30 PM TimeText$ must represent a time between 00:00:00 and 23:59:59 on the 24-hour clock. TimeValue() generates an error if TimeText$ is out of this range.

Example

This example displays the serial number for the current time in the status bar:

Print TimeValue(Time$())

See Also

DateSerial(), DateValue(), Day(), Month(), Now(), Time$(), TimeSerial(), Today(), Year()


TipWizard

Syntax

TipWizard

Remarks

Displays or hides the TipWizard toolbar. In Word version 6.0, TipWizard is unavailable and generates an error.

See Also

AutomaticChange, Help, ShowMe


Today()

Syntax

Today()

Remarks

Returns a serial number that represents the current date according to the computer's system date. Unlike Now(), which returns a serial number in which the digits after the decimal point represent the time as a fraction of a day, Today() returns strictly whole numbers. For more information about serial numbers, see DateSerial().

Example

This example displays a message box stating the number of days until the new year. The number of days is calculated by subtracting the serial number for the current date from the serial number for January 1 of the following year.

yr = Year(Today())
rightNow = Today()
jan1 = DateSerial(yr + 1, 1, 1)
MsgBox "Days until the new year:" + Str$(jan1-rightNow)

See Also

Date$(), DateSerial(), DateValue(), Day(), Month(), Now(), Time$(), TimeSerial(), TimeValue(), Year()


ToggleFieldDisplay

Syntax

ToggleFieldDisplay

Remarks

Toggles the display of the fields in the selection between field codes and field results. If the selection does not contain at least one field, an error occurs. The exception to this rule is in page layout view, where ToggleFieldDisplay toggles the display of all fields.

Example

This example uses the ViewFieldCodes statement to change the display of all fields to field results, and then changes the display of fields in the current paragraph (selected using the predefined bookmark " \ Para") back to field codes:

ViewFieldCodes 0
EditGoTo .Destination = "\Para"
ToggleFieldDisplay

See Also

ViewFieldCodes


ToggleFull

Syntax

ToggleFull

Remarks

Toggles full screen mode on and off.

See Also

ToolsOptionsView, ViewToolbars


ToggleHeaderFooterLink

Syntax

ToggleHeaderFooterLink

Remarks

If the current header or footer is not linked to the previous section, replaces the header or footer with the corresponding header or footer from the previous section and establishes a link. If the current header or footer is already linked, ToggleHeaderFooterLink breaks the link so you can modify the headers or footers independently. If the insertion point is not in a header or footer, an error occurs.

See Also

FormatHeaderFooterLink, ShowNextHeaderFooter, ShowPrevHeaderFooter, ViewHeader


ToggleMainTextLayer

Syntax

ToggleMainTextLayer

Remarks

Toggles the display of the main text layer when headers and footers are displayed. If headers and footers are not displayed, an error occurs.

See Also

ViewHeader


TogglePortrait

Syntax

TogglePortrait

Remarks

Switches the selected sections between portrait and landscape page orientations.
If the selected sections have different page orientations, an error occurs.

See Also

FilePageSetup


ToggleScribbleMode

Syntax

ToggleScribbleMode

Remarks

In Windows, toggles hand annotation mode on and off. When you activate hand annotation mode, Word switches the active document to page layout view. This statement is for use with Windows for Pen Computing only. On the Macintosh, ToggleScribbleMode is not available and generates an error.


ToolbarButtonMacro$()

Syntax

ToolbarButtonMacro$(Toolbar$, Position [, Context])

Remarks

Returns the name of the built-in command, macro, font, AutoText entry, or style assigned to the specified toolbar button. If you specify a position that corresponds to a space, ToolbarButtonMacro$() returns an empty string ("").

Argument | Explanation
Toolbar$ | The name of the toolbar as it appears in the Toolbars dialog box (View menu).
Position | A number corresponding to the position of the button on the specified toolbar, where 1 is the first position, 2 is the second position, and so on. Note that a list box or space counts as one position.
Context | Specifies the button for which to return the name: 0 (zero) The button displayed on the toolbar when a document based on the Normal template is active. 1 or omitted The button currently displayed on the toolbar. Note that the button displayed on the toolbar depends on the custom settings, if any, of the active template, any loaded global templates, and the Normal template.

Example

This example fills an array with the names of commands assigned to the Standard toolbar when a document based on the Normal template is active.

size = CountToolbarButtons("Standard", 0) - 1
Dim standardmacro$(size)
For i = 0 To size
    standardmacro$(i) = ToolbarButtonMacro$("Standard", i + 1, 0)
Next i

See Also

CountToolbarButtons(), CountToolbars(), ToolbarName$()


ToolbarName$()

Syntax

ToolbarName$(Toolbar [, Context])

Remarks

Returns the name of the specified toolbar as it appears in the Toolbars dialog box (View menu).

Argument | Explanation
Toolbar | A number in the range 1 to CountToolbars(), corresponding to the toolbar whose name you want to return
Context | Specifies the list of toolbars from which to return a name for Toolbar: 0 (zero) The list of toolbars available to all documents, including those from loaded global templates 1 or omitted The list of all toolbars currently available, including those available only to documents based on the active template

For an example, see CountToolbars().

See Also

CountToolbarButtons(), CountToolbars(), ToolbarButtonMacro$()


ToolbarState()

Syntax

ToolbarState(Toolbar$)

Remarks

Returns –1 if the toolbar specified by Toolbar$ is displayed and 0 (zero) if it is not.

Example

This example switches to page layout view if the Drawing toolbar is displayed.

If ToolbarState("Drawing") Then ViewPage

See Also

ToolbarName$(), ViewRibbon, ViewRuler, ViewStatusBar, ViewToolbars


ToolsAddRecordDefault

Syntax

ToolsAddRecordDefault

Remarks

Adds an empty record to the end of a data source. For example, ToolsAddRecordDefault adds an empty row to the bottom of a table in a Word document containing data for a mail merge. ToolsAddRecordDefault can be used with any document that could be used as a data source during a mail merge.

See Also

MailMergeEditDataSource, ToolsRemoveRecordDefault


ToolsAdvancedSettings

Syntax

ToolsAdvancedSettings .Application = text, .Option = text , .Setting = text [, .Delete] [, .Set]

Remarks

Changes settings in a settings file, such as WINWORD6.INI (Windows 3.x) or Word Settings (6) (Macintosh), or a private settings file. The arguments for ToolsAdvancedSettings correspond to the options in the Advanced Settings dialog box, which you can display by choosing Macro from the Tools menu and running the Word command ToolsAdvancedSettings. Note that in Windows 95 and Windows NT, settings are stored in the registry and you cannot useToolsAdvancedSettings to change them.

Argument | Explanation
.Application | The name of a section in a settings file, as listed in the Categories box. Note that by following the section name with a space and the name of a settings file in parentheses, you can set a key in any settings file. In Windows for example, "Macro Settings (MY.INI)" specifies the [Macro Settings] section of the MY.INI file in the Windows folder. On the Macintosh, "Macro Settings (MY SETTINGS)" specifies the [Macro Settings] section of the MY SETTINGS file in SYSTEM FOLDER:PREFERENCES.
.Option | The key to set.
.Setting | The new setting.
.Delete | Deletes the key.
.Set | Sets the key.

For more information about changing settings in a settings file, see SetPrivateProfileString.

Example

This example sets the date format in the [Microsoft Word] section of the Word settings file:

ToolsAdvancedSettings .Application = "Microsoft Word", \
        .Option = "DateFormat", .Setting = "M/D/YYYY", .Set

See Also

GetPrivateProfileString$(), GetProfileString$(), SetPrivateProfileString, SetProfileString, ToolsOptionsFileLocations


ToolsAutoCorrect

Syntax

ToolsAutoCorrect [.InitialCaps = number] [, .SentenceCaps = number] [, .Days = number] [, .CapsLock = number] [, .ReplaceText = number] [, .Formatting = number] [, .Replace = text] [, .With = text] [, .Add] [, .Delete] [, .SmartQuotes = number]

Remarks

Sets AutoCorrect options. The arguments for the ToolsAutoCorrect statement correspond to the options in the AutoCorrect dialog box (Tools menu).

Argument | Explanation
.InitialCaps | If 1, Word corrects words in which the first two letters are capitalized. For example, "WOrd" becomes "Word."
.SentenceCaps | If 1, Word capitalizes the first letter of new sentences.
.Days | If 1, Word capitalizes the days of the week. For example, "tuesday" becomes "Tuesday."
.CapsLock | If 1, Word corrects typing with CAPS LOCK on.
.ReplaceText | If 1, activates automatic replacement of text.
.Formatting | If 1, formatting is stored with the replacement text when a replacement entry is added; available only if text is selected before running ToolsAutoCorrect.
.Replace | The text you want to replace automatically with the text specified by .With (for example, a person's initials).
.With | The text you want to insert automatically when the text specified by .Replace is typed (for example, a person's full name).
.Add | Adds the text specified by .Replace and .With to the list of replacement entries.
.Delete | Deletes the replacement entry specified by .Replace.
.SmartQuotes | If 1, Word inserts "smart" quotation marks (" " and ' ') and apostrophes (').

Example

This example adds a replacement entry and activates automatic replacement of text:

ToolsAutoCorrect .ReplaceText = 1, .Replace = "sr", \
        .With = "Stella Richards", .Add

See Also

ToolsAutoCorrectCapsLockOff, ToolsAutoCorrectDays, ToolsAutoCorrectInitialCaps, ToolsAutoCorrectReplaceText, ToolsAutoCorrectSentenceCaps, ToolsAutoCorrectSmartQuotes


ToolsAutoCorrectCapsLockOff, ToolsAutoCorrectCapsLockOff()

Syntax

ToolsAutoCorrectCapsLockOff [On]

ToolsAutoCorrectCapsLockOff()

The ToolsAutoCorrectCapsLockOff statement selects or clears the Correct Accidental Usage Of cAPS LOCK Key check box in the AutoCorrect dialog box (Tools menu). The ToolsAutoCorrectCapsLockOff() function returns information about the state of the check box. For information about arguments and return values, see ToolsAutoCorrectDays.

Remarks

In Word version 6.0, ToolsAutoCorrectCapsLockOff and ToolsAutoCorrectCapsLockOff() are unavailable and generate errors.

See Also

ToolsAutoCorrect, ToolsAutoCorrectInitialDays


ToolsAutoCorrectDays, ToolsAutoCorrectDays()

Syntax

ToolsAutoCorrectDays [On]

ToolsAutoCorrectDays()

Remarks

The ToolsAutoCorrectDays statement selects or clears the Capitalize Names Of Days check box in the AutoCorrect dialog box (Tools menu).

Argument | Explanation
On | Specifies whether to select or clear the check box: 1 Selects the check box. 0 (zero) Clears the check box. Omitted Toggles the check box.

The ToolsAutoCorrectDays() function returns the following values.

Value | Explanation
0 (zero) | If the Capitalize Names Of Days check box is cleared
–1 | If the Capitalize Names Of Days check box is selected

See Also

ToolsAutoCorrect


ToolsAutoCorrectExceptions

Syntax

ToolsAutoCorrectExceptions [.Tab = number] [, .Name = text] [, .AutoAdd = number] [, .Add] [, .Delete]

Remarks

Adds words to or deletes words from the list of AutoCorrect exceptions. The arguments for the ToolsAutoCorrectExceptions statement correspond to the options in the AutoCorrect Exceptions dialog box (AutoCorrect command, Tools menu). In Word version 6.0, ToolsAutoCorrectExceptions is unavailable and generates an error.

Argument | Explanation
.Tab | The tab where the exception is added or deleted: 0 (zero) First Letter 1 INitial CAps
.Name | The exception list entry to be added or deleted.
.AutoAdd | If 1, Word adds to the list of exceptions any word that the user changes back to its original spelling or capitalization after it has been automatically corrected.
.Add | Adds .Name to the exception list specified by .Tab.
.Delete | Deletes .Name from the exception list specified by .Tab.

See Also

CountAutoCorrectExceptions(), GetAutoCorrectException$(), IsAutoCorrectException()


ToolsAutoCorrectInitialCaps, ToolsAutoCorrectInitialCaps()

Syntax

ToolsAutoCorrectInitialCaps [On]

ToolsAutoCorrectInitialCaps()

Remarks

The ToolsAutoCorrectInitialCaps statement selects, clears, or toggles the Correct TWo INitial CApitals check box in the AutoCorrect dialog box (Tools menu). The ToolsAutoCorrectInitialCaps() function returns information about the state of the check box. For information on arguments and return values, see ToolsAutoCorrectDays.

See Also

ToolsAutoCorrect, ToolsAutoCorrectDays


ToolsAutoCorrectReplaceText, ToolsAutoCorrectReplaceText()

Syntax

ToolsAutoCorrectReplaceText [On]

ToolsAutoCorrectReplaceText()

Remarks

The ToolsAutoCorrectReplaceText statement selects, clears, or toggles the Replace Text As You Type check box in the AutoCorrect dialog box (Tools menu). The ToolsAutoCorrectReplaceText() function returns information about the state of the check box. For information on arguments and return values, see ToolsAutoCorrectDays.

See Also

ToolsAutoCorrect, ToolsAutoCorrectDays


ToolsAutoCorrectSentenceCaps, ToolsAutoCorrectSentenceCaps()

Syntax

ToolsAutoCorrectSentenceCaps [On]

ToolsAutoCorrectSentenceCaps()

Remarks

The ToolsAutoCorrectSentenceCaps statement selects, clears, or toggles the Capitalize First Letter Of Sentences check box in the AutoCorrect dialog box (Tools menu). The ToolsAutoCorrectSentenceCaps() function returns information about the state of the check box. For information on arguments and return values, see ToolsAutoCorrectDays.

See Also

ToolsAutoCorrect, ToolsAutoCorrectDays


ToolsAutoCorrectSmartQuotes, ToolsAutoCorrectSmartQuotes()

Syntax

ToolsAutoCorrectSmartQuotes [On]

ToolsAutoCorrectSmartQuotes()

Remarks

The ToolsAutoCorrectSmartQuotes statement selects, clears, or toggles the Change 'Straight Quotes' To 'Smart Quotes' check box in the AutoCorrect dialog box (Tools menu). The ToolsAutoCorrectSmartQuotes() function returns information about the state of the check box. For information on arguments and return values, see ToolsAutoCorrectDays.

See Also

ToolsAutoCorrect, ToolsAutoCorrectDays


ToolsBulletListDefault

Syntax

ToolsBulletListDefault

Remarks

Adds bullets and tab characters to the selected paragraphs and formats the paragraphs with a hanging indent. Bullets are inserted as SYMBOL fields.

Note

The ToolsBulletListDefault statement corresponds to the Bulleted List button on the Toolbar in Word for Windows version 2.x. In Word version 6.0, the Bullets button is on the Formatting toolbar and its corresponding WordBasic statement is FormatBulletDefault.

See Also

FormatBulletDefault, FormatBulletsAndNumbering, FormatNumberDefault, ToolsBulletsNumbers, ToolsNumberListDefault


ToolsBulletsNumbers

Syntax

ToolsBulletsNumbers [.Replace = number] [, .Font = text] [, .CharNum = text] [, .Type = number] [, .FormatOutline = text] [, .AutoUpdate = number] [, .FormatNumber = number] [, .Punctuation = text] [, .StartAt = text] [, .Points = number or text] [, .Hang = number] [, .Indent = number or text] [, .Remove]

Remarks

Sets formats for bulleted, numbered, and outline-numbered paragraphs. This statement is included for compatibility with the previous version of Word for Windows; the arguments for ToolsBulletsNumbers correspond to the options in the Bullets And Numbering dialog box (Tools menu) in Word for Windows version 2.x. Not every argument applies to each type of list.

Argument | Explanation
.Replace | If 1, Word updates bullets only for paragraphs that are already bulleted, or updates numbers only for paragraphs that are already numbered.
.Font | The font for the numbers or the bullet character in a list.
.CharNum | The character or ANSI code for the character to use as the bullet. Bullets are inserted as SYMBOL fields.
.Type | The type of list to create: 0 (zero) Bulleted list 1 Numbered list 2 Outline-numbered list
.FormatOutline | A format for numbering outlines. The available formats are Legal, Outline, Sequence, Learn, and Outline All. The Learn format applies a format based on the first number for each level in the selection.
.AutoUpdate | If 1, numbers are inserted as fields that update automatically when the sequence of paragraphs changes.
.FormatNumber | Specifies a format for numbering lists: 0 (zero) 1, 2, 3, 4 1 I, II, III, IV 2 i, ii, iii, iv 3 A, B, C, D 4 a, b, c, d
.Punctuation | The separator character or characters for numbers in a list. If you specify one character, it follows each number; if you specify two characters, they enclose each number.
.StartAt | The starting number or letter for the list.

Argument | Explanation
.Points | The size of the bullet character, in points, in a bulleted list.
.Hang | If 1, sets a hanging indent for the list.
.Indent | If .Hang is set to 1, the width of the left indent in points or a text measurement.
.Remove | Removes existing bullets or numbers.

Example

This example formats the selection as a bulleted list, with the bullet defined as character code 183 in the Symbol font, at 10 points in size:

ToolsBulletsNumbers .Font = "Symbol", .CharNum = "183", .Type = 0, \
    .Points = 10, .Hang = 1, .Indent = "0.25 in", .Replace = 0

See Also

FormatBulletDefault, FormatBulletsAndNumbering, FormatNumberDefault, ToolsBulletListDefault, ToolsNumberListDefault


ToolsCalculate, ToolsCalculate()

Syntax

ToolsCalculate

ToolsCalculate([Expression$])

Remarks

The ToolsCalculate statement evaluates the selection as a mathematical expression, and then displays the result in the status bar. The result is also placed on the Clipboard.

If Expression$ is not specified, the ToolsCalculate() function acts just like the statement except that it returns the result instead of displaying it in the status bar and placing it on the Clipboard. If you do specify Expression$, it is evaluated as a mathematical expression; Expression$ can include bookmark names and simple cell references (such as a5).

Example

In this example, the ToolsCalculate() function adds values from two table cells and returns the result in the variable total. The insertion point must be within the table containing the values.

total = ToolsCalculate("a5 + b5")

See Also

TableAutoSum, TableFormula


ToolsCompareVersions

Syntax

ToolsCompareVersions .Name = text

Remarks

Displays revision marks indicating where the active document differs from the specified document. ToolsCompareVersions corresponds to the Compare Versions dialog box (Revisions command, Tools menu).

Argument | Explanation
.Name | The name of the document to which the active document is compared; include a path if the document is not in the current folder.

Example

This example compares the active document to C:\DRAFT\REV1DOC.DOC. On the Macintosh, substitute a path such as HD:DRAFT:FIRST REV.

ToolsCompareVersions .Name = "C:\DRAFT\REV1DOC.DOC"

See Also

ToolsOptionsRevisions, ToolsRevisions


ToolsCreateEnvelope

Syntax

ToolsCreateEnvelope [.ExtractAddress = number] [, .EnvAddress = text] [, .EnvOmitReturn = number] [, .EnvReturn = text] [, .PrintBarCode = number] [, .EnvWidth = number or text] [, .EnvHeight = number or text] [, .EnvPaperSize = number] [, .PrintFIMA = number] [, .LabelAutoText = text] [, .UseEnvFeeder = number] [, .AddrFromLeft = number or text] [, .AddrFromTop = number or text] [, .RetAddrFromLeft = number or text] [, .RetAddrFromTop = number or text] [, .PrintEnvLabel] [, .AddToDocument]

Remarks

Creates an envelope that is printed with the active document. The arguments for the ToolsCreateEnvelope statement correspond to the options on the Envelopes tab in the Envelopes And Labels dialog box (Tools menu). To specify address formatting, use FormatAddrFonts and FormatRetAddrFonts.

Argument | Explanation
.ExtractAddress | Specifies whether or not to use the text marked by the "EnvelopeAddress" bookmark (a user-defined bookmark) as the recipient's address: 0 (zero) The "EnvelopeAddress" bookmark is not used. 1 The "EnvelopeAddress" bookmark is used.
.EnvAddress | Text specifying the recipient's address (ignored if .ExtractAddress is specified).
.EnvOmitReturn | Specifies whether or not to omit the return address: 0 The return address is not omitted. 1 The return address is omitted.
.EnvReturn | Text specifying the return address.
.PrintBarCode | Specifies whether or not to add a POSTNET bar code: 1 adds the bar code, 0 (zero) does not. For U.S. mail only.

Argument | Explanation
.EnvWidth, .EnvHeight | The width and height of the envelope, in points or a text measurement, when .EnvPaperSize corresponds to Custom Size.
.EnvPaperSize | Corresponds to a size in the Envelope Size box in the Envelope Options dialog box: 0 (zero) corresponds to the first size, 1 to the second size, and so on.
.PrintFIMA | Specifies whether or not to add a Facing Identification Mark (FIM A) for use in presorting courtesy reply mail: 1 adds the FIM A, 0 (zero) does not. For U.S. mail only.
.LabelAutoText | The name of an AutoText entry in which the address fields for a data source are stored (only recorded when creating envelopes in a mail merge).
.UseEnvFeeder | A number corresponding to the envelope source listed in the Feed From box: 0 (zero) corresponds to the first source, 1 to the second source, and so on.
.AddrFromLeft | The distance, in the current default unit or a text measurement, between the left edge of the envelope and the recipient's address.
.AddrFromTop | The distance, in the current default unit or a text measurement, between the top edge of the envelope and the recipient's address.
.RetAddrFromLeft | The distance, in the current default unit or a text measurement, between the left edge of the envelope and the return address.
.RetAddrFromTop | The distance, in the current default unit or a text measurement, between the top edge of the envelope and the return address.
.PrintEnvLabel | Prints the envelope.
.AddToDocument | Adds a section with the recipient's address and the return address to the beginning of the document.

Example

This example adds an envelope to the active document with addresses specified in the variables to$ and from$. The recipient's address is bold.

rtn$ = Chr$(13)
to$ = "Jane Doe"  + rtn$ + "123 Skye St." + \
        rtn$ + "OurTown, WA 98107"
from$ = "John Doe" + rtn$ + "456 Erde Lane" + \
        rtn$ + "OurTown, WA 98107"
FormatAddrFonts .Bold = 1
ToolsCreateEnvelope .EnvAddress = to$, .EnvReturn = from$, \
        .AddToDocument

See Also

FormatAddrFonts, FormatRetAddrFonts, ToolsCreateLabels


ToolsCreateLabels

Syntax

ToolsCreateLabels [.ExtractAddress = number] [, .LabelListIndex = number] [, .LabelIndex = number] [, .LabelDotMatrix = number] [, .LabelTray = number] [, .LabelAcross = number] [, .LabelDown = number] [, .SingleLabel = number] [, .LabelRow = number] [, .LabelColumn = number] [, .LabelAutoText = text] [, .LabelText = text] [, .PrintEnvLabel] [, .AddToDocument] [, .LabelTopMargin = number or text] [, .LabelSideMargin = number or text] [, .LabelVertPitch = number or text] [, .LabelHorPitch = number or text] [, .LabelHeight = number or text] [, .LabelWidth = number or text]

Remarks

Creates a label or a sheet of labels that is printed with the active document. The arguments for the ToolsCreateLabels statement correspond to the options on the Labels tab in the Envelopes And Labels dialog box (Tools menu).

Argument | Explanation
.ExtractAddress | Specifies whether or not to use the text marked by the "EnvelopeAddress" bookmark (a user-defined bookmark) as the label text: 0 (zero) The "EnvelopeAddress" bookmark is not used. 1 The "EnvelopeAddress" bookmark is used.
.LabelListIndex | For dot matrix printers, the values are: 1 Avery® Standard 3 Avery Intl (UK) 4 Avery Intl (France) 6 CoStar LabelWriter For laser printers, the values are: 0 (zero) Avery Standard 2 Avery Pan European 5 Other
.LabelIndex | Corresponds to an item in the Product Number box in the Label Options dialog box: 0 (zero) corresponds to the first item, 1 to the second item, and so on.
.LabelDotMatrix | Specifies the kind of printer: 0 (zero) Laser 1 Dot matrix
.LabelTray | Corresponds to a tray listed in the Tray list box in the Label Options dialog box: 0 (zero) corresponds to the first tray in the list, 1 to the second, and so on. Available only if .LabelDotMatrix is set to 0 (zero).

Argument | Explanation
.SingleLabel | If 1, allows you to print a single label on a page of labels by specifying .LabelRow and .LabelColumn.
.LabelRow | If .SingleLabel is set to 1, the row containing the label you want to print.
.LabelColumn | If .SingleLabel is set to 1, the column containing the label you want to print.
.LabelAutoText | The name of an AutoText entry in which the label text is stored (ignored if .ExtractAddress is specified).
.LabelText | The text to print on the labels (ignored if .ExtractAddress or .LabelAutoText is specified).
.PrintEnvLabel | Prints the labels.
.AddToDocument | Creates a new document with label text ready for printing.

The following arguments are for creating custom labels and need not be specified (and are ignored) if the combination of .LabelListIndex, .LabelIndex, and .LabelDotMatrix specifies valid labels.

Argument | Explanation
.LabelAcross | The number of labels in a row
.LabelDown | The number of labels in a column
.LabelTopMargin | The width of the top margin on the page of labels, in the current default unit or a text measurement
.LabelSideMargin | The width of the side margins on the page of labels, in the current default unit or a text measurement
.LabelVertPitch | The distance from the top of one label to the top of the next label down, in the current default unit or a text measurement
.LabelHorPitch | The distance from the left edge of one label to the left edge of the next label across, in the current default unit or a text measurement
.LabelHeight | The height of the labels, in the current default unit or a text measurement.
.LabelWidth | The width of the labels, in the current default unit or a text measurement.

Example

This example creates a new document with label text arranged for printing onto a sheet of Avery labels. The argument .LabelListIndex = 0 specifies Avery Standard as the label product, and .LabelIndex = 4 specifies product number 5160 (for addresses). The label text is retrieved from the AutoText entry "MyLabelAddress."

ToolsCreateLabels .LabelListIndex = 0, .LabelIndex = 10, \
    .LabelDotMatrix = 0, .LabelTray = 1, .AddToDocument, \
    .LabelAutoText = "MyLabelAddress"

See Also

ToolsCreateEnvelope


ToolsCustomize

Syntax

ToolsCustomize [.Tab = number]

Remarks

Displays the Customize dialog box (Tools menu) with the specified tab selected.

Argument | Explanation
.Tab | The tab to select: 0 (zero) Toolbars 1 Menus 2 Keyboard

See Also

AddButton, ToolsCustomizeKeyboard, ToolsCustomizeMenuBar, ToolsCustomizeMenus


ToolsCustomizeKeyboard

Syntax

ToolsCustomizeKeyboard [.KeyCode = number] [, .KeyCode2 = number] [, .Category = number] [, .Name = text] [, .Add] [, .Remove] [, .ResetAll] [, .CommandValue = text] [, .Context = number]

Remarks

Assigns and reassigns shortcut keys to built-in commands, macros, fonts, AutoText entries, styles, or common symbols. The arguments for the ToolsCustomizeKeyboard statement correspond to the options on the Keyboard tab in the Customize dialog box (Tools menu).

Argument | Explanation
.KeyCode | A number representing the key combination, as listed later in this entry.
.KeyCode2 | A number representing the second key combination in a key sequence. For example, to assign the key sequence CTRL+S, 1 (on the Macintosh, COMMAND+S, 1) to the Heading 1 style, you set .KeyCode to 339 (for CTRL+S or COMMAND+S) and .KeyCode2 to 49 (for 1).
.Category | Specifies the kind of item to assign a shortcut key: 1 or omitted Built-in commands 2 Macros 3 Fonts 4 AutoText entries 5 Styles 6 Common symbols

Argument | Explanation
.Name | The name of the command, macro, or other item. If .Category is set to 6, you can specify a symbol by typing or pasting it into the macro-editing window or using a Chr$() instruction such as Chr$(167).
.Add | Adds the key assignment or assignments to the specified item.
.Remove | If the specified key code is currently assigned, removes the assignment such that the associated key combination has no effect. If the specified key code is not assigned, .Remove resets the key code to its default action. Note that specifying .Name is not required when removing or resetting a key assignment.
.ResetAll | Resets all key assignments to their defaults.
.CommandValue | Additional text required for the command specified by .Name, if any. For example, if .Name is set to Color, .CommandValue specifies the color. For more information, see the table of settings for .CommandValue in ToolsCustomizeMenus.
.Context | Determines where new key assignments are stored: 0 (zero) or omitted Normal template 1 Active template

The following tables list the values you need to specify the appropriate number for .KeyCode. The first table contains values you add to values in the second table when specifying a key combination (for example, you would specify CTRL+S (on the Macintosh, COMMAND+S) as the sum of 256 and 83, or 339).

Add this | To combine with this key
256 | CTRL (Windows) or COMMAND (Macintosh)
512 | SHIFT
1024 | ALT (Windows) or OPTION (Macintosh)
2048 | CONTROL (Macintosh)

In Windows, function keys F11 through F16 are equivalent to Alt+F1 through Alt+F6. Therefore, the key code corresponding to F11 has the same effect as a key code corresponding to Alt+F1. Similarly, specifying Alt+F11 — effectively Alt+Alt+F1 — is no different from specifying alt+F1.

This key code | Corresponds to
8 | BACKSPACE
9 | TAB
12 | 5 on the numeric keypad when Num Lock is off
13 | ENTER
19 | Pause

This key code | Corresponds to
27 | ESC
32 | SPACEBAR
33 | PAGE UP
34 | PAGE DOWN
35 | END
36 | HOME
45 | INS
46 | DEL
48 | 0
49 | 1
50 | 2
51 | 3
52 | 4
53 | 5
54 | 6
55 | 7
56 | 8
57 | 9
65 | A
66 | B
67 | C
68 | D
69 | E
70 | F
71 | G
72 | H
73 | I
74 | J
75 | K
76 | L
77 | M
78 | N
79 | O
80 | P

This key code | Corresponds to
81 | Q
82 | R
83 | S
84 | T
85 | U
86 | V
87 | W
88 | X
89 | Y
90 | Z
96 | 0 on the numeric keypad
97 | 1 on the numeric keypad
98 | 2 on the numeric keypad
99 | 3 on the numeric keypad
100 | 4 on the numeric keypad
101 | 5 on the numeric keypad
102 | 6 on the numeric keypad
103 | 7 on the numeric keypad
104 | 8 on the numeric keypad
105 | 9 on the numeric keypad
106 | * on the numeric keypad
107 | + on the numeric keypad
109 | – on the numeric keypad
110 | . on the numeric keypad
111 | / on the numeric keypad
112 | F1
113 | F2
114 | F3
115 | F4
116 | F5
117 | F6
118 | F7
119 | F8
120 | F9

This key code | Corresponds to
121 | F10
122 | F11
123 | F12
124 | F13
125 | F14
126 | F15
127 | F16
145 | Scroll Lock
186 | ;
187 | =
188 | ,
189 | -
190 | .
191 | /
192 | `
219 | [
220 | \
221 | ]
222 | '

Examples

This example assigns CTRL+SHIFT+F (Windows) or command+SHIFT+F (Macintosh) to FileFind:

ToolsCustomizeKeyboard .Category = 1, .Name = "FileFind", \
    .KeyCode = 838, .Add

The following example removes the key assignment from FileFind:

ToolsCustomizeKeyboard .Category = 1, .Name = "FileFind", \
    .KeyCode = 838, .Remove

See Also

CountKeys(), KeyCode(), KeyMacro$()


PrintToolsCustomizeMenuBar

Syntax

ToolsCustomizeMenuBar [.Context = number] [, .Position = number] [, .MenuType = number] [, .MenuText = text] [, .Menu = text] [, .Add] [, .Remove] [, .Rename]

Remarks

Adds, removes, or renames menus on the menu bar. Arguments for the ToolsCustomizeMenuBar statement correspond to options in the Menu Bar dialog box (Menus tab, Customize command, Tools menu).

Argument | Explanation
.Context | Determines where the menu change is stored: 0 (zero) or omitted Normal template 1 Active template
.Position | Specifies where to add a new menu: 0 (zero) corresponds to the first (leftmost) position, 1 to the second, and so on. To add a menu to the rightmost position, set .Position to –1.
.MenuType | Specifies which menu bar to change: 0 or omitted The menu bar when a document is open 1 The menu bar when no document is open
.MenuText | A new name for the menu; used with .Add and .Rename. Place an ampersand (&) in front of the access key, if any. Note that a menu bar can have only one menu of a given name (irrespective of ampersands).
.Menu | The name of the menu you want to change; used with .Rename and .Remove. Including an ampersand (&) before the access key in the menu name is optional (for example, you can specify either "File" or "&File").
.Add | Adds the menu specified by .MenuText to the menu bar.
.Remove | Removes the specified menu.
.Rename | Renames the specified menu.

If you do not specify .Add, .Remove, or .Rename, Word adds the menu.

To reset menu bars, use the .ResetAll argument with ToolsCustomizeMenus. Note that this resets all menu assignments to their defaults.

Example

This example adds a new menu named Macros to the right of the Help menu (Windows) or Window menu (Macintosh):

ToolsCustomizeMenuBar .MenuText = "&Macros", .Add, .Position = -1

See Also

ToolsCustomizeMenus


ToolsCustomizeMenus

Syntax

ToolsCustomizeMenus [.MenuType = number] [, .Position = number] [, .Category = number] [, .Name = text] [, .Menu = text] [, .AddBelow = text] [, .MenuText = text] [, .Rename] [, .Add] [, .Remove] [, .ResetAll] [, .CommandValue = text] [, .Context = number]

Remarks

Changes menu assignments for built-in commands, macros, fonts, AutoText entries, and styles. The arguments for the ToolsCustomizeMenus statement correspond to the options on the Menus tab in the Customize dialog box (Tools menu).

Argument | Explanation
.MenuType | The type of menu you want to modify: 0 or omitted Menus on the menu bar when a document is open 1 Menus on the menu bar when no document is open 2 Shortcut menus
.Position | The position on the menu where you want to add or remove an item: –1 or omitted Automatically determines an appropriate position for adding the item. –2 Adds the item to the bottom of the menu. n Adds, removes, or renames the item at the specified position, where 1 is the first position, 2 is the second position, and so on. When adding an item, if n is greater than the number of existing menu items plus one, the item is added to the bottom of the menu. Note that separators are considered items and that in some cases, a set of menu items is counted as one. For more information, see CountMenuItems().
.Category | The type of item to be assigned: 1 or omitted Built-in commands 2 Macros 3 Fonts 4 AutoText entries 5 Styles

Argument | Explanation
.Name | The name of the built-in command, macro, font, AutoText entry, or style whose menu assignment you want to change. When adding or removing a separator, specify "(Separator)."
.Menu | The menu you want to change. Menu names are listed in the Change What Menu list box. Including an ampersand (&) before the access key in the menu name is optional (for example, you can specify either "File" or "&File"). Do not include the parenthetical phrases "(No Document)" and "(Shortcut)" even though that text appears in the Customize dialog box.
.AddBelow | The text of or command name associated with the menu item after which you want to add the new item. Note that you do not need to specify this argument if you specify .Position. If you specify both arguments, .AddBelow takes precedence.
.MenuText | The text as it will appear on the menu. Place an ampersand (&) in front of the access key, if any. On the Macintosh, access keys are displayed only in menu mode, which is activated by pressing the DECIMAL (.) key on the numeric keypad (Num Lock off). If you want an ampersand to appear in the menu text, include two ampersands. For example, setting .MenuText to "&Examples && Practices" creates the menu item "Examples & Practices."
.Rename | Renames the menu item specified by .Menu and .Name (and .Position, if specified), with the text specified by .MenuText.
.Add | Adds the item to the menu.
.Remove | Removes the item from the menu.
.ResetAll | Resets all menu assignments to their defaults. Note that this argument resets changes made with ToolsCustomizeMenuBar as well as ToolsCustomizeMenus.
.CommandValue | Additional text required for the command specified by .Name, if any. For example, if .Name is set to Color, .CommandValue specifies the color. For more information, see the next table in this entry.
.Context | Determines where the new menu assignment is stored: 0 (zero) or omitted Normal template 1 Active template

When removing or renaming menu items, you must specify .Name and .Menu. Word starts at the bottom of the specified menu and moves up until it finds an item that performs the action specified by .Name. You can also specify .Position and .MenuText if you need to be sure that the menu item you are changing is at a specific position and has specific menu text. Note that if Word can't find an item that matches each of the specified criteria, an error occurs.

The following table lists in the left column commands that require a command value and describes in the right column how to specify .CommandValue. The equivalent action in the Customize dialog box (Tools menu) to specifying .CommandValue is selecting an item in the list box that appears when you select one of the following commands in the Commands box.

If .Name is set to | .CommandValue must be
Borders, Color, or Shading | A number — specified as text — corresponding to the position of the setting in the list box containing values, where 0 (zero) is the first item, 1 is the second item, and so on.
Columns | A number between 1 and 45 — specified as text — corresponding to the number of columns you want to apply.
Condensed | A text measurement between 0.1 pt and 12.75 pt specified in 0.05-point increments (72 points = 1 inch).
Expanded | A text measurement between 0.1 pt and 12.75 pt specified in 0.05-point increments (72 points = 1 inch).
FileOpenFile | The path and filename of the file to open. If the path is not specified, the current folder is assumed.
Font Size | A positive text measurement, specified in 0.5-point increments (72 points = 1 inch).
Lowered, Raised | A text measurement between 1 pt and 64 pt specified in 0.5-point increments (72 points = 1 inch).
Symbol | A string created by concatenating a Chr$() instruction and the name of a symbol font (for example, Chr$(167) + "Symbol").

Example

This example adds the macro TestMacro to the Help menu. The menu item for this macro is Test, which appears immediately after Index. Because .AddBelow is specified, .Position is not required.

ToolsCustomizeMenus .Category = 2, .Name = "TestMacro", \
        .MenuType = 0, .Menu = "Help", .MenuText = "&Test", \
        .AddBelow = "Index", .Context = 0, .Add

See Also

CountMenuItems(), MenuItemMacro$(), MenuText$(), ToolsCustomizeMenuBar


ToolsGetSpelling, ToolsGetSpelling()

Syntax

ToolsGetSpelling FillArray$() [, Word$] [, MainDic$] [, SuppDic$] [, Mode]

ToolsGetSpelling(FillArray$() [, Word$] [, MainDic$] [, SuppDic$] [, Mode])

Remarks

The ToolsGetSpelling statement fills an array with the words suggested as replacements for a misspelled word. Suggestions are assigned to elements of the array in the order they appear in the spelling checker.

Argument | Explanation
FillArray$ | The array — which must be defined before ToolsGetSpelling is run — to fill with suggested replacements.
Word$ | The word for which you want suggested replacements. If Word$ is omitted, Word uses the word closest to the insertion point.
MainDic$ | A text string that represents the language name for the main dictionary in the specified language. For a list of valid foreign language names, see ToolsLanguage. If you specify neither a word nor a main dictionary, Word uses the main dictionary that corresponds to the language formatting of the word closest to the insertion point.
SuppDic$ | A path and filename for a custom dictionary (for example, "C:\WINWORD\USER1.DIC" (Windows) or "HD:WORD:MY TERMS" (Macintosh)). If Word$ is found in the custom dictionary, ToolsGetSpelling puts no words in the array. If .SuggestFromMainDictOnly (ToolsOptionsSpelling statement) is 0 (zero), suggested replacements are retrieved from the custom dictionary as well as the main dictionary. Note that anagrams are retrieved from the main dictionary only.
Mode | Specifies how Word makes suggestions for Word$: 0 or omitted Returns suggested correct spellings for Word$. 1 Returns suggested replacements that match the search criteria when Word$ contains the question mark (?) and asterisk (*) wildcard characters. 2 Returns anagrams for Word$ (words composed of the same letters as Word$). Word does not return anagrams from a custom dictionary. Note that this functionality may not be available if you are using a spelling checker other than the one shipped with Word.

The ToolsGetSpelling() function returns the number of replacements suggested by the spelling checker. If the word is spelled correctly, 0 (zero) is returned.

Example

This example checks the spelling of the word "kolor," and then displays up to five suggested replacements in a series of message boxes:

Dim suggest$(4)
ToolsGetSpelling suggest$(), "kolor"
For count = 0 To 4
    If suggest$(count) <> "" Then MsgBox suggest$(count)
Next

See Also

ToolsGetSynonyms, ToolsLanguage, ToolsOptionsSpelling


ToolsGetSynonyms, ToolsGetSynonyms()

Syntax

ToolsGetSynonyms FillArray$() [, Word$] [, MainDic$]

ToolsGetSynonyms(FillArray$() [, Word$] [, MainDic$])

Remarks

The ToolsGetSynonyms statement fills an array with synonyms for a word.

Argument | Explanation
FillArray$ | The array — which must be defined before ToolsGetSynonyms is run — to fill with synonyms.
Word$ | The word for which you want synonyms. If Word$ is omitted, Word uses the word closest to the insertion point.
MainDic$ | A text string that represents the language name for the main dictionary in the specified language. For a list of valid foreign language names, see ToolsLanguage. If you specify neither a word nor a main dictionary, Word uses the main dictionary that corresponds to the language formatting of the word closest to the insertion point.

The ToolsGetSynonyms() function returns the following values.

Value | Explanation
0 (zero) | If there are no synonyms available
–1 | If one or more synonyms are available

Example

This example prompts the user for a word, and then displays up to five synonyms for that word in a message box:

word$ = InputBox$("Display synonyms for: ", "Get Synonyms")
Dim synonyms$(4)
ToolsGetSynonyms synonyms$(), word$
list$ = synonyms$(0)
For count = 1 To 4
    If synonyms$(count) <> "" Then
        list$ = list$ + ", " + synonyms$(count)
    End If
Next
MsgBox list$, "Synonyms for " + word$

See Also

ToolsGetSpelling


ToolsGrammar

Syntax

ToolsGrammar

Remarks

Displays the Grammar dialog box (Tools menu) and begins checking grammar in the active document.

Example

This example displays a message box that asks whether or not to check grammar. If the user chooses the Yes button (returning a value of –1), Word begins checking grammar.

ans = MsgBox("Check grammar now?", 3)
If ans = -1 Then ToolsGrammar

See Also

ToolsSpelling


ToolsGrammarStatisticsArray

Syntax

ToolsGrammarStatisticsArray TwoDimensionalArray$()

Remarks

Performs a grammar check, and then fills a two-dimensional array with the available grammar statistics for the active document.

Argument | Explanation
TwoDimensionalArray$() | The two-dimensional array — which must be defined before ToolsGrammarStatisticsArray is run — to fill with the names of counts, averages, and indexes (the first dimension) and their associated statistics (the second dimension).

Example

This example defines a two-dimensional array for storing grammar statistics, fills the array with grammar statistics for the active document, and then inserts a two-column list of statistics at the insertion point (names of counts, averages, and indexes on the left and their associated statistics on the right, separated by tab characters):

numstats = CountToolsGrammarStatistics()
size = numstats -1
Dim docstats$(size, 1)
ToolsGrammarStatisticsArray docstats$()
For count = 0 To size
    InsertPara
    Insert docstats$(count, 0) + Chr$(9) + docstats$(count, 1)
Next

See Also

CountToolsGrammarStatistics()


ToolsHyphenation

Syntax

ToolsHyphenation [.AutoHyphenation = number] [.HyphenateCaps = number] [, .HyphenationZone = number or text] [, .LimitConsecutiveHyphens = number]

Remarks

Hyphenates the selected text or the entire document. The arguments for the ToolsHyphenation statement correspond to the options in the Hyphenation dialog box (Tools menu).

Argument | Explanation
.AutoHyphenation | If 1, hyphenates without prompting for verification.
.HyphenateCaps | If 1, allows hyphenation of words in all capital letters.
.HyphenationZone | A measurement for the hyphenation zone in points or a text measurement. The hyphenation zone is the maximum amount of space to allow between the end of a line and the right margin.
.LimitConsecutiveHyphens | The maximum number of consecutive lines that can end with hyphens (or 0 (zero) for No Limit).

Example

This example begins hyphenation, allowing hyphenation of words in all capital letters and setting a hyphenation zone of 24 points:

ToolsHyphenation .AutoHyphenation = 1, .HyphenateCaps = 1, \
        .HyphenationZone = "24 pt"

See Also

ToolsHyphenationManual


ToolsHyphenationManual

Syntax

ToolsHyphenationManual

Remarks

Hyphenates the document, displaying the Manual Hyphenation dialog box (Manual button, Hyphenation dialog box, Tools menu) each time Word proposes that a word be hyphenated so the user can manually adjust the placement of hyphens. To set hyphenation options before running ToolsHyphenationManual, use the ToolsHyphenation statement and set .AutoHyphenation to 0 (zero).

Example

This example sets a hyphenation zone of 16 points before running ToolsHyphenationManual. An error handler prevents error 102 ("Command failed") from appearing if the user cancels the Manual Hyphenation dialog box.

ToolsHyphenation .AutoHyphenation = 0, .HyphenationZone = 16
On Error Goto trap
ToolsHyphenationManual
trap:
If Err = 102 Then Goto bye Else Error Err
bye:

See Also

ToolsHyphenation


ToolsLanguage

Syntax

ToolsLanguage .Language = text [, .Default]

Remarks

Sets the language format for the selected text. The language format identifies the text for the proofing tools in Word so that rules appropriate to the specified language are used.

Argument | Explanation
.Language | The name of the language
.Default | Adds the specified language format to the definition of the active template's Normal style

The following list includes valid settings for .Language. Note that languages marked with an asterisk (*) are valid only in Word version 7.0.

To specify this language | Set .Language to this text
(no proofing) | 0 (zero) Do not include the text "(zero)"
Basque * | Euskera
Brazilian Portuguese | Português (BR)
Catalan | Català

To specify this language | Set .Language to this text
Czech * | Èeština
Danish | Dansk
Dutch | Nederlands
Dutch (preferred) | Nederlands (voorkeur)
English (AUS) | English (AUS)
English (UK) | English (UK)
English (US) | English (US)
Finnish | Suomi
French | Français
French Candien | Canadien Français
German | Deutsch
Greek * | ÅëëçíêÜ
Hungarian * | Magyar
Italian | Italiano
Norwegian Bokmål | Norsk Bokmål
Norwegian Nynorsk | Norsk Nynorsk
Polish * | Polski
Portuguese | Português (POR)
Russian * | Ðóññêèé
Slovenian * | Slovenian
Spanish | Español
Swedish | Svenska
Swiss German | Deutsch (Schweiz)
Turkish * | Türkçe

Example

This example makes Brazilian Portuguese an attribute of the Normal style:

ToolsLanguage .Language = "Português (BR)", .Default

See Also

CountLanguages(), FormatDefineStyleLang, Language


ToolsMacro

Syntax

ToolsMacro .Name = text [, .Run] [, .Edit] [, .Show = number] [, .Delete] [, .Rename] [, .Description = text] [, .NewName = text] [, .SetDesc]

Remarks

Runs or records a macro, sets the description of a macro, renames a macro, or opens a new or existing macro in a macro-editing window. The arguments for the ToolsMacro statement correspond to the options in the Macro dialog box (Tools menu). Note that the .Rename and .NewName arguments are included for compatibility with previous versions of Word.

Argument | Explanation
.Name | The name of the macro.
.Run | Runs the macro.
.Edit | Opens a macro-editing window containing the macro specified by .Name.
.Show | Specifies the context: 0 (zero) All available macros; includes macros in loaded global templates 1 Macros in the Normal template 2 Built-in commands 3 If the active document is not based on the Normal template, macros in the active template; otherwise, macros in the first loaded global template (global templates are listed in alphabetic order) > 3 Macros in the remaining loaded global templates (in alphabetic order) Omitted Word looks for the macro in whatever context was last selected in the Macro dialog box. To ensure that the correct macro runs, especially if a macro naming conflict between templates is possible, you should specify a value for .Show.
.Delete | Deletes the specified macro.
.Rename | Renames the specified macro.
.Description | Specifies a new description for the macro; used with .SetDesc. If the macro is assigned to a menu or toolbar and is selected or pointed to, the description is displayed in the status bar.
.NewName | A new name for the macro; used with .Rename.
.SetDesc | Sets a new description for the macro.

Example

This example opens a macro-editing window for the macro Test stored in the Normal template:

ToolsMacro .Name = "Test", .Show = 1, .Edit

See Also

CountMacros(), IsMacro(), KeyMacro$(), MacroDesc$(), MacroFileName$(), MacroNameFromWindow$(), MenuItemMacro$(), Organizer, PauseRecorder


ToolsManageFields

Syntax

ToolsManageFields [.FieldName = text] [, .Add] [, .Remove] [, .Rename] [, .NewName = text]

Remarks

Adds, removes, or renames a field name in a mail-merge data source or header source. If the active document does not contain a table with the specified field in the first row of the table, an error occurs.

Argument | Explanation
.FieldName | The field name you want to add, remove, or rename
.Add | Adds the specified field name to a new table column
.Remove | Removes the specified field name and the associated table column
.Rename | Renames the specified field name
.NewName | A new name for the field; used with .Rename

Example

This example renames the "Name1" field to "FirstName":

ToolsManageFields .FieldName = "Name1", .NewName = "FirstName", \
        .Rename

See Also

MailMergeEditDataSource


ToolsMergeRevisions

Syntax

ToolsMergeRevisions .Name = text

Remarks

Merges the revision marks from the active document into the specified document, which Word opens if it is not open already. If the active document minus revision marks is not equivalent to the specified document minus revision marks, an error occurs. You can use a series of FileOpen instructions followed by ToolsMergeRevisions instructions to collect revision marks from multiple review copies into one document.

Argument | Explanation
.Name | The path and filename of the document from which you want to merge revisions

Example

This example opens REVISE1.DOC, merges revision marks into ORIGINAL.DOC, and then performs the same action with REVISE2.DOC:

FileOpen .Name = "REVISE1.DOC"
ToolsMergeRevisions .Name = "ORIGINAL.DOC"
FileOpen .Name = "REVISE2.DOC"
ToolsMergeRevisions .Name = "ORIGINAL.DOC"

See Also

ToolsCompareVersions, ToolsOptionsRevisions, ToolsReviewRevisions, ToolsRevisions


ToolsNumberListDefault

Syntax

ToolsNumberListDefault

Remarks

Adds numbers and tab characters to the selected paragraphs and formats the paragraphs with a hanging indent.

Note

The ToolsNumberListDefault statement corresponds to the Numbered List button on the Toolbar in Word for Windows version 2.x. In Word version 6.0, the Numbering button is on the Formatting toolbar and its corresponding WordBasic statement is FormatNumberDefault.

See Also

FormatBulletDefault, FormatBulletsAndNumbering, FormatNumberDefault, ToolsBulletListDefault, ToolsBulletsNumbers


ToolsOptions

Syntax

ToolsOptions .Tab = number

Remarks

Displays the Options dialog box (Tools menu) with the specified tab selected. Unless you precede ToolsOptions with an On Error instruction, Word displays an error message if the dialog box is canceled.

Argument | Explanation
.Tab | The tab to select: 0 (zero) View 1 General 2 Edit 3 Print 4 Save 5 Spelling 6 Grammar 7 AutoFormat 8 Revisions 9 User Info 10 Compatibility 11 File Locations

Example

This example displays the View tab in the Options dialog box. The On Error Resume Next instruction prevents Word from displaying an error message if the user chooses Cancel.

On Error Resume Next
ToolsOptions .Tab = 0

See Also

ToolsCustomize


ToolsOptionsAutoFormat

Syntax

ToolsOptionsAutoFormat [.PreserveStyles = number] [, .ApplyStylesHeadings = number] [, .ApplyStylesLists = number] [, .ApplyStylesOtherParas = number] [, .AdjustParaMarks = number] [, .AdjustTabsSpaces = number] [, .AdjustEmptyParas = number] [, .ReplaceQuotes = number] [, .ReplaceSymbols = number] [, .ReplaceBullets = number] [, .ApplyBulletedLists = number] [, .ReplaceOrdinals = number] [, .ReplaceFractions = number] [, .ApplyBorders = number] [, .ApplyNumberedLists = number] [, .ShowOptionsFor = number]

Remarks

Sets automatic formatting options for FormatAutoFormat or the AutoFormat As You Type feature (Word version 7.0 only). The arguments for the ToolsOptionsAutoFormat statement correspond to the options on the AutoFormat tab in the Options dialog box (Tools menu). Note that the .ReplaceBullets, .AdjustParaMarks, .AdjustTabsSpaces, and .AdjustEmptyParas arguments are retained for backward compatibility with Word version 6.0 macros.

Argument | Explanation
.PreserveStyles | If 1, preserves previously applied styles. In Word version 7.0, this argument is ignored when .ShowOptionsFor is set to 0 (zero).
.ApplyStylesHeadings | If 1, applies automatic styles to headings. In Word version 7.0, this argument is ignored when .ShowOptionsFor is set to 0 (zero).
.ApplyStylesLists | If 1, applies automatic styles to lists. In Word version 7.0, this argument is ignored when .ShowOptionsFor is set to 0 (zero).
.ApplyStylesOtherParas | If 1, applies automatic styles to paragraphs.
.AdjustParaMarks | If 1, adds or removes paragraph marks in a document (for example, removes extra paragraph marks from lines of text copied from an electronic mail message).
.AdjustTabsSpaces | If 1, adjusts tab settings and spaces automatically.
.AdjustEmptyParas | If 1, removes empty paragraph marks used to add space between paragraphs.
.ReplaceQuotes | If 1, replaces straight double quotation marks (" "), single quotation marks (' '), and apostrophes ( ' ) with "smart" quotation marks (" " or ' ') and apostrophes ( ' ).
.ReplaceSymbols | If 1, replaces "(r)", "(c)", and "(tm)" with the Ò, Ó, and Ô symbols from the Symbol dialog box (Insert menu).
.ReplaceBullets | If 1, replaces bullet characters with bullets from the Bullets And Numbering dialog box (Format menu). If -1, the setting specified by .ApplyBulletedLists is used. This argument is ignored when .ShowOptionsFor is set to 0 (zero).
.ApplyBulletedLists | If 1, replaces bullet characters with bullets from the Bullets And Numbering dialog box (Format menu), according to what is typed. For example, "=>" is replaced with "ð". This argument is available only in Word version 7.0.
.ReplaceOrdinals | If 1, replaces "st", "nd", "rd", or "th" in ordinal numbers with the same letters in superscript. For example, "1st" is replaced with "1st."

Argument | Explanation
.ReplaceFractions | If 1, replaces typed fractions with fractions from the current character set. For example, 1/2 is replaced with ½.
.ApplyBorders | If 1, applies borders by replacing a series of three or more minus signs (-), equal signs (=), or underlines ( _ ) with a specific border line. For example, a series of three or more equal signs (=) is replaced by a double border line. This argument is available only in Word version 7.0. It is ignored when .ShowOptionsFor is set to 1 or is omitted.
.ApplyNumberedLists | If 1, interprets and formats paragraphs as numbered lists with a numbering scheme from the Bullets And Numbering dialog box (Format menu), according to what is typed. For example, if a paragraph starts with "1.1" and a tab, Word automatically inserts "1.2" and a tab after the ENTER key is pressed. This argument is available only in Word version 7.0. It is ignored when .ShowOptionsFor is set to 1 or is omitted.
.ShowOptionsFor | Specifies which group of options are set by the ToolsOptionsAutoFormat statement: 0 (zero) AutoFormat As You Type feature 1 or omitted FormatAutoFormat statement This argument is available only in Word version 7.0.

See Also

FormatAutoFormat, ToolsAutoCorrect


ToolsOptionsCompatibility

Syntax

ToolsOptionsCompatibility [.Product = text] [, .Default] [, .NoTabHangIndent = number] [, .NoSpaceRaiseLower = number] [, .PrintColBlack = number] [, .WrapTrailSpaces = number] [, .NoColumnBalance = number] [, .ConvMailMergeEsc = number] [, .SuppressSpBfAfterPgBrk = number] [, .SuppressTopSpacing = number] [, .OrigWordTableRules = number] [, .TransparentMetafiles = number] [, .ShowBreaksInFrames = number] [, .SwapBordersFacingPages = number] [, .LeaveBackslashAlone = number] [, .ExpandShiftReturn = number] [, .DontULTrailSpace = number] [, .DontBalanceSbDbWidth = number] [, .SuppressTopSpacingMac5 = number] [, .SpacingInWholePoints = number] [, .PrintBodyTextBeforeHeader = number] [, .NoLeading = number]
[, .NoSpaceForUL = number] [, .MWSmallCaps = number]
[, .NoExtraLineSpacing = number] [, .TruncateFontHeight = number] [.SubFontBySize = number]

Remarks

Adjusts the display of certain elements in the active document to mimic the display in other word-processing applications. For example, you can specify that spaces at the end of a line wrap to the next line as they do in WordPerfect. The arguments for the ToolsOptionsCompatibility statement correspond to the options on the Compatibility tab in the Options dialog box (Tools menu).

Argument | Explanation
.Product | The name of the product whose display you want to mimic, as listed in the Recommended Options For box. If you specify .Product, display options are determined automatically.
.Default | Makes the display options you specify the default for new documents based on the active template.
.NoTabHangIndent | If 1, a tab stop is not added automatically to a paragraph formatted with a hanging indent.
.NoSpaceRaiseLower | If 1, extra line spacing is not added for raised and lowered characters.
.PrintColBlack | If 1, colors are printed as black on printers that don't support color.
.WrapTrailSpaces | If 1, spaces at the end of lines wrap to the next line.
.NoColumnBalance | If 1, text columns are not balanced above continuous section breaks.
.ConvMailMergeEsc | If 1, correctly interprets characters preceded by backslashes (\) in Word version 2.x mail-merge data sources. For example, \" is interpreted as ".
.SuppressSpBfAfterPgBrk | If 1, space before or after hard page and column breaks is removed.
.SuppressTopSpacing | If 1, extra line spacing at the top of the page is removed.
.OrigWordTableRules | If 1, table borders are combined as in Word for the Macintosh version 5.x.
.TransparentMetafiles | If 1, the area behind metafile pictures is not blanked.
.ShowBreaksInFrames | If 1, Word displays manual, or "hard," page or column breaks in any frames that contain them.
.SwapBordersFacingPages | If 1, Word prints a left paragraph border (not a box) on the right on odd numbered pages if either the Different Odd And Even or Mirror Margins check box (Page Setup dialog box, File menu) is selected.
.SuppressTopSpacingMac5 | If 1, extra line spacing at the top of the page is handled as in Word for the Macintosh version 5.x.

Argument | Explanation
.SpacingInWholePoints | If 1, rounds character spacing measurements to the nearest whole number.
.PrintBodyTextBeforeHeader | If 1, the main text layer prints before the header/footer layer (the reverse of the default order). This allows Word to process PostScript codes in the main text layer the same as Word for the Macintosh version 5.x.
.NoLeading | If 1, displays lines of text without leading as in Word for the Macintosh version 5.x.
.NoSpaceForUL | If 1, no extra space for underlines is added. This argument is available only in Word version 7.0.
.MWSmallCaps | If 1, Word applies small caps formatting as in Word for the Macintosh version 5.x (which produces slightly larger small caps).
.NoExtraLineSpacing | If 1, line spacing is handled as in WordPerfect version 5.x. This argument is available only in Word version 7.0.
.TruncateFontHeight | If 1, font size is rounded up or down as in WordPerfect version 6.x for Windows. This argument is available only in Word version 7.0.
.SubFontBySize | If 1, fonts are substituted based on the font size in WordPerfect version 6.0 documents. This argument is available only in Word version 7.0.

Note

The arguments .LeaveBackslashAlone, .ExpandShiftReturn, .DontULTrailSpace, and .DontBalanceSbDbWidth affect only the Japanese version of Word and are otherwise ignored.

If you specify .Product and at least one other display option, the display option settings take precedence.

See Also

FontSubstitution


ToolsOptionsEdit

Syntax

ToolsOptionsEdit [.ReplaceSelection = number] [, .DragAndDrop = number] [, .AutoWordSelection = number] [, .InsForPaste = number] [, .Overtype = number] [, .SmartCutPaste = number] [, .AllowAccentedUppercase = number] [, .PictureEditor = text]
[, .TabIndent = number]

Remarks

Sets editing options. The arguments for the ToolsOptionsEdit statement correspond to the options on the Edit tab in the Options dialog box (Tools menu).

Argument |  | Explanation
.ReplaceSelection |  | If 1, replaces selected text with typed text.
.DragAndDrop |  | If 1, allows drag-and-drop editing.
.AutoWordSelection |  | If 1, dragging selects one word at a time instead of one character at a time.
.InsForPaste |  | If 1, allows the INS key to be used for pasting the Clipboard contents.
.Overtype |  | If 1, replaces text following the insertion point with typed text.
.SmartCutPaste |  | If 1, automatically adjusts spacing between words and punctuation when cutting and pasting.
.AllowAccentedUppercase | If 1, allows proofing tools and the Change Case feature to suggest that Word add an accent mark to an uppercase letter.
.PictureEditor | The name of the application you want to use to edit pictures, as it appears in the Picture Editor box.
.TabIndent | If 1, TAB and BACKSPACE can be used to add or remove list formatting. This argument is available only in Word version 7.0.

Example

This example toggles the Drag-And-Drop Text Editing check box:

Dim dlg As ToolsOptionsEdit
GetCurValues dlg
If dlg.DragAndDrop Then
    dlg.DragAndDrop = 0
Else
    dlg.DragAndDrop = 1
End If
ToolsOptionsEdit dlg

See Also

Overtype


ToolsOptionsFileLocations

Syntax

ToolsOptionsFileLocations .Path = text , .Setting = text

Remarks

Sets default folders. The arguments for the ToolsOptionsFileLocations statement correspond to the options on the File Locations tab in the Options dialog box (Tools menu). The new setting takes effect immediately.

Argument | Explanation
.Path | One of the following settings in the [Microsoft Word] section of WINWORD6.INI (Windows 3.x), Word Settings (6) (Macintosh), or the registry (Windows 95 and Windows NT): DOC-PATH PICTURE-PATH USER-DOT-PATH WORKGROUP-DOT-PATH INI-PATH AUTOSAVE-PATH TOOLS-PATH CBT-PATH STARTUP-PATH
.Setting | The path for the default folder, or an empty string ("") to remove the setting from WINWORD6.INI (Windows), Word Settings (6) (Macintosh), or the registry (Windows 95 and Windows NT).

Example

This example sets the default folder for documents to C:\MYDOCS. On the Macintosh, substitute a folder name such as HD:WORD DOCS.

ToolsOptionsFileLocations .Path = "DOC-PATH", \
        .Setting = "C:\MYDOCS"

See Also

SetPrivateProfileString


ToolsOptionsGeneral

Syntax

ToolsOptionsGeneral [.Pagination = number] [, .WPHelp = number] [, .WPDocNavKeys = number] [, .BlueScreen = number] [, .ErrorBeeps = number] [, .Effects3d = number] [, .UpdateLinks = number] [, .SendMailAttach = number] [, .RecentFiles = number] [, .RecentFileCount = number] [, .Units = number] [, .ButtonFieldClicks = number] [, .ShortMenuNames = number] [, .RTFInClipboard = number]
[, .ConfirmConversions = number] [, .TipWizardActive = number]

Remarks

Sets general options. The arguments for the ToolsOptionsGeneral statement correspond to the options on the General tab in the Options dialog box (Tools menu).

Argument | Explanation
.Pagination | If 1, allows background repagination.
.WPHelp | If 1, enables WordPerfect Help (ignored on the Macintosh).

Argument | Explanation
.WPDocNavKeys | If 1, enables WordPerfect document navigation keys (ignored on the Macintosh).
.BlueScreen | If 1, changes the document window to display white text on a blue background.
.ErrorBeeps | If 1, Word beeps when an action occurs that generates an error.
.Effects3d | If 1, Word displays dialog boxes with three-dimensional effects. This argument is ignored in Word version 7.0.
.UpdateLinks | If 1, automatically updates linked information when you open documents.
.SendMailAttach | If 1, the Send command (File menu) sends the active document as an attachment instead of text in an electronic mail message.
.RecentFiles | If 1, lists recently used files above the Exit command on the File menu.
.RecentFileCount | A number from 1 to 9 corresponding to the maximum number of recently used files you want to be listed.
.Units | Sets the default unit of measurement: 0 (zero) Inches 1 Centimeters 2 Points 3 Picas
.ButtonFieldClicks | Sets the number of clicks (1 or 2) required to run a macro with a MACROBUTTON field.
.ShortMenuNames | If 1, on the Macintosh, substitutes "Ins" for "Insert," "Fmt" for "Format," and "Wnd" for "Window" on the menu bar. In Windows, this argument produces an error.
.RTFInClipboard | If 1, on the Macintosh, text copied to the Clipboard retains its character and paragraph formatting. In Windows, this argument produces an error.
.ConfirmConversions | If 1, displays the Convert File dialog box if the file you want to open is not in Word format. This argument is available only in Word version 7.0.
.TipWizardActive | If 1, activates the TipWizard. If the TipWizard is already activated, resets the TipWizard (the TipWizard may display tips that you have already seen). This argument is available only in Word verison 7.0.

Example

Before opening TEST.DOC, this example ensures that no filename will be "bumped off" the list of recently used files when changes are saved to TEST.DOC (unless the list already contains the maximum of nine filenames):

Dim dlg As ToolsOptionsGeneral
GetCurValues dlg
num = CountFiles()
If num < 9 Then
    num$ = LTrim$(Str$(num))
    If dlg.RecentFileCount = num$ Then
        dlg.RecentFileCount = num + 1
        ToolsOptionsGeneral dlg
    End If
End If
FileOpen .Name = "TEST.DOC"

See Also

Beep, CountFiles(), HelpWordPerfectHelpOptions, ToolsRepaginate


ToolsOptionsGrammar

Syntax

ToolsOptionsGrammar [.Options = number] [.CheckSpelling = number] [, .ShowStatistics = number]

Remarks

Sets grammar checking options. The arguments for the ToolsOptionsGrammar statement correspond to the options on the Grammar tab in the Options dialog box (Tools menu).

Argument | Explanation
.Options | Specifies which set of grammar rules to use: 0 (zero) All rules 1 Rules for business writing 2 Rules for casual writing 3 First custom settings 4 Second custom settings 5 Third custom settings
.CheckSpelling | If 1, checks spelling during grammar checking.
.ShowStatistics | If 1, readability statistics are displayed when the grammar check is complete.

Example

This example specifies that spelling be checked with grammar, and then starts the grammar checker:

ToolsOptionsGrammar .CheckSpelling = 1, .ShowStatistics = 1
ToolsGrammar

See Also

ToolsGrammar


ToolsOptionsPrint

Syntax

ToolsOptionsPrint [.Draft = number] [, .Reverse = number] [, .UpdateFields = number] [, .Summary = number] [, .ShowCodes = number] [, .Annotations = number] [, .ShowHidden = number] [, .EnvFeederInstalled = number] [, .UpdateLinks = number] [, .Background = number] [, .DrawingObjects = number] [, .FormsData = number] [, .DefaultTray = text] [, .FractionalWidths = number] [, .PSOverText = number]

Remarks

Sets options for printing a document. The arguments for the ToolsOptionsPrint statement correspond to the options on the Print tab in the Options dialog box (Tools menu).

Argument | Explanation
.Draft | If 1, prints in draft output (ignored on the Macintosh).
.Reverse | If 1, prints pages in reverse order.
.UpdateFields | If 1, updates all fields in the document when printed.
.Summary | If 1, prints summary information with the document.
.ShowCodes | If 1, prints field codes instead of field results.
.Annotations | If 1, prints annotations with the document.
.ShowHidden | If 1, prints all hidden text with the document.
.EnvFeederInstalled | If 1, indicates that an envelope feeder is installed.
.UpdateLinks | If 1, automatically updates all linked information when you print documents.
.Background | If 1, allows background printing (ignored on the Macintosh).
.DrawingObjects | If 1, prints Word drawing objects with the document.
.FormsData | If 1, prints only the data entered by the user in an online form onto a preprinted form.
.DefaultTray | Specifies the default paper tray as it appears in the Default Tray box.
.FractionalWidths | If 1, improves the character spacing in proportionally spaced fonts when printing on a LaserWriter® (Macintosh only).
.PSOverText | If 1, prints the result of PRINT field instructions (such as PostScript commands) on top of text or other graphics when printing on a LaserWriter (Macintosh only).

Example

This example specifies that documents be printed in reverse page order:

ToolsOptionsPrint .Reverse = 1

See Also

FilePrint, FilePrintSetup


ToolsOptionsRevisions

Syntax

ToolsOptionsRevisions [.InsertedTextMark = number] [, .InsertedTextColor = number] [, .DeletedTextMark = number] [, .DeletedTextColor = number] [, .RevisedLinesMark = number] [, .RevisedLinesColor = number] [, .HighlightColor = number]

Remarks

Sets options for marking revisions. The arguments for the ToolsOptionsRevisions statement correspond to the options on the Revisions tab in the Options dialog box (Tools menu). The options affect documents in which revision marking is active, and documents you compare to other documents with the Compare Versions command (Revisions dialog box, Tools menu).

Argument | Explanation
.InsertedTextMark | The format for inserted text: 0 (zero) None 1 Bold 2 Italic 3 Underline 4 Double underline
.DeletedTextMark | The format for deleted text: 0 (zero) Hidden 1 Strikethrough
.RevisedLinesMark | The position for revision lines: 0 (zero) None 1 Left border 2 Right border 3 Outside border
.InsertedTextColor, .DeletedTextColor, .RevisedLinesColor | The colors for inserted text, deleted text, and revision lines. If omitted, the color is set to "Auto." For a list of values, see CharColor.
.HighlightColor | The color for highlighting. The highlighting color remains the current color unless a different one is specified. If .HighlightColor is set to 0 (zero), no highlighting is applied. For a list of values, see CharColor. This argument is available only in Word version 7.0.

Example

When revision marking is active, this example instructs Word to format inserted text with a double underline and to add blue revision lines in the left margin:

ToolsOptionsRevisions .InsertedTextMark = 4, \
        .RevisedLinesMark = 1, .RevisedLinesColor = 2

See Also

ToolsCompareVersions, ToolsRevisions


ToolsOptionsSave

Syntax

ToolsOptionsSave [.CreateBackup = number] [, .FastSaves = number] [, .SummaryPrompt = number] [, .GlobalDotPrompt = number] [, .NativePictureFormat = number] [, .EmbedFonts = number] [, .FormsData = number] [, .AutoSave = number] [, .SaveInterval = text] [, .Password = text] [, .WritePassword = text] [, .RecommendReadOnly = number]

Remarks

Sets options for saving documents. The arguments for the ToolsOptionsSave statement correspond to the options on the Save tab in the Options dialog box (Tools menu).

Argument | Explanation
.CreateBackup | If 1, creates a backup copy every time you save, and fast saves are not allowed.
.FastSaves | If 1, allows fast saves.
.SummaryPrompt | If 1, prompts for summary information when you save a new document.
.GlobalDotPrompt | If 1 and you make changes to the Normal template, displays a message box asking if you want save the changes when you quit Word; if 0 (zero), changes to the Normal template are saved automatically.
.NativePictureFormat | If 1, saves imported graphics in the format of the current platform only (for example, in Windows, saves only the Windows version of graphics imported from the Macintosh).
.EmbedFonts | If 1, embeds TrueType fonts when you save.
.FormsData | If 1, saves the data entered by a user in a form as a tab-delimited record for use in a database.
.AutoSave | If 1, allows automatic saving.
.SaveInterval | Specifies the time interval for saving documents automatically, in minutes; available only if .AutoSave has been set to 1.
.Password | The password for opening the document.
.WritePassword | The password for saving changes to the document.
.RecommendReadOnly | If 1, displays a message box upon opening the document suggesting that it be opened as read-only.

Example

This example sets an interval of 10 minutes between automatic saves:

ToolsOptionsSave .AutoSave = 1, .SaveInterval = "10"

See Also

FileSave, FileSaveAll, FileSaveAs


ToolsOptionsSpelling

Syntax

ToolsOptionsSpelling [.AlwaysSuggest = number] [, .SuggestFromMainDictOnly = number] [, .IgnoreAllCaps = number] [, .IgnoreMixedDigits = number] [, .ResetIgnoreAll] [, .Type = number] [, .CustomDict n = text] [, .AutomaticSpellChecking = number] [, .HideSpellingErrors = number] [, .RecheckDocument]

Remarks

Sets options for checking spelling in a document. The arguments for the ToolsOptionsSpelling statement correspond to the options on the Spelling tab in the Options dialog box (Tools menu).

Argument | Explanation
.AlwaysSuggest | If 1, always suggests a replacement spelling for each misspelled word.
.SuggestFromMainDictOnly | If 1, draws spelling suggestions from the main dictionary only.
.IgnoreAllCaps | If 1, ignores words in all capital letters.
.IgnoreMixedDigits | If 1, ignores words that contain numbers.
.ResetIgnoreAll | Resets the Ignore All list so that Word will not ignore words for which you chose Ignore All while checking spelling during the current Word session.
.Type | Type of dictionary being searched: 0 (zero) Normal 2 Complete 3 Medical 4 Legal Note that if you specify 2, 3, or 4 and have not installed the corresponding dictionary, an error occurs. For information on how to purchase supplemental dictionaries, contact Microsoft Customer Service.
.CustomDictn | The path and filename of a custom dictionary to create or add; include a separate .CustomDictn argument for each custom dictionary, up to 10.

Argument | Explanation
.AutomaticSpellChecking | If 1, enables automatic checking for spelling in the current document. This argument is available only in Word version 7.0.
.HideSpellingErrors | If 1, hides spelling error underlines in the active document. This argument is available only in Word version 7.0.
.RecheckDocument | Rechecks the entire document for spelling errors. This ensures that words that have already been reviewed and corrected are checked for spelling errors again. This argument is available only in Word version 7.0.

Example

This example performs a spelling check in which words in all capital letters and words that contain numbers are not checked. The custom dictionary MYTERMS.DIC is used with the main dictionary. On the Macintosh, substitute a path such as HD:WORD:MY TERMS.

ToolsOptionsSpelling .IgnoreAllCaps = 1, .IgnoreMixedDigits = 1,\
        .Type = 0, .CustomDict1 = "C:\WINWORD\MYTERMS.DIC"
ToolsSpelling

See Also

DocumentHasMisspellings, NextMisspelling, ToolsSpelling, ToolsSpellSelection


ToolsOptionsUserInfo

Syntax

ToolsOptionsUserInfo [.Name = text] [, .Initials = text] [, .Address = text]

Remarks

Changes user information. The arguments for the ToolsOptionsUserInfo statement correspond to the options on the User Info tab in the Options dialog box (Tools menu).

Argument | Explanation
.Name | The name of the current user
.Initials | The initials of the current user
.Address | The mailing address of the current user

Example

This example sets the current user name and initials:

ToolsOptionsUserInfo .Name = "Gina Fiori", .Initials = "GF"

See Also

DocumentStatistics, FileSummaryInfo


ToolsOptionsView

Syntax

ToolsOptionsView [.DraftFont = number] [, .WrapToWindow = number] [, .PicturePlaceHolders = number] [, .FieldCodes = number] [, .BookMarks = number] [, .FieldShading = number] [, .StatusBar = number] [, .HScroll = number] [, .VScroll = number] [, .StyleAreaWidth = number or text] [, .Tabs = number] [, .Spaces = number] [, .Paras = number] [, .Hyphens = number] [, .Hidden = number] [, .ShowAll = number] [, .Drawings = number] [, .Anchors = number] [, .TextBoundaries = number] [, .VRuler = number] [, .Highlight = number]

Remarks

Displays or hides various elements in the active document or macro-editing window and the Word window. With the exception of .StatusBar, which controls the display of the status bar no matter which window is active, the arguments for ToolsOptionsView control the display of elements on a window-by-window basis. The arguments correspond to the options on the View tab in the Options dialog box (Tools menu). As indicated in the following table, not all arguments are available in every view or in the macro-editing window. Specifying an argument that is not available in the active view generates an error.

Argument | Explanation | Available in these views
.DraftFont | If 1, shows all text in the same font without formatting. | Normal, outline, macro
.WrapToWindow | If 1, Word wraps text within document windows; column formatting is ignored. | Normal, outline, macro
.PicturePlaceHolders | If 1, displays placeholders for graphics. | Normal, outline, page layout
.FieldCodes | If 1, displays field codes. | Normal, outline, page layout
.BookMarks | If 1, displays bold brackets around text marked with a bookmark. | Normal, outline, page layout
.FieldShading | Specifies when to display fields with shading: 0 (zero) Never 1 Always 2 When Selected | Normal, outline, page layout
.StatusBar | If 1, displays the status bar. | All
.HScroll | If 1, displays horizontal scroll bars in document windows. | All

Argument | Explanation | Available in these views
.VScroll | If 1, displays vertical scroll bars in document windows. | All
.StyleAreaWidth | Sets the width of the style area in twips (20 twips = 1 point; 72 points = 1 inch) or a text measurement. | Normal, outline
.Tabs | If 1, displays tab marks. | All
.Spaces | If 1, displays space marks. | All
.Paras | If 1, displays paragraph marks. | All
.Hyphens | If 1, displays optional hyphens. | All
.Hidden | If 1, displays hidden text. | All
.ShowAll | If 1, displays all nonprinting characters. | All
.Drawings | If 0 (zero), hides any drawing objects you've created in your documents. | Page layout
.Anchors | If 1, displays anchors next to items that may be positioned. | Page layout
.TextBoundaries | If 1, displays text boundaries. | Page layout
.VRuler | If 1, displays the vertical ruler. | Page layout
.Highlight | If 1, displays highlight formatting that has been applied to text. This argument is available only in Word version 7.0. | Normal, outline, page layout

Example

This example toggles the display of hidden text:

Dim dlg As ToolsOptionsView
GetCurValues dlg
dlg.ShowAll = 0
If dlg.Hidden Then
    dlg.Hidden = 0
Else
    dlg.Hidden = 1
End If
ToolsOptionsView dlg

See Also

ShowAll, TableGridlines, ToggleFull, ToolsOptionsCompatibility, ViewDraft, ViewRibbon, ViewRuler, ViewStatusBar


ToolsProtectDocument

Syntax

ToolsProtectDocument [.DocumentPassword = text] [, .NoReset = number] [, .Type = number]

Remarks

Protects the document from changes. According to the value of .Type, the user can make limited changes such as adding annotations or revision marks. If the document is already protected, an error occurs.

Argument | Explanation
.DocumentPassword | The password required to "unprotect" the document after choosing Unprotect Document (Tools menu).
.NoReset | If 1, Word does not reset form fields to their default results when a form is protected from changes using ToolsProtectDocument (applies only if .Type is 2). This option allows the form designer to create an "on entry" or "on exit" macro that removes protection from the form, modifies the form, and then protects it again without resetting form fields. Note that form fields are always reset when you protect a form using the Forms toolbar or the Protect Document dialog box (Tools menu).
.Type | The type of protection: 0 (zero) or omitted Users can select and edit text, but all changes are tracked with revision marks. 1 Users can only add annotations. 2 Users can only select and modify text in form fields. To specify which sections of a multiple-section form should be protected and which should not, use ToolsProtectSection.

Unlike FileSaveAs or ToolsOptionsSave, which you can use to protect a document from being opened or saved, ToolsProtectDocument controls what
the user is allowed to do while the document is open.

See Also

DocumentProtection(), FileSaveAs, ToolsOptionsSave, ToolsProtectSection, ToolsUnprotectDocument


ToolsProtectSection

Syntax

ToolsProtectSection .Protect = number [, .Section = number]

Remarks

Enables or disables protection for sections within a document when the document is protected for forms with ToolsProtectDocument. ToolsProtectSection has no effect if the document is protected for annotations or revision marks.

Argument | Explanation
.Protect | Specifies whether to enable or disable protection for the specified section: 0 (zero) or omitted Disables protection. 1 Enables protection.
.Section | The section for which you want to enable or disable protection: 1 corresponds to the first section, 2 to the second section, and so on.

Example

This example protects a document for forms, but disables protection for the second section of the document:

ToolsProtectDocument .Type = 2
ToolsProtectSection .Section = 2, .Protect = 0

See Also

DocumentProtection(), ToolsProtectDocument, ToolsUnprotectDocument


ToolsRemoveRecordDefault

Syntax

ToolsRemoveRecordDefault

Remarks

Removes the data record containing the insertion point — for example, removes the table row containing the insertion point. ToolsRemoveRecordDefault can be used with any document that could be used as a data source during a mail merge.

See Also

MailMergeEditDataSource, ToolsAddRecordDefault


ToolsRepaginate

Syntax

ToolsRepaginate

Remarks

Forces repagination of the entire document.

Example

This example repaginates the document if it has been changed since the last time it was saved:

If IsDocumentDirty() Then ToolsRepaginate

See Also

ToolsOptionsGeneral


ToolsReviewRevisions

Syntax

ToolsReviewRevisions [.ShowMarks] [, .HideMarks] [, .Wrap = number] [, .FindPrevious] [, .FindNext] [, .AcceptRevisions] [, .RejectRevisions]

Remarks

Searches for revision marks or accepts or rejects the selected revisions. The arguments for ToolsReviewRevisions correspond to the options in the Review Revisions dialog box (Revisions command, Tools menu).

You can use only one of the following arguments per ToolsReviewRevisions instruction.

Argument | Explanation
.ShowMarks | Displays revision marks in the active document.
.HideMarks | Hides revision marks in the active document.
.Wrap | Controls what happens if the search begins at a point other than the beginning of the document and the end of the document is reached: 0 (zero) or omitted The search operation ends and the macro continues. 1 The search continues from the beginning of the document to the point where the search began. 2 Word displays a message box asking whether to continue the search from the beginning of the document.
.FindPrevious | Searches toward the beginning of the document and selects the nearest text with revision marks.
.FindNext | Searches toward the end of the document and selects the nearest text with revision marks.
.AcceptRevisions | Accepts the revisions to the selected text.
.RejectRevisions | Cancels the revisions to the selected text.

Example

This example displays revision marks, selects the next marked text, and then accepts the revisions:

ToolsReviewRevisions .ShowMarks
ToolsReviewRevisions .FindNext
ToolsReviewRevisions .AcceptRevisions

See Also

ToolsCompareVersions, ToolsOptionsRevisions, ToolsRevisions, ToolsRevisionType()


ToolsRevisionAuthor$()

Syntax

ToolsRevisionAuthor$()

Remarks

Returns the name of the person who made the selected revision. If the selection does not include revision marks, ToolsRevisionAuthor$() returns an empty string ("").

Example

This example finds the next revision and checks the revision author. If the revision author is Stella Richards, the revision is accepted.

ToolsRevisions .ViewRevisions = 1
ToolsReviewRevisions .FindNext
If ToolsRevisionAuthor$() = "Stella Richards" Then
    ToolsReviewRevisions .AcceptRevisions
End If

See Also

ToolsReviewRevisions, ToolsRevisionDate$(), ToolsRevisions, ToolsRevisionType()


PrintToolsRevisionDate()

Syntax

ToolsRevisionDate()

Remarks

Returns a serial number corresponding to the date and time the selected revision was made, or –1 if the selection contains no revisions. For information on serial numbers, see DateSerial().

Example

This example finds the next revision and checks the revision date. The revision
is rejected if it was made more than 10 days before the current date.

ToolsRevisions .ViewRevisions = 1
ToolsReviewRevisions .FindNext
If (Now() - ToolsRevisionDate()) > 10 Then
    ToolsReviewRevisions .RejectRevisions
End If

See Also

ToolsReviewRevisions, ToolsRevisionAuthor$(), ToolsRevisionDate$(), ToolsRevisions, ToolsRevisionType()


ToolsRevisionDate$()

Syntax

ToolsRevisionDate$()

Remarks

Returns the date and time the selected revision was made. If the selection does
not include revision marks, ToolsRevisionDate$() returns an empty string ("").

Example

This example uses the ToolsRevisionType() function to determine whether the selection contains a revision. If so, a message box displays the date and time the selected revision was made. If the selected text contains no revision, Word displays an appropriate message box.

If ToolsRevisionType() <> 0 Then
    MsgBox "Revision made " + ToolsRevisionDate$() + "."
Else
    MsgBox "No revisions are selected."
End If

See Also

ToolsReviewRevisions, ToolsRevisionAuthor$(), ToolsRevisionDate(), ToolsRevisions, ToolsRevisionType()


ToolsRevisions

Syntax

ToolsRevisions [.MarkRevisions = number] [, .ViewRevisions = number] [, .PrintRevisions = number] [, .AcceptAll] [, .RejectAll]

Remarks

Specifies how revisions are marked and reviewed in the active document. The arguments for the ToolsRevisions statement correspond to the options in the Revisions dialog box (Tools menu).

Argument | Explanation
.MarkRevisions | If 1, activates revision marking.
.ViewRevisions | If 1, revision marks appear in the document when you edit it with revision marking on.
.PrintRevisions | Specifies whether or not to include revision marks in the printed document: 0 (zero) Revision marks do not appear (revisions are printed as if they were accepted). 1 Revision marks appear.
.AcceptAll | Accepts all revisions in the active document.
.RejectAll | Rejects all revisions in the active document.

Example

This example activates revision marking in the active document, but prevents the revision marks from appearing while the document is edited:

ToolsRevisions .MarkRevisions = 1, .ViewRevisions = 0

See Also

ToolsCompareVersions, ToolsMergeRevisions, ToolsOptionsRevisions, ToolsReviewRevisions, ToolsRevisionType()


ToolsRevisionType()

Syntax

ToolsRevisionType()

Remarks

Returns one of the following values, corresponding to the type of revision made to the selected text.

Value | Explanation
0 (zero) | If the selection contains no revisions
1 | If all or part of the selection contains text marked as inserted
2 | If all or part of the selection contains text marked as deleted
3 | If the selection contains a replacement (text marked as inserted followed immediately by text marked as deleted)
4 | If the selection contains more than one revision

For an example, see the entry for ToolsRevisionDate$().

See Also

ToolsReviewRevisions, ToolsRevisionAuthor$(), ToolsRevisionDate(), ToolsRevisionDate$(), ToolsRevisions


ToolsShrinkToFit

Syntax

ToolsShrinkToFit

Remarks

Attempts to decrease the font size of text just enough to fit the active document on one fewer pages. ToolsShrinkToFit is handy for saving paper when printing if the last page contains only a few lines of text. If Word is unable to perform the operation, a message box is displayed.

See Also

ViewZoomWholePage


ToolsSpelling

Syntax

ToolsSpelling

Remarks

Checks spelling in the current selection or, if there isn't a selection, checks spelling from the location of the insertion point to the end of the document.

Example

This example asks whether or not to check spelling, and then checks spelling if the user chooses the Yes button:

ans = MsgBox("Check spelling now?", 3)
If ans = -1 Then
    StartOfDocument
    ToolsSpelling
End If

See Also

ToolsOptionsSpelling, ToolsSpellSelection


ToolsSpellingRecheckDocument

Syntax

ToolsSpellingRecheckDocument

Remarks

Rechecks the entire document for spelling errors, ensuring that words that have already been reviewed and corrected are checked for spelling errors again. In Word version 6.0, ToolsSpellingRecheckDocument is unavailable and generates an error.

See Also

DocumentHasMisspellings(), NextMisspelling, SpellChecked, ToolsSpelling, ToolsSpellSelection


ToolsSpellSelection

Syntax

ToolsSpellSelection

Remarks

Checks spelling in the current selection. If the selection is only part of a word, or if the insertion point is at the end of a word, the selection is extended to include the whole word. If the insertion point isn't in or doesn't follow a word, the next word is checked.

Example

This example asks whether or not to check the spelling of the current selection, and then checks spelling if the user chooses the Yes button:

ans = MsgBox("Check spelling of selection?", 3)
If ans = -1 Then ToolsSpellSelection

See Also

ToolsOptionsSpelling, ToolsSpelling


ToolsThesaurus

Syntax

ToolsThesaurus

Remarks

Displays the Thesaurus dialog box (Tools menu), which lists alternatives for the selected word.

See Also

ToolsGetSynonyms


ToolsUnprotectDocument

Syntax

ToolsUnprotectDocument [.DocumentPassword = text]

Remarks

Removes protection from the active document. If the document is not protected, an error occurs.

Argument | Explanation
.DocumentPassword | The password, if any, used to protect the document. Note that passwords are case-sensitive. If the document is protected with a password and you don't specify .DocumentPassword, a dialog box prompts the user for the password.

See Also

DocumentProtection(), ToolsProtectDocument, ToolsProtectSection


ToolsWordCount

Syntax

ToolsWordCount [.CountFootnotes = number] [, .Pages = text] [, .Words = text] [, .Characters = text] [, .Paragraphs = text] [, .Lines = text]

Remarks

Counts the number of pages, words, characters, paragraphs, and lines in the active document. The .CountFootnotes argument is the only one that can be set; the remaining arguments are read-only and can be used with a dialog record to return information about the active document. For more information, see the example for this entry. For information about dialog records, see Chapter 4, "Advanced WordBasic," in Part 1, "Learning WordBasic."

Argument | Explanation
.CountFootnotes | If 1, text in footnotes and endnotes is included in the count.
.Pages | The number of pages in the document.
.Words | The number of words in the document.
.Characters | The number of characters in the document.
.Paragraphs | The number of paragraphs in the document.

Example

This example counts the number of pages, words, characters, paragraphs, and lines in the active document — including text in footnotes and endnotes — and then displays the word count in a message box:

ToolsWordCount .CountFootnotes = 1
Dim dlg As ToolsWordCount
GetCurValues dlg
MsgBox "Current word count: " + dlg.Words

See Also

DocumentStatistics, FileSummaryInfo


UCase$()

Syntax

UCase$(Source$)

Remarks

Returns a string in which all letters of Source$ have been converted to uppercase.

Example

This example displays an InputBox$ dialog box that prompts the user to type an acronym. When the user chooses OK, the text is stored in the variable acronym$, which is then converted to uppercase.

acronym$ = InputBox$("Please enter an acronym.")
acronym$ = UCase$(acronym$)

See Also

ChangeCase, LCase$()


Underline, Underline()

Syntax

Underline [On]

Underline()

Remarks

The Underline statement adds or removes the single-underline character format for the selected text, or controls single-underline formatting for characters to be inserted at the insertion point.

Argument | Explanation
On | Specifies whether to add or remove the single-underline format: 1 Formats the selection with the single-underline format. 0 (zero) Removes the single-underline format. Omitted Toggles the single-underline format.

The Underline() function returns the following values.

Value | Explanation
0 (zero) | If none of the selection is in the single-underline format
–1 | If part of the selection is in the single-underline format
1 | If all the selection is in the single-underline format

See Also

DottedUnderline, DoubleUnderline, FormatFont, WordUnderline


UnHang

Syntax

UnHang

Remarks

Removes a hanging indent from the selected paragraphs, or reduces the current hanging indent to the previous tab stop of the first paragraph in the selection.

See Also

HangingIndent, UnIndent


UnIndent

Syntax

UnIndent

Remarks

Moves the left indent of the selected paragraphs to the previous tab stop of the first paragraph in the selection. UnIndent maintains the setting of a first-line or hanging indent.

See Also

Indent, UnHang


UnlinkFields

Syntax

UnlinkFields

Remarks

Replaces the selected fields with their most recent results. When you unlink a field, it is converted to regular text or graphics and can no longer be updated automatically. Note that some fields cannot be unlinked — for example, XE (Index Entry) fields, which show no result. If the selection does not contain fields that can be unlinked, an error occurs.

Example

This example unlinks all fields in the active document. First, Word displays
a message box giving the user the option to update all fields before unlinking. Then, depending on the user's response, Word carries out the appropriate action.

answer = MsgBox("Update all fields before unlinking?", \
    "Unlink All Fields", 35)
On Error Goto trap
Select Case answer
    Case -1                    'Yes
        EditSelectAll
        UpdateFields
        UnlinkFields
    Case 0                    'No
        EditSelectAll
        UnlinkFields
    Case 1                    'Cancel
        Goto bye
trap:
    If Err = 102 Then MsgBox "No fields to unlink." Else Error Err
bye:
End Select

See Also

LockFields, UnlockFields, UpdateFields


UnlockFields

Syntax

UnlockFields

Remarks

Allows selected fields that were previously locked with LockFields to be updated.

See Also

LockFields, UnlinkFields, UpdateFields


UpdateFields

Syntax

UpdateFields

Remarks

Updates the selected fields.

See Also

LockFields, UnlinkFields, UnlockFields


UpdateSource

Syntax

UpdateSource

Remarks

Saves the changes made to the result of an INCLUDETEXT field back to the source document. The source document must be formatted as a Word document.

See Also

UpdateFields


Val()

Syntax

Val(a$)

Remarks

Returns the numeric value of a$. A common use of Val() is to convert strings containing digit characters to numbers so they may be used in mathematical formulas. If a$ does not begin with a digit character, Val() returns 0 (zero). The a$ string can be as long as 255 characters.

Note

Whereas raw numbers in a WordBasic instruction are not affected by the current settings for decimal and thousands separators, the Val() function is. For example, if the thousands separator is a period, the instruction a = 1.001 sets a to 1.001 but the instruction a = Val("1.001") sets a to 1001.

Examples

In both of the following instructions, Val() returns 10:

num = Val("10")
num = Val("10 Apples")

In both of the following instructions, Val() returns 0 (zero):

num = Val("ten")
num = Val("Apartment 10")

The following example prompts the user to type a number, which the InputBox$() function returns as a string. Val() converts the string to a number and multiplies it by 12. Str$() converts the product to a string so that it can be displayed in a message box.

a$ = InputBox$("How many dozen apples?")
total = Val(a$) * 12
MsgBox a$ + " dozen equals" + Str$(total)

See Also

Str$()


ViewAnnotations, ViewAnnotations()

Syntax

ViewAnnotations [On]

ViewAnnotations()

Remarks

The ViewAnnotations statement opens or closes the annotation pane. An error occurs if there are no annotations in the active document.

Argument | Explanation
On | Specifies whether to open or close the annotation pane: 0 (zero) Closes the annotation pane. 1 Opens the annotation pane. Omitted Toggles the display of the annotation pane.

The ViewAnnotations() function returns the following values.

Value | Explanation
0 (zero) | If the annotation pane is closed
–1 | If the annotation pane is open

See Also

InsertAnnotation, ViewEndnoteArea, ViewFootnoteArea, ViewFootnotes


ViewBorderToolbar

Syntax

ViewBorderToolbar

Remarks

Displays the Borders toolbar if it is hidden or hides the Borders toolbar if it is displayed.

See Also

ViewDrawingToolbar, ViewToolbars


ViewDraft, ViewDraft()

Syntax

ViewDraft [On]

ViewDraft()

Remarks

The ViewDraft statement turns draft mode on or off for the active document or macro-editing window. Draft mode is specified by the Draft Font check box on the View tab in the Options dialog box (Tools menu).

Argument | Explanation
On | Specifies whether to turn draft mode on or off: 0 (zero) Turns draft mode off. 1 Turns draft mode on. Omitted Toggles draft mode.

The ViewDraft() function returns the following values.

Value | Explanation
0 (zero) | If draft mode is off
–1 | If draft mode is on

See Also

ToolsOptionsView


ViewDrawingToolbar

Syntax

ViewDrawingToolbar

Remarks

Displays the Drawing toolbar if it is hidden or hides the Drawing toolbar if it is displayed.

See Also

ViewBorderToolbar, ViewToolbars


ViewEndnoteArea, ViewEndnoteArea()

Syntax

ViewEndnoteArea [On]

ViewEndnoteArea()

Remarks

In normal and outline views, the ViewEndnoteArea statement opens or closes the endnote pane. In page layout view, ViewEndnoteArea moves the insertion point to or from the endnote area. If there are no endnotes in the active document, this statement has no effect.

Argument | Explanation
On | Specifies whether to open or close the endnote pane: 0 (zero) In normal and outline views, closes the endnote pane; in page layout view, has no effect. 1 In normal and outline views, opens the endnote pane; in page layout view, moves the insertion point between an endnote and its associated reference mark in the document text. Omitted In normal and outline views, toggles the display of the endnote pane; in page layout view, moves the insertion point between an endnote and its associated reference mark in the document text.

The ViewEndnoteArea() function returns the following values.

Value | Explanation
0 (zero) | If the endnote pane is closed
–1 | If the endnote pane is open

See Also

ViewAnnotations, ViewFootnoteArea, ViewFootnotes


ViewEndnoteContNotice

Syntax

ViewEndnoteContNotice

Remarks

Opens a pane containing the endnote continuation notice, which indicates that an endnote is continued on the following page.

See Also

ResetNoteSepOrNotice, ViewEndnoteContSeparator, ViewEndnoteSeparator, ViewFootnoteContNotice


ViewEndnoteContSeparator

Syntax

ViewEndnoteContSeparator

Remarks

Opens a pane containing the endnote continuation separator, which appears before endnote text that is continued from the previous page.

See Also

ResetNoteSepOrNotice, ViewEndnoteContNotice, ViewEndnoteSeparator, ViewFootnoteContSeparator


ViewEndnoteSeparator

Syntax

ViewEndnoteSeparator

Remarks

Opens a pane containing the endnote separator, which appears between document text and the endnotes.

See Also

ResetNoteSepOrNotice, ViewEndnoteContNotice, ViewEndnoteContSeparator, ViewFootnoteSeparator


ViewFieldCodes, ViewFieldCodes()

Syntax

ViewFieldCodes [On]

ViewFieldCodes()

Remarks

The ViewFieldCodes statement controls the display of all fields in the active document. The display of field codes is specified by the Field Codes check box on the View tab in the Options dialog box (Tools menu). You can control the display of selected fields with the ToggleFieldDisplay statement.

Argument | Explanation
On | Specifies how to display fields: 0 (zero) Displays field results. 1 Displays field codes. Omitted Toggles the display of fields.

The ViewFieldCodes() function returns the following values.

Value | Explanation
0 (zero) | If field results are displayed
–1 | If field codes are displayed

See Also

ToggleFieldDisplay, ToolsOptionsView


ViewFooter, ViewFooter()

Syntax

ViewFooter

ViewFooter()

Remarks

The ViewFooter statement switches the active document to page layout view, positions the insertion point in the footer area, and then displays the Header And Footer toolbar. If the Header And Footer toolbar is already displayed, ViewFooter hides it and moves the insertion point to the document area.

The ViewFooter() function returns the following values.

Value | Explanation
0 (zero) | If the insertion point is not in the footer area
–1 | If the insertion point is in the footer area

See Also

CloseViewHeaderFooter, ViewHeader


ViewFootnoteArea, ViewFootnoteArea()

Syntax

ViewFootnoteArea [On]

ViewFootnoteArea()

Remarks

The ViewFootnoteArea statement opens or closes the footnote pane (in normal view) and moves the insertion point between the document area and the footnote area. If there are no footnotes in the active document, this statement has no effect.

Argument | Explanation
On | Specifies whether to display the footnote area: 0 (zero) Closes the footnote pane (in normal view) and moves the insertion point to the appropriate reference mark in the document area. 1 Opens the footnote pane (in normal view) and moves the insertion point between a footnote and its associated reference mark in the document text. Omitted Toggles the display of the footnote pane (in normal view) and moves the insertion point from the document area to the footnote area, or vice versa.

The ViewFootnoteArea() function returns the following values.

Value | Explanation
0 (zero) | If the footnote pane is closed
–1 | If the footnote pane is open

See Also

ViewAnnotations, ViewEndnoteArea, ViewFootnotes


ViewFootnoteContNotice

Syntax

ViewFootnoteContNotice

Remarks

Opens a pane containing the footnote continuation notice, which indicates that a footnote is continued on the following page.

See Also

ResetNoteSepOrNotice, ViewEndnoteContNotice, ViewFootnoteContSeparator, ViewFootnoteSeparator


ViewFootnoteContSeparator

Syntax

ViewFootnoteContSeparator

Remarks

Opens a pane containing the footnote continuation separator, which appears before footnote text that is continued from the previous page.

See Also

ResetNoteSepOrNotice, ViewEndnoteContSeparator, ViewFootnoteContNotice, ViewFootnoteSeparator


ViewFootnotes, ViewFootnotes()

Syntax

ViewFootnotes

ViewFootnotes()

Remarks

In normal view, the ViewFootnotes statement opens or closes the footnote pane or endnote pane according to the following rules:

  • If the document contains footnotes, opens the footnote pane.
  • If the document contains endnotes, but no footnotes, opens the endnote pane.
  • If the footnote pane or endnote pane is already open, closes the pane.

In page layout view, ViewFootnotes moves the insertion point according to the following rules:

  • If the document has only footnotes, moves the insertion point to the footnote area; if it has only endnotes, moves the insertion point to the endnote area.
  • If the document has both footnotes and endnotes, displays a dialog box that asks the user to choose between the footnote and endnote area.
  • If the insertion point is already in a footnote or endnote area, moves the insertion point to the document area.

If the document contains no footnotes or endnotes, ViewFootnotes has no effect.

The ViewFootnotes() function returns the following values.

Value | Explanation
0 (zero) | If neither the footnote nor endnote pane is open
–1 | If either the footnote or endnote pane is open

See Also

ViewEndnoteArea, ViewFootnoteArea


ViewFootnoteSeparator

Syntax

ViewFootnoteSeparator

Remarks

Opens a pane containing the footnote separator, which appears between document text and the footnotes.

See Also

ResetNoteSepOrNotice, ViewEndnoteSeparator, ViewFootnoteContNotice, ViewFootnoteContSeparator


ViewHeader, ViewHeader()

Syntax

ViewHeader

ViewHeader()

Remarks

The ViewHeader statement switches the active document to page layout view, positions the insertion point in the header area, and then displays the Header
And Footer toolbar. If the Header And Footer toolbar is already displayed, ViewHeader hides it and moves the insertion point to the document area.

The ViewHeader() function returns the following values.

Value | Explanation
0 (zero) | If the insertion point is not in the header area
–1 | If the insertion point is in the header area

See Also

ViewFooter


ViewMasterDocument, ViewMasterDocument()

Syntax

ViewMasterDocument

ViewMasterDocument()

Remarks

The ViewMasterDocument statement switches the active document to master document view. The ViewMasterDocument() function returns the following values.

Value | Explanation
0 (zero) | If the active document is not in master document view
–1 | If the active document is in master document view

See Also

ViewOutline, ViewToggleMasterDocument


ViewMenus()

Syntax

ViewMenus()

Remarks

Returns a value that indicates which menu bar is displayed: the full menu bar when a document window is open, or the abbreviated menu bar when no document window is open. You can use ViewMenus() as an alternative to CountWindows() to determine whether at least one document window is open.

Value | Explanation
0 (zero) | If the full menu bar is displayed
1 | In Windows, if only the File, Help, and application Control menus are displayed; on the Macintosh, if only the Apple, File, Help, and Application menus are displayed. Note that other menus may be available if they've been added with ToolsCustomizeMenuBar

Note

These values correspond to values allowed for the .MenuType argument when you customize menus with ToolsCustomizeMenus and ToolsCustomizeMenuBar.

See Also

ToolsCustomizeMenus, ToolsCustomizeMenuBar


ViewNormal, ViewNormal()

Syntax

ViewNormal

ViewNormal()

Remarks

The ViewNormal statement switches the active document to normal view. The ViewNormal() function returns the following values.

Value | Explanation
0 (zero) | If the active document is not in normal view
–1 | If the active document is in normal view

See Also

FilePrintPreview, ViewDraft, ViewMasterDocument, ViewOutline, ViewPage


ViewOutline, ViewOutline()

Syntax

ViewOutline

ViewOutline()

Remarks

The ViewOutline statement switches the active document to outline view. The ViewOutline() function returns the following values.

Value | Explanation
0 (zero) | If the active document is not in outline view
–1 | If the active document is in outline view

See Also

FilePrintPreview, ViewDraft, ViewMasterDocument, ViewNormal, ViewPage


ViewPage, ViewPage()

Syntax

ViewPage

ViewPage()

Remarks

The ViewPage statement switches the active document to page layout view. The ViewPage() function returns the following values.

Value | Explanation
0 (zero) | If the active document is not in page layout view
–1 | If the active document is in page layout view

See Also

FilePrintPreview, ViewDraft, ViewMasterDocument, ViewNormal, ViewOutline


ViewRibbon, ViewRibbon()

Syntax

ViewRibbon [On]

ViewRibbon()

Remarks

The ViewRibbon statement displays or hides the Formatting toolbar. This statement is included for compatibility with the previous version of Word.

Argument | Explanation
On | Specifies whether to display or hide the Formatting toolbar: 0 (zero) Hides the Formatting toolbar. 1 Displays the Formatting toolbar. Omitted Toggles the Formatting toolbar on and off.

The ViewRibbon() function returns the following values.

Value | Explanation
0 (zero) | If the Formatting toolbar is hidden
–1 | If the Formatting toolbar is displayed

See Also

ToolsOptionsView, ViewRuler, ViewStatusBar, ViewToolbars


ViewRuler, ViewRuler()

Syntax

ViewRuler [On]

ViewRuler()

Remarks

The ViewRuler statement displays or hides the rulers. If the active document is in outline or master document view, an error occurs.

Argument | Explanation
On | Specifies whether to display or hide the rulers: 0 (zero) Hides the rulers. 1 Displays the rulers. Omitted Toggles the rulers on and off.

The ViewRuler() function returns the following values.

Value | Explanation
0 (zero) | If the rulers are hidden
–1 | If the rulers are displayed

See Also

ToolsOptionsView, ViewRibbon, ViewStatusBar, ViewToolbars


ViewStatusBar, ViewStatusBar()

Syntax

ViewStatusBar [On]

ViewStatusBar()

Remarks

The ViewStatusBar statement displays or hides the status bar.

Argument | Explanation
On | Specifies whether to display or hide the status bar: 0 (zero) Hides the status bar. 1 Displays the status bar. Omitted Toggles the status bar on and off.

The ViewStatusBar() function returns the following values.

Value | Explanation
0 (zero) | If the status bar is hidden
–1 | If the status bar is displayed

See Also

ToolsOptionsView, ViewRibbon, ViewRuler, ViewToolbars


ViewToggleMasterDocument

Syntax

ViewToggleMasterDocument

Remarks

Switches the active document from outline view to master document view or from master document view to outline view. If the document is in normal view, page layout view, or print preview, an error occurs.

See Also

ViewMasterDocument, ViewOutline


ViewToolbars

Syntax

ViewToolbars [.Toolbar = text] [, .Context = number] [, .ColorButtons = number] [, .LargeButtons = number] [, .ToolTips = number] [, .ToolTipsKey = number] [, .Reset] [, .Delete] [, .Show] [, .Hide]

Remarks

The arguments for the ViewToolbars statement correspond to the options in the Toolbars dialog box (View menu).

Argument | Explanation
.Toolbar | The name of the toolbar you want to reset, delete, display, or hide, as listed in the Toolbars box.
.Context | Specifies a template in which to reset an existing toolbar: 0 (zero) or omitted Normal template 1 Active template
.ColorButtons | If 1, displays color toolbar buttons.
.LargeButtons | If 1, displays enlarged toolbar buttons.
.ToolTips | If 1, displays the button name beneath a button when the mouse pointer is over it.
.ToolTipsKey | If 1, displays the shortcut key assigned to the toolbar button in the button's ToolTip.
.Reset | Restores the specified toolbar to its default configuration of buttons.
.Delete | Deletes the specified toolbar.
.Show | Displays the specified toolbar.
.Hide | Hides the specified toolbar.

See Also

NewToolbar, ToolsOptionsView, ViewRibbon, ViewRuler, ViewStatusBar


ViewZoom

Syntax

ViewZoom [.AutoFit] [, .TwoPages] [, .FullPage] [, .NumColumns = number] [, .NumRows = number] [, .ZoomPercent = text]

Remarks

Changes the magnification for the active document and new documents in the current view. The arguments for ViewZoom correspond to the options in the Zoom dialog box (View menu). If the active document is not in page layout view and you specify .TwoPages, .FullPage, .NumColumns, or .NumRows, an error occurs.

Argument | Explanation
.AutoFit | Sets magnification so the entire width of the page is visible.
.TwoPages | In page layout view, sets magnification so two entire pages are visible.

Argument | Explanation
.FullPage | In page layout view, sets magnification so the entire page is visible.
.NumColumns | When displaying multiple pages in grid formation, the number of columns in the grid.
.NumRows | When displaying multiple pages in grid formation, the number of rows in the grid.
.ZoomPercent | The percentage of magnification relative to the default display (100 percent).

See Also

ViewZoom100, ViewZoom200, ViewZoom75, ViewZoomPageWidth, ViewZoomWholePage


ViewZoom100

Syntax

ViewZoom100

Remarks

Switches to normal view and sets magnification to 100 percent for the active document and new documents.

See Also

ViewZoom, ViewZoom200, ViewZoom75, ViewZoomPageWidth, ViewZoomWholePage


ViewZoom200

Syntax

ViewZoom200

Remarks

Switches to normal view and sets magnification to 200 percent for the active document and new documents.

See Also

ViewZoom, ViewZoom100, ViewZoom75, ViewZoomPageWidth, ViewZoomWholePage


ViewZoom75

Syntax

ViewZoom75

Remarks

Switches to normal view and sets magnification to 75 percent for the active document and new documents.

See Also

ViewZoom, ViewZoom100, ViewZoom200, ViewZoomPageWidth, ViewZoomWholePage


ViewZoomPageWidth

Syntax

ViewZoomPageWidth

Remarks

Sets magnification so the entire width of the page is visible.

See Also

ViewZoom, ViewZoom100, ViewZoom200, ViewZoom75, ViewZoomWholePage


ViewZoomWholePage

Syntax

ViewZoomWholePage

Remarks

Sets magnification so the entire page is visible in page layout view. ViewZoomWholePage switches to page layout view if the active document is in another view.

See Also

ViewZoom, ViewZoom100, ViewZoom200, ViewZoom75, ViewZoomPageWidth


VLine

Syntax

VLine [Count]

Remarks

Scrolls the active document vertically. A "line" corresponds to clicking a scroll arrow on the vertical scroll bar once.

Argument | Explanation
Count | The amount to scroll, in lines: Omitted One line down > 0 (zero) The specified number of lines down < 0 (zero) The specified number of lines up

See Also

HLine, VPage, VScroll


VPage

Syntax

VPage [Count]

Remarks

Scrolls the active document vertically. VPage corresponds to clicking the vertical scroll bar above or below the scroll box.

Argument | Explanation
Count | The amount to scroll, in screens: Omitted One screen down > 0 (zero) The specified number of screens down < 0 (zero) The specified number of screens up

See Also

HPage, VLine, VScroll


VScroll, VScroll()

Syntax

VScroll Percentage

VScroll()

Remarks

The VScroll statement scrolls vertically to the specified percentage of the document length. VScroll corresponds to dragging the scroll box on the vertical scroll bar.

The VScroll() function returns the current vertical scroll position as a percentage of the document length.

Example

This example scrolls to the middle of the active document:

VScroll 50

See Also

HScroll, VLine, VPage


WaitCursor

Syntax

WaitCursor Wait

Remarks

Changes the mouse pointer from the current pointer to an hourglass or watch, or vice versa. Control of the pointer is restored to Word when the macro ends.

Argument | Explanation
Wait | Specifies the mouse pointer to display: 0 (zero) The current pointer 1 The hourglass pointer (Windows) or watch pointer (Macintosh)

Example

This example suppresses the hourglass or watch pointer for the first half of the total iterations of a For ¼ Next loop and then displays the hourglass or watch for the second half:

WaitCursor 0
For i = 1 To 1000
    If i = 500 Then WaitCursor 1
Next I


Weekday()

Syntax

Weekday(SerialNumber)

Remarks

Returns an integer between 1 and 7, inclusive, corresponding to the day of the week (where 1 is Sunday) on which the date represented by SerialNumber falls.
A serial number is a decimal representation of the date, time, or both. For information about serial numbers, see DateSerial().

Example

This example defines an array containing the names of the days of the week, returns a number corresponding to the current weekday, and then uses this number with the array to return the name of the current weekday. This name is then displayed in a message box.

Dim days$(7)
days$(1) = "Sunday" : days$(2) = "Monday" : days$(3) = "Tuesday"
days$(4) = "Wednesday" : days$(5) = "Thursday"
days$(6) = "Friday" : days$(7) = "Saturday"
thisday = Weekday(Now())
MsgBox "Would you believe it's " + days$(thisday) + " already?"

See Also

DateSerial(), Day(), Hour(), Minute(), Month(), Now(), Second(), Today(), Year()


While...Wend

Syntax

While Condition
 Series of instructions
Wend

Remarks

Repeats a series of instructions between While and Wend while the specified condition is true. The While ¼ Wend control structure is often used in WordBasic to repeat a series of instructions each time a given piece of text or formatting is found in a Word document. For an example of this use of While ¼ Wend, see EditFind.

Example

This Windows example uses the Files$() function within a While ¼ Wend loop to insert a list of files in the current folder whose filenames end with the .DOC filename extension. The instruction a$ = Files$("*.DOC") returns the first filename with a .DOC extension and a$ = Files$() returns the next filename with a .DOC extension each time the instructions within the loop run. As soon as Files$() returns an empty string (""), indicating there are no other .DOC files in the current folder, the condition a$ <> "" is false and Word exits the While ¼ Wend loop.

FileNewDefault
currdir$ = Files$(".")
a$ = Files$("*.DOC")
While a$ <> ""
    count = count + 1
    a$ = FileNameInfo$(a$, 3)
    InsertPara : Insert a$
    a$ = Files$()
Wend
StartOfDocument : Bold 1
Insert currdir$ + " contains" + Str$(count) + " files."

On the Macintosh, you can use a similar example to create a list of Word documents in the current folder by modifying the instruction that sets the currdir$ variable and by specifying a signature instead of "*.DOC" as the file specification. Replace the first two Files$() instructions in the previous example with the following instructions:

currdir$ = Files$(":")
a$ = Files$(MacID$("W6BN"))

See Also

For ¼ Next, Goto, If ¼ Then ¼ Else, Select Case


Window()

Syntax

Window()

Remarks

Returns a number that corresponds to the position of the active window on the Window menu, where 1 corresponds to the first position, 2 to the second position, and so on. If there are no open windows, Window() returns 0 (zero). Word lists windows on the Window menu in alphabetic order.

See Also

WindowList, WindowName$(), Window Number, WindowPane()


WindowArrangeAll

Syntax

WindowArrangeAll

Remarks

Arranges all open windows so they do not overlap.

See Also

DocMove, DocRestore, DocSize


WindowList

Syntax

WindowList Number

Remarks

Activates a window listed on the Window menu. The instruction WindowList 1 activates the first window in the list, WindowList 2 activates the second window, and so on through the number of open windows. If no windows are listed, or if Number is greater than the number of open windows, an error occurs.

Example

This example activates the first window containing the document TEST.DOC. The InStr() function checks for the string "TEST.DOC" in the window name, which may include extra text such as "(Read-Only)" if the document is read-only, or ":2" if the document is open in more than one window.

numwin = CountWindows()
If numwin <> 0 Then
    i = 1
    While i <= numwin And leave <> 1
        winname$ = WindowName$(i)
        If InStr(winname$, "TEST.DOC") Then leave = 1
        If leave <> 1 Then i = i + 1
    Wend
End If
If InStr(winname$, "TEST.DOC") Then
    WindowList i
Else
    MsgBox "There is no window containing TEST.DOC."
End If

See Also

CountWindows(), Window(), WindowName$(), Window Number, WindowPane()


WindowName$()

Syntax

WindowName$(Number)

Remarks

Returns the title of the open window listed at position Number on the Window menu, where 1 corresponds to the first position, 2 to the second position, and so on. If Number is 0 (zero) or omitted, WindowName$() returns the title of the active window.

For an example, see WindowList.

See Also

CountWindows(), Window(), WindowList, Window Number, WindowPane()


WindowNewWindow

Syntax

WindowNewWindow

Remarks

Opens a new window containing the active document. Word adds a colon (:) and a number to the titles of windows containing a document that is open in more than one window. For example, if the window title of the active document is TEST.DOC and you run WindowNewWindow, Word opens a new window titled TEST.DOC:2 and changes the original window title to TEST.DOC:1.

See Also

DocSplit, WindowArrangeAll, WindowName$()


WindowNumber

Syntax

Window Number

Remarks

Activates a window listed on the Window menu. Window1 activates the first window in the list, Window2 activates the second window, and so on through Window9. If no windows are listed, or if Number is greater than the number of windows listed, an error occurs.

Note

You cannot use a variable in place of Number; you must use an integer. WindowList provides the same functionality as Window Number but accepts a numeric variable to specify the window to activate.

See Also

Activate, CountWindows(), Window(), WindowList, WindowName$(), WindowPane()


WindowPane()

Syntax

WindowPane()

Remarks

Returns the following values.

Value | Explanation
1 | If the active window is not split or if the insertion point is in the top pane of the active window
3 | If the insertion point is in the bottom pane of the active window (for example, the footnote pane, the annotation pane, or the lower of two document panes)

Example

This example moves the insertion point to the top pane of the active document if the active window is split and the insertion point is in the bottom pane:

If WindowPane() = 3 Then OtherPane

See Also

DocSplit, OtherPane, ViewAnnotations(), ViewFootnoteArea()


WinToDOS$()

Syntax

WinToDOS$(StringToTranslate$)

Remarks

In Windows, translates a string from the Windows character set to the original equipment manufacturer (OEM) character set. On the Macintosh, WinToDOS$() performs no translation and returns the specified string unchanged.

The OEM character set is typically used by MS-DOS applications. Characters 32 through 127 are usually the same in the OEM and Windows character sets. The other characters in the OEM character set (0 through 31 and 128 through 255) are generally different from the Windows characters.

Example

This example opens a sequential file created by a Windows-based application, translates each line to the OEM character set, and places the result in a new sequential file:

ChDir "C:\TMP"
Open "WINDOWS.TXT" For Input As #1
Open "DOS.TXT" For Output As #2
While Not Eof(1)
    Line Input #1, temp$
    Print #2, WinToDOS$(temp$)
Wend
Close

See Also

DOSToWin$()


WordLeft, WordLeft()

Syntax

WordLeft [Count,] [Select]

WordLeft([Count,] [Select])

Remarks

The WordLeft statement moves the insertion point or the active end of the selection (the end that moves when you press CTRL+SHIFT+LEFT ARROW (Windows) or COMMAND+SHIFT+LEFT ARROW (Macintosh)) to the left by the specified number of words.

Argument | Explanation
Count | The number of words to move; if less than one or omitted, 1 is assumed.
Select | Specifies whether to select text: 0 (zero) or omitted Text is not selected. If there is already a selection, WordLeft moves the insertion point Count–1 words to the left of the selection. Nonzero Text is selected. If there is already a selection, WordLeft moves the active end of the selection toward the beginning of the document. In a typical selection made from left to right, where the active end of the selection is closer to the end of the document, WordLeft shrinks the selection. In a selection made from right to left, it extends the selection.

Note that Word includes spaces following a word as part of the word. However, Word counts punctuation, tab characters, and paragraph marks as "words." For example, if a word is enclosed in quotation marks, moving the insertion point from the position following the closing quotation mark to the position preceding the opening quotation mark using WordLeft would require the instruction WordLeft 3.

The WordLeft() function behaves the same as the statement and also returns the following values.

Value | Explanation
0 (zero) | If the insertion point or the active end of the selection cannot be moved to the left.
–1 | If the insertion point or the active end of the selection is moved to the left by any number of words, even if less than Count. For example, WordLeft(10) returns –1 even if the insertion point is only three words from the start of the document.

See Also

CharLeft, SelectCurWord, SentLeft, WordRight


WordRight, WordRight()

Syntax

WordRight [Count,] [Select]

WordRight([Count,] [Select])

Remarks

The WordRight statement moves the insertion point or the active end of the selection (the end that moves when you press CTRL+SHIFT+RIGHT ARROW (Windows) or COMMAND+SHIFT+RIGHT ARROW (Macintosh)) to the right by the specified number of words.

Argument | Explanation
Count | The number of words to move; if less than one or omitted, 1 is assumed.
Select | Specifies whether to select text: 0 (zero) or omitted Text is not selected. If there is already a selection, WordRight moves the insertion point Count–1 words to the right of the selection. Nonzero Text is selected. If there is already a selection, WordRight moves the active end of the selection toward the end of the document. In a typical selection made from left to right, where the active end of the selection is closer to the end of the document, WordRight extends the selection. In a selection made from right to left, it shrinks the selection.

Note that Word includes spaces following a word as part of the word. However, Word counts punctuation, tab characters, and paragraph marks as "words."

The WordRight() function behaves the same as the statement and also returns the following values.

Value | Explanation
0 (zero) | If the insertion point or the active end of the selection cannot be moved to the right.
–1 | If the insertion point or the active end of the selection is moved to the right by any number of characters, even if less than Count. For example, WordRight(10) returns –1 even if the insertion point is only three words from the end of the document.

Example

This example counts the number of words (including punctuation, tab characters, and paragraph marks) in the selection and then displays the result in a message box:

EditBookmark "CountMe", .Add
SelType 1
While CmpBookmarks("\Sel", "CountMe") = 6 \
        Or CmpBookmarks("\Sel", "CountMe") = 8
    WordRight
    count = count + 1
Wend
EditGoTo "CountMe"
EditBookmark "CountMe", .Delete
MsgBox "There are" + Str$(count) + " words in the selection."

See Also

CharRight, SelectCurWord, SentRight, WordLeft


WordUnderline, WordUnderline()

Syntax

WordUnderline [On]

WordUnderline()

Remarks

The WordUnderline statement adds or removes the word-underline character format for the selected text, or controls word-underline formatting for characters to be inserted at the insertion point.

Argument | Explanation
On | Specifies whether to add or remove the word-underline format: 1 Formats the selection with the word-underline format. 0 (zero) Removes the word-underline format. Omitted Toggles the word-underline format.

The WordUnderline() function returns the following values.

Value | Explanation
0 (zero) | If none of the selection is in the word-underline format
–1 | If part of the selection is in the word-underline format
1 | If all the selection is in the word-underline format

See Also

DottedUnderline, DoubleUnderline, FormatFont, Underline


Write

Syntax

Write #FileNumber, Expression1[$] [, Expression2[$]] [, ¼]

Remarks

Writes the specified expressions to an open sequential file. FileNumber is the number specified in the Open instruction that opened the file for output or appending. For more information about sequential files, see Chapter 9, "More WordBasic Techniques," in Part 1, "Learning WordBasic."

Write is similar to the Print statement, but instead of separating the expressions with tab characters, Write separates them with commas; also, Write encloses strings in quotation marks. This allows the resulting values to be read by a Read instruction. For an illustration of the respective output of the Print and Write statements, see Print.

Example

This example opens a sequential file for output (creating it if it does not already exist), prompts the user for three pieces of data, and then uses the Write statement to insert the data into the sequential file:

Open "DATAFILE.TXT" For Output As #1
name$ = InputBox$("Enter name:")
age = Val(InputBox$("Enter age:"))
job$ = InputBox$("Enter occupation:")
Write #1, name$, age, job$
Close #1

The following is an example of a paragraph in DATAFILE.TXT inserted by the Write statement:

"Michelle Levine", 26,"Dancer"

See Also

Close, Eof(), Input, Input$(), Line Input, Lof(), Open, Print, Read, Seek


Year()

Syntax

Year(SerialNumber)

Remarks

Returns an integer between 1899 and 4095, inclusive, corresponding to the year component of SerialNumber, a decimal representation of the date, time, or both. For information about serial numbers, see DateSerial().

Example

This example returns the year component of the current date, converts it to a string, and then shortens the string to only the final two digits:

years = Year(Now())
years$ = Str$(years)
years$ = Right$(years$, 2)

See Also

DateSerial(), Day(), Hour(), Minute(), Month(), Now(), Second(), Today(), Weekday()


Operators and Predefined Bookmarks

The following sections provide detailed information about WordBasic operators and predefined bookmarks.


Operators

An expression is any valid combination of operators, variables, numbers, strings, and WordBasic functions that can be evaluated to a single result. Depending on the kind of operator and values used, the result of an expression can be a number, string, or logical value, where the numbers –1 and 0 (zero) represent the logical values true and false, respectively. In WordBasic, there are four categories of operators to use with values to form expressions: arithmetic, string concatenation, comparison, and logical. This section describes the operators within these categories in order of operator precedence.

Operator Precedence

When several operations occur in an expression, each part is evaluated and resolved in a predetermined order known as operator precedence. Parentheses can be used to override the order of precedence and force some parts of an expression to be evaluated before others. Operations within parentheses are always performed before those outside parentheses.

Within parentheses, however, normal operator precedence is maintained. When expressions contain operators from more than one category, arithmetic operators (including the string concatenation operator) are evaluated first, comparison operators are evaluated next, and logical operators are evaluated last.

Within an expression, multiplication and division operations are evaluated before addition and subtraction operations. When multiplication and division occur together in an expression, each operation is evaluated as it occurs from left to right. Likewise, when addition and subtraction occur together in an expression, each operation is evaluated in order of appearance from left to right. All comparison operators have equal precedence; that is, they are evaluated in the left-to-right order in which they appear in an expression.

The string concatenation operator (+) is not really an arithmetic operator, but in precedence it does fall after all arithmetic operators and before all comparison operators.

Arithmetic Operators

Use these operators to generate any numeric value to assign to a variable or to use in input, output, or loops.

Operator | Description
– (Negation) | Indicates that the operand is a negative value. The operand can be any numeric expression.
* (Multiplication) | Multiplies two numbers. The operands can be any numeric expressions.
/ (Division) | Divides two numbers. The operands can be any numeric expressions.
MOD (Modular division) | Divides two operands and returns only the remainder. For example, the result of the expression 19 MOD 7 (which can be read as 19 modulo 7) is 5. The operands can be any numeric expressions.
+ (Addition) | Sums two numbers. The operands can be any numeric expressions. Note that you also use + as the string concatenation operator.
– (Subtraction) | Finds the difference between two numbers. The operands can be any numeric expressions.

The String Concatenation Operator

Use the string concatenation operator to link literal strings and string variables.

Operator | Description
+ (String concatenation) | Concatenates two strings. For example, the result of "Microsoft " + "Word" is "Microsoft Word". You must ensure that spaces are included in the strings being concatenated to avoid running words or characters together. If you use the Str$() function to return numbers as strings, note that the function adds a space before positive numbers (for example, Str$(47) returns " 47"), but not before negative numbers (for example, Str$(-47) returns "-47"). Note that you also use + as the addition operator.

Comparison Operators

Use these operators, also known as relational operators, to compare two expressions (numeric or string) and return true (–1) or false (0) values for use in control structures such as If conditionals and While ¼ Wend loops. The following table lists the comparison operators and the conditions that determine whether the result is true or false.

Operator | True | False
= (Equal to) | exp1 = exp2 | exp1 <> exp2
<> (Not equal to) | exp1 <> exp2 | exp1 = exp2
< (Less than) | exp1 < exp2 | exp1 >= exp2
> (Greater than) | exp1 > exp2 | exp1 <= exp2
<= (Less than or equal to) | exp1 <= exp2 | exp1 > exp2
>= (Greater than or equal to) | exp1 >= exp2 | exp1 < exp2

Logical Operators

Use these operators in combination with comparison expressions to create compound logical expressions that return true (–1) or false (0) values.

Operator | Description
AND | If, and only if, both expressions evaluate true, the result is true. If either expression evaluates false, the result is false. The result is determined as follows: True AND True True False AND True False True AND False False False AND False False

Operator | Description
OR | If either or both expressions evaluate true, the result is true. The result is determined as follows: True OR True True False OR True True True OR False True False OR False False
NOT | The result is determined as follows: NOT False True NOT True False Note that a NOT compound expression evaluates as described only when the operands are comparisons or numeric true and false values, where true is –1 and false is 0 (zero).

True, False, and Bitwise Comparisons

In WordBasic, "true" is represented by the number –1, and "false" by the number 0 (zero). When WordBasic recognizes the number –1 as true and 0 (zero) as false, it is actually recognizing the values of each bit in the bytes that represent those numbers: –1 is the byte 1111 1111 and 0 (zero) is the byte 0000 0000. In fact, if WordBasic finds at least one "1" bit in any byte that represents a number, it recognizes the byte as true. Therefore, any nonzero number can represent true because the bytes for all nonzero numbers, both positive and negative, include at least one "1" bit. Only the byte for the number 0 (zero) contains all "0" bits and is therefore considered false.

When WordBasic evaluates a comparison — such as "A" = "A" or 5 < 2 —
it returns the standard true or false byte. But when WordBasic evaluates a compound expression (using one of the logical operators AND, OR, or NOT), it returns the byte for whatever number results from the eight "bitwise" comparisons that the logical operator makes with the original numbers. In a bitwise comparison, the operator compares each corresponding bit in the bytes that represent the values in the expression.

For example, in an AND bitwise comparison, if the first bit in each byte is set to 1, the first bit in the resulting byte is set to 1; otherwise, the bit is set to 0 (zero). In the expression "A" = "A" AND 5 < 2, the byte that represents "A" = "A" is 1111 1111 (the byte for –1, or true), and the byte that represents 5 < 2 is 0000 0000 (the byte for 0, or false). So WordBasic makes the following eight bitwise comparisons.

Bit in "A" = "A" | Bit in 5 < 2 | Bit in AND result
1 | 0 | 0
1 | 0 | 0
1 | 0 | 0
1 | 0 | 0
1 | 0 | 0
1 | 0 | 0
1 | 0 | 0
1 | 0 | 0

The resulting byte is 0000 0000, which is the number 0 (zero). Therefore, because WordBasic considers the value 0 (zero) to be false, the result of "A" = "A" AND 5 < 2 is false.

Note

If the eight bitwise comparisons are made with bytes other than those representing –1 and 0 (zero), unexpected results may occur. (Remember that WordBasic recognizes any nonzero value as true because every nonzero value contains at least one "1" bit.) For example, with the compound expression 5 AND 2, where the byte for 5 is 0000 0101 and the byte for 2 is 0000 0010, the resulting byte is 0000 0000, which is the number 0 (zero). Because WordBasic always considers 0 (zero) to be false, the result of 5 AND 2 is false, even though the nonzero values 5 and 2 are considered "true" on their own.

In a compound expression, the three logical operators AND, OR, and NOT make the following bitwise comparisons for each bit in the bytes that represent the values in the expression.

AND

This operator returns the "1" bit if, and only if, both bits in the bytes being compared are "1" bits.

Bit in first byte | Bit in second byte | Bit in AND result
0 | 0 | 0
0 | 1 | 0
1 | 0 | 0
1 | 1 | 1

OR

This operator returns the "1" bit if either bit in the bytes being compared is a "1" bit.

Bit in first byte | Bit in second byte | Bit in OR result
0 | 0 | 0
0 | 1 | 1
1 | 0 | 1
1 | 1 | 1

NOT

This operator converts each bit in a single byte to its opposite bit in the result.

Bit in byte | Bit in NOT result
0 | 1
1 | 0

You can get unexpected results using the NOT operator with true values other than –1. For example, the number 1 evaluates true, but the expression NOT 1 also evaluates true. The result is true because 1 is the byte 0000 0001, and the NOT operator changes each bit to its opposite value; thus, the result of NOT 1 is the byte 1111 1110, which is the number –2. Just as WordBasic recognizes 1 as a numeric value for true, it also recognizes –2 as a numeric value for true.

A number of WordBasic functions can return the value 1. For example, Bold() returns 1 if all the current selection is bold and –1 if some of the current selection is bold. Consider the following instruction:

If Bold() Then MsgBox "Some or all of the selection is bold."

This instruction works reliably because both 1 and –1 evaluate true. But the following instruction will not work reliably:

If NOT Bold() Then MsgBox "None of the selection is bold."

If none of the selection is bold, Bold() returns 0 (zero), and the message box is displayed as expected. Likewise, if some of the selection is bold, Bold() returns –1, and the message box is not displayed. But if all the selected text is bold, Bold() returns 1; because NOT 1 is true (as shown earlier), the message box will be displayed, even though the selection is bold. To avoid unexpected results with NOT, you should use only the values –1 and 0 (zero) to represent true and false.


Predefined Bookmarks

Word sets and automatically updates a number of reserved bookmarks. You
can use these predefined bookmarks just as you use the ones that you place in documents, except that you don't have to set them and they are not listed in the Go To dialog box (Edit menu). The following table describes the predefined bookmarks available in Word.

Bookmark | Description
\ Sel | Current selection or the insertion point.
\ PrevSel1 | Most recent selection where editing occurred; going to this bookmark is equivalent to running the GoBack statement once.
\ PrevSel2 | Second most recent selection where editing occurred; going to this bookmark is equivalent to running the GoBack statement twice.
\ StartOfSel | Start of the current selection.
\ EndOfSel | End of the current selection.
\ Line | Current line or the first line of the current selection. If the insertion point is at the end of a line that is not the last line in the paragraph, the bookmark includes the entire next line.
\ Char | Current character, which is the character following the insertion point if there is no selection, or the first character of the selection.
\ Para | Current paragraph, which is the paragraph containing the insertion point or, if more than one paragraph is selected, the first paragraph of the selection. Note that if the insertion point or selection is in the last paragraph of the document, the "\ Para" bookmark does not include the paragraph mark.
\ Section | Current section, including the break at the end of the section, if any. The current section contains the insertion point or selection. If the selection contains more than one section, the " \ Section" bookmark is the first section in the selection.
\ Doc | Entire contents of the active document, with the exception of the final paragraph mark.
\ Page | Current page, including the break at the end of the page, if any. The current page contains the insertion point. If the current selection contains more than one page, the " \ Page" bookmark is the first page of the selection. Note that if the insertion point or selection is in the last page of the document, the "\ Page" bookmark does not include the final paragraph mark.
\ StartOfDoc | Beginning of the document.
\ EndOfDoc | End of the document.

Bookmark | Description
\ Cell | Current cell in a table, which is the cell containing the insertion point. If one or more cells of a table are included in the current selection, the " \ Cell" bookmark is the first cell in the selection.
\ Table | Current table, which is the table containing the insertion point or selection. If the selection includes more than one table, the " \ Table" bookmark is the entire first table of the selection, even if the entire table is not selected.
\ HeadingLevel | The heading that contains the insertion point or selection, plus any subordinate headings and text. If the current selection is body text, the " \ HeadingLevel" bookmark includes the preceding heading, plus any headings and text subordinate to that heading.

The following macro demonstrates a typical use of predefined bookmarks. The macro moves line by line through a document from the current line and removes any leading spaces from the lines. The While ¼ Wend instruction uses the " \ Sel" (current selection) and " \ EndofDoc" bookmarks with the CmpBookmarks() function to determine whether the selection is at the end of the document. When the end of the document is reached, Word displays a message to alert the user.

Sub MAIN
StartOfLine
While CmpBookmarks("\Sel", "\EndOfDoc")
    A$ = GetBookmark$("\Line")
    B = Asc(A$)
    If B = 32 Then DeleteWord
    EndOfLine
    CharRight
Wend
MsgBox "End of document."
End Sub

The CmpBookmarks() function compares two bookmarks and can return a number of different values according to the relative location and size of the bookmarks. For more information on CmpBookmarks(), see the entry in "Statements and Functions" earlier in this part.

For other examples of predefined bookmarks used in WordBasic macros,
see the following entries in "Statements and Functions" earlier in this part: CmpBookmarks(), CopyBookmark, ParaDown, Select Case.


Error Messages

The following list of Microsoft Word error messages and their corresponding error codes is divided into two parts: WordBasic error messages and Word error messages. The list is included for use in error trapping using the WordBasic statements On Error, Err, and Error. For more information, see the corresponding entries in "Statements and Functions."


WordBasic Error Messages

When you run a macro and an error occurs, you can get more information by choosing the Help button in the error message box. For information about an error message at any time, see "Error Messages" in Help. Choose an error from the list to display the corresponding Help topic. The following list of macro errors includes error numbers you can use with the Error statement.

Note

In Windows, if an untrapped error occurs in a macro while Word is minimized, the macro halts, Word remains minimized, and the Word icon flashes. When Word is maximized, an error message that indicates the nature of the error is displayed.

Error Number | Error Message
5 |  | Illegal function call
6 |  | Overflow
7 |  | Out of memory
9 |  | Subscript out of range
11 |  | Division by zero
14 |  | Out of string space
22 |  | Invalid array dimension
24 |  | Bad parameter
25 |  | Out of memory (stack space)
26 |  | Dialog needs End Dialog or a push button

Error Number | Error Message
28 |  | Directory already exists
39 |  | CASE ELSE expected
51 |  | Internal error
52 |  | Bad file name or number
53 |  | File not found
54 |  | Bad file mode
55 |  | File already open
57 |  | Device I/O error
62 |  | Input past end of file
64 |  | Bad file name
67 |  | Too many files
74 |  | Rename across disks
75 |  | Path/File access error
76 |  | Path not found
100 |  | Syntax error
101 |  | Comma missing
102 |  | Command failed
103 |  | Dialog record variable expected
104 |  | ELSE without IF
105 |  | END IF without IF
109 |  | INPUT missing
111 |  | Expression too complex
112 |  | Identifier expected
113 |  | Duplicate label
114 |  | Label not found
115 |  | Right parenthesis missing
116 |  | Argument-count mismatch
117 |  | Missing NEXT or WEND
118 |  | Nested SUB or FUNCTION definitions
119 |  | NEXT without FOR
120 |  | Array already dimensioned
122 |  | Type mismatch
123 |  | Undefined dialog record field
124 |  | Unknown Command, Subroutine, or Function
125 |  | Unexpected end of macro

Error Number | Error Message
126 |  | WEND without WHILE
127 |  | Wrong number of dimensions
129 |  | Too many nested control structures
130 |  | SELECT without END SELECT
131 |  | Illegal Redim to dialog record
132 |  | External call caused string overflow
133 |  | Wrong number or type of arguments for DLL call
134 |  | An argument to a function contained an illegal date or time.
135 |  | The () statement is not available in Word for ().
136 |  | The () statement is not available in Word for ().
137 |  | The specified path is not a valid path option.
138 |  | The current selection cannot be modified by this command.
139 |  | Only one user dialog may be up at any time.
140 |  | Dialog control identifier does not match any current control.
141 |  | The () statement is not available on this dialog control type.
142 |  | Specified application is not currently running
143 |  | The dialog control with the focus may not be disabled or hidden.
144 |  | Focus may not be set to a hidden or disabled control.
149 |  | The () command cannot be called as a function.
150 |  | Dialog control identifier is already defined.
152 |  | This command is not available because no document is open.
155 |  | The selection does not start in a field.
157 |  | The field cannot contain data.
158 |  | The value of one of the fields is too low.
159 |  | The value of one of the fields is too high.
160 |  | Wrong number of parameters
161 |  | Cannot change dialogs when focus is changing (action 4)
162 |  | The () command can only be called as a function.
163 |  | This statement can only be used when a user dialog is active.
164 |  | Array variable has not been initialized.
500 |  | Cannot initiate link
501 |  | Invalid channel number
502 |  | Application does not respond
503 |  | Process failed in other application
504 |  | Window does not exist

Error Number | Error Message
505 |  | Cannot activate application
506 |  | Cannot send keys
508 |  | Other application is busy
509 |  | The () command is not available because ().
511 |  | No such macro or command
512 |  | Value out of range
513 |  | String too long
514 |  | Document not open
528 |  | Unable to load spelling checker
529 |  | Cannot open dictionary
530 |  | Dialog box description too complex
535 |  | Macro cannot be run because it is already running.
536 |  | There is no macro with that name.
537 |  | Unable to run macro specified
538 |  | Unable to edit macro specified
539 |  | Unable to rename macro specified
540 |  | Unable to delete macro specified
541 |  | Unable to set description of macro specified
543 |  | Unable to open specified library
544 |  | Unable to execute the scroll command; the scroll bar is not active.
545 |  | The () statement is currently disabled.
546 |  | Footnotes or endnotes must start at 1 if numbering is not continuous.
547 |  | Network Permission Error
549 |  | The specified menu or menu item does not exist.
551 |  | Word is unable to perform this action because the specified template is locked.
552 |  | Word is unable to perform this action because the specified template does not exist.
553 |  | Unable to create macro specified
554 |  | No drawing range has been set.
555 |  | The bookmark specified for the drawing range is invalid.
556 |  | Wrong drawing object type for this command
557 |  | Could not insert the drawing object
558 |  | At least one subdocument in this master document is locked. No changes can be made to any locked subdocuments.
559 |  | The current selection is a block.

Error Number | Error Message
560 |  | The revision marks are not visible.
561 |  | Document is protected
562 |  | ToolsGrammarStatisticsArray cannot be run on a document that contains more than one language format.
563 |  | The document is not a master document.
564 |  | There are no subdocuments in that direction.
565 |  | The specified document is not in the Add-in list.
566 |  | The specified Word library cannot be unloaded because it is in use.
567 |  | Cannot add more than 25 items in the dropdown list box
568 |  | The specified font doesn't exist
569 |  | PatternMatch and SoundsLike parameters cannot both be set to 1
570 |  | Cannot sort arrays with more than two dimensions
574 |  | Address not found
575 |  | MAPI returned error
576 |  | Cannot add address to Personal Address Book
577 |  | You must specify display name for a new address
578 |  | Unknown document property
579 |  | Cannot delete a built-in document property
580 |  | Unknown link
581 |  | Cannot change the value of a read-only document property
582 |  | Unable to load specified library
583 |  | Illegal function name


Word Error Messages

These error messages are generated outside WordBasic, by Word itself. Word always displays an error message box for these messages and waits for the user to choose the OK button, regardless of whether a macro contains error-trapping statements. Once the user responds, Word returns control to the WordBasic macro, and the error can be trapped and handled like any other. Note that the Error statement cannot create these error conditions, nor can it be used to display these error messages.

Error Number | Error Message
1001 |  | There is insufficient memory. Save the document now.
1003 |  | You can specify only one line, footnote, endnote, annotation, or field at a time.

Error Number | Error Message
1005 |  | This bookmark does not exist.
1006 |  | You entered multiple destinations for a page, line, footnote, endnote, or annotation.
1008 |  | Word cannot insert a section break here.
1009 |  | The bookmark name is not valid.
1011 |  | There is not enough memory to compile the index.
1013 |  | There is not enough memory to run the DDE application.
1014 |  | There is not enough memory to run the application.
1015 |  | This command is not available in Word for the Macintosh.
1016 |  | There is not enough memory to complete the operation.
1017 |  | There is not enough memory to update the display.
1018 |  | There is not enough memory to define the AutoText entry.
1019 |  | There is not enough memory to merge the styles.
1020 |  | There is not enough memory to display the outline.
1021 |  | There is not enough memory to display the ruler.
1022 |  | The name you typed is not a valid AutoText entry. Use the AutoText button on the Standard toolbar to define AutoText entries that can be inserted as a long piece of text or a graphic.
1023 |  | There is a serious disk error on file ().
1024 |  | The file () is not available.
1025 |  | Word cannot open the document.
1026 |  | This style name does not exist.
1027 |  | There is insufficient memory, and Word cannot perform the replace operation.
1028 |  | The search item was not found.
1029 |  | There is not enough memory to display or print the picture.
1030 |  | The dimensions after cropping are too small or too large.
1031 |  | The dimensions after resizing are too small or too large.
1032 |  | The file is too large to save. Delete some text and try again.
1033 |  | Word cannot use the DOT-PATH specified in the File Locations panel because it is not valid.
1034 |  | Word cannot use the INI-PATH specified in the File Locations panel because it is not valid.
1035 |  | Word cannot use the TOOLS-PATH specified in the File Locations panel because it is not valid.
1036 |  | Word cannot start the converter ().
1037 |  | There is not enough memory to run this converter.

Error Number | Error Message
1038 |  | The password is incorrect. Word cannot overwrite the document.
1039 |  | This is not a valid hyphenation zone measurement.
1041 |  | This document template does not exist.
1042 |  | Settings you chose for the left and right margins, column spacing, or paragraph indents are too large for the page width in some sections.
1043 |  | This tab stop is too large.
1044 |  | Word cannot print.
1045 |  | This is not a valid print range.
1046 |  | Word cannot print due to a problem with the current printer.
1047 |  | There is not enough memory to repaginate or print this document.
1048 |  | Windows needs more disk space to print this document.
1049 |  | Another window cannot be opened until one is closed.
1050 |  | This is not a valid number.
1051 |  | This is not a valid measurement.
1052 |  | The number must be between () and ().
1053 |  | The measurement must be between () and ().
1054 |  | Word cannot write to file ().
1055 |  | The document name or path is not valid.
1056 |  | This is not a valid filename.
1057 |  | Word cannot give a document the same name as an open document.
1058 |  | You cannot save a template file to non-template format.
1059 |  | This file is read-only.
1060 |  | Word cannot save or create this file. Make sure the disk is not write protected
1062 |  | Fields are nested too deeply.
1066 |  | There is not enough memory to run Word.
1069 |  | Word cannot open the existing ().
1070 |  | This is not a valid date.
1071 |  | This is not a valid style name.
1072 |  | The style sheet is full. Word cannot define the new style.
1073 |  | You cannot base a style on itself.
1074 |  | The Based On style name does not exist or is of incorrect type.
1075 |  | The Next style name does not exist or is of incorrect type.
1076 |  | Word cannot merge the style sheet from the active template.
1077 |  | This style name already exists or is reserved for a built-in style.

Error Number | Error Message
1078 |  | This file could not be found.
1079 |  | There is not enough memory for such a large Clipboard.
1080 |  | The indent size is too large.
1081 |  | The paragraph is too wide.
1083 |  | The command name must have an extension.
1084 |  | Word cannot open this document template.
1085 |  | The document template is not valid.
1090 |  | The style sheet is full. The style of some paragraphs may become Normal.
1091 |  | Word cannot insert a file into itself.
1093 |  | There is not enough memory to run the thesaurus.
1094 |  | Word cannot start the thesaurus.
1095 |  | There is not enough memory to run the spelling checker.
1097 |  | Word cannot start the spelling checker.
1103 |  | Word cannot find the file WORDCBT.CBT.
1104 |  | This is not a valid tab stop.
1105 |  | There are too many tab stops set in this paragraph.
1106 |  | There are too many tab stops to clear at one time.
1107 |  | Word found no XE (Index Entry) fields for the index.
1108 |  | Word cannot create a work file.
1109 |  | A settings file is not valid. Word will use the defaults.
1111 |  | Word cannot open a window for the result. Close some open windows and try again.
1112 |  | You cannot insert DATA, NEXT, NEXTIF, or SKIPIF fields inside other fields.
1113 |  | You cannot include DATA, NEXT, NEXTIF, or SKIPIF fields in annotations, headers, footers, footnotes or endnotes.
1114 |  | A DATA field must be the first field in the main document.
1115 |  | A DATA field does not contain a data filename.
1116 |  | There is a syntax error in a field condition.
1117 |  | Word does not recognize the filename in the data source you typed.
1118 |  | Word does not recognize the filename in the header source you typed.
1119 |  | The requested record is beyond the end of the mail merge data source.
1120 |  | There is a printer error.

Error Number | Error Message
1121 |  | Word cannot change printers. No printers are installed.
1122 |  | The number in the Start At box is not valid.
1123 |  | The number in the Format box is not valid.
1124 |  | The numbers in the Start At and Format boxes are not valid.
1125 |  | Word found no TC (Table of Contents Entry) fields for the table of contents.
1126 |  | Word found no paragraphs with heading styles to include in the table of contents.
1127 |  | Make a selection first.
1128 |  | This is not a valid selection.
1129 |  | The document is too large to save. Delete some text before saving.
1130 |  | The document is too large for Word to handle.
1132 |  | There is insufficient memory. Close an application.
1133 |  | This search list is not valid.
1134 |  | This search expression is not valid.
1138 |  | The window is too small.
1140 |  | This is not a valid action for endnotes.
1142 |  | Word found no revision marks.
1143 |  | This document has too many styles. Word discarded some styles.
1144 |  | Word cannot read the formatting in this document.
1145 |  | Word found no footnotes.
1146 |  | Word found no annotations.
1147 |  | There is insufficient memory. The fonts in the copied text may be incorrect.
1151 |  | Word cannot move text containing a section break to the selected destination.
1152 |  | Word cannot move footnote, endnote, or annotation references to the selected destination.
1153 |  | Word cannot replace footnote, endnote, or annotation references.
1154 |  | There are too many edits in the document. This operation will be incomplete. Save your work.
1155 |  | This is not a valid action for the end of a row.
1156 |  | This is not a valid action for footnotes.
1157 |  | Word did not save the document.
1158 |  | The original file may be damaged due to a serious disk error. Save it with a new filename.

Error Number | Error Message
1159 |  | You are working without a Word work file and memory is nearly full. Save your work.
1160 |  | The Word work file and memory are nearly full. Save your work.
1161 |  | This exceeds the maximum number of columns.
1162 |  | This exceeds the maximum width.
1163 |  | The end of a row cannot be deleted.
1164 |  | You cannot insert this selection into a table.
1170 |  | You cannot paste this selection into a table.
1172 |  | Word cannot paste text containing a section break.
1175 |  | The Paste command failed because the copy and paste areas are different shapes.
1176 |  | There is insufficient memory. Close extra windows and save your work.
1177 |  | The document name or path is not valid.
1179 |  | This is not a valid action for annotations.
1180 |  | The value is out of range.
1181 |  | Word could not create a work file.
1182 |  | There is not enough memory to sort.
1183 |  | Word cannot sort fields in the selection.
1184 |  | Word found no valid records to sort.
1185 |  | The style you want to create is based on too many styles.
1186 |  | There is insufficient memory. Word is closing the saved document.
1190 |  | There is an unrecoverable disk error on file ().
1191 |  | The disk is full trying to write to (). Free some space on this drive or save the document on a different disk.
1194 |  | You cannot close a running macro.
1195 |  | () is not a valid macro or command name.
1196 |  | There is not enough memory to record the command.
1198 |  | Cannot run Word: incorrect system version.
1200 |  | Word cannot start Examples and Demos.
1202 |  | There is not enough memory to run Examples and Demos.
1208 |  | Word cannot rename or delete a macro that is open for editing.
1209 |  | You cannot edit a macro while it is being recorded.
1210 |  | This macro line is too long.
1211 |  | You cannot record over a macro that is open for editing.

Error Number | Error Message
1215 |  | There is insufficient memory. Close extra windows and try again.
1217 |  | One or more rows are too wide to split.
1218 |  | The recorded macro was too long and has been truncated.
1219 |  | One or more rows are too wide for this operation.
1220 |  | Word cannot find or run the application.
1225 |  | You cannot copy or move this selection.
1226 |  | There is insufficient memory. Word cannot display the requested font.
1227 |  | Word cannot open the graphics file.
1229 |  | This style has a circular Based On list.
1234 |  | Records with an incorrect number of fields will be skipped.
1235 |  | There is not enough memory to complete the operation.
1236 |  | There is insufficient memory. The list may be incomplete.
1237 |  | You cannot quit Microsoft Word because a dialog is active. Switch to Microsoft Word first and close the dialog.
1240 |  | You cannot repaginate until a printer is installed.
1241 |  | Word is opening a Word for OS/2 document. (This document may be fully converted by saving it as a Word for Windows document from within Word for OS/2.)
1245 |  | Word cannot display this picture format.
1246 |  | The specified data type is unavailable.
1247 |  | Word cannot start the file converter () because it is being used by another Word session.
1248 |  | Word cannot locate the server application for () objects. Install the server application with the Setup program.
1249 |  | Word cannot obtain the data for the () link.
1250 |  | Word cannot change the function of the specified key.
1251 |  | The key name is not valid.
1255 |  | The spelling checker is in use.
1256 |  | The link does not exist.
1257 |  | You cannot save while the file is in use by another process. Try saving the file with a new name.
1260 |  | Word cannot save this file because it is already open elsewhere.
1261 |  | Word cannot open this file because it is being updated by another process.
1262 |  | You cannot modify a specified link.

Error Number | Error Message
1263 |  | You have tried to open too many custom dictionaries. Word can have up to 10 custom dictionaries open at the same time.
1264 |  | The server application, source file, or item cannot be found.\rMake sure the application is properly installed, and that it has not been deleted, moved, or renamed.
1265 |  | You cannot change printer orientation with the current printer installed.
1266 |  | Line spacing must be at least ().
1267 |  | Word cannot create the custom dictionary ().
1268 |  | Word cannot open custom dictionary ().
1269 |  | Word cannot edit the ().
1270 |  | Word cannot use the AUTOSAVE-PATH specified in the File Locations panel because it is not valid.
1271 |  | Word cannot recognize this language.
1272 |  | There is not enough memory to run Help for WordPerfect Users.
1273 |  | Word cannot start Help for WordPerfect Users.
1275 |  | The object () is locked for editing.
1276 |  | No text or formatting is in the Find box.
1277 |  | The custom dictionary is full. The word was not added.
1278 |  | The custom dictionary () is too large. Try dividing it in half.
1279 |  | A spelling checker error occurred. Word is ending the current session.
1280 |  | The custom dictionary () is not available.
1282 |  | The number in the Position box must be positive.
1283 |  | This file was not recognized by the specified graphics filter.
1284 |  | The graphics file is too large to be converted.
1285 |  | This graphics file may be damaged and cannot be converted.
1286 |  | The graphics filter was unable to convert this file.
1287 |  | Word cannot start the graphics filter.
1289 |  | The grammar checker is in use.
1290 |  | There is not enough memory to run the grammar checker.
1291 |  | Word cannot start the grammar checker.
1292 |  | Word cannot read this file. Install Graphics filters by running setup.
1293 |  | Word does not recognize the object ().
1295 |  | The item name "()" of link () cannot be found.
1297 |  | The setting does not exist or cannot be deleted.

Error Number | Error Message
1298 |  | This document could not be registered.
1299 |  | The list of paths is full.
1300 |  | Word cannot save the document while the backup file is open. Clear the backup option or save the document with a new name.
1302 |  | The operation is cancelled.
1304 |  | There is not enough memory to hyphenate the document.
1305 |  | Word cannot locate the hyphenator file.
1306 |  | The file viewer could not be initialized.
1309 |  | There is not enough memory to create the hand annotation.
1310 |  | Make the list separator and the decimal separator different before calculating.
1311 |  | The thesaurus is in use.
1312 |  | The password is incorrect. Word cannot open the document.
1313 |  | Word cannot make the current document into both a mail merge main document and a data document.
1314 |  | The disk drive is not valid.
1315 |  | The path is not valid.
1316 |  | This action will not change the default page number format. To change the default page number format for this section, use Insert Page Number and choose the Format button.
1317 |  | The disk is full.
1318 |  | There is not enough memory to display the Mail Merge toolbar.
1319 |  | The disk search failed. Word has restored the previous search path.
1320 |  | The setting could not be created.
1321 |  | The directory or folder is not valid.
1323 |  | Word cannot find the () ().
1324 |  | Word cannot find the () for ().
1325 |  | The style name contains a character that is not valid.
1326 |  | The style name is too long. The maximum number of characters allowed is 253.
1327 |  | Word cannot create the specified destination file.
1328 |  | This file is empty or does not contain a graphic image.
1331 |  | A grammar checker error occurred. Word is ending the current session.
1332 |  | The path cannot contain any periods as path elements.
1333 |  | Word is unable to start Help.

Error Number | Error Message
1334 |  | You cannot edit the result of a link or embedded object.
1335 |  | Word cannot convert graphics files because no printer has been selected in File Print.
1336 |  | Word cannot create the () file because no field names were specified.
1338 |  | The maximum number of fields allowed is 31.
1339 |  | Word cannot write to the settings file.
1340 |  | The destination document did not accept the update.
1341 |  | This filename is not valid or it contains a path.
1342 |  | Graphics files can be inserted using the Picture option from the Insert menu.
1343 |  | Word is hyphenating another document.
1345 |  | You cannot print a graphics file using the Find File command.
1346 |  | You cannot attach a document template as a data or header source.
1347 |  | A hyphenation error occurred. Word is ending the current session.
1348 |  | A thesaurus error occurred. Word is ending the current session.
1349 |  | Word cannot use the DOC-PATH specified in the File Locations panel because it is not valid.
1351 |  | Word cannot search for paragraph marks in Outline View.
1352 |  | Word cannot delete the old backup file because it is read-only or another user has it open.
1353 |  | Word cannot open the () for ().
1354 |  | There are too many characters in the selection for the edit text window.
1355 |  | The selection contains characters that cannot be edited using the edit text window.
1356 |  | Word has finished searching the (). The search item was not found.
1357 |  | Word has finished searching the ().
1358 |  | Word cannot use the PICTURE-PATH specified in the File Locations panel because it is not valid.
1359 |  | The directory or folder name is not valid.
1360 |  | You do not have network permissions for this action.
1361 |  | This file is in use by another application or user.
1362 |  | There are too many open files.
1363 |  | Cannot delete the current working directory or folder.
1364 |  | A file error has occurred.
1366 |  | There is no picture available at the specified location.

Error Number | Error Message
1367 |  | A directory or folder of the proposed name already exists.
1368 |  | A file of the proposed name already exists.
1369 |  | Word cannot rename the file.
1371 |  | You must type some text for a custom footnote or endnote mark.
1372 |  | The AutoText name is not valid.
1373 |  | The AutoText name already exists.
1374 |  | The macro name is not valid.
1375 |  | The macro name already exists.
1376 |  | The organizer was unable to rename the () ().
1377 |  | The built in () () cannot be deleted.
1378 |  | A built in style cannot be renamed.
1380 |  | The password is too long.
1381 |  | Word detected an error while trying to bring up the Connect Network dialog box.
1382 |  | There is not enough memory to edit a macro.
1383 |  | You cannot close Microsoft Word because a dialog is active.\rSwitch to Microsoft Word first and close the dialog.
1385 |  | There is not enough memory to convert the macros in this file.
1386 |  | The organizer was unable to copy the () ().
1387 |  | Word could not determine the destination.
1388 |  | Word cannot add the entry because AutoCorrect entries cannot be blank.
1389 |  | The password is incorrect.
1391 |  | Word cannot complete the save due to a file permission error.
1392 |  | Unable to add because AutoCorrect entries are limited to 31 characters in length.
1394 |  | Unable to add entry to AutoCorrect because there is insufficient memory.
1395 |  | AutoCorrect cannot replace text which contains a space character. Please remove the space, or replace it with something else.
1396 |  | Word could not save the language setting in the custom dictionary.
1397 |  | The active document is not a valid mail merge main document.
1398 |  | Word did not update the source file.
1399 |  | Dropdown list form fields must have at least one item in their list.
1400 |  | Check the floppy drive to make sure the door is closed and it contains the correct disk.

Error Number | Error Message
1402 |  | There is not enough memory to save the entire Ignore All list.
1405 |  | The document is locked and cannot be opened.
1406 |  | The disk is full or too many files are open.
1407 |  | Word cannot replace the found item with text containing a break.
1408 |  | This version of the spelling checker does not understand the language formatting of custom dictionary ().
1409 |  | Column widths cannot be less than ().
1410 |  | One or more columns or column spaces with zero width were found and removed.
1411 |  | There must be at least one column defined.
1412 |  | The linked document in () is unavailable.
1413 |  | This font style name does not exist.
1414 |  | You cannot put drawing objects into a text box, callout, annotation, footnote, endnote, or macro.
1415 |  | The requested envelope size is not valid.
1419 |  | The page height for some sections is greater than the maximum allowable page height.
1420 |  | The top/bottom margins are too large for the page height in some sections.
1422 |  | Increasing left margin causes first column to become too narrow in some sections having unevenly spaced columns.
1423 |  | Increasing right margin causes last column to become too narrow in some sections having unevenly spaced columns.
1424 |  | The network drive cannot be connected because there are no free drive letters.
1425 |  | The network drive cannot be accessed without a password.
1426 |  | The network path is not valid.
1427 |  | The network password is not valid.
1428 |  | Word has finished searching the (). () replacements were made.
1429 |  | Word has finished searching the (). () replacement was made.
1431 |  | () is not a valid () file.
1432 |  | () is an incorrect version of the () file.
1433 |  | There is not enough memory to make the indicated changes to the menu.
1434 |  | Word cannot find the designated menu.
1435 |  | There is no header layer for this page. All available layers will be displayed.

Error Number | Error Message
1436 |  | The number must be between () and ().
1437 |  | This caption label is not valid.
1438 |  | You can have no more than 25 items in your drop-down list box.
1439 |  | Word could not finish merging these documents or inserting this database.
1440 |  | This command is available only from a macro.
1441 |  | This AutoCorrect entry does not exist.
1442 |  | Word could not shrink the document by one page because the document is already only one page.
1443 |  | After several attempts, Word was unable to shrink the document by one page.
1444 |  | Word could not successfully convert the picture into drawing objects.
1445 |  | There are not enough system resources to complete the operation.
1446 |  | The new toolbar must have a name.
1447 |  | The formula is empty.
1448 |  | The default directory or folder for this item cannot be on a floppy drive. Please choose a directory or folder on a hard drive.
1449 |  | That toolbar already exists in the specified context. Please choose a different name.
1450 |  | The document contains a character set that is not supported by this version of Word.
1451 |  | Word found no TA (Table of Authorities Entry) fields for the table of authorities.
1452 |  | Word cannot open () as a data or header source because it contains no data.
1453 |  | The name you have chosen is already used for a built-in toolbar. Please choose a different name.
1454 |  | Word cannot save the mail file.
1455 |  | The new menu name cannot be the same as an existing menu name.
1456 |  | The selection does not consist of heading levels.
1457 |  | An unlocked subdocument already exists in another master document.
1458 |  | The file cannot be opened with write privileges.
1459 |  | The master document needs to be saved. Please save it now and try the operation again.
1460 |  | Word could not save the subdocument. Please try a full save of the master document.

Error Number | Error Message
1461 |  | Unknown mail address.
1462 |  | Ambiguous mail address. There are two or more people whose mail addresses match the one specified.
1463 |  | Word was unable to mail your document.
1464 |  | The Find What text contains a Pattern Match expression which is not valid.
1465 |  | The field delimiter cannot be the same as the record delimiter.
1466 |  | The row or column value is too large or small for this sheet of labels.
1467 |  | The margins, label size, and number across or down values produce a page that is larger than the label page size.
1468 |  | Horizontal and vertical pitch must be greater than or equal to the label width and height, respectively.
1469 |  | Label width and height must be positive values.
1470 |  | Word could not recognize the field and record delimiter you specified.
1471 |  | This save format is not valid.
1472 |  | Word cannot save a document as form data only with the same name as an open document.
1475 |  | Your mail system does not support certain services needed for document routing.
1474 |  | Word cannot print because there is no default printer selected. Please select a printer.
1476 |  | Too many mail sessions. Log off other mail sessions and try again.
1477 |  | General mail failure. Close Microsoft Word, restart the mail system, and try again.
1478 |  | The entry is empty.
1479 |  | No citation was found.
1480 |  | The Update Source command cannot be used to update a master document.
1481 |  | Word cannot rename a file to another drive.
1482 |  | The Find What text for a Sounds Like search can only contain non-accented alphabetic letters.
1483 |  | Word found no captions to include in the table of figures.
1484 |  | Word cannot load help because the Microsoft Help application or the () file was not found.
1485 |  | The operation cannot be completed because a master document cannot contain more than 9 levels of subdocuments.

Error Number | Error Message
1486 |  | There has been a network or file permission error. The network connection may be lost.
1487 |  | Too many files are open. Please close a window.
1488 |  | Too many DDE channels are open. Please close a window.
1489 |  | Too many Word documents are open. Please close a window.
1490 |  | The template cannot be customized because it is locked for editing.
1491 |  | The style () refers to more than one style in the destination document.
1492 |  | This menu item is automatically added by Word and cannot be removed from the menu.
1493 |  | A proofing tool menu item is automatically added when Word detects that the tool has been installed. This item cannot be removed from the menu.
1494 |  | The Find What text contains a range that is not valid.
1495 |  | This command supports only table and paragraph-delimited lists.
1496 |  | Record () contained too many field delimiters ( () ).
1497 |  | Record () contained too few field delimiters ( () ).
1498 |  | Word found no endnotes.
1499 |  | Word could not load this add-in program.
1500 |  | Start At must be between () and () for this format.
1502 |  | Word cannot attach a document to a protected template.
1503 |  | You cannot record a macro to a locked file.
1504 |  | No index entries were marked.
1505 |  | Word cannot insert a database that has no field names selected.
1506 |  | Word cannot update the index.
1507 |  | Subdocument () cannot be inserted because it is the current master document or because it contains the current master document as a subdocument.
1508 |  | The maximum length value must be equal to or greater than the length of the default text, () characters.
1509 |  | Word cannot create a subdocument within a field code or result.
1510 |  | Word cannot create a subdocument within a table.
1511 |  | Word cannot create a subdocument within a frame.
1512 |  | () is not a style name.
1513 |  | () refers to more than one style.

Error Number | Error Message
1515 |  | Word cannot copy style () because it matches a style of a different type.
1516 |  | Word cannot find the graphics filter, or there is not enough memory to load it.
1517 |  | Word cannot find the designated menu item.
1518 |  | The macro () cannot be renamed or deleted because it is currently open for editing or recording.
1519 |  | Word cannot load the Button Editor, COMMTB.DLL.
1520 |  | Mail is not installed on your system.
1521 |  | Word has already routed this message. Reset the routing slip and try again.
1522 |  | Word cannot run a macro until it has finished routing this document.
1523 |  | The document does not have a routing slip. Add a routing slip and try again.
1524 |  | Word for Windows cannot open a Word for the Macintosh glossary file.
1525 |  | Word did not update the source file because it is protected or is an open subdocument.
1526 |  | You must type a character for the custom separator.
1527 |  | The Replace With text contains a group number which is out of range.
1528 |  | () is not a valid special character for the Replace With box.
1529 |  | () is not a valid special character for the Find What box.
1530 |  | The current selection does not contain a valid table or list.
1531 |  | Word cannot read the header or footer in this document. Save the document in Rich Text Format, close it, and then reopen it.
1532 |  | Word cannot create a master document from these Word for the Macintosh files. Perhaps there is not enough memory.
1533 |  | The list of filenames is too long. Word cannot open this many files at one time.
1534 |  | Word cannot merge documents that can be distributed by mail or fax without a valid mail address. Choose the Setup button to select a mail address data field.
1535 |  | Word could not merge the main document with the data source because the data records were empty or no data records matched your query options.
1536 |  | Word cannot find or run the Print Manager.
1537 |  | A valid date or time is required.

Error Number | Error Message
1538 |  | A valid number is required.
1539 |  | Word found no paragraphs with the styles needed to compile a table of figures.
1540 |  | Word found no paragraphs with the styles needed to compile a table of contents.
1541 |  | Word found no TC (Table of Contents Entry) fields for the table of figures.
1542 |  | Word could not parse your query options into a valid SQL string.
1543 |  | You can type no more than 32 characters in the Text Before and Text After boxes.
1544 |  | Word could not re-establish a DDE connection to () to complete the current task.
1545 |  | This is not a valid filename '()'.
1546 |  | Word could not retrieve a SQL string from the active data source.
1547 |  | This document cannot be opened in the Organizer dialog box.
1548 |  | The default menu for this command does not exist. Use the Customize command to add this command to a menu.
1549 |  | Word has increased the envelope height or width because it was too small. The minimum envelope dimensions are () by ().
1550 |  | This toolbar name is not valid.
1551 |  | This toolbar name already exists.
1552 |  | The built-in styles Normal and Default Paragraph Font cannot be based on any style.
1553 |  | Word could not open () because it didn't contain a valid database
1554 |  | This command is unavailable because the form field was not inserted with the Forms toolbar or by using the Insert Form Field dialog box.
1555 |  | Word cannot switch applications.
1556 |  | Word could not locate or start ().
1557 |  | The organizer could not delete the () ().
1558 |  | The () () does not exist.
1559 |  | Word could not restore an automatically saved document from the last session.
1560 |  | Word could not replace the selection with the specified database.
1561 |  | Word cannot start the grammar checker.
1562 |  | No citations were marked.
1563 |  | Word cannot open () as a data or header source because it is a mail merge main document.

Error Number | Error Message
1564 |  | The document cannot be locked.
1565 |  | You cannot send a catalog created by merging documents directly to mail, fax, or a printer.
1566 |  | Word could not merge these documents or insert this database.
1567 |  | Microsoft Mail Local Fax is not installed on your system.
1568 |  | The registration database file is not valid. You can correct it with Word's Setup program.
1569 |  | Word cannot complete the current operation because the Microsoft OLE Extension is missing or there is insufficient memory to use it.
1570 |  | There is not enough available disk space to run Word.
1571 |  | You cannot paste form fields into annotations, headers, footers, footnotes, endnotes, or text boxes.
1572 |  | The formatting in this document is too complex. Please full save the document now.
1573 |  | Word cannot undo this action because a subdocument or master document is locked.
1574 |  | You cannot change a locked subdocument or master document.
1575 |  | A valid date format is required.
1576 |  | A valid number format is required.
1577 |  | The add-in template is not valid.
1578 |  | This entry is not valid for sorting. Please type or select another entry from the list.
1579 |  | Word cannot sort this table or selection because all of its rows are table headings.
1580 |  | Word cannot sort these numbers because it does not recognize the list separator, number format, or currency format settings used in (). To see the current settings, double-click the International icon in the () Control Panel.
1581 |  | Word cannot start the Quick Preview.
1582 |  | Word cannot find the requested bookmark.
1583 |  | These query options are too complex for Microsoft Access version 1.0. Please upgrade to a later version of Microsoft Access to perform these query options.
1584 |  | Word cannot sort Microsoft Access queries. You must sort the query in Microsoft Access.
1585 |  | The global template, Normal, is already open as an add-in program.

Error Number | Error Message
1586 |  | Word is opening a Word version 1.x for Windows template. Macros from Word 1.x for Windows cannot be converted and will be lost if this file is saved in Word 6.0 for Windows format.
1587 |  | This page contains too many drawing objects to update the display.
1588 |  | You cannot put section breaks into a header, footer, footnote, endnote, annotation, text box, callout, or macro.
1589 |  | The operation cannot be completed because the subdocument is open in another window.
1590 |  | The operation cannot be completed because the subdocument has a different type of protection from the master document. Make the protection the same for the master document and the subdocuments.
1591 |  | The operation cannot be completed because the master document or subdocument contains an open embedded object. You must update and close these objects before you can continue.
1592 |  | Word cannot make the requested network connection.
1593 |  | There are too many characters in the form field.
1594 |  | The selection is marked as deleted text.
1595 |  | Word cannot search for paragraph marks in master document view.
1596 |  | () is not a valid special character for the Find What box or is not supported when the Use Pattern Matching checkbox is selected
1597 |  | There is not enough memory to display the menus. Save all changes and close Word.
1598 |  | You cannot edit a picture that is not saved in the document.
1599 |  | The selected drawing objects will not fit in a single group.
1600 |  | You cannot copy text to another document before you finish reviewing changes made with the AutoFormat command.
1601 |  | Word could not insert the results because your query generated an empty result.
1602 |  | Word cannot open () as a header file because it cannot be converted to a Word file format.
1603 |  | There is no grammar checker available for English.
1605 |  | Word is still active. Save your document and close Word before shutting down.
1609 |  | Apple PowerTalk (AOCE) is not installed.
1610 |  | Before sending a letter, you must fill in a subject and add at least one recipient.
1611 |  | There are no more letters that Word can open.
1612 |  | Word cannot open the letter unless Apple PowerTalk is installed.
1613 |  | There is not enough memory available to run the application.
1614 |  | Word cannot find the application.
1615 |  | Word cannot place a subscription there.
1616 |  | Word was unable to create a publisher.
1617 |  | The original file for this alias could not be found.
1618 |  | () contains () Publishers to the Edition (). If there is more than one Publisher to an Edition, the Edition's contents aren't predictable.
1620 |  | There is another Publisher open to the Edition (). If there is more than one Publisher to an Edition, the Edition's contents aren't predictable.
1621 |  | There is not enough memory to run Apple PowerTalk.
1623 |  | Word is unable to connect to the edition file for this publisher/subscriber.
1624 |  | Word can only convert Word 5.0 and 5.1 settings files.
1625 |  | Word cannot find the application (). Run Setup to install ().
1627 |  | Apple PowerTalk is not fully initialized. Try restarting Word after your Mailbox appears.
1629 |  | A document with a PowerTalk Mailer cannot be shown in multiple windows.
1630 |  | Changes to the PowerTalk Mailer cannot be recorded.
1631 |  | The server application can edit only one object each time. Close the application before you insert a new object.
1633 |  | There is not enough memory to convert the side-by-side paragraphs to tables.
1691 |  | Word cannot start help because the help application or help file was not found. Choose Microsoft Word Help from the Help menu to locate help.
1692 |  | Word needs the Helvetica® 9 point font to display properly on this Macintosh. Please install this font to obtain the best results.
1693 |  | Word was unable to write some of the embedded objects due to insufficient memory.
1694 |  | There was an error reading from the file.
1695 |  | Word cannot convert this document.
1696 |  | The file appears to be corrupted.
1697 |  | The file is not the right file type.
1698 |  | There was an error opening the file.
1699 |  | There was an error saving the file.
1700 |  | Word cannot save the file here because the path name is too long.
1701 |  | Word will not be able to save this file in its current directory. It will be opened Read Only.
1702 |  | Address Book failure: ()
1703 |  | Logon failed. You must log on to Microsoft Exchange to access your address book.
1704 |  | Cannot load Extended MAPI library ()
1705 |  | () is an invalid Extended MAPI library
1707 |  | Extended MAPI initialization failed.
1708 |  | Word was unable to post your document.
1709 |  | The AutoCorrect Exception name contains invalid or no characters.
1710 |  | Unable to add the AutoCorrect Exception name to the list.
1711 |  | Unable to delete the AutoCorrect Exception name from the list.
1712 |  | AutoCorrect Exception .Tab value out of range (0-1).


Workgroup Extensions for Microsoft Word

Note to User

WBMAPI.DLL is not supported by Microsoft Corporation. It is provided "as is" because we believe it may be useful to you. We regret that Microsoft is unable to support or assist you, should you have problems using this tool or any code that relies on this tool.

With the workgroup extensions for Microsoft Word, Word developers can include electronic mail (e-mail) in their custom applications. With the workgroup extensions and WordBasic, you can access the messaging application programming interface (MAPI) to create applications in Word that can:

  • Send messages and attached files to multiple users.
  • Search for messages in your Mail Inbox.
  • Read or delete messages in your Mail Inbox.

To use the workgroup extensions, you must have Microsoft Word version 6.0 for Windows and one of the following:

  • Microsoft Windows version 3.1 or later and Microsoft Mail for PC Networks version 3.0 or later
  • Microsoft Windows for Workgroups version 3.1 or later

You can also use the workgroup extensions if you have Microsoft Word version 6.0 for Windows NT and Microsoft Windows NT version 3.5 or later, or Microsoft Word version 7.0 and Microsoft Windows 95 or Microsoft Windows NT version 3.51 or later.

The WordBasic MAPI functions of the workgroup extensions consist of wrapper and helper functions. Wrapper functions mirror the arguments, data types, and functionality of corresponding MAPI functions. Helper functions read individual fields within MAPI data types or construct the aggregate data types that MAPI requires. The names of helper functions begin with "MAPISet" or "MAPIQuery."

For more in-depth information about MAPI, see the Microsoft Mail Technical Reference in your Microsoft Mail for PC Networks package.

Note

The workgroup extensions described in this appendix are not available on the Macintosh. For information about using messaging services in WordBasic on the Macintosh, see the AOCE statements and functions in Part 2, "WordBasic Reference."


Loading the Workgroup Extensions

The WordBasic MAPI functions are provided in WBMAPI.DLL, a Windows dynamic-link library (DLL) provided on the Microsoft Word Developer's Kit disk. Copy WBMAPI.DLL from either the WIN16 (Windows 3.x) or the WIN32 (Windows 95 and Windows NT) subfolder in the WBMAPI folder to the user's Windows System folder, or to any folder recognized automatically by the operating system. Every user of a workgroup application based on WBMAPI.DLL must have this file installed.

All of the Declare statements for the WBMAPI.DLL functions documented in this appendix, as well as useful constants, are included in the aaAllDeclarations macro, which is stored in WBMAPI.DOT, a template in the WBMAPI folder on the Microsoft Word Developer's Kit disk. Copy these declarations from the macro and include them in every macro you create that uses the WBMAPI.DLL functions.

In addition to aaAllDeclarations, many example macros are contained in WBMAPI.DOT; they provide a good starting point for building new applications that use the workgroup extensions. Users do not require WBMAPI.DOT.


Understanding the Workgroup Extensions

The workgroup extensions for Word provide functions that mirror MAPI functions. Since WordBasic cannot directly manipulate MAPI data types such as messages or recipient lists, the MAPI data types are managed by the WBMAPI.DLL library. The library, in turn, provides WordBasic handles to the MAPI data types. All references to MAPI data types are made by referencing handles. The WBMAPI.DLL library provides functions to create and destroy MAPI data types, as well as to examine and manipulate fields within MAPI
data types.

When a WBMAPI.DLL function is successful, it returns a handle as a non-negative value. When a function is not successful, it returns a MAPI error value
as a negative integer.


Understanding Mail Sessions

The workgroup extensions for Word messaging functions require that a Mail session is established before they are used. A Mail session validates the identity of the user and indicates which message store to use when finding and saving messages.

Because the current version of WordBasic does not support global variables, a Mail session cannot remain open when a macro completes execution. To open and close a Mail session, include both MAPILogon and MAPILogoff in every macro that uses the workgroup extensions.

Subroutines and functions can use the Mail session established by a calling procedure or function if you pass the Mail session handle to the subroutine or function. The following example passes the session handle from the main subroutine to the DisplayOriginator subroutine:

Sub MAIN
    Session = MAPILogon(0, "", "", 0, 0)
    DisplayOriginator Session
    result = MAPILogoff(Session, 0, 0, 0)
End Sub

Sub DisplayOriginator(MainSession)
    Dim MessageID$, Originator$, Address$
    result = MAPIFindNext(MainSession, 0, "", "", 0, 0, MessageID$)
    result = MAPIReadMail(MainSession, 0, MessageID$, 0, 0)
    result = MAPIQueryOriginator(Originator$, Address$)
    MsgBox Originator$ + " @ " + Address$
End Sub


Understanding Messages

The Current Messages

The workgroup extensions for Word maintain two current messages in memory. The current outbound message is the message you are preparing to send with MAPISendMail or to save with MAPISaveMail. The current inbound message is the message you most recently read with MAPIReadMail. MAPISet helper functions update the current outbound message, while MAPIQuery helper functions retrieve information from the current inbound message.

To send the current outbound message, use MAPISendMail. To save the current outbound message in the Mail Inbox without sending it, use MAPISaveMail. To retrieve a message from the Inbox and make it the current inbound message, use MAPIFindNext and MAPIReadMail.

The workgroup extensions for Word initialize both current messages when your macro calls the MAPILogon function. It removes both current messages from memory when your macro ends.

Recipients

Messages are sent to a recipient list. Each recipient is identified with a friendly name and an address. A friendly name is the descriptive name of the user. Friendly names can be ambiguous, so additional information is required to guarantee unique addressing. The address is a unique string that contains the account name of the user and must be unambiguous. The address string format varies depending on the configuration of the Mail transport system and must be obtained from the workgroup extensions before it can be used. The workgroup extensions return both strings for recipients that are selected using the Mail Address Book.

When setting message recipients, use both the name and address strings to avoid problems with ambiguous names. If you do not supply an address string, the recipient is treated as unresolved. When sending a message, the workgroup extensions will automatically attempt to resolve unresolved recipients and will return an error if it cannot resolve all recipients. You can use MAPIResolveName to force resolution before sending.

WBMAPI.DLL initializes a recipient list for the current outbound message when your macro calls the MAPILogon function. It removes the recipient list from memory when your macro ends.


Working with MAPI Data Types

Handle

A handle is a short, signed integer. A valid handle is a non-negative integer. In the current release of MAPI, 0 (zero) is a valid session handle. A negative value for a handle indicates an error. The errors returned are the negative values of the MAPI errors documented in the Microsoft Mail Technical Reference. For example, the MAPI error MAPI_E_INVALID_RECIPS is returned as –25. SUCCESS_SUCCESS is returned as 0 (zero).

MapiFile

The MapiFile data type is not supported in WordBasic. To retrieve the information about the file attachments of a message, use the MAPIQueryAttachments helper function. To add file attachments, use MAPISetAttachment.

MapiMessage

The MapiMessage data type is broken into its component data types. After MAPIReadMail returns successfully, use MAPIQuerySubject, MAPIQueryOriginator, and MAPIQueryDateReceived to retrieve envelope information about a message. Use MAPIQueryNoteText to retrieve the text of the message. Use successive calls to MAPIQueryNoteText to retrieve the text in usable chunks, since the message text can be longer than 65,280 characters, the maximum length of a WordBasic string.

MapiRecip

Several functions use or return a handle to a MapiRecip data type, which contains the recipient list of a message. To add addresses to new messages, follow this general procedure:

1. Use MAPIAddress to allow the user to specify a recipient list.

2. Use MAPIQueryRecipientList to retrieve information about recipients in the recipient list.

3. Use MAPIResolveName to resolve ambiguous names in a recipient list.

4. Finally, use MAPISetRecipient to add recipients to the current outbound message.

See "MAPIQueryRecipientList" later in this appendix for an example of addressing messages and resolving names.

Other helper functions, which you will probably use infrequently, provide greater detail and additional functionality. MAPISetRecipientList adds a complete recipient list to the current outbound message, but the function is useful only if the list does not contain any unresolved names. MAPIQueryRecipientListCount returns the number of names in a recipient list, and MAPIQueryRecipientListElement retrieves information about a specific recipient in the list.


WordBasic MAPI Functions

Consider the following for all the WBMAPI.DLL functions:

  • To use a function described in this section, you must include the corresponding Declare statement, which you can copy directly from the aaAllDeclarations macro in WBMAPI.DOT. For more information, see "Loading the Workgroup Extensions" earlier in this appendix.
  • MAPILogon must be called successfully to open a MAPI session before any other function call. End each WordBasic macro with MAPILogoff to close the MAPI session.
  • You should usually pass 0 (zero) for the UIParam argument in the function declarations later in this appendix. Although it is unlikely that dialog box pointers could be useful to the typical WordBasic programmer, the argument is still represented to support the full generality of MAPI.
  • Always pass 0 (zero) for the Reserved argument in the functions declarations. The current version of MAPI does not support this argument.
  • Add flag values to set multiple flags for a function call. The following example calls MAPILogon with two flags:

    MAPI_LOGON_UI = 1
MAPI_NEW_SESSION = 2
Flags = MAPI_LOGON_UI + MAPI_NEW_SESSION
Session = MAPILogon(0, "", "", Flags, 0)


MAPIAddress

Syntax

MAPIAddress(Session, UIParam, Caption$, EditFields, Label$, Flags, Reserved)

Remarks

Addresses a mail message. With this function, users can create a set of address list entries using the Mail Address Book, a standard address list dialog box. The dialog box cannot be suppressed, but function arguments allow the caller to set characteristics of the dialog box.

The call is made with the recipient list of the current outbound message, which can be empty. Users can add new entries to the set. MAPIAddress returns a handle to a recipient list. Use MAPIQueryRecipientList to retrieve names, addresses, or recipient classes from the recipient list. Use MAPISetRecipient
to copy recipients to the current outbound message.

In addition to choosing names from the Address Book list, users can type names in the Address Book fields. Use MAPIResolveName to resolve these names before sending the message.

Argument | Explanation
Session | An opaque session handle whose value represents a session with the messaging system. The session handle is returned by MAPILogon and invalidated by MAPILogoff. If the value is 0 (zero), the messaging system initiates a session from a system default session (if one exists) or presents a log-in dialog box. In all cases, the messaging system returns to its state before the call.
UIParam | The parent window handle for the dialog box. A value of 0 (zero) specifies that any dialog box displayed is application modal.
Caption$ | The caption of the Address Book dialog box.
EditFields | The number of edit controls that should be present in the address list. The values 0 (zero) to 4 are valid. If EditFields is 0 (zero), only address list browsing is allowed. EditFields values of 1 to 3 control the number of edit controls present. Entries selected for the different controls are differentiated by the RecipClass field of the returned recipient list. If EditFields is 4, each recipient class supported by the underlying messaging system has an edit control.
Label$ | A string used as an edit control label in the address list dialog box. This argument is ignored and should be an empty string ("") except when EditFields is 1. An ampersand (&) in the Label$ argument marks the following character as the access key for the field. If you want the label to be the default control label "To:", Label$ should be an empty string ("").
Flags | A bitmask of flags. Unspecified flags should always be set to 0 (zero). Undocumented flags are reserved. The following flags are defined: MAPI_LOGON_UI = 1 MAPI_NEW_SESSION = 2 Set MAPI_LOGON_UI if the function should display a log-in dialog box (if required). When this flag is not set, the function does not display a dialog box and returns an error if the user is not logged in. If the session passed in Session is not 0 (zero), this flag is ignored. Set MAPI_NEW_SESSION to establish a session other than the current one. For instance, if the Mail client application is already running, another MAPI application can piggyback on the session created by the Mail client application. Do not set this flag if you want the default session (if it still exists). If the session passed in Session is not 0 (zero), this flag is ignored.
Reserved | Reserved for future use. This argument must be 0 (zero).

The following table lists the possible return values of the MAPIAddress function and their meanings.

Value | Name | Meaning
Positive integer |  | A handle to a recipient list. MAPIAddress was successful.
–2 | MAPI_E_FAILURE | One or more unspecified errors occurred while addressing the mail. No list of entries was returned.
–3 | MAPI_E_LOGIN_FAILURE | There was no default log-in, and the user failed to log in successfully when the log-in dialog box was displayed. No list of entries was returned.
–5 | MAPI_E_INSUFFICIENT_MEMORY | There was insufficient memory to proceed. No list of entries was returned.
–17 | MAPI_E_INVALID_MESSAGE | An invalid message ID was used for the MessageID$ argument. No list of entries was returned.
–19 | MAPI_E_INVALID_SESSION | An invalid session handle was used for the Session argument. No list of entries was returned.
–24 | MAPI_E_INVALID_EDITFIELDS | The value of EditFields was outside the range of 0 (zero) to 4. No list of entries was returned.
–25 | MAPI_E_INVALID_RECIPIENTS | One or more of the recipients in the address list were not valid. No list of entries was returned.
–26 | MAPI_E_NOT_SUPPORTED | The operation was not supported by the underlying messaging system.
–1 | MAPI_USER_ABORT | The user canceled the process. No list of entries was returned.

Example

The following example displays the Address Book dialog box with one edit field. The dialog box title is "Submit Report" and the edit field label is "Manager:". Users can press ALT+M to access the edit field.

Sub MAIN
MAPI_LOGON_UI = 1
Session = MAPILogon(0, "", "", MAPI_LOGON_UI, 0)
RecipList = MAPIAddress(Session, 0, "Submit Report", 1, "&Manager:",\
         0, 0)
result = MAPILogoff(Session, 0, 0, 0)
End Sub


MAPIDeleteMail

Syntax

MAPIDeleteMail(Session, UIParam, MessageID$, Flags, Reserved)

Remarks

Deletes a message from the Inbox. Before calling MAPIDeleteMail, use MAPIFindNext to verify that the correct message will be deleted.

Argument | Explanation
Session | An opaque session handle whose value represents a session with the messaging system. The session handle is returned by MAPILogon and invalidated by MAPILogoff. If the value is 0 (zero), the messaging system establishes a session from a system default session (if one exists) or presents a log-in dialog box. In all cases, the messaging system returns to its state before the call.
UIParam | The parent window handle for the dialog box. A value of 0 (zero) specifies that any dialog box displayed is application modal.
MessageID$ | The messaging system's string identifier for the message being deleted. The string identifier is returned by MAPIFindNext or MAPISaveMail. Applications should assume that this identifier is invalid after MAPIDeleteMail returns successfully.
Flags | A bitmask of flags. All flags are reserved and should be set to 0 (zero).
Reserved | Reserved for future use. This argument must be 0 (zero).

The following table lists the possible return values of the MAPIDeleteMail function and their meanings.

Value | Name | Meaning
–2 | MAPI_E_FAILURE | One or more unspecified errors occurred while deleting the mail. No mail was deleted.
–5 | MAPI_E_INSUFFICIENT_MEMORY | There was insufficient memory to proceed. No mail was deleted.

Value | Name | Meaning
–17 | MAPI_E_INVALID_MESSAGE | An invalid message ID was used for the MessageID$ argument. No mail was deleted.
–19 | MAPI_E_INVALID_SESSION | An invalid session handle was used for the Session argument. No mail was deleted.
–1 | MAPI_USER_ABORT | The user canceled the process. No mail was deleted.
0 | SUCCESS_SUCCESS | The function returned successfully.

Examples

The following example finds and deletes the first message in the Inbox.

Sub MAIN
MAPI_LOGON_UI = 1
Session = MAPILogon(0, "", "", MAPI_LOGON_UI, 0)
Dim MessageID$
result = MAPIFindNext(Session, 0, "", "", 0, 0, MessageID$)
result = MAPIDeleteMail(Session, 0, MessageID$, 0, 0)
result = MAPILogoff(Session, 0, 0, 0)
End Sub

The following example saves a message in the Inbox, reads it, then deletes it. Use this example to determine the name of the current user.

Sub MAIN
MAPI_LOGON_UI = 1
Session = MAPILogon(0, "", "", MAPI_LOGON_UI, 0)
Dim MessageID$, UserName$, Address$
result = MAPISaveMail(Session, 0, "New Subject", "New Message",\
    0, 0, MessageID$)
result = MAPIReadMail(Session, 0, MessageID$, 0, 0)
result = MAPIQueryOriginator(UserName$, Address$)
result = MAPIDeleteMail(Session, 0, MessageID$, 0, 0)
result = MAPILogoff(Session, 0, 0, 0)
MsgBox "Current user: " + UserName$ + " @ " + Address$
End Sub


MAPIDetails

Syntax

MAPIDetails(Session, UIParam, Recipients, RecipIndex, Flags, Reserved)

Remarks

Displays a dialog box that provides the details of a recipient in a recipient list. Use the RecipIndex argument to specify which recipient to display. Use MAPIQueryRecipientListCount to determine the number of recipients in
a list.

The dialog box cannot be suppressed. The caller can make the entry either modifiable or fixed. The call works only for recipients that have been resolved either as the recipients of read mail, resolved entries returned by MAPIAddress, or entries returned by MAPIResolveName.

The folder the entry belongs to determines the amount of information presented in the details dialog box. It contains at least the friendly name and address of the recipient.

Argument | Explanation
Session | An opaque session handle whose value represents a session with the messaging system. Session handles are returned by MAPILogon and invalidated by MAPILogoff. If the value is 0 (zero), the messaging system sets up a session from a system default session (if one exists) or presents a log-in dialog box. In all cases, the messaging system returns to its state before the call.
UIParam | The parent window handle for the dialog box. A value of 0 (zero) specifies that any dialog box displayed is application modal.
Recipients | A handle to the recipient list containing the entry whose details are to be displayed.
RecipIndex | The index of the recipient to display. Recipients are numbered from 0 (zero) to MAPIQueryRecipientListCount minus 1.
Flags | A bitmask of flags. Unspecified flags should always be set to 0 (zero). Undocumented flags are reserved. The following flags are defined: MAPI_LOGON_UI = 1 MAPI_NEW_SESSION = 2 MAPI_AB_NOMODIFY = 1024 Set MAPI_LOGON_UI if the function should display a log-in dialog box (if required). When this flag is not set, the function does not display a dialog box and returns an error if the user is not logged in. Set MAPI_NEW_SESSION if you want to establish a session other than the current one. For instance, if a mail client is already running, another MAPI e-mail client can piggyback on the session created by the mail client application. Do not set this flag if you want the default session (if it still exists). If the session passed in Session is not 0 (zero), this flag is ignored. Set MAPI_AB_NOMODIFY if the details of the entry should not be modifiable even if the entry belongs to the personal address book.
Reserved | Reserved for future use. This argument must be 0 (zero).

The following table lists the possible return values of the MAPIDetails function and their meanings.

Value | Name | Meaning
–21 | MAPI_E_AMBIGUOUS_RECIPIENT | The recipient is not a resolved recipient. No dialog box was displayed.
–2 | MAPI_E_FAILURE | One or more unspecified errors occurred while matching the message type. The call failed before message type matching could take place.
–5 | MAPI_E_INSUFFICIENT_MEMORY | There was insufficient memory to proceed. No dialog box was displayed.
–3 | MAPI_E_LOGIN_FAILURE | There was no default log-in, and the user failed to log in successfully when the log-in dialog box was displayed. No dialog box was displayed.
–26 | MAPI_E_NOT_SUPPORTED | The operation was not supported by the underlying messaging system.
–1 | MAPI_USER_ABORT | The user canceled the process. No dialog box was displayed.
0 | SUCCESS_SUCCESS | The function returned successfully.

Example

The following example displays a standard Mail Address Book dialog box, then the details for the last recipient selected by the user. The user cannot modify the details.

Sub MAIN
MAPI_LOGON_UI = 1
Session = MAPILogon(0, "", "", MAPI_LOGON_UI, 0)
RecipList = MAPIAddress(Session, 0, "Address Book", 4, "", 0, 0)
RecipCount = MAPIQueryRecipientListCount(RecipList)
MAPI_AB_NOMODIFY = 1024
result = MAPIDetails(Session, 0, RecipList, RecipCount - 1,\
    MAPI_AB_NOMODIFY, 0)
result = MAPILogoff(Session, 0, 0, 0)
End Sub


MAPIFindNext

Syntax

MAPIFindNext(Session, UIParam, MessageType$, SeedMessageID$, Flags, Reserved, MessageID$)

Remarks

Returns the ID of the next (or first) message of a specified type. This function allows an application to enumerate messages of a given type. It returns message identifiers that can be used in subsequent MAPI function calls to retrieve and delete messages. MAPIFindNext is for processing incoming mail, not for managing received mail. MAPIFindNext looks for messages in the folder in which new messages of the specified type are delivered. MAPIFindNext calls can be made only in the context of a valid MAPI session established with MAPILogon.

When provided an empty SeedMessageID$, MAPIFindNext returns the ID
of the first message specified with MessageType$. When provided a non-empty SeedMessageID$, MAPIFindNext returns the next matching message of the type specified with MessageType$. Repeated calls to MAPIFindNext ultimately result
in a return of MAPI_E_NO_MESSAGES, which means the enumeration of the matching message types is complete.

Message identifiers are not guaranteed to remain valid, because other applications can move or delete messages. Applications must be able to handle calls to MAPIFindNext, MAPIDeleteMail, and MAPIReadMail that fail because they are for invalid message IDs. The ordering of messages is system specific. Message ID strings must be dynamic strings.

Message type matching is done against message type strings. All message types whose names match (up to the length of the MessageType$ argument) are returned. If the MessageType$ argument begins with "IPM.", matching occurs in the Inbox. If the MessageType$ argument begins with "IPC.", matching is performed in the hidden application mail folder. IPM messages are interpersonal messages; IPC messages are interprocess communication messages that are not visible to the user. If the message type is an empty string (""), the list includes all messages in the Inbox.

Argument | Explanation
Session | An opaque session handle whose value represents a session with the messaging system. Session handles are returned by MAPILogon and invalidated by MAPILogoff. If the value is 0 (zero), MAPIFindNext returns MAPI_E_INVALID_SESSION. In all cases, the messaging system returns to its state before the call.
UIParam | The parent window handle for the dialog box. A value of 0 (zero) specifies that any dialog box displayed is application modal.

Argument | Explanation
MessageType$ | A string that is the message type. To specify normal interpersonal messages, use an empty string ("").
SeedMessageID$ | A string that is the message identifier seed for the request. If the identifier is an empty string (""), the first message matching the type specified in the MessageType$ argument is returned. Message IDs are system specific and opaque. Message IDs might be invalidated at any time if another application moves or deletes a message.
Flags | A bitmask of flags. Unspecified flags should always be set to 0 (zero). Undocumented flags are reserved. The following flags are defined: MAPI_UNREAD_ONLY = 32 MAPI_NEW_SESSION = 2 MAPI_GUARANTEE_FIFO = 256 Set MAPI_UNREAD_ONLY if the function should enumerate only unread messages. When this flag is not set, all messages of the given type are returned. Set MAPI_NEW_SESSION if you want to establish a session other than the current one . For instance, if a mail client is already running, another MAPI e-mail client can piggyback on the session created by the mail client application. Do not set this flag if you want the default session (if it still exists). If the session passed in Session is not 0 (zero), this flag is ignored. Set MAPI_GUARANTEE_FIFO if you want the message IDs returned in the order the messages were received. MAPIFindNext calls may take longer if this flag is set.
Reserved | Reserved for future use. This argument must be 0 (zero).
MessageID$ | A variable-length string that is the message identifier. Message IDs are system specific, nonprintable, and opaque. Message ID strings must be dynamic strings. Message IDs might be invalidated at any time if another application deletes or moves a message.

The following table lists the possible return values of the MAPIFindNext function and their meanings.

Value | Name | Meaning
–2 | MAPI_E_FAILURE | One or more unspecified errors occurred while matching the message type. The call failed before message type matching could take place.
–5 | MAPI_E_INSUFFICIENT_MEMORY | There was insufficient memory to proceed. No mail was found.

Value | Name | Meaning
–17 | MAPI_E_INVALID_MESSAGE | An invalid message ID was used for the SeedMessageID$ argument. No mail was found.
–19 | MAPI_E_INVALID_SESSION | An invalid session handle was used for the Session argument. No mail was found.
–16 | MAPI_E_NO_MESSAGES | The MAPIFindNext function could not find a matching message.
–1 | MAPI_USER_ABORT | The user canceled the process. No mail was found.
0 | SUCCESS_SUCCESS | The function returned successfully.

Examples

The following example finds and displays the subject of messages in the Inbox that belong to the message type, "IPM.Sample.Report".

Sub MAIN
MAPI_LOGON_UI = 1
Session = MAPILogon(0, "", "", MAPI_LOGON_UI, 0)
Dim MessageID$, Subject$
result = MAPIFindNext(Session, 0, "IPM.Sample.Report", "",\
        0, 0, MessageID$)
While result = 0
    result = MAPIReadMail(Session, 0, MessageID$, 0, 0)
    result = MAPIQuerySubject(Subject$)
    MsgBox Subject$
    result = MAPIFindNext(Session, 0, "IPM.Sample.Report", MessageID$,\
        0, 0, MessageID$)
Wend
result = MAPILogoff(Session, 0, 0, 0)
End Sub

The following example finds and deletes all IPC messages.

Sub MAIN
MAPI_LOGON_UI = 1
Session = MAPILogon(0, "", "", MAPI_LOGON_UI, 0)
Dim MessageID$
result = MAPIFindNext(Session, 0, "IPC.", "", 0, 0, MessageID$)
While result = 0
    result = MAPIDeleteMail(Session, 0, MessageID$, 0, 0)
    result = MAPIFindNext(Session, 0, "IPC.", MessageID$, 0, 0,\
        MessageID$)
Wend
result = MAPILogoff(Session, 0, 0, 0)
End Sub


MAPILogoff

Syntax

MAPILogoff(Session, UIParam, Flags, Reserved)

Remarks

Ends a session with the messaging system.

Argument | Explanation
Session | An opaque session handle whose value represents a session with the messaging system. Session handles are returned by MAPILogon and invalidated by MAPILogoff.
UIParam | The parent window handle for the dialog box. A value of 0 (zero) specifies that any dialog box displayed is application modal.
Flags | Reserved for future use. This argument must be 0 (zero).
Reserved | Reserved for future use. This argument must be 0 (zero).

The following table lists the possible return values of the MAPILogoff function and their meanings.

Value | Name | Meaning
–5 | MAPI_E_INSUFFICIENT_MEMORY | There was insufficient memory to proceed. The session was not terminated.
–19 | MAPI_E_INVALID_SESSION | An invalid session handle was used for the Session argument. The session was not terminated.
0 | SUCCESS_SUCCESS | The function returned successfully.

Example

The following example begins and ends a Mail session.

Sub MAIN
MAPI_LOGON_UI = 1
Session = MAPILogon(0, "", "", MAPI_LOGON_UI, 0)
result = MAPILogoff(Session, 0, 0, 0)
End Sub


MAPILogon

Syntax

MAPILogon(UIParam, User$, Password$, Flags, Reserved)

Remarks

Begins a session with the messaging system. You can log in to the messaging system in two ways, using simple MAPI mail calls:

  • Implicitly log in.

    Any MAPI function call made outside an established MAPI session generates a log-in dialog box, which the calling application can suppress. In this case, when the call returns, the session is terminated and the messaging system returns to its state before the call was made. For example, a user logged off from the messaging system before the call would also be logged off after the call was completed.

  • Explicitly log in using the MAPILogon function (and log off using MAPILogoff).

    If you want to maintain a session over a number of simple MAPI calls,
    you can use the MAPILogon function to provide a session handle to the messaging system. This session handle can be used in subsequent MAPI calls to explicitly provide user credentials to the messaging system. A flag is available to display a log-in dialog box if the credentials presented fail to validate the session. You can pass an empty password, although it may not validate the mail session.

MAPILogon returns a session handle. A negative value for the handle indicates an error. Currently, 0 (zero) is a valid session handle.

Argument | Explanation
UIParam | The parent window handle for the dialog box. A value of 0 (zero) specifies that any dialog box displayed is application modal.
User$ | A client account-name string, limited to 256 characters or fewer. An empty string ("") indicates that a log-in dialog box with an empty name field should be generated (if the appropriate flag is set).
Password$ | A credential string, limited to 256 characters or fewer. An empty string ("") indicates that a log-in dialog box with an empty password field should be generated (if the appropriate flag is set) or that the messaging system does not require password credentials.

Argument

Explanation

Flags

A bitmask of flags. Unspecified flags should always be set to
0 (zero). Undocumented flags are reserved. The following flags
are defined:

MAPI_LOGON_UI = 1
MAPI_NEW_SESSION = 2
MAPI_FORCE_DOWNLOAD = 4096

Set MAPI_LOGON_UI if the function should display a dialog box
to prompt for name and password (if required). When this flag is not set, the MAPILogon function does not display a log-in dialog box and returns an error if the user is not logged in.

Set MAPI_NEW_SESSION to establish a session other than the current one. For instance, if a mail client is already running, another MAPI e-mail client can piggyback on the session created by the mail client application. Do not set this flag if you want the default session (if it still exists).

Set MAPI_FORCE_DOWNLOAD to force a download of all new messages from the mail server to a user's Inbox during the log-in process. Use this flag so an application can deal with the user's complete set of messages when it logs in. When this flag is set, a progress indicator is displayed, and is automatically removed when the process is complete. Use of this flag may increase processing time.

Reserved

Reserved for future use. This argument must be 0 (zero).

The following table lists the possible return values of the MAPILogon function and their meanings.

Value | Name | Meaning
–2 | MAPI_E_FAILURE | One or more unspecified errors occurred during log-in. No session handle was returned.
–5 | MAPI_E_INSUFFICIENT_MEMORY | There was insufficient memory to proceed. No session handle was returned.
–3 | MAPI_E_LOGIN_FAILURE | There was no default log-in, and the user failed to log in successfully when the log-in dialog box was displayed. No session handle was returned.
–8 | MAPI_E_TOO_MANY_SESSIONS | The user had too many sessions open at once. No session handle was returned.

Value | Name | Meaning
–1 | MAPI_USER_ABORT | The user canceled the process. No session handle was returned.
0 | SUCCESS_SUCCESS | The function returned successfully.

Example

The following example begins a Mail session and downloads new mail into the Inbox.

Sub MAIN
MAPI_LOGON_UI = 1
MAPI_FORCE_DOWNLOAD = 4096
Flags = MAPI_LOGON_UI + MAPI_FORCE_DOWNLOAD
Session = MAPILogon(0, "", "", Flags, 0)
result = MAPILogoff(Session, 0, 0, 0)
End Sub


MAPIQueryAttachments

Syntax

MAPIQueryAttachments(PathName$, FileName$, Position$)

Remarks

Retrieves information about the file attachments of the current inbound message. First use MAPIReadMail to make a message the current inbound message, then successively call MAPIQueryAttachments to enumerate the attachments of the message. MAPIQueryAttachments returns either the type of the attachment or –1 to indicate no more attachments.

MAPIReadMail automatically creates a temporary file for every attachment unless you call MAPIReadMail with the MAPI_ENVELOPE_ONLY or MAPI_SUPPRESS_ATTACH flag. The temporary files are not deleted automatically by the workgroup extensions. You must use MAPIQueryAttachments to enumerate the attachments and delete the
temporary files.

Argument | Explanation
PathName$ | The full path of a temporary file that contains a copy of the attached file.
FileName$ | The filename seen by the recipient. This name can differ from the filename in PathName$ if temporary files are being used. If FileName$ is empty, the filename from PathName$ is used. If the attachment is an OLE object, FileName$ contains the class name of the object; for example, "Microsoft Excel Worksheet."
Position$ | An integer formatted as a string indicating where the attachment is placed in the message body.

The following table lists the possible return values of the MAPIQueryAttachments function and their meanings.

Value | Name | Meaning
0 |  | Attachment is a data file, not an OLE object.
1 | MAPI_OLE | Attachment is an embedded OLE object.
2 | MAPI_OLE_STATIC | Attachment is a static OLE object.
–1 |  | Message contains no attachments or all attachments have been queried.

Example

The following example successively displays the filename of each attachment of the first message in the Inbox:

Sub MAIN
MAPI_LOGON_UI = 1
Session = MAPILogon(0, "", "", MAPI_LOGON_UI, 0)
Dim MessageID$, PathName$, MailFileName$, Position$
result = MAPIFindNext(Session, 0, "", "", 0, 0, MessageID$)
result = MAPIReadMail(Session, 0, MessageID$, 0, 0)
While result >= 0
    result = MAPIQueryAttachments(PathName$, MailFileName$, Position$)
    If result >= 0 Then
        MsgBox MailFileName$
        Kill PathName$
    End If
Wend
result = MAPILogoff(Session, 0, 0, 0)
End Sub


MAPIQueryDateReceived

Syntax

MAPIQueryDateReceived(DateReceived$)

Remarks

Returns the date and time of the current inbound message.

Argument | Explanation
DateReceived$ | A string indicating the date and time a message is received. The format is YYYY/MM/DD HH:MM; hours are measured on a 24-hour clock.

Example

The following example displays the date and time of the first message in the Inbox.

Sub MAIN
MAPI_LOGON_UI = 1
Session = MAPILogon(0, "", "", MAPI_LOGON_UI, 0)
Dim MessageID$, MailDate$
result = MAPIFindNext(Session, 0, "", "", 0, 0, MessageID$)
MAPI_ENVELOPE_ONLY = 64
MAPI_PEEK = 128
Flags = MAPI_ENVELOPE_ONLY + MAPI_PEEK
result = MAPIReadMail(Session, 0, MessageID$, Flags, 0)
result = MAPIQueryDateReceived(MailDate$)
MsgBox MailDate$
result = MAPILogoff(Session, 0, 0, 0)
End Sub


MAPIQueryNoteText

Syntax

MAPIQueryNoteText(NoteText$, Size)

Remarks

Returns the text of the current inbound message. Of the current inbound message, MAPIQueryNoteText returns at most the number of characters specified in the Size argument. The function returns 1 if there is more text, or 0 (zero) if there is not.

Use successive calls to MAPIQueryNoteText to retrieve the text in usable chunks since the message text can be longer than 65,280 characters, the maximum length of a WordBasic string.

Argument | Explanation
NoteText$ | A string containing text in the message
Size | The maximum number of characters to return

The following table lists the possible return values of the MAPIQueryNoteText function and their meanings.

Value | Meaning
1 | The message contains additional text.
0 | The message contains no additional text.

Example

The following example creates a new Word document, and copies to the document all the text of the first message in the Inbox. The text is copied in chunks of 1,024 characters.

Sub MAIN
FileNew
MAPI_LOGON_UI = 1
Session = MAPILogon(0, "", "", MAPI_LOGON_UI, 0)
Dim MessageID$, NoteText$
result = MAPIFindNext(Session, 0, "", "", 0, 0, MessageID$)
MAPI_SUPPRESS_ATTACH = 2048
MAPI_PEEK = 128
Flags = MAPI_SUPPRESS_ATTACH + MAPI_PEEK
result = MAPIReadMail(Session, 0, MessageID$, Flags, 0)
result = 1
While result = 1
    NoteText$ = String$(1024, 32)
    result = MAPIQueryNoteText(NoteText$, Len(NoteText$))
    Insert NoteText$
Wend
result = MAPILogoff(Session, 0, 0, 0)
End Sub


MAPIQueryOriginator

Syntax

MAPIQueryOriginator(OrigName$, Address$)

Remarks

Returns the friendly name of the originator of the current inbound message.

Argument | Explanation
OrigName$ | The friendly name of the originator of the current inbound message
Address$ | The address of the originator of the current inbound message

Example

The following example displays the friendly name and address of the originator of the first message in the Inbox.

Sub MAIN
MAPI_LOGON_UI = 1
Session = MAPILogon(0, "", "", MAPI_LOGON_UI, 0)
Dim MessageID$, Originator$, Address$
result = MAPIFindNext(Session, 0, "", "", 0, 0, MessageID$)
MAPI_ENVELOPE_ONLY = 64
MAPI_PEEK = 128
Flags = MAPI_ENVELOPE_ONLY + MAPI_PEEK
result = MAPIReadMail(Session, 0, MessageID$, Flags, 0)
result = MAPIQueryOriginator(Originator$, Address$)
MsgBox Originator$ + " @ " + Address$
result = MAPILogoff(Session, 0, 0, 0)
End Sub


MAPIQueryRecipientList

Syntax

MAPIQueryRecipientList(Recipients, RecipName$, Address$)

Remarks

Retrieves information about recipients in a recipient list. On the first call to MAPIQueryRecipientList, Recipients must be a handle
to a recipient list of the type returned by MAPIAddress. The MAPIQueryRecipientList function returns –1 to indicate that there are no
more recipients. Otherwise, it returns the recipient class of the recipient.

Argument | Explanation
Recipients | A handle to a recipient list on the first call to MAPIQueryRecipientList. Use 0 (zero) for succeeding calls.
RecipName$ | The friendly name of the recipient as displayed by the messaging system.
Address$ | Provider-specific message delivery data. This field can be used by the message system to identify recipients who are not in an address list (custom recipients).

The following table lists the possible return values of the MAPIQueryRecipientList function and their meanings.

Value | Name | Meaning
0 | MAPI_ORIG | The recipient is the originator of the message.
1 | MAPI_TO | The recipient is a To recipient of the message.
2 | MAPI_CC | The recipient is a carbon-copy (CC) recipient of the message.
3 | MAPI_BCC | The recipient is a blind carbon-copy (BCC) recipient of the message.
–1 |  | Either the recipient list contains no recipients or all recipients have been queried.

Example

The following example displays the Mail Address Book, which returns a handle to a recipient list. The example then prompts the user to resolve any unresolved names in the list. Finally, all resolved names are added to a new message.

Sub MAIN
MAPI_LOGON_UI = 1
MAPI_DIALOG = 8
Session = MAPILogon(0, "", "", MAPI_LOGON_UI, 0)
RecipList = MAPIAddress(Session, 0, "", 4, "", 0, 0)
If RecipList >= 0 Then
    'Query the first recipient
    RecipClass = 0
    RecipName$ = ""
    Address$ = ""
    RecipClass = MAPIQueryRecipientList(RecipList, RecipName$, Address$)
    While RecipClass >= 0
        'Process the recipient
        If Address$ <> "" Then
            result = MAPISetRecipient(RecipClass, RecipName$, Address$)
        Else
            ResolveList = MAPIResolveName(Session, 0, RecipName$, \
              Address$, MAPI_DIALOG, 0)
            If ResolveList >= 0 Then
                result = MAPIQueryRecipientListElement(ResolveList, 0, \
                  RecipName$, Address$)
                result = MAPISetRecipient(RecipClass, RecipName$, \
                  Address$)
            Else
                result = MAPISetRecipient(RecipClass, RecipName$, "")
            End If
        End If
        'Query the next recipient
        RecipClass = 0
        RecipName$ = ""
        Address$ = ""
        RecipClass = MAPIQueryRecipientList(0, RecipName$, Address$)
    Wend
    'Display the Send Note dialog
    result = MAPISendMail(Session, 0, "", "", MAPI_DIALOG, 0)
End If
result = MAPILogoff(Session, 0, 0, 0)
End Sub


MAPIQueryRecipientListCount

Syntax

MAPIQueryRecipientListCount(Recipients)

Remarks

Returns the number of names in a recipient list.

Argument | Explanation
Recipients | A handle to a recipient list

The following table lists the possible return values of the MAPIQueryRecipientListCount function and their meanings.

Value | Meaning
0 | Recipients is not a valid handle to a recipient list, or the recipient list is empty.
Positive integer | The number of recipients in the recipient list.

Example

The following example displays the Mail Address Book, and then the number of resolved recipients selected by the user.

Sub MAIN
MAPI_LOGON_UI = 1
Session = MAPILogon(0, "", "", MAPI_LOGON_UI, 0)
RecipList = MAPIAddress(Session, 0, "", 4, "", 0, 0)
TotalCount = MAPIQueryRecipientListCount(RecipList)
ResolvedCount = 0
For i = 0 To TotalCount - 1
    RecipName$ = ""
    Address$ = ""
    result = MAPIQueryRecipientListElement(RecipList, i, RecipName$,\
      Address$)
    If Address$ <> "" Then ResolvedCount = ResolvedCount + 1
Next
MsgBox Str$(ResolvedCount) + " of " + Str$(TotalCount) + " recipients resolved"
result = MAPILogoff(Session, 0, 0, 0)
End Sub


MAPIQueryRecipientListElement

Syntax

MAPIQueryRecipientListElement(Recipients, RecipIndex, RecipName$, Address$)

Remarks

Retrieves information about one recipient in a recipient list. MAPIQueryRecipientList and MAPIQueryRecipientListElement return the same information about recipients. MAPIQueryRecipientList steps through the recipient list one-at-a-time in order, while MAPIQueryRecipientListElement retrieves information about one recipient anywhere in the list.

Recipients must be a handle to a recipient list of the type returned by MAPIAddress. Use RecipIndex to specify which recipient to query.

Argument | Explanation
Recipients | A handle to a recipient list.
RecipIndex | The index of the recipient to query. Recipients are numbered from 0 (zero) to MAPIQueryRecipientListCount minus 1.
RecipName$ | The friendly name of the recipient as displayed by the messaging system.
Address$ | Provider-specific message delivery data. This field can be used by the message system to identify recipients who are not in an address list (custom recipients).

The following table lists the possible return values of the MAPIQueryRecipientListElement function and their meanings.

Value | Name | Meaning
0 | MAPI_ORIG | The recipient is the originator of the message.
1 | MAPI_TO | The recipient is a To recipient of the message.
2 | MAPI_CC | The recipient is a carbon-copy (CC) recipient of the message.
3 | MAPI_BCC | The recipient is a blind carbon-copy (BCC) recipient of the message.

Example

The following example displays the Mail Address Book, and then the name and address of the last name selected by the user.

Sub MAIN
MAPI_LOGON_UI = 1
Session = MAPILogon(0, "", "", MAPI_LOGON_UI, 0)
RecipList = MAPIAddress(Session, 0, "", 4, "", 0, 0)
RecipCount = MAPIQueryRecipientListCount(RecipList)
Dim RecipName$, Address$
result = MAPIQueryRecipientListElement(RecipList, RecipCount - 1, \
        RecipName$, Address$)
MsgBox RecipName$ + " @ " + Address$
result = MAPILogoff(Session, 0, 0, 0)
End Sub


MAPIQuerySubject

Syntax

MAPIQuerySubject(Subject$)

Remarks

Returns the subject text of the current inbound message.

Argument | Explanation
Subject$ | The subject text, limited to 256 characters. (Messages saved with MAPISaveMail are not limited to 256 characters.) An empty string ("") indicates no subject text.

Example

The following example displays the subject of the first message in the Inbox.

Sub MAIN
MAPI_LOGON_UI = 1
Session = MAPILogon(0, "", "", MAPI_LOGON_UI, 0)
Dim MessageID$, Subject$
result = MAPIFindNext(Session, 0, "", "", 0, 0, MessageID$)
MAPI_ENVELOPE_ONLY = 64
MAPI_PEEK = 128
Flags = MAPI_ENVELOPE_ONLY + MAPI_PEEK
result = MAPIReadMail(Session, 0, MessageID$, Flags, 0)
result = MAPIQuerySubject(Subject$)
MsgBox Subject$
result = MAPILogoff(Session, 0, 0, 0)
End Sub


MAPIReadMail

Syntax

MAPIReadMail(Session, UIParam, MessageID$, Flags, Reserved)

Remarks

Reads a mail message and makes it the current inbound message. Before calling MAPIReadMail, use MAPIFindNext to verify that the correct message will be read. Use the MAPIQuery helper functions to retrieve information about the message. Use the MAPISet helper functions and MAPISaveMail to change the message. Use the MAPISet helper functions and MAPISendMail to forward or reply to the message.

MAPIReadMail automatically creates a temporary file for every attachment unless you call MAPIReadMail with the MAPI_ENVELOPE_ONLY or MAPI_SUPPRESS_ATTACH flag. The temporary files are not deleted automatically by the workgroup extensions. You must use MAPIQueryAttachments to enumerate the attachments and delete the
temporary files.

Recipients, attachments, and contents are copied from the message before the function returns to the caller, so later changes to these elements do not affect the contents of the message unless changes are explicitly saved with MAPISaveMail or MAPISendMail.

Argument

Explanation

Session

An opaque session handle whose value represents a session with the messaging system. If the value is 0 (zero), MAPIReadMail returns MAPI_E_INVALID_SESSION.

UIParam

The parent window handle for the dialog box. A value of 0 (zero) specifies that any dialog box displayed is application modal.

MessageID$

A variable-length string that is the message identifier of the message to be read. Message IDs are system specific, nonprintable, and opaque. Message IDs can be obtained from the MAPIFindNext and MAPISaveMail functions.

Flags

A bitmask of flags. Unspecified flags should always be set to
0 (zero). Undocumented flags are reserved. The following flags
are defined:

MAPI_ENVELOPE_ONLY = 64
MAPI_SUPPRESS_ATTACH = 2048
MAPI_BODY_AS_FILE = 512
MAPI_PEEK = 128

Set MAPI_ENVELOPE_ONLY if you don't want the function to copy attachments to temporary files or return the note text. All other message information (except temporary filenames) is returned. Setting this flag usually reduces the processing time required for
the function.

Set MAPI_SUPPRESS_ATTACH if you don't want MAPIReadMail to copy attachments but just to return note text.
If MAPI_ENVELOPE_ONLY is set, this flag is ignored. The flag should reduce the time required by the MAPIReadMail function.

Set MAPI_BODY_AS_FILE if you want the message body written to a temporary file and added to the attachment list as the first attachment, instead of using MAPIQueryNoteText to retrieve the message body (the default behavior). The Position argument of a body attachment is –1.

Set MAPI_PEEK if you don't want MAPIReadMail to mark the message as read. Any unsuccessful return leaves the message unread.

Reserved

Reserved for future use. This argument must be 0 (zero).

The following table lists the possible return values of the MAPIReadMail function and their meanings.

Value | Name | Meaning
–13 | MAPI_E_ATTACHMENT_ WRITE_FAILURE | An attachment could not be written to a temporary file. Check folder permissions.
–4 | MAPI_E_DISK_FULL | The disk was full.
–2 | MAPI_E_FAILURE | One or more unspecified errors occurred while reading the mail. No mail was read.
–5 | MAPI_E_INSUFFICIENT_MEMORY | There was insufficient memory to proceed. No mail was read.
–17 | MAPI_E_INVALID_MESSAGE | The message ID was invalid. It may have been deleted or changed by another process.
–19 | MAPI_E_INVALID_SESSION | An invalid session handle was used for the Session argument. No mail was read.
–26 | MAPI_E_NOT_SUPPORTED | The operation was not supported by the underlying messaging system.
–9 | MAPI_E_TOO_MANY_FILES | Too many file attachments were contained in the message. No mail was read.
–10 | MAPI_E_TOO_MANY_RECIPIENTS | There were too many recipients of the message. No mail was read.
0 | SUCCESS_SUCCESS | The function returned successfully.

Example

The following example displays the subject of the first message in the Inbox. The MAPIReadMail function in the example does not retrieve the note text or attachments of the message, and it does not mark the message as read.

Sub MAIN
MAPI_LOGON_UI = 1
Session = MAPILogon(0, "", "", MAPI_LOGON_UI, 0)
Dim MessageID$, Subject$
result = MAPIFindNext(Session, 0, "", "", 0, 0, MessageID$)
MAPI_ENVELOPE_ONLY = 64
MAPI_PEEK = 128
Flags = MAPI_ENVELOPE_ONLY + MAPI_PEEK
result = MAPIReadMail(Session, 0, MessageID$, Flags, 0)
result = MAPIQuerySubject(Subject$)
MsgBox Subject$
result = MAPILogoff(Session, 0, 0, 0)
End Sub


MAPIResolveName

Syntax

MAPIResolveName(Session, UIParam, RecipName$, Address$, Flags, Reserved)

Remarks

Displays a dialog box to resolve an ambiguous recipient name. This function resolves a mail recipient's name (as entered by a user) to an unambiguous address list entry. MAPIResolveName prompts the user to choose between ambiguous entries, if necessary. A recipient list containing fully resolved information about the entry is allocated and returned.

Some RecipName$ strings cannot be resolved. Some strings may produce too many matches or no matches at all, or the user can cancel the Resolve Name dialog box.

MAPIResolveName returns a handle to a recipient list.

Argument | Explanation
Session | An opaque session handle whose value represents a session with the messaging system. The session handle is returned by MAPILogon and invalidated by MAPILogoff. If the value is 0 (zero), the messaging system initiates a session from a system default session (if one exists) or presents a log-in dialog box. In all cases, the messaging system returns to its state before the call.
UIParam | The parent window handle for the dialog box. A value of 0 (zero) specifies that any dialog box displayed is application modal.
RecipName$ | A string containing the name to be resolved.

Argument

Explanation

Address$

Provider-specific Mail address of the recipient.

Flags

A bitmask of flags. Unspecified flags should always be set to
0 (zero). Undocumented flags are reserved. The following flags
are defined:

MAPI_LOGON_UI = 1
MAPI_NEW_SESSION = 2
MAPI_DIALOG = 8
MAPI_AB_NOMODIFY = 1024

Set MAPI_LOGON_UI if the function should display a log-in dialog box (if required). When this flag is not set, the function does not display a dialog box and returns an error if the user is not logged in.

Set MAPI_NEW_SESSION if you want to establish a session other than the current one. For instance, if a mail client is already running, another MAPI e-mail client can piggyback on the session created by the mail client application. Do not set this flag if you want the default session (if it still exists). If the session passed in Session is not 0 (zero), this flag is ignored.

Set MAPI_DIALOG if MAPIResolveName should attempt to resolve names by displaying a name resolution dialog box to the user. If this flag is not set, resolutions which do not result in a single name return MAPI_E_AMBIGUOUS_RECIPIENT.

Set MAPI_AB_NOMODIFY if the details of the entry should not be modifiable even if the entry belongs to the personal address book. Part of the resolution dialog box could involve displaying details about the various entries that match the RecipName$ argument. Set this flag if these details should not be modifiable. This flag is ignored if MAPI_DIALOG is not set.

Reserved

Reserved for future use. This argument must be 0 (zero).

The following table lists the possible return values of the MAPIResolveName function and their meanings.

Value | Name | Meaning
–21 | MAPI_E_AMBIGUOUS_RECIPIENT | One or more recipients were specified ambiguously. The name was not resolved.
–2 | MAPI_E_FAILURE | One or more unspecified errors occurred while addressing the mail. The name was not resolved.

Value | Name | Meaning
–5 | MAPI_E_INSUFFICIENT_MEMORY | There was insufficient memory to proceed. The name was not resolved.
–3 | MAPI_E_LOGIN_FAILURE | There was no default log-in, and the user failed to log in successfully when the log-in dialog box was displayed. The name was not resolved.
–26 | MAPI_E_NOT_SUPPORTED | The operation was not supported by the underlying messaging system.
–1 | MAPI_USER_ABORT | The user canceled the process. The name was not resolved.
Positive integer |  | A handle to a recipient list.

Example

The following example resolves a name.

Sub MAIN
MAPI_LOGON_UI = 1
MAPI_DIALOG = 8
Session = MAPILogon(0, "", "", MAPI_LOGON_UI, 0)
RecipName$ = "carlos"
Address$ = ""
ResolveList = MAPIResolveName(Session, 0, RecipName$, Address$,\
    MAPI_DIALOG, 0)
If ResolveList > 0 Then MsgBox Address$
result = MAPILogoff(Session, 0, 0, 0)
End Sub


MAPISaveMail

Syntax

MAPISaveMail(Session, UIParam, Subject$, NoteText$, Flags, Reserved, MessageID$)

Remarks

Saves the current outbound message in the Mail Inbox, optionally replacing an existing message. Before calling MAPISaveMail, use MAPIFindNext to verify that the correct message will be saved. MessageID$ must be a variable-length string. The elements of the message identified by the MessageID$ argument are replaced by the elements of the current outbound message. If the MessageID$ argument is empty, a new message is created. The new message ID is returned
in the MessageID$ argument on completion of the call. All replaced messages
are saved in their appropriate folders. New messages are saved in the folder appropriate for incoming messages of that class.

The MAPISaveMail function uses the recipients and file attachments that you previously specified with the MAPISetRecipient, MAPISetRecipientList, MAPISetMessageType and MAPISetAttachment functions.

Argument | Explanation
Session | An opaque session handle whose value represents a session with the messaging system. Session handles are returned by MAPILogon and invalidated by MAPILogoff. If the value is 0 (zero) and MessageID is an empty string (""), the messaging system establishes a session from a system default session (if one exists) or presents a log-in dialog box. Otherwise, calls with Session equal to 0 (zero) return MAPI_E_INVALID_SESSION.
UIParam | The parent window handle for the dialog box. A value of 0 (zero) specifies that any dialog box displayed is application modal.
Subject$ | The subject text, limited to 256 characters. (Messages saved with MAPISaveMail are not limited to 256 characters.) An empty string ("") indicates no subject text.
NoteText$ | A string containing the text of the message.
Flags | A bitmask of flags. Unspecified flags should always be set to 0 (zero). Undocumented flags are reserved. The following flags are defined: MAPI_LOGON_UI = 1 MAPI_NEW_SESSION = 2 Set MAPI_LOGON_UI if the function should display a log-in dialog box (if required). When this flag is not set, the function does not display a dialog box and returns an error if the user is not logged in. Set MAPI_NEW_SESSION if you want to establish a session other than the current one. For instance, if a mail client is already running, another MAPI e-mail client can piggyback on the session created by the mail client application. Do not set this flag if you want the default session (if it still exists). If the session passed in Session is not 0 (zero), this flag is ignored.
Reserved | Reserved for future use. This argument must be 0 (zero).
MessageID$ | The variable-length string identifier for this message. It is returned by the MAPIFindNext function or a previous call to MAPISaveMail. If a new message is to be created, this argument should be an empty string (""). Message ID strings must be dynamic strings.

The following table lists the possible return values of the MAPISaveMail function and their meanings.

Value | Name | Meaning
–4 | MAPI_E_DISK_FULL | The disk was full.
–2 | MAPI_E_FAILURE | One or more unspecified errors occurred while saving the mail. No mail was saved.
–5 | MAPI_E_INSUFFICIENT_MEMORY | There was insufficient memory to proceed. No mail was saved.
–17 | MAPI_E_INVALID_MESSAGE | An invalid message ID was used for the MessageID$ argument. No mail was saved.
–19 | MAPI_E_INVALID_SESSION | An invalid session handle was used for the Session argument. No mail was saved.
–3 | MAPI_E_LOGIN_FAILURE | There was no default log-in, and the user failed to log in successfully when the log-in dialog box was displayed. No mail was saved.
–26 | MAPI_E_NOT_SUPPORTED | The operation was not supported by the underlying messaging system.
–1 | MAPI_USER_ABORT | The user canceled the process. No mail was saved.
0 | SUCCESS_SUCCESS | The function returned successfully.

Example

The following example saves a message in the Inbox with two unresolved recipients.

Sub MAIN
MAPI_LOGON_UI = 1
Session = MAPILogon(0, "", "", MAPI_LOGON_UI, 0)
Dim MessageID$
result= MAPISetRecipient(1,"Anita Kopf","")
result= MAPISetRecipient(2,"Roger Selva","")
result = MAPISaveMail(Session, 0, "Monthly Summary",\
    "We will quickly satisfy all orders for clamps.", 0, 0, MessageID$)
result = MAPILogoff(Session, 0, 0, 0)
End Sub


MAPISendDocuments

Syntax

MAPISendDocuments(UIParam, DelimChar$, FilePaths$, FileNames$, Reserved)

Remarks

Sends a standard mail message. Calling the function displays a Send Note dialog box, which prompts the user to send a mail message with data file attachments. Attachments can include the active document or all the currently open documents. The function is used primarily for calls from a macro or scripting language, often found in applications such as spreadsheet or word-processing programs.

If the user is not currently logged in, a standard log-in dialog box appears. After the user logs in succesfully, the Send Note dialog box appears.

The user's default messaging options are used as the default dialog box values. The function caller is responsible for deleting temporary files created when using this function.

Argument | Explanation
UIParam | The parent window handle for the dialog box. A value of 0 (zero) specifies that the Send Note dialog box is application modal.
DelimChar$ | A string containing the character used to delimit the names in the FilePaths$ and FileNames$ arguments. This character should not be a character that your operating system uses or allows in filenames.
FilePaths$ | A string containing the list of full paths (including drive letters) for the attached files. The list is formed by concatenating correctly formed paths separated by the character specified in the DelimChar$ argument. For example: C:\TMP\TEMP1.DOC;C:\TMP\TEMP2.DOC The files specified in this argument are added to the message as file attachments. If this argument contains an empty string (""), the Send Note dialog box is displayed with no attached files.
FileNames$ | A string containing the list of the original filenames (in 8.3 format) as they should be displayed in the message. When multiple names are specified, the list is formed by concatenating the filenames separated by the character specified in the DelimChar$ argument. For example: MEMO.DOC;EXPENSES.DOC Note that the icon displayed for a file is based on the filename extension supplied in this argument. For example, a filename with an .XLS extension is displayed with a Microsoft Excel icon. Mail also relies on the file extension when opening and saving a file. If an attached file has no extension, append the default extension for your application's document type.
Reserved | Reserved for future use. This argument must be 0 (zero).

The following table lists the possible return values of the MAPISendDocuments function and their meanings.

Value | Name | Meaning
–12 | MAPI_E_ATTACHMENT_ OPEN_FAILURE | One or more files in the FilePaths$ argument could not be located. No mail was sent.
–4 | MAPI_E_DISK_FULL | The disk was full.
–2 | MAPI_E_FAILURE | One or more unspecified errors occurred while sending the mail. It is not known if the mail was sent.
–5 | MAPI_E_INSUFFICIENT_MEMORY | There was insufficient memory to proceed.
–3 | MAPI_E_LOGIN_FAILURE | There was no default log-in, and the user failed to log in successfully when the log-in dialog box was displayed. No mail was sent.
–1 | MAPI_USER_ABORT | The user canceled the process (from the send dialog box). No mail was sent.
0 | SUCCESS_SUCCESS | The mail was successfully sent. The caller is responsible for deleting any temporary files referenced in the FilePaths$ argument.

Example

The following example displays the Send Note dialog box with two attachments.

Sub MAIN
result = MAPISendDocuments(0, ";",\
    "C:\DOCUMENT\THANKYOU.DOC;C:\WGTPLATE\CONTRACT.DOC" \
    "THANKYOU.DOC;CONTRACT.DOC",0)
End Sub


MAPISendMail

Syntax

MAPISendMail(Session, UIParam, Subject$, NoteText$, Flags, Reserved)

Remarks

Sends a mail message, allowing greater flexibility than MapiSendDocuments
in message generation. This function sends the current outbound message as a standard mail message. It can, if you choose, prompt for user input with a dialog box or proceed without any user interaction.

You can optionally provide a list of subject or note text when you call MAPISendMail. The MAPISendMail function uses the recipients and file attachments that you previously specified with the MAPISetRecipient, MAPISetRecipientList, or MAPISetAttachment functions.

If you provide recipient names, file attachments, or note text, the function can send the files or note without prompting users. If the optional arguments are specified and a dialog box is requested with the MAPI_DIALOG flag, the arguments provide the initial values for the Send Note dialog box.

File attachments are copied to the message before the function returns; therefore, later changes to the files do not affect the contents of the message. The files must be closed when they are copied.

Argument | Explanation
Session | An opaque session handle whose value represents a session with the messaging system. If the value is 0 (zero), the messaging system sets up a session either from a system default session (if one exists) or by presenting a log-in dialog box. In all cases, the messaging system returns to its state before the call.
UIParam | The parent window handle for the dialog box. A value of 0 (zero) specifies that any dialog box displayed is application modal.
Subject$ | The subject text, limited to 256 characters. An empty string ("") indicates no subject text. Some implementations may truncate subject lines that are too long or contain carriage returns, linefeeds, or other control characters.
NoteText$ | A string containing the text of the message. An empty string ("") indicates no text. The implementation wraps lines as appropriate. Implementations may place limits on the size of the text. A return of MAPI_E_TEXT_TOO_LARGE is generated if this limit is exceeded.

Argument

Explanation

Flags

A bitmask of flags. Unspecified flags should always be set to
0 (zero). Undocumented flags are reserved. The following flags
are defined:

MAPI_LOGON_UI = 1
MAPI_NEW_SESSION = 2
MAPI_DIALOG = 8

Set MAPI_LOGON_UI if the function should display a dialog box to prompt for log-in (if required). When this flag is not set, the function does not display a dialog box and returns an error if the user is not logged in.

Set MAPI_NEW_SESSION if you want to establish a session other than the current one. For instance, if a mail client is already running, another MAPI e-mail client can piggyback on the session created by the mail client application. Do not set this flag if you want the default session (if it still exists). If the session passed in Session is not 0 (zero), this flag is ignored.

Set MAPI_DIALOG if the function should display a dialog box to prompt the user for recipients and other sending options. When you do not set this flag, the function does not display a dialog box, but at least one recipient must be specified.

Reserved

Reserved for future use. This argument must be 0 (zero).

The following table lists the possible return values of the MAPISendMail function and their meanings.

Value | Name | Meaning
–21 | MAPI_E_AMBIGUOUS_RECIPIENT | A recipient matched more than one of the recipient descriptor types, and MAPI_DIALOG was not set. No mail was sent.
–11 | MAPI_E_ATTACHMENT_ NOT_FOUND | The specified attachment was not found. No mail was sent.
–15 | MAPI_E_BAD_RECIPTYPE | The type of a recipient was not MAPI_TO, MAPI_CC, or MAPI_BCC. No mail was sent.
–4 | MAPI_E_DISK_FULL | The disk was full. No mail was sent.
–2 | MAPI_E_FAILURE | One or more unspecified errors occurred while sending the mail. No mail was sent.

Value | Name | Meaning
–5 | MAPI_E_INSUFFICIENT_MEMORY | There was insufficient memory to proceed. No mail was sent.
–19 | MAPI_E_INVALID_SESSION | An invalid session handle was used for the Session argument. No mail was sent.
–3 | MAPI_E_LOGIN_FAILURE | There was no default log-in, and the user failed to log in successfully when the log-in dialog box was displayed. No mail was sent.
–18 | MAPI_E_TEXT_TOO_LARGE | The text in the message was too large to be sent. No mail was sent.
–9 | MAPI_E_TOO_MANY_FILES | There were too many file attachments. No mail was sent.
–10 | MAPI_E_TOO_MANY_RECIPIENTS | There were too many message recipients specified. No mail was sent.
–8 | MAPI_E_TOO_MANY_SESSIONS | The user had too many sessions open at once. No mail was sent.
–14 | MAPI_E_UNKNOWN_RECIPIENT | The recipient did not appear in the address list. No mail was sent.
–1 | MAPI_USER_ABORT | The user canceled the process from the send dialog box. No mail was sent.
0 | SUCCESS_SUCCESS | The function returned successfully.

Examples

The following example sends a message to two unresolved recipients. MAPISendMail will return an error if the names cannot be resolved unambiguously.

Sub MAIN
MAPI_LOGON_UI = 1
Session = MAPILogon(0, "", "", MAPI_LOGON_UI, 0)
result = MAPISetRecipient(1, "Anne Gabor", "")
result = MAPISetRecipient(2, "Roger Selva", "")
result = MAPISendMail(Session, 0, "Monthly Summary",\
    "We will quickly satisfy all orders for clamps.", 0, 0)
result = MAPILogoff(Session, 0, 0, 0)
End Sub

The following example prepares a message for sending to two recipients, then displays the Send Note dialog box to allow the user to modify, cancel, or send the message.

Sub MAIN
MAPI_LOGON_UI = 1
Session = MAPILogon(0, "", "", MAPI_LOGON_UI, 0)
Dim MessageID$
result = MAPISetRecipient(1, "Phillipe Tran", "AF:TBU/WGAM/PHILT")
result = MAPISetRecipient(1, "Patricia Loren", "AF:TBU/WGAM/PATL")
MAPI_DIALOG = 8
result = MAPISendMail(Session, 0, "Monthly Summary",\
    "We will quickly satisfy all orders for clamps.", MAPI_DIALOG, 0)
result = MAPILogoff(Session, 0, 0, 0)
End Sub


MAPISetAttachment

Syntax

MAPISetAttachment(FileName$, PathName$, Position, Flags, Reserved)

Remarks

Attaches a file to the current outbound message. A message can include multiple attachments. MAPISetAttachment attaches Word documents or any other data file, but the function does not support OLE objects.

Errors in attachment processing are not returned until the message is actually sent with MAPISendMail.

Argument | Explanation
FileName$ | The filename seen by the recipient. This name can differ from the filename in PathName$. If FileName$ is empty, the filename from PathName$ is used.
PathName$ | The full path of the file to be attached.
Position | An integer indicating where the attachment is placed in the message body. The first position is 0 (zero), and the last position is the length of the note text minus 1. The file attachment overwrites the existing character in its position. Use –1 for Position to insert the attachment at the beginning of the message without overwriting an existing character.
Flags | Reserved for future use. This argument must be 0 (zero).
Reserved | Reserved for future use. This argument must be 0 (zero).

Example

This example attaches two files to the current outbound message, then sends the message. One file is attached at the beginning of the message, the other at the end.

Sub MAIN
MAPI_LOGON_UI = 1
Session = MAPILogon(0, "", "", MAPI_LOGON_UI, 0)
Dim NoteText$
NoteText$ = "We will quickly satisfy all orders for clamps. "
result = MAPISetRecipient(1, "Phillipe Tran", "AF:TBU/WGAM/PHILT")
result = MAPISetRecipient(2, "Patricia Loren", "AF:TBU/WGAM/PATL")
result = MAPISetAttachment("THANKYOU.DOC", "C:\DOCUMENT\THANKYOU.DOC",\
    - 1, 0, 0)
result = MAPISetAttachment("CONTRACT.DOC", "C:\WGTPLATE\CONTRACT.DOC",\
    Len(NoteText$) - 1, 0, 0)
result = MAPISendMail(Session, 0, "Monthly Summary", NoteText$, 0, 0)
result = MAPILogoff(Session, 0, 0, 0)
End Sub


MAPISetMessageType

Syntax

MAPISetMessageType(MessageType$)

Remarks

Sets the message type of the current outbound message. Message types allow custom messages within Mail. You can use custom messages to associate messages with specific projects or applications. Messages can be interpersonal messages that appear in the user's Inbox, or interprocess communication messages that are invisible to the user. The MessageType$ argument begins with "IPM." for interpersonal messages or with "IPC." for interprocess communication messages. The standard format for message types is "IPM.Vendor.Application" or "IPC.Vendor.Application."

Use MAPIFindNext to retrieve messages using the message type. This procedure is faster and more reliable than retrieving every message in the Inbox or searching for certain strings within the message subject or note text.

Message types are optional. For normal interpersonal messages, do not use MAPISetMessageType, or specify an empty string ("").

If your application generates IPC messages, you should provide users or administrators with a utility to find and delete outdated IPC messages in the Inbox. For an example, see MAPIFindNext.

Argument | Explanation
MessageType$ | A string that is the message type

Example

The following example sends a message with a custom message type.

Sub MAIN
MAPI_LOGON_UI = 1
Session = MAPILogon(0, "", "", MAPI_LOGON_UI, 0)
result = MAPISetRecipient(1, "Michael Ranwez", "")
result = MAPISetMessageType("IPM.Sample.Report")
result = MAPISendMail(Session, 0, "Monthly Summary",\
    "We will quickly satisfy all orders for clamps.", 0, 0)
result = MAPILogoff(Session, 0, 0, 0)
End Sub


MAPISetRecipient

Syntax

MAPISetRecipient(RecipClass, RecipName$, Address$)

Remarks

Adds one recipient to the current outbound message. Use MAPISetRecipientList to add a recipient list with one or more recipients to the current outbound message.

Either RecipName or Address can be an empty string (""). If Address is an empty string (""), the recipient is treated as unresolved, and MAPISendMail automatically attempts resolution when the message is sent. If RecipName cannot be resolved unambiguously, MAPISendMail returns an error.

Argument | Explanation
RecipClass | Classifies the recipient of the message. The following RecipClass values are defined: MAPI_ORIG = 0 MAPI_TO = 1 MAPI_CC = 2 MAPI_BCC = 3 Set MAPI_TO to specify a To recipient. Set MAPI_CC to specify a carbon-copy (CC) recipient. Set MAPI_BCC to specify a blind carbon-copy (BCC) recipient. Do not set MAPI_ORIG. The messaging system automatically establishes the originator.
RecipName$ | The friendly name of the recipient as displayed by the messaging system.
Address$ | Provider-specific message delivery data. This field can be used by the message system to identify recipients who are not in an address list (custom recipients).

Example

The following example adds two recipients to the current outbound message,
then sends the message. The To recipient is resolved, and the CC recipient is unresolved. If the unresolved recipient cannot be resolved unambiguously, MAPISendMail returns an error.

Sub MAIN
MAPI_LOGON_UI = 1
Session = MAPILogon(0, "", "", MAPI_LOGON_UI, 0)
MAPI_TO = 1
MAPI_CC = 2
result = MAPISetRecipient(MAPI_TO, "Phillipe Tran", \
    "AF:TBU/WGAM/PHILT")
result = MAPISetRecipient(MAPI_CC, "Patricia Loren", "")
result = MAPISendMail(Session, 0, "Monthly Summary",\
    "We will quickly satisfy all orders for clamps.", 0, 0)
result = MAPILogoff(Session, 0, 0, 0)
End Sub


MAPISetRecipientList

Syntax

MAPISetRecipientList(Recipients)

Remarks

Copies a recipient list with one or more recipients to the current outbound message. The function replaces the existing recipient list of the current outbound message. Use MAPISetRecipient to add one recipient to the current outbound message without removing existing recipients.

Use MAPIAddress to allow users to add users to a recipient list.

If any recipients within the recipient list are unresolved, MAPISendMail automatically attempts resolution when the message is sent. If all recipients cannot be resolved unambiguously, MAPISendMail returns an error.

Argument | Explanation
Recipients | A handle to a recipient list

Example

The following example displays the Mail Address Book dialog box, then copies the recipient list to a new message.

Sub MAIN
MAPI_LOGON_UI = 1
Session = MAPILogon(0, "", "", MAPI_LOGON_UI, 0)
RecipList = MAPIAddress(Session, 0, "Address Book", 4, "", 0, 0)
If RecipList >= 0 Then
    result = MAPISetRecipientList(RecipList)
    MAPI_DIALOG = 8
    result = MAPISendMail(Session, 0, "", "", MAPI_DIALOG, 0)
End If
result = MAPILogoff(Session, 0, 0, 0)
End Sub


ODBC Extensions forMicrosoft Word

Appendix B

ODBC Extensions for
Microsoft Word

Note to User

WBODBC.WLL is not supported by Microsoft Corporation. It is provided "as is" because we believe it may be useful to you. We regret that Microsoft is unable to support or assist you, should you have problems using this tool or any code that relies on this tool.

With the functions provided in the ODBC add-in library for Microsoft Word, you can create WordBasic macros that can access data in any database management system (DBMS) that supports the open database connectivity (ODBC) application programming interface (API) standard. With the ODBC extensions, you can:

  • Update data or add new data to a DBMS data source.

    For example, employees can update personnel records in a DBMS by filling in a form in Word. Or you can add a table of data created in Word as a new data source in an existing database.

  • Retrieve data for use as a mail-merge data source and insert tables of data in
    a document.

    With the ODBC extensions, you can access data directly from a DBMS through Structured Query Language (SQL) statements. If you are retrieving large amounts of data or retrieving data from large databases, bypassing the Word command interface can speed data access.

  • Retrieve data for use in calculations by other WordBasic functions.

    For example, you can create a macro to retrieve the daily price of commodities and interest rates from your company's database and then use the values as variables in calculating projected expenses.

  • Interactively compose and issue queries and retrieve results from the database.

Information in this appendix is intended only for WordBasic programmers. If you are developing C language or Visual Basic applications that support the ODBC API, you can obtain the Microsoft ODBC Software Development Kit version 2.10 as part of a Level 2 membership in the Microsoft Developer Network (MSDN). To join MSDN in the United States and Canada, call (800) 759-5474 from 6:30 a.m. to 5:30 p.m. (Pacific time), Monday through Friday. Outside North America, contact your local Microsoft subsidiary, or call (303) 684-0914 in the United States to obtain local contact information. The ODBC SDK isn't required to use the ODBC extensions in the WBODBC.WLL add-in that is provided in the Microsoft Word Developer's Kit.

Note

The ODBC extensions described in this appendix are not available on the Macintosh.


Understanding the ODBC Extensions

Open database connectivity (ODBC) is an application programming interface that uses structured query language (SQL) to access and manipulate data in database management systems such as dBASE®, Paradox®, and Microsoft Access.

SQL is a widely accepted industry standard for storing, maintaining, and retrieving information from a DBMS. A particular DBMS may support different SQL functions and grammar to take advantage of unique, proprietary features. For that reason, if SQL statements are used to access data directly, an application would require separate programs, each targeted to a specific DBMS, to work with external data.

Using ODBC API functions, however, a single application can access data in diverse DBMSs without supporting multiple implementations of SQL. To access
a particular DBMS, an application supporting ODBC uses software components called drivers, which perform all interaction between an application and a specific DBMS. The following illustration shows the relationship between the dBASE ODBC driver and an application accessing dBASE database files.

To provide the same interoperability for WordBasic macros, the WBODBC.WLL add-in provides functions you can call from WordBasic that mirror ODBC functions. With these functions, you can create a macro that can access data in any ODBC-supporting DBMS for which you have an ODBC driver.

The ODBC Extensions and SQL

After establishing a data source connection through a call to SQLOpen, you issue SQL queries to an ODBC-supporting DBMS by calls to the WordBasic ODBC extensions SQLExecQuery or SQLQueryExec. The SQL statements in the query should conform to SQL grammar. If the SQL grammar is supported by the ODBC API, the query is interpreted by the ODBC driver. The ODBC Driver Manager (ODBC.DLL) then calls the appropriate ODBC API functions to execute the query.

If the query contains SQL grammar that is not supported by the ODBC driver, the query is passed directly to the DBMS without further processing by ODBC API functions. In this way, a driver can support a superset of SQL, including vendor-specific grammar.

You can see some examples of SQL queries in the sample macros in the WBODBC.DOT, which is included on the Microsoft Word Developer's Kit disk. When you run the Exec macro, you can compose and issue queries interactively; you can also use this macro to test queries you create before including the query strings in other macros.

To learn more about the SQL grammar supported by a specific ODBC driver, see the online Help file provided with each driver. For more information about SQL, the following standards are available:

  • Database Language – SQL with Integrity Enhancement, ANSI, 1989 ANSI X3.135-1989.
  • X/Open and SQL Access Group SQL CAE draft specification (1991).
  • Database Language SQL: ANSI X3H2 and ISO/IEC JTC1,SC21,WG3 (draft international standard).

In addition to standards and the SQL documentation provided with the DBMS you are using, there are many books that describe SQL, including:

  • Microsoft ODBC Programmer's Reference, provided with the Microsoft ODBC Software Development Kit version 2.10.
  • Date, C. J.: A Guide to the SQL Standard (Addison-Wesley, 1989).
  • Emerson, Sandra L., Darnovsky, Marcy, and Bowman, Judith S.: The Practical SQL Handbook (Addison-Wesley, 1989).
  • Groff, James R. and Weinberg, Paul N.: Using SQL (Osborne McGraw-Hill, 1990).
  • Gruber, Martin: Understanding SQL (Sybex, 1990).
  • Hursch, Jack L. and Carolyn J.: SQL, The Structured Query Language
    (TAB Books, 1988).
  • Pascal, Fabian: SQL and Relational Basics (M & T Books, 1990).
  • Trimble, J. Harvey, Jr. and Chappell, David: A Visual Introduction to SQL (Wiley, 1989).
  • Van der Lans, Rick F.: Introduction to SQL (Addison-Wesley, 1988).
  • Vang, Soren: SQL and Relational Databases (Microtrend Books, 1990).
  • Viescas, John: Quick Reference Guide to SQL (Microsoft Corp., 1989).

Tip

If you use Microsoft Query, you can create a query in the Query window and then copy the equivalent SQL statements to your WordBasic macro.

ODBC SQL Data Types

Each ODBC driver has different naming syntax for its own SQL data types. A given ODBC driver maps its native SQL data types to ODBC SQL data types. Information about data-type mapping for a specific ODBC driver is provided in the online Help file for each installed driver. For example, the following table shows how the ODBC driver for Paradox maps native Paradox data types.

Paradox data type | ODBC SQL data type
Alphanumeric | SQL_CHAR
Date | SQL_DATE
Number | SQL_DOUBLE
Short | SQL_SMALLINT

A given driver and ODBC data source do not necessarily support all ODBC SQL data types. For complete information about ODBC SQL data types, see the Microsoft ODBC Programmer's Reference in the Microsoft ODBC Software Development Kit version 2.10.

The extensions in WBODBC.WLL allow you to create and delete ODBC tables, as well as to examine and manipulate fields within ODBC tables. When using the SQL statements CREATE TABLE and ALTER TABLE, you must specify the data types native to that particular DBMS. For example, if you are adding a column to a table in Microsoft FoxPro and the data type of the column is "Date," you must specify "Date" as the column data type in the ALTER TABLE statement, not the ODBC SQL data type "SQL_DATE." To determine the appropriate data type for the DBMS you are using, use the WordBasic ODBC function SQLGetTypeInfo$. For any valid SQL data type, this function returns the corresponding data type for the DBMS of the current data source.

Note that the ODBC extensions for Word cannot directly manipulate ODBC SQL data types; the ODBC extensions use only string data types. Numbers are formatted and manipulated as strings.


Before You Begin

Before you use the add-in functions described in this chapter, you must do the following:

  • Install the appropriate ODBC driver needed to access the DBMS you are using. Each DBMS requires a different driver.
  • Define specific data sources you want to access in the selected DBMS. You must have previously created the specific database file or table in the DBMS before defining the data source.
  • Install the WBODBC.WLL add-in library.
  • Load the WBODBC.WLL add-in library by using the Templates command
    on the File menu.

Installing ODBC Drivers

An ODBC driver is a dynamic-link library (DLL) that an application supporting ODBC can use to gain access to a particular DBMS, such as dBASE or Microsoft Access. The ODBC driver implements ODBC API function calls that are compatible with the SQL statements used by a particular DBMS and performs all interaction with a data source.

Installing the ODBC Drivers Provided with Word

You can install the ODBC drivers for DBMSs such as Microsoft Access, Microsoft FoxPro, Paradox, and dBASE when you install Word or any time you run the Setup program with the Custom installation option. All the provided ODBC drivers are installed unless you change the Data Access options. The ODBC drivers must be installed in your Windows System folder or in a folder recognized automatically by the operating system.

Installing Additional ODBC Drivers

To install other Microsoft or third-party ODBC drivers you purchase after installing Word, you can use the ODBC installer provided with the ODBC drivers. Install the drivers to your Windows System folder or a folder recognized automatically by the operating system.

If you've already installed at least one ODBC driver on your hard disk, you can use the ODBC Administrator program to install additional third-party ODBC drivers. (ODBC drivers provided by Word must be installed by using the Word Setup program.) To start the ODBC Administrator program, double-click the ODBC icon in the Control Panel. Then choose the Drivers button in the Data Sources dialog box.

Note

The ODBC driver you install may share some of the same dynamic-link libraries (DLLs) as other drivers installed on your computer. If so, you may be asked if you want to overwrite the driver you specified, whether or not it has been installed. Choose the Yes button to install the driver.

Setting Up Data Sources

After you install an ODBC driver, you must set up the data sources you want to access in a particular DBMS. A data source is a specific set of data in a DBMS and any information about the network or operating system (or both) needed to access the data. The following are examples of data sources:

  • A Microsoft Access database file in a public folder of a colleague's computer running Windows 95.
  • An ORACLE® DBMS running on an OS/2® operating system, accessed by Novell® NetWare®.
  • A dBASE file on your computer hard disk; in this case a network and remote operating system are not included in the data source.
  • A Tandem NonStop SQL DBMS running on the Guardian™ 90 operating system, accessed through a gateway.

You add, change, or delete a data source by using the ODBC Administrator program. To start the program, double-click the ODBC icon in the Control Panel or run ODBCADM.EXE (Windows 3.x) or ODBCAD32.EXE (Windows 95 and Windows NT). You can add any data source to the list in the Data Sources dialog box, providing the driver it uses is already installed on your machine.

When you add a new data source, the setup information you provide is stored
in the ODBC.INI file (Windows 3.x) or the registry (Windows 95 and Windows NT) and is used each time you access the data source. The minimum connection information typically includes the name of the data source, a user ID, and a password. Some ODBC drivers allow you to specify additional required information, such as a network address or additional passwords. For information about the connection options for a particular ODBC driver, choose the Help button in the Setup dialog box.

If you don't provide sufficient information when you set up the data source, you can provide the needed connection arguments in calls to the add-in function SQLOpen. You may also want to specify the connection string arguments to override the arguments stored during setup. If sufficient connection information is not provided in calls to SQLOpen, the ODBC driver may display a dialog box for entering the missing information, depending on the value of the DriverPrompt argument in the SQLOpen instruction.

Installing and Loading WBODBC.WLL

The ODBC extensions for WordBasic are provided in WBODBC.WLL, a Word add-in library (WLL) on the Microsoft Word Developer's Kit disk. To install the add-in library, copy the WBODBC.WLL file from the WIN16 (Windows 3.x) or WIN32 (Windows 95 and Windows NT) subfolder in the WBODBC folder to your Template folder.

Before running a macro that uses the ODBC extensions, you must load the add-in in Word. To load the add-in library, use the Templates command (File menu) to add the WBODBC.WLL to the list of global templates and add-ins. If you will frequently use the ODBC extensions in macros, you can load the add-in automatically each time you start Word by storing the WBODBC.WLL file in
the STARTUP folder in your Word program folder.

The WBODBC.DOT and INVOICE3.DOT templates in the WBODBC folder on the Microsoft Word Developer's Kit disk contain the example macros described in this appendix. Copy the templates to your Template folder to use, copy, and modify those macros. If you have installed the Microsoft Access ODBC driver provided with Word, you can copy the TEST.MDB database (also located in the WBODBC folder on the Microsoft Word Developer's Kit disk) to your hard disk and set it up as an ODBC data source to use when running the example macros.


Using the ODBC Extensions

This section contains basic information on using the ODBC extensions. Three example macros included in WBODBC.DOT illustrate the use of the functions. The sample form, INVOICE3.DOT, which shows how you can automate Word forms to take advantage of the ODBC extensions, is described at the end of this section.

Declaring the Functions

To indicate that the ODBC extensions are located in the WBODBC.WLL add-in library, you must declare the functions prior to calling them in a macro. All of the Declare statements for the WBODBC.WLL functions documented in this appendix are included in the AllDeclarations macro stored in the WBODBC.DOT template. Copy these declarations into every macro that uses the WBODBC.WLL functions.

Sequence of Use

To retrieve data, you must first establish a connection with a data source by
using SQLOpen. A successful call to SQLOpen returns a unique connection identification number. The connection ID identifies the specified data source until the connection is closed by using SQLClose or SQLCloseAll. The connection ID is used by SQLExecQuery or SQLQueryExecto send a query, and the SQL retrieve functions then use the same connection ID to retrieve the query results.

You can use the following SQL retrieve functions with SQLExecQuery: SQLRetrieveColumns, SQLRetrieveFlush, SQLRetrieveItem$, SQLRetrieveRows, SQLRetrieveToDocument.

You can use the following SQL retrieve functions with SQLQueryExec: SQLQueryFetch, SQLQueryRetrieve, SQLRetrieveColSize, SQLRetrieveColumns, SQLRetrieveFlush, SQLSetRowPos.

Mapping the Structure of a Database

Before sending a query with SQLExecQuery or SQLQueryExec, you might want to determine the underlying structure, or schema, of a DBMS. This is called mapping the database. For example, you might want to know whether the database is organized as "tables" or "files." Once you've mapped the database, you can more easily write macros to manipulate the data.

You map a database by using the SQLGetSchema and SQLGetSchemaItem$ functions. With SQLGetSchema, you specify the type of information, or property, that you want to learn about the DBMS. You then use SQLGetSchemaItem$ to retrieve a specific description of the property. The third example macro described later in this section shows how to use these functions.

Checking for Error Conditions

After a call to any ODBC extension that returns a numeric value, you should check for a returned error condition, which is indicated by a 0 (zero) or a negative integer. The ODBC extensions include functions for examining errors. First you call SQLCountErrors, which returns a count of the number of lines of error information stored in memory after a preceding WordBasic ODBC function call returned an error value. If SQLCountErrors returns a positive integer, you then call SQLErrorText$ to return each line of error message text. The returned error message text can then be evaluated by an error trap or displayed to the user.

ODBC Examples

The macros shown in the following examples are available in WBODBC.DOT, the template provided on the Microsoft Word Developer's Kit disk. Only portions of the macros are included here; to review the complete code for an example, open the macro in a macro-editing window.

Example 1: Issuing SQL queries interactively

When you run the Exec example macro, you type the SQL query in a dialog box. If the query string results in an error, the ParseErrors subroutine is called to display the error message. The query is then redisplayed in a dialog box so that you can edit the query string. Successful queries are stored in a new document so that you can reuse them in other macros.

While quit = 0
    s$ = InputBox$("SQL> ", "SQL Interactive Interpreter", prompt$)
    If Len(s$) = 0 Then
        quit = 1
    Else
        ret = SQLExecQuery(connect_num, s$)
        If ret <= 0 Then
            prompt$ = s$
            x$ = "Error: " + Str$(ret) + "," + Str$(SQLErrorCount)
            MsgBox x$
            ParseErrors
        Else
            If FirstLog <> 0 Then
                FileNew
                FirstLog = 0
            EndIf
            LogString(s$)
            prompt$ = ""
        EndIf
    EndIf
Wend

And here is the ParseErrors subroutine:

Sub ParseErrors
nerrors = SQLCountErrors()
For i = 1 To nerrors
    MsgBox "error: class(" + SQLErrorClass(i) + ") code(" + \
            Str$(SQLErrorCode(i)) + "): " + SQLErrorText(i)
Next
End Sub

Example 2: Retrieving data and inserting it into a table

The Report example macro opens a Microsoft Access data source named "test.mdb," a data source set up from the Microsoft Access database TEST.MDB that is provided on the Microsoft Word Developer's Kit disk.

The SQL query string sent with the SQLExecQuery function selects each row, or record, of information for which there is an entry in the "name" field. (Note that the Quote2$() user-defined function, not shown here, returns the string "name" preceded and followed by Chr$(34), the ANSI character code for a double quotation mark.) Next, the macro creates a table in a new Word document and inserts each data item retrieved by SQLRetrieveItem$ into the appropriate table cell. If the amount in any account field is less than 1, that amount is formatted as bold. If an ODBC extension returns an error value, control is passed to the MyError error handler.

connect_num = SQLOpen("DSN=test.mdb", output_ref$, 0)
If connect_num <= 0 Then Goto MyError
ret = SQLExecQuery(connect_num, "Select * from table4 " + \
        Quote2$("name"))
If ret <= 0 Then Goto MyError
col = SQLRetrieveColumns(connect_num)
row = SQLRetrieveRows(connect_num)
If col <= 0 Or row <= 0 Then Goto MyError
FileNew
TableInsertTable  .ConvertFrom = 0, .NumColumns = col, .NumRows = row
For i = 1 To row
        For j = 1 To Col
        item$ = SQLRetrieveItem$(connect_num, j, i)
        If (j = 1) Then
            Insert item$
        Else
            v = Val(item$)
            s$ = Str$(v / 100)
            Insert s$
            If (v < 100) Then
                ParaUp 1, 1
                Bold(1)
                CharRight 1, 0
            End If
        End If
        If j <> col Or i <> row Then NextCell
    Next
Next
ret = SQLClose(connect_num)
If ret > 0 Then Goto MyEnd

Example 3: Mapping the database structure

The Schema example macro displays a dynamic dialog box in which you can
select an option corresponding to a database property to see a description of that property. The macro uses SQLGetSchema and SQLGetSchemaItem$ to build a shared array of the strings describing the database properties. The array, called combobox1$(), is then displayed in the dialog box.

In the main subroutine (not shown here), the connection information for SQLOpen — the name of a data source, the database name, and any other required connection string arguments — is entered in response to dialog boxes.

After the custom dialog box is defined, it is displayed. The following subroutine, GetDBInfoWithQualifier, is called by the dialog function (or by the intermediate function GetDBInfo if there is no value for the qual$ argument) every time the user selects a different property in the dialog box. The dialog function then uses the shared array combobox1$() to update the custom dialog box.

Function GetDBInfoWithQualifier(itemid, qual$)
i = SQLGetSchema(connect_num, itemid, qual$)
If i > 0 Then
    For j = i - 1 To MaxItem
        combobox1$(j) = ""
    Next
    For j = 0 To i - 1
        s$ = SQLGetSchemaText(connect_num, j + 1)
        combobox1$(j) = s$
    Next
Else
    MsgBox "No Information"
End If
GetDBInfoWithQualifier = i
End Function

Example of Automating Forms Using ODBC

The INVOICE3.DOT template included in the WBODBC folder on the Microsoft Word Developer's Kit disk contains an integrated collection of macros similar to the INVOICE2.DOT macros described in Chapter 9, "More WordBasic Techniques," in Part 1, "Learning WordBasic." The primary difference between the two templates is that INVOICE2.DOT uses dynamic data exchange (DDE) to retrieve data from and write data to a data source in a running application (a workbook open in Microsoft Excel), while INVOICE3.DOT uses the ODBC extensions to retrieve data from and write data to a data source in a DBMS (an .MDB file created in Microsoft Access).

The advantages of using the ODBC extensions to automate Word forms are simple: the ODBC functions are faster than comparable DDE commands; the ODBC functions require only a data source, not both a data source and the application that was used to create it; and the ODBC functions can be used to read and modify data sources created by DBMSs that do not support DDE. In general, the ODBC error reporting functions make debugging and handling ODBC errors more flexible than handling and debugging comparable DDE errors in WordBasic.

The following table shows a comparison of the steps that macros using DDE versus macros using the ODBC extensions must carry out to automate a form.

DDE macro steps | ODBC macro steps
Determine whether required application is running; start the application if it is not running. | Not required.
Locate the file that will act as the data source and open it in the running application. | Connect to an established ODBC data source (previously set up using the ODBC Administrator program).
Execute a query in the form of the application's programming language with DDEExecute. | Execute a query in ODBC SQL using SQLExecQuery or SQLQueryExec.
Retrieve data as strings using DDERequest; parse as required by the application's DDE and database functionality. | With SQLExecQuery, retrieve data items as strings using row and column notation with SQLRetrieveItem$, or retrieve the entire query and insert it as a table with SQLRetrieveToDocument. With SQLQueryExec, move through rows using SQLQueryFetch or SQLSetRowPos and return data from columns using SQLQueryRetrieve.
Close the DDE channel using DDETerminate. | Close the data source channel using SQLClose.

For comparison, open the macros in the two templates on the Microsoft Word Devleoper's Kit disk: INVOICE2.DOT in the WRDBASIC folder and INVOICE3.DOT in the WBODBC folder. Looking at the areas in the macros that retrieve and write data, you can compare and contrast the amount of code, the data parsing routines, and the error handling routines required by ODBC and DDE. Create a new document based on each form and use it to run the macros and demonstrate the differences in speed.

For complete information about the purpose and functionality of the Invoice form itself and the use of form fields to trigger WordBasic macros, see "Automating Forms" in Chapter 9, "More WordBasic Techniques," in Part 1, "Learning WordBasic."

Note

To run the macros in the INVOICE3.DOT template, you must have access to the NWIND.MDB or NORTHWIND.MDB file (shipped with Microsoft Access version 2.0 and version 7.0, respectively) and you must create a data source called "Northwind" associated with that database. For information about creating ODBC data sources, see "Setting Up Data Sources," earlier in this appendix.


WordBasic ODBC Functions

Consider the following for all the WordBasic ODBC functions:

  • To use a function described in this section, you must include the corresponding Declare statement, which you can copy directly from the AllDeclarations macro in WBODBC.DOT. For more information, see "Using the ODBC Extensions" earlier in this appendix.
  • In general, an error value is an integer that is less than or equal to zero. A return value of 0 (zero) implies a general error, for which more information can be obtained using the error functions.
  • A return value of –1 (SQL_NoMoreData) implies that the logical end of a file has been reached.
  • A return value of –2 (SQL_StillExecuting) during asynchronous processing implies that an ODBC operation is still in progress.
  • If a string function cannot return a value from a data source, it returns an empty string ("").


SQLClose

Syntax

SQLClose(ConnectNum)

Remarks

Terminates a connection with an external data source. If the call is successful, then SQLClose will terminate the specified data source connection.

Argument | Explanation
ConnectNum | The unique connection ID of the data source from which you want to disconnect. ConnectNum was returned by a previously executed SQLOpen function. If ConnectNum is not valid, SQLClose returns an error value.

If the connection is successfully terminated, SQLClose returns 1, and the connection ID number is no longer valid. If SQLClose is unable to disconnect from the data source, it returns an error value and places error information in memory for the error functions, if such information is available.


SQLCloseAll

Syntax

SQLCloseAll()

Remarks

Terminates all connections with external data sources. If the call is successful, then SQLCloseAll terminates all data source connections. This is useful when you want to ensure that any existing connections are closed before a macro or subroutine runs.

If the connections are successfully terminated, SQLCloseAll returns 1, and
no connection ID numbers are valid. If SQLCloseAll is unable to disconnect
from any single data source, it returns an error value and places error information in memory for the error functions, if
such information is available.


SQLCountErrors

Syntax

SQLCountErrors()

Remarks

Returns the number of rows of detailed error information available. Each available row can be retrieved by calling SQLErrorText$ and passing a row number from 1 through the value returned by SQLCountErrors (1 is the first available row). For information about the structure of error rows, see SQLErrorText$.

A return value of 0 (zero) indicates no error information is available. A return value greater than 0 (zero) indicates the number of rows of error information available. Note that SQLErrorCount does not return information on itself.


SQLErrorClass$

Syntax

SQLErrorClass$(ErrorNum)

Remarks

Determines the ODBC SQLSTATE class and subclass of the specified error. For errors that occur in the data source, the ODBC driver maps the returned native error to the appropriate SQLSTATE. For errors that are detected by the driver or the Driver Manager, the driver or Driver Manager generates the appropriate SQLSTATE.

SQLSTATE values are specified by the X/Open and SQL Access Group SQL CAE specification (1992). For complete information on ODBC error codes and the ODBC API SQLError function, see the Microsoft ODBC Programmer's Reference in the Microsoft ODBC Software Development Kit version 2.10.

Argument | Explanation
ErrorNum | A row number between 1 and the value returned by the SQLCountErrors function (1 is the first available item).

SQLSTATE, the five-character string value returned by SQLErrorClass$, consists of a two-character class value followed by a three-character subclass value. If the error class is not available for the type of error that was encountered, this function returns an empty string ("").

Example

The following example parses the five-character SQLSTATE value returned by SQLErrorClass$ into its class and subclass components.

SQLSTATE$ = SQLErrorClass$(connect_num)
class$ = Left$(2,SQLSTATE$)
subclass$ = Right$(3,SQLSTATE$)


SQLErrorCode

Syntax

SQLErrorCode(ErrorNum)

Remarks

Determines the native error code in the data source for the specified error. Native errors are generated and returned from the DBMS of the data source on
a given connection. For information about particular native error codes, see the documentation for the appropriate DBMS.

Argument | Explanation
ErrorNum | A row number between 1 and the value returned by the SQLCountErrors function (1 is the first available item).

This function returns the numeric native error code for errors generated in the data source. For errors detected by the driver or the Driver Manager, SQLErrorCode returns a native error of 0 (zero).


SQLErrorFlush

Syntax

SQLErrorFlush()

Remarks

Removes error information for the current error. Although you can use SQLErrorFlush to deliberately remove current error information, note that all error information is automatically removed whenever an ODBC high-level function completes successfully.

If the error information could not be flushed, the SQLErrorFlush function returns a negative error value.


SQLErrorText$

Syntax

SQLErrorText$(ErrorNum)

Remarks

Retrieves a row of available error information. SQLErrorText$ returns a single string that contains a delimited list of error information that can be evaluated by an error trap or displayed to the user.

Argument | Explanation
ErrorNum | A row number between 1 and the value returned by the SQLCountErrors function (1 is the first available item).

Each row of error information has the following four fields:

  • The vendor
  • The ODBC component
  • The name of the data source
  • A text message describing the error

If one or more of these fields is not available for the type of error that was encountered, those fields are left blank. For more information about ODBC error messages, see the Microsoft ODBC Programmer's Reference in the Microsoft ODBC Software Development Kit version 2.10. For information about specific return values, see the Help file for the appropriate ODBC driver.

Example

The following example demonstrates a simple loop for displaying error information to the user in a message box. After the number of lines of error information is returned by SQLCountErrors, a For ¼ Next loop displays the errors.

count = SQLCountErrors()
for msgs = 1 to count
    MsgBox SQLErrorText$(count), "ODBC Error", 48
next count


SQLExecQuery

Syntax

SQLExecQuery(ConnectNum, Query$)

Remarks

Sends a query to a data source using an existing connection and stores the entire query result in memory.

Note

Unlike SQLExecQuery, SQLQueryExec does not store the entire query result in memory. To avoid resource problems when creating complex database solutions using the ODBC add-in library, use SQLQueryExec.

Before calling SQLExecQuery, a connection must be established with a data source using SQLOpen. A successful call to SQLOpen returns a unique connection ID number. SQLExecQuery uses that connection ID number to send SQL language queries to the data source.

SQLExecQuery only executes a query; results generated from the query are
not returned. Retrieving results is handled by the SQLRetrieveColumns, SQLRetrieveItem$, and SQLRetrieveRows functions. If SQLExecQuery is called using an existing connection ID number, all pending results on that connection will automatically be discarded. The connection ID will then refer
to the new query and its results.

Argument | Explanation
ConnectNum | The unique connection ID of the data source you want to query returned by a previously executed SQLOpen function. If ConnectNum is not valid, SQLExecQuery returns 0 (zero).
Query$ | The SQL language query that is to be executed on the data source. The query should follow SQL grammar; the Help file for the appropriate ODBC driver also describes any SQL language limitations or modifications for the given DBMS. If SQLExecQuery is unable to execute Query$ on the specified data source, SQLExecQuery returns 0 (zero). The exact error can be obtained from the error functions.

If SQLExecQuery is able to successfully execute the query on the specified connection, it will return one of three values, depending on the type of SQL statement that was executed.

SQL statement | Return value
SELECT | The number of result columns available
UPDATE, INSERT or DELETE | The number of rows affected by the statement
Other | A positive value

If there was an error executing the query, SQLExecQuery returns a negative error value.

Example

The following example sends a simple SELECT query to an established data source connection during asynchronous processing. While SQLExecQuery continues to return the value –2, the query is still being processed; the macro should wait for a final return value from SQLExecQuery before determining whether an error occurred.

ret = -2
While ret = -2
    ret = SQLExecQuery(connect_num, "select * from authors")
Wend
If ret <= 0 Then Goto ParseErrors


SQLGetSchema

Syntax

SQLGetSchema(ConnectNum, Type, Qualifier$)

Remarks

Establishes a pseudo-query on a data source connection to provide information about the schema (structure) of the data source. After SQLGetSchema establishes a pseudo-query and returns a value describing the available information, use SQLGetSchemaItem$ one or more times to return the available string or strings of information about the data source structure. SQLGetSchema works with the ODBC API functions SQLGetInfo and SQLTables to find the requested information; for complete information about these API functions, see the Microsoft ODBC Programmer's Reference in the Microsoft ODBC Software Development Kit version 2.10.

For a complete example macro using SQLGetSchema, see the third example macro described in "Using the ODBC Extensions" earlier in this appendix.

Arguments

Explanation

ConnectNum

The unique connection ID of the data source you want information about, returned by a previously executed SQLOpen function. If ConnectNum is not valid, SQLGetSchema returns 0 (zero).

Type

A value between 1 and 14 that specifies the type of information
you want returned. For descriptions of the information that can be returned, see the table of return values, following.

Qualifier$

A text string used to qualify the search for the requested information. This string should be enclosed by quotation marks. Note that Qualifier$ is only included for Type values of 3, 4, and 5. For other Type values, Qualifier$ should be an empty string ("").

If Type is 3, Qualifier$ should be the name of a database in the current data source. SQLGetSchema will then only return the number of table owners in that database. If you specify an empty string (""), the function will return the number of all owners of all databases on ConnectNum.

If Type is 4, Qualifier$ should be both a database name and an owner name. The syntax of Qualifier$ is "Database.Owner". SQLGetSchema will then return the number of tables that are located in the given database and owned by the given owner. If you specify an empty string (""), the function will return the number of all table names in all databases owned by all owners on ConnectNum.

If Type is 5, Qualifier$ should be the name of a table. Information about the columns in that table will be returned.

The numeric value returned by the SQLGetSchema function depends on the value of the Type argument that was passed, as described in the following table. Use SQLGetSchemaItem$ one or more times to return the available string or strings, as indicated by the numeric return value of SQLGetSchema.

Type | Meaning of return value
1 | Number of available data sources.
2 | Number of databases on the current connection.
3 | Number of owners in a database on the current connection. This Type requires that a value be specified for Qualifier$.
4 | Number of tables for a given owner and database on the current connection. This Type requires that a value be specified for Qualifier$.
5 | Number describing a two-dimensional array listing the columns in a particular table and their data types. The return value is the total number of string values available. The odd-numbered items are the names of the columns. The even-numbered items are the data types of the columns. This Type requires that a value be specified for Qualifier$.
6 | If a non-error value, the user ID of the current user is available.
7 | If a non-error value, the name of the current database is available.
8 | If a non-error value, the name of the data source as given in the ODBC.INI file (Windows 3.x) or the registry (Windows 95 and Windows NT) is available.
9 | If a non-error value, the name of the data source DBMS (i.e. Oracle, SQL Server, etc.) is available.
10 | If a non-error value, the name of the server name for the data source is available.
11 | If a non-error value, the terminology used by the data source to refer to owners ( i.e. "owner", "Authorization ID", "Schema", etc.) is available.
12 | If a non-error value, the terminology used by the data source to refer to tables ( i.e. "table", "file", etc.) is available.
13 | If a non-error value, the terminology used by the data source to refer to qualifiers (i.e. "database" or "directory") is available.
14 | If a non-error value, the terminology used by the data source to refer to procedures (i.e. "database procedure", "stored procedure", or "procedure") is available.

Note

The SQLGetSchema function should not overwrite the pending results of another query sent to the same data source. To avoid overwriting pending query results, establish a new connection to the data source using SQLOpen, and specify the resulting connection ID for SQLGetSchema.


SQLGetSchemaItem$

Syntax

SQLGetSchemaItem$(ConnectNum, Item)

Remarks

Returns a string that provides information about the schema (structure) of the data source on a particular connection. After a successful call to SQLGetSchema, you can use SQLGetSchemaItem$ one or more times to return the string value or values that SQLGetSchema indicates are available for a particular aspect of the data source structure. The values available from SQLGetSchemaItem$ depend on the type of information that was requested.

For a complete example macro using SQLGetSchemaItem$, see the third example macro described in "Using the ODBC Extensions" earlier in this appendix.

Argument | Explanation
ConnectNum | The unique connection ID of the data source you want information about, returned by a previously executed SQLOpen function. If ConnectNum is not valid, SQLGetSchemaItem$ returns 0 (zero).
Item | Specifies the item of information you want returned. Note that Item should be a value between 1 and the number returned by SQLGetSchema for an established pseudo-query.

The string values available from this function depend on the type of information that was requested. See the table of return values for SQLGetSchema for descriptions.


SQLGetTypeInfo$

Syntax

SQLGetTypeInfo$(ConnectNum, Type$)

Remarks

Maps a known data type into an acceptable native data type. When using the SQL statements CREATE TABLE and ALTER TABLE, you must specify the data types native to that particular DBMS. To determine an appropriate data type for the DBMS you are using, you use the SQLGetTypeInfo$ function. For more information about data-type mapping for a given ODBC driver, see the corresponding Help file.

Argument | Explanation
ConnectNum | The unique connection ID of the data source to which you want to map a known data type to a native data type. The connection ID is returned by a previously executed SQLOpen function. If ConnectNum is not valid, SQLGetTypeInfo$ returns an error value.
Type$ | A data type for which you want to know the equivalent DBMS native data type.

For any valid SQL data type, this function returns the corresponding data type
for the DBMS of the current data source.

Example

This example demonstrates how SQLGetTypeInfo$ can be used to make WordBasic ODBC macros portable to multiple DBMSs. Here, SQLGetTypeInfo$ stores native data types in variables; as a result, the SQL CREATE TABLE query specified in SQLExecQuery works regardless of the DBMS in which the data source was created.

int$ = SQLGetTypeInfo$(connect_num,"integer")
txt$ = SQLGetTypeInfo$(connect_num,"text")
ret = SQLExecQuery(connect_num, \
        "create table emp_id(id " + int$ + ", name" + txt$ + "(32))")


SQLOpen

Syntax

SQLOpen(Connect$, Output$, DriverPrompt)

Remarks

Establishes a connection with a data source. A connection established with SQLOpen can be used throughout a macro until the connection is closed with SQLClose. Note that SQLOpen can prompt the user for additionally needed connection information.

Argument | Explanation
Connect$ | The information necessary to establish a connection to a data source. Note that any data-source name that is used in Connect$ must be an existing data-source name defined with ODBC Setup or the ODBC Administration Utility. For more information on how to define data-source names, see "Setting Up Data Sources" earlier in this appendix. Note that Connect$ should follow the format described in the Help file for the appropriate ODBC driver. This string may require the data-source name, one or more user IDs, one or more passwords, and any other information necessary to successfully connect to the particular DBMS.
Output$ | A predefined string variable where you want the completed connection string to be placed. If Output$ is omitted, a completed connection string will not be returned.

Argument | Explanation
DriverPrompt | A number from 1 to 4 specifying if, and how, the driver should display prompts. This sets the fDriverCompletion flag in the ODBC API SQLDriverConnect function. 1 Always display a dialog box. The flag is set to SQL_DRIVER_PROMPT. 2 Display a dialog box only if there is not enough information to connect. The driver uses information from the connection string and from the data source specification as its defaults. The flag is set to SQL_DRIVER_COMPLETE. 3 Same as 2, but the driver grays and disables any unnecessary prompts. The flag is set to SQL_DRIVER_COMPLETE_REQUIRED. 4 If the connection string is unsuccessful, do not display a dialog box. The flag is set to SQL_DRIVER_NOPROMPT.

If the connection is successfully established, SQLOpen returns a connection
ID number. Use the connection ID number with other functions to reference that connection.

If SQLOpen is unable to connect with the information provided, it returns the error value 0 (zero). In such cases, and if more information is available, SQLOpen places error information in memory for the error functions to return,
if such information is available.

Examples

This example uses SQLOpen to create a connection to a Microsoft Access data source without displaying unnecessary prompts.

connect_num = SQLOpen("mydata.mdb", output_string$, 2)

The following example uses SQLOpen with a complex Connect$.

connect_num = SQLOpen("DSN = MyServer; UID = dbayer; PWD = 123; \
    Database = pubs", output_string$, 1)


SQLQueryExec

Syntax

SQLQueryExec(ConnectNum, Query$)

Remarks

Sends a query to a data source using an existing connection.

Note

Unlike SQLExecQuery, SQLQueryExec does not store the entire query result in memory. To avoid resource problems when creating complex database solutions using the ODBC add-in library, use SQLQueryExec.

Before calling SQLQueryExec, a connection must be established with a data source using SQLOpen. A successful call to SQLOpen returns a unique connection ID number. SQLQueryExec uses that connection ID number to send SQL language queries to the data source.

SQLQueryExec only executes a query; results generated from the query are
not returned. Retrieving results is handled by the SQLQueryFetch, SQLQueryRetrieve, SQLRetrieveColSize, and SQLSetRowPos functions. If SQLQueryExec is called using an existing connection ID number, all pending results on that connection will automatically be discarded. The connection ID will then refer to the new query and its results.

You cannot use SQLRetrieveItem$ or SQLRetrieveToDocument to return data from a SQLQueryExec instruction.

Argument | Explanation
ConnectNum | The unique connection ID of the data source you want to query returned by a previously executed SQLOpen function. If ConnectNum is not valid, SQLQueryExec returns 0 (zero).
Query$ | The SQL language query that is to be executed on the data source. The query should follow SQL grammar; the Help file for the appropriate ODBC driver also describes any SQL language limitations or modifications for the given DBMS. If SQLQueryExec is unable to execute Query$ on the specified data source, SQLQueryExec returns 0 (zero). The exact error can be obtained from the error functions.

If SQLQueryExec is able to successfully execute the query on the specified connection, it will return one of three values, depending on the type of SQL statement that was executed.

SQL statement | Return value
SELECT | The number of result columns available
UPDATE, INSERT or DELETE | The number of rows affected by the statement
Other | A positive value

If there was an error executing the query, SQLQueryExec returns a negative error value.

Note

If SQLQueryExec successfully executes the query but the result of the query contains no data, the function will return 0 (zero). To determine whether this return value indicates an error or simply that the result contains no data, check for error messages with SQLCountErrors. If SQLCountErrors returns 0 (zero), then SQLQueryExec successfully executed the SQL query but the result is empty.

Example

The following example sends a simple SELECT query to an established data source connection during asynchronous processing. While SQLQueryExec continues to return the value –2, the query is still being processed; the macro should wait for a final return value from SQLQueryExec before determining whether an error occurred.

ret = -2
While ret = -2
    ret = SQLQueryExec(connect_num, "select * from authors")
Wend
If ret <= 0 Then Goto ParseErrors


SQLQueryFetch

Syntax

SQLQueryFetch(ConnectNum)

Remarks

Positions the cursor at the next row of data in the query result of SQLQueryExec. The cursor cannot be moved backward. To use SQLQueryFetch, a macro must have already established a connection using SQLOpen. Also, a query must have already been executed using SQLQueryExec, and results must be pending.

Use SQLQueryRetrieve to return data from the row of data at which the cursor is positioned.

You cannot use SQLQueryFetch in combination with SQLRetrieveItem$ or SQLRetrieveToDocument to return data from a data source.

Argument | Explanation
ConnectNum | The unique connection ID for a data source. The data source specified must have pending query results. If ConnectNum is not valid, SQLQueryExec would have returned an error value. In such a case, SQLQueryExec places error information in memory for the error functions, if such information is available.

If the cursor was moved, SQLQueryFetch returns 1; if the cursor is already positioned at the last row of data, it returns –1 (SQL_NoMoreData). Otherwise, SQLQueryFetch returns 0 (zero) or a negative error value.

Example

The following example uses a While...Wend loop to return the data in each column of each row of the pending data source until SQLQueryFetch returns a value indicating that the cursor is already at the last row of the query results.

cols = SQLRetrieveColumns(connect_no)
ret = SQLQueryFetch(connect_no)
While ret = 1
    For i = 1 To cols
        storsize = SQLRetrieveColSize(connect_no, i)
        stor$ = String$(storsize, 50)
        SQLQueryRetrieve(connect_no, i, stor$, storsize)
        ' Statement block that processes the value of stor$
    Next i
ret = SQLQueryFetch(connect_no)
Wend


SQLQueryRetrieve

Syntax

SQLQueryRetrieve(ConnectNum, Column, DataVar$, DataSize)

Remarks

Assigns to the DataVar$ variable the data in the specified Column of the current row (the row where SQLQueryFetch or SQLSetRowPos positioned the cursor) of the query result. To use SQLQueryRetrieve, a macro must have already established a connection using SQLOpen. Also, a query must have already been executed using SQLQueryExec, and results must be pending.

You cannot use SQLQueryRetrieve to return data from a query executed by SQLExecQuery.

Caution

SQLQueryRetrieve assigns the data to the characters in DataVar$, up to the number of characters specified by DataSize. If the number of characters assigned to DataVar$ before it is used by SQLQueryRetrieve is less than DataSize, SQLQueryRetrieve may cause memory errors.

To avoid memory errors, the macro must ensure that the value of DataVar$ is at least DataSize characters long before it is used in a SQLQueryRetrieve instruction.

Argument | Explanation
ConnectNum | The unique connection ID for a data source. The data source specified must have pending query results. If ConnectNum is not valid, SQLQueryExec would have returned an error value. In such a case, SQLQueryRetrieve places error information in memory for the error functions, if such information is available.
Column | The number of a column in the data source from which to retrieve data. Use SQLRetrieveColumns to determine the valid range of values. If the column value is out of range, SQLQueryRetrieve returns 0 (zero) and places the error information in memory for the error functions.
DataVar$ | The variable to which SQLQueryRetrieve assigns the data, up to the number of characters specified by DataSize. Before the SQLQueryRetrieve instruction is run, the value of DataVar$ must be at least DataSize characters long. Otherwise, memory errors may occur.
DataSize | Specifies the width of the data at Column. To determine the value for DataSize, use SQLRetrieveColSize. If the length of the data in Column exceeds DataSize, SQLQueryRetrieve truncates the data.

If the data cannot be returned successfully, SQLQueryRetrieve returns 0 (zero) or a negative error value.

Example

The following example uses a While...Wend loop to return the data in each column of each row in the pending data source with SQLQueryRetrieve so it can be processed.

cols = SQLRetrieveColumns(connect_no)
ret = SQLQueryFetch(connect_no)
While ret = 1
    For i = 1 To cols
        storsize = SQLRetrieveColSize(connect_no, i)
        stor$ = String$(storsize, 50)
        SQLQueryRetrieve(connect_no, i, stor$, storsize)
        ' Statement block that processes the value of stor$
    Next i
ret = SQLQueryFetch(connect_no)


SQLRetrieveColSize

Syntax

SQLRetrieveColSize(ConnectNum, ColNum)

Remarks

Determines the maximum width of the string values in the specified column of the data source. To use SQLRetrieveColSize, a macro must have already established a connection using SQLOpen. Also, a query must already have been executed using SQLQueryExec, and results must be pending. Use the value returned by SQLRetrieveColSize in a String$() instruction to create a variable large enough to contain the value assigned to it by subsequent SQLQueryRetrieve instructions.

You cannot use SQLRetrieveColSize to determine the width of a column in the query results returned by SQLExecQuery.

Argument | Explanation
ConnectNum | The unique connection ID for a data source. If ConnectNum is not valid, SQLQueryExec would have returned an error value. In such a case, SQLRetrieveColSize places error information in memory for the error functions, if such information is available.

SQLRetrieveColSize returns the maximum width of the specified column in the data source. Note that the column size is one-based; that is, the first column is 1, not 0 (zero).

SQLRetrieveColSize returns 0 (zero) if it cannot determine the maximum width of the column, and places error information in memory for the error functions, if such information is available.

If there are no results pending on the connection, no data was found, or there is no data, SQLRetrieveColSize returns –1 (SQL_NoMoreData).

Example

The following example uses the value returned by SQLRetrieveColSize in a String$() instruction to make the variable stor$ large enough to use in the subsequent SQLQueryRetrieve instruction. The value returned by SQLRetrieveColSize is also used in the SQLQueryRetrieve instruction to indicate how many characters to return from specified column of the data source.

storsize = SQLRetrieveColSize(connect_no, 1)
stor$ = String$(storsize, 35)        'creates a string # characters
SQLQueryRetrieve(connect_no, 1, stor$, storsize)


SQLRetrieveColumns

Syntax

SQLRetrieveColumns(ConnectNum)

Remarks

Determines the number of columns available in the data source. To use SQLRetrieveColumns, a macro must have already established a connection using SQLOpen. Also, a query must already have been executed using SQLExecQuery or SQLQueryExec, and results must be pending.

Argument | Explanation
ConnectNum | The unique connection ID for a data source. If ConnectNum is not valid, SQLExecQuery or SQLQueryExec would have returned an error value. In such a case, SQLRetrieveColumns places error information in memory for the error functions, if such information is available.

SQLRetrieveColumns returns the number of columns in the data source. Note that the column count is one-based; that is, the first column is 1, not 0 (zero).

If there are no results pending on the connection, no data was found, or there is no data, SQLRetrieveColumns returns –1 (SQL_NoMoreData).


SQLRetrieveFlush

Syntax

SQLRetrieveFlush(ConnectNum)

Remarks

Flushes the current query and frees any resources held. In general, data from old queries is flushed when a new query is established, but you can use SQLRetrieveFlush to deliberately remove current query results. To use SQLRetrieveFlush, a macro must have already established a connection using SQLOpen. Also, a query must already have been executed using SQLExecQuery or SQLQueryExec, and results must be pending.

Argument | Explanation
ConnectNum | The unique connection ID for a data source. The data source specified must have pending query results. If ConnectNum is not valid, SQLExecQuery or SQLQueryExec would have returned an error value. In such a case, SQLRetrieveFlush places error information in memory for the error functions, if such information is available.

If the current query could not be flushed, the SQLErrorFlush function returns
a negative error value.


SQLRetrieveItem$

Syntax

SQLRetrieveItem$(ConnectNum, Column, Row)

Remarks

Extracts an available data item from a data source. To use SQLRetrieveItem$, a macro must have already established a connection using SQLOpen. Also, a query must have already been executed using SQLExecQuery, and results must be pending.

You cannot use SQLRetrieveItem$ to return data from a SQLQueryExec instruction.

For a complete example macro using SQLRetrieveItem$ and the other functions used to retrieve information from a data source, see the second example macro described in "Using the ODBC Extensions" earlier in this appendix.

Argument | Explanation
ConnectNum | The unique connection ID for a data source. The data source specified must have pending query results. If ConnectNum is not valid, SQLExecQuery would have returned an error value. In such a case, SQLRetrieveItem$ places error information in memory for the error functions, if such information is available.
Column | The number of a column in the data source. Use SQLRetrieveColumns to determine the valid range of values. If the column value is out of range, SQLRetrieveItem$ returns an empty string ("").
Row | The number of a row in the data source. Use SQLRetrieveRows to determine the valid range of values. If the row value is out of range, SQLRetrieveItem$ returns an empty string ("").

SQLRetrieveItem$ returns the specified data item as a string.


SQLRetrieveRows

Syntax

SQLRetrieveRows(ConnectNum)

Remarks

Determines the number of rows available in the data source. To use SQLRetrieveRows, a macro must have already established a connection using SQLOpen. Also, a query must have already been executed using SQLExecQuery, and results must be pending.

Argument | Explanation
ConnectNum | The unique connection ID for a data source. If ConnectNum is not valid, SQLExecQuery would have returned an error value. In such a case, SQLRetrieveRows places error information in memory for the error functions, if such information is available.

Returns the number of rows in the data source. Note that the row count is one-based; that is, the first row is 1, not 0 (zero).

SQLRetrieveRows returns 0 (zero) if used to determine the number of rows in the query result of a SQLQueryExec instruction.

If there are no results pending on the connection, no data was found, or there is no data, SQLRetrieveRows returns –1 (SQL_NoMoreData).


SQLRetrieveToDocument

Syntax

SQLRetrieveToDocument(ConnectNum)

Remarks

Retrieves the results of a query and places the entire contents into a table in the active document. To use SQLRetrieveToDocument, a macro must have already established a connection using SQLOpen. Also, a query must already have been executed using SQLExecQuery, and results must be pending.

You cannot use SQLRetrieveToDocument to return data from a SQLQueryExec instruction.

Argument | Explanation
ConnectNum | The unique connection ID of the data source you want to query returned by a previously executed SQLOpen function. If ConnectNum is not valid, SQLRetrieveToDocument returns 0 (zero).

If the pending query result cannot be returned successfully, SQLRetrieveToDocument returns a negative error value.

Example

The following example establishes a connection to a data source, queries the data source to select every record, and then uses SQLRetrieveToDocument to insert the entire data source in a table in a new Word document.

connect_num = SQLOpen("DSN=test.mdb", output_ref$, 0)
ret = SQLExecQuery(connect_num, "Select * from table4 " + \
        Quote2$("name"))
FileNew
ret = SQLRetrieveToDocument(connect_num)
ret = SQLClose(connect_num)


SQLSetRowPos

Syntax

SQLSetRowPos(ConnectNum, Row)

Remarks

Positions the cursor at a specified row of the query results of SQLQueryExec. To use SQLSetRowPos, a macro must have already established a connection using SQLOpen. Also, a query must have already been executed using SQLQueryExec, and results must be pending.

Note

Not all DBMSs can move the cursor to an arbitrary row of a query result. If a SQLOpen instruction returned a connection to a DBMS that cannot use move the cursor arbitrarily, SQLSetRowPos returns 0 (zero).

Use SQLQueryRetrieve to return data from the row of data at which the cursor is positioned.

You cannot use SQLSetRowPos to return data from a SQLExecQuery instruction.

Argument | Explanation
ConnectNum | The unique connection ID for a data source. The data source specified must have pending query results. If ConnectNum is not valid, SQLQueryExec would have returned an error value. In such a case, SQLSetRowPos places error information in memory for the error functions, if such information is available.
Row | The number of a row in the data source. If the row value is out of range, SQLSetRowPos returns 0 (zero). You cannot use SQLRetrieveRows to determine the number of rows in a query result from a SQLQueryExec instruction. Therefore, you must use one of the following two methods to determine valid values for Row: Create a While...Wend loop to call SQLQueryFetch and increment a counter variable until SQLQueryFetch returns –1. Then use any value between 1 and the counter variable for Row. Use any value and then determine whether SQLQueryFetch succeeded: if it didn't, try another value; if it did, process the data in the row at which the cursor was successfully positioned.

If the cursor was moved, SQLSetRowPos returns 1. If an error occurred, SQLSetRowPos returns 0 (zero) or a negative error value.

If the DBMS specified by the SQLOpen instruction that returned ConnectNum does not support this functionality, SQLSetRowPos returns 0 (zero).


SQLSynchronize

Syntax

SQLSynchronize(Flag)

Remarks

Specifies whether to allow ODBC functions to be called asynchronously. Several of the functions in the ODBC API can be called asynchronously. The ODBC extensions for Microsoft Word take advantage of this functionality. Not all ODBC drivers can handle asynchronous calls, but the ODBC API was designed so that the calling convention is the same for all drivers.

For complete information on asynchronous processing, see "Requesting Asynchronous Processing" in Chapter 6, "Executing SQL Statements," in the Microsoft ODBC Programmer's Reference in the Microsoft ODBC Software Development Kit version 2.0.

Argument | Explanation
Flag | Specifies whether to enable or disable asynchronous processing: 0 (zero) Enables asynchronous processing; subsequently, SQL functions may return –2 (SQL_StillExecuting) if activity on the connection is not complete. 1 Disables asynchronous processing.

If SQLSynchronize is unsuccessful, the function returns a negative error value.

Example

The following example demonstrates the calling convention for asynchronous ODBC functions.

err = SQLSynchronize(0)
status = SQLExecQuery(connection, query_string$)
While SQLRetrieveRows(connection) = -2
    'Series of statements to perform other processing
Wend

The ODBC functions used in the WBODBC.WLL can be called in this manner after asynchronous processing is enabled.


Microsoft Word Application Programming Interface

The Microsoft Word application programming interface (Word API) is the doorway into the internal functionality of Microsoft Word. Using a programming language such as Microsoft Visual C++ (Windows) or Symantec® THINK C (Macintosh), the Word API, and the tools provided on the Microsoft Word Developer's Kit disk, you can create add-ins that interact directly with Microsoft Word. This appendix covers the concepts, tools, and methods for programming Word add-in libraries (WLLs).


Why Use the Word API?

The WordBasic macro language provides one method of controlling Word through programming. WordBasic can access all of Word's functionality, and, in Windows, can even call Windows API functions directly, which provides a significant degree of power and flexibility. However, the Word API goes beyond WordBasic, providing even more flexibility and better performance.

Word API programming has several advantages over WordBasic. You can write code that is fast, efficient, and flexible. You can use pre-existing libraries of external code, or create new code using any compiler suitable for creating code modules. There are few limitations to the complexity or sophistication of WLLs that you can design and create for Word.

In Windows, a Word add-in library is a special form of a standard Windows dynamic-link library (DLL). On the Macintosh, a Word add-in library is a WDLL code resource designed to be available directly to WordBasic. You can use any language that can create a Windows DLL or Macintosh code resource, such as C, Pascal, or Assembler. However, C is the language of choice for most people.

Note

In this appendix, the term "WLL" is used to refer to a Word add-in library developed for either Windows or the Macintosh.


What You Need to Know

Before using the Word API, you should know the basics of creating a DLL (Windows) or a code resource (Macintosh). You should also be familiar with Word and the WordBasic macro language.

Requirements

Windows 3.x, Windows 95, or Windows NT

To develop WLLs in Windows 3.x, Windows 95, or Windows NT, you need the following:

  • Microsoft Word Developer's Kit
  • Microsoft Word version 6.0 for Windows or Windows NT, or Word version 7.0
  • Microsoft Windows version 3.1 or later, Microsoft Windows 95, or Microsoft Windows NT version 3.5 or later
  • A compiler that can produce Windows-compatible DLL files (for example, Microsoft Visual C++)

Macintosh

To develop WLLs on the Macintosh, you need the following:

  • Microsoft Word Developer's Kit
  • Microsoft Word version 6.0 or later for the Macintosh
  • Apple Macintosh System 7.0 or later
  • A compiler that can produce Macintosh code resources (for example, Symantec THINK C)

Installation

The files necessary to build WLLs are located in the CAPI folder on the Microsoft Word Developer's Kit disk. Within the CAPI folder, the SAMPLE subfolder contains the files needed to build a sample WLL in Visual C++ (Windows) or Symantec THINK C (Macintosh). This sample code provides a good starting point for developing your own WLLs.

Windows, Windows 95, or Windows NT

From the Microsoft Word Developer's Kit disk, copy the entire CAPI subfolder to an appropriate location in your compiler folder structure. The CAPI subfolder contains the following files, which need to be available to each WLL project you create:

  • CAPILIB.C, a collection of helper functions described in the section "Using the CAPILIB Functions" later in this appendix
  • CAPILIB.H, the header file defining the CAPILIB functions
  • WDCAPI.H, the header file defining the functions, data structures, and constants needed to program WLLs
  • CONFIG.H, the header file required to compile WLLs correctly on either 16-bit or 32-bit platforms
  • WDCMDS.H, the header file defining all of the Word commands and functions available through the Word API
  • WDERROR.H, the header file defining the Word API error codes returned by Word
  • WDFID.H, the header file defining all of the arguments taken by the Word commands listed in WDCMDS.H

Macintosh

From the Microsoft Word Developer's Kit disk, drag the CAPI folder to an appropriate location in your compiler folder. The CAPI folder contains files similar to those described for the Windows disk; these files need to be available to each WLL project you create.


Overview of Add-ins and WLLs

External functions in a library are called add-ins, or add-in functions. Add-in functions for Word are faster and more efficient than equivalent WordBasic macros because they are written in C and compiled, and can take advantage of the full functionality of the operating system. You can declare and call external add-in functions in a WLL from WordBasic, or they can be registered with Word using the functions in the Word API.

What Is a Word Add-in Library?

In Windows, a Word add-in library (WLL) is a stand-alone dynamic-link library (DLL) with the filename extension .WLL (once built, the DLL filename extension is renamed to WLL so that the file can be identified as a Word add-in library). On the Macintosh, a WLL is a WDLL code resource, which is designed especially for Word. The rules for compiling, linking, and building a WLL are the same as those for creating a DLL (Windows) or code resource (Macintosh). What sets a WLL apart are the special functions that Word looks for and calls automatically when the WLL is loaded and unloaded: wdAutoOpen and wdAutoRemove.

Word uses these two functions as automatic points of entry into a WLL. Word calls the wdAutoOpen function when the WLL is loaded. This is where the WLL should register its functions and customize Word so that the functions can be called from menu items or toolbar buttons. After doing so, the function returns a value to Word indicating success or failure (on the Macintosh, the function must return the value to the main routine, which in turn returns the value to Word). Here is the syntax:

// Windows
short FAR PASCAL wdAutoOpen( short DocID );

// Macintosh
short wdAutoOpen( short DocID );

Word calls the optional wdAutoRemove function, if included, when the WLL is being unloaded, either by the user or when Word shuts down. Here is the syntax:

// Windows
void FAR PASCAL wdAutoRemove( void );

// Macintosh
void wdAutoRemove( void );

This function can be used to free dynamically allocated memory when the WLL is unloaded. In addition, if your WLL makes permanent changes to the Normal or active template, you should include the wdAutoRemove function to remove any customization that you don't want the template to retain. If your WLL does not specify permanent changes, the Normal or active template is not "dirtied" by the WLL; all customization is temporary and is automatically removed when the WLL is unloaded. In that case, the wdAutoRemove function is not necessary.

For descriptions of the other WLL-specific functions that Word makes available through the Word API, see "Word API Functions" later in this appendix.

WordBasic and the Word API

For the most part, there's a one-to-one correspondence between the statements and functions in WordBasic and those that can be called from an add-in function in a WLL. However, the Word API is intended to provide word-processing functionality rather than to duplicate WordBasic functionality. Therefore, elements of the WordBasic language such as control structures, variable declarations, basic file I/O, and custom dialog boxes cannot be called from an add-in function in a WLL. Also note that you can run existing WordBasic macros through the Word API just as you would use the WordBasic ToolsMacro statement, but you cannot access the functionality of the WordBasic Call statement to pass arguments or run specific subroutines or functions.

In addition to wdAutoOpen and wdAutoRemove, described earlier, there are a handful of Word functions that are available only to WLLs through the Word API. For information on these Windows and Macintosh functions and their use in WLLs, see "Word API Functions" later in this appendix.

Loading a WLL

There are several ways to load a WLL, either directly by the user or automatically when Word is started or a WordBasic macro is run.

Templates command

From the File menu, choose Templates. Word displays the Templates And Add-ins dialog box. Under Global Templates And Add-ins, choose the Add button. In the Add Template dialog box, select Word Add-ins in the list of file types, and then select a WLL. Choose OK to add the WLL to the list of selected add-ins. When you close the Templates And Add-ins dialog box, Word loads the WLL.

Open command

From the File menu, choose Open. Type the path and filename
of the WLL to load it. To see a list that includes all WLLs in the selected folder, type *.wll in the File Name box and choose OK (Windows) or select All Files in the List Files Of Type box (Macintosh).

AddAddIn statement

A WLL can be loaded from any WordBasic macro, or from a function in another WLL, by calling AddAddIn. This statement and others used in WordBasic macros to work with Word add-in libraries are described in Part 2, "WordBasic Reference."

Auto macros

If a WordBasic auto macro, such as AutoExec, AutoNew, or AutoOpen, is available, Word runs it automatically. You can use the AddAddIn statement in any auto macro to automatically load a WLL. For example, an AutoExec macro in the Normal template can automatically load a WLL every time Word is started.

Startup folder

All WLLs located in Word's designated startup folder will automatically load when Word is started. To set the startup folder, choose Options from the Tools menu, select the File Locations tab, and then specify the folder for the Startup option.

Command line

In Windows, you can load a WLL when Word is started by adding an /l command line switch to the command line for a Microsoft Word program item in Program Manager (Windows 3.x and Windows NT) or a Microsoft Word shortcut in Windows Explorer (Windows 95). The following example command line loads CAPI.WLL when Word is started.

c:\winword\winword.exe /lc:\winword\templates\capi.wll

On the Macintosh, you can modify the Word Switches setting in Word Settings (6) to load a WLL when Word is started. For information about modifying this setting, see "Startup Switches" in WordBasic Help.

Note

It is also possible for a WordBasic macro to declare and then directly call a function in a WLL, but this doesn't guarantee that the WLL will be loaded as expected. Unless the WLL is loaded in one of the ways described above, the wdAutoOpen function does not have the chance to register other functions, and any intended modifications to menus or toolbars will not be made.


Calling Word from a WLL

To call Word with the Word API, a WLL fills WDOPR data structures with data that is meaningful to a Word function, and then sends the structures through the wdCommandDispatch function, which identifies the Word function to use. The WDOPR data structure and wdCommandDispatch are discussed in detail in the following sections. The CAPILIB functions provided on the Microsoft Word Developer's Kit disk wrap up many of the steps required to build arrays of WDOPRs, and they help perform common WLL tasks, such as customizing Word.

Use the sections on wdCommandDispatch ("The wdCommandDispatch Function"), WDOPRs ("The Word Operator (WDOPR)"), and basic Word API techniques ("Techniques for Successful Calling") to learn about the Word API in general and some platform-specific issues. Then use the section on CAPILIB ("Using the CAPILIB Functions") to get an overview of the helper functions you can use to program WLLs quickly and efficiently.


The wdCommandDispatch Function

An add-in library function accesses Word by calling the wdCommandDispatch function. This is the only function in Word that your add-ins will call. The wdCommandDispatch function lets you call virtually all WordBasic statements and functions. It passes the same arguments as those described for WordBasic statements and functions in Part 2, "WordBasic Reference."

Here is the syntax for the wdCommandDispatch function:

// Windows
short FAR PASCAL wdCommandDispatch( short CommandID, short DlgOptions,
    short cArgs, LPWDOPR lpwdoprArgs, LPWDOPR lpwdoprReturn );

// Macintosh
pascal short (*wdCommandDispatch) ( short CommandID, short DlgOptions,
    short cArgs, LPWDOPR lpwdoprArgs, LPWDOPR lpwdoprReturn );

For platform-specific details about declaring wdCommandDispatch in your WLL code, see "Platform-Specific Notes About wdCommandDispatch" later in this section.

Step by Step Through the Parameters

Understanding each of the parameters of the wdCommandDispatch function is important. The following paragraphs detail the purpose and use of each parameter.

CommandID

This is the WordBasic command Word is to execute. The names of available functions are provided as constants in the header file WDCMDS.H. Most of these command names closely parallel their WordBasic equivalents.

DlgOptions

This is the "dialog options" parameter, and is only necessary for WordBasic commands that correspond to Word dialog boxes. This parameter is ignored if
the command doesn't involve a dialog box. The following constants for this parameter are defined in WDCAPI.H.

CommandDefaults

Returns default values for the dialog box's fields, without actually activating the dialog box. This is similar to the GetCurValues statement in WordBasic.

CommandDialog

Activates the dialog box. This is similar to the Dialog statement in WordBasic. If the function is set to return values from Word, the field settings are just returned to the calling code, and no implied action takes place.

CommandAction

Causes the action indicated by the dialog box to actually take place. When combined with CommandDialog, the dialog box will first be displayed, letting the user make any desired changes to the fields, and then the dialog box's action will take place.

cArgs

This is the number of Word arguments being passed. (Arguments for Word commands are wrapped in a data structure called a WDOPR.) The next parameter, lpwdoprArgs, points to an array of WDOPR arguments; cArgs simply provides the count for this array.

lpwdoprArgs

This is a pointer to an array of WDOPR arguments passed to the function dispatcher; in other words, these are the actual arguments for the Word command. Building up this array of arguments is an important part of preparing to call wdCommandDispatch. The next section explains this parameter in greater detail.

lpwdoprReturn

This parameter points to a single WDOPR data structure that returns one data item from a WordBasic function. The returned data item can be any of the supported WDOPR data types. When using wdCommandDispatch to execute WordBasic statements that correspond to dialog boxes, you should set this parameter to lpwdoprNil. If you are calling a WordBasic statement that can also be called as a function — for example, Bold and Bold() — this parameter must correspond to how you want to use the statement: as a statement or as a function.

Platform-Specific Notes About wdCommandDispatch

The following topics address specific issues about accessing wdCommandDispatch and the Word API on the Windows 3.x, Windows 95, Windows NT, and Macintosh platforms.

Windows 3.x

In Windows 3.x, a WLL imports wdCommandDispatch directly from Word version 6.0 for Windows. By declaring the function as described earlier in this section and including the function in the IMPORTS section of the .DEF file for you WLL, your add-in library will work correctly in Windows 3.x.

Windows 95 and Windows NT

In Windows 95 and Windows NT, importing functions directly from applications (as Windows 3.x allows) is discouraged. To use wdCommandDispatch successfully in Windows 95 and Windows NT, your WLL should declare the following function:

static unsigned int (*pfn_wdCommandDispatch) () = NULL;
{
    if (pfn_wdCommandDispatch == NULL)
        pfn_wdCommandDispatch = GetProcAddress(GetModuleHandle(NULL),
        "wdCommandDispatch");
    return ((*pfn_wdCommandDispatch)
        (CommandID, DlgOptions, cArgs, lpwdoprArgs, lpwdoprRetrun));
}

After declaring this function, the WLL should behave the same as one created for Windows 3.x. However, bear the following details in mind when programming 32-bit WLLs or migrating 16-bit WLLs to 32-bit WLLs:

  • Any code that assumes an int or stack is 16 bits will cause problems in Windows 95 or Windows NT. This is especially important when calling functions in which you are expecting a variable number of parameters; the mechanism to get the parameters cannot assume a 16-bit stack.
  • For Windows NT on x86 platforms, make sure that you use standard calling conventions (__stdcall) for all the functions you export to or import from Word. For Windows NT on a MIPS® or Alpha AXP™ platform, use the C calling convention (__cdecl). One way to handle this is to not use any calling convention prefix at all and control stdcall or cdecl from the .MAK file by using the appropriate switch (for example, in Microsoft Visual C++, -Gz on x86 platforms and default on MIPS or Alpha AXP).
  • Several 32-bit Windows API functions with default unicode support have a suffix: W or A. For ANSI, you need to pick the one with suffix A (for example, CallWindowProcA instead of CallWindowProcW).

Passing Floating-Point Parameters on a RISC Platform

If you are writing external DLLs or WLLs to run in Word version 6.0 for Windows NT or Word version 7.0 on a RISC platform, you should be aware of the following issue. Although some processor architectures define a special mechanism for supplying floating-point parameters to functions, WordBasic always passes parameters to external functions using the method for integers, pointers, and structures. Therefore, if your code includes functions with floating-point parameters that will be declared and called by WordBasic macros, you need to use a special technique for passing the parameters.

To access floating-point parameters within a DLL or WLL, you must declare them as structures, and then copy them into a local variable for use within your routine. You can use the following structure and macro definition to accomplish this.

struct WORDARGDBL

{

char x[sizeof(double)];

};

#define DblArgValue(a) (*(double*)&(a))

Here is an example of how you can use this structure and definition in a WLL function:

double WINAPI AbsCapi (struct WORDARGDBL arg1)

{

InitWCB (&wcb, TypeDouble, NULL, 0);

AddDoubleParam (&wcb, DblArgValue(arg1));

err = wdCommandDispatch (wdAbs, 0, wcb.cArgs, wcb.wdoprArgs,

&wcb.wdoprReturn);

return wcb.wdoprReturn.Double;

}

Macintosh

A Macintosh code resource cannot import a function directly from an application. Therefore, the application must provide the resource with a pointer to the parameters for wdCommandDispatch. Every time Word calls the WLL, it passes a pointer to a WCDB structure. Here is the structure:

typedef struct _WCDB
{
    short            cac;
    char                fLock;
    char                fPurge;
    char                szFunction[66];
    pascal short        (*pfnWordCapi)();
    short            *prgParams;
    union
    {
        long        Short;
        long        Long;
        double        Double;
        uchar         *String;
    } retval;
} WCDB;

Element | Description
cac | CAPI Call, the action to be taken by the main function. The defined actions are cacCallFunction, cacCallTimer, cacTerminate, cacWdAutoOpen, cacWdAutoRemove, and cacWindEvent.
fLock | Specifies whether the WLL should remain locked after being called.
fPurge | Specifies whether the WLL should be purged after being called.
szFunction | The function being called from WordBasic; cac is cacCallFunction. On the Macintosh, if the function being called does not exist in the WLL, the WLL should return CAPINoSuchFunction (5) to Word.
pfnWordCapi | A pointer to wdCommandDispatch.
prgParams | A pointer to the parameter list passed to szFunction.
retval (union) | The return value of szFunction, if any, as one of the data types specified in the union.

In the main function of the WLL, the dispatcher must be based on the value of the CAPI Call (cac) passed by Word. Apart from this behavior, a Macintosh WLL should work the same as a Windows WLL.

Note

On the Macintosh, WordBasic passes function names to a WLL in all uppercase. For simplicity and speed, a WLL should be written to perform a case-insensitive comparison to determine which function in the WLL is being called.

At the same time Word passes a pointer to the WCDB for a WLL to use, it passes a pointer to lUser, a long that holds global data for the WLL. Word initializes this value to 0 (zero); a WLL can modify the data at any time, and Word will return the current data in lUser each time it calls the WLL.


The Word Operator (WDOPR)

The lpwdoprArgs parameter of wdCommandDispatch is a pointer to an array of Word operator (WDOPR) data structures. The WDOPR structure lets you pass one of several types of data, and even lets you pass entire arrays of strings or double-precision floating-point values.

For efficiency, several types of data can be passed in the same memory location through the union part of the WDOPR structure; the Type field determines how the data is to be interpreted. Other bit fields in the WDOPR data structure convey to and from the Word API function important information about the argument.

Here is the Windows WDOPR and LPWDOPR type definition, which is found in WDCAPI.H:

typedef struct
{
    union
        {
        short       Short;
        long        Long;
        double      Double;
        LPUCHAR     String;
        struct
            {
            ARRAY_DEF far *  ArrayDef;
            union
                {
                double far *       DoubleArray;
                LPUCHAR far *      StringArray;
                };
            };
        };
    ushort BufferSize;
    ushort Type      :4;
    ushort IsArray   :1;
    ushort ForInput  :1;
    ushort ForOutput :1;
    ushort BufferTooSmall :1;
    ushort :8;
    ushort FieldId;
} WDOPR, far * LPWDOPR;

Note

On the Macintosh, the corresponding type definition has named unions, Macintosh-specific types (for example, StringPtr instead of LPUCHAR), and a different bit-field order. Otherwise, the information for the Macintosh is the same as the information given for Windows in the following sections. For the complete Macintosh WDOPR data structure, see WDCAPI.H on the Microsoft Word Developer's Kit disk (Macintosh).

Step by Step Through the Data Structure

The following paragraphs describe in detail each part of the WDOPR data structure.

The Type Union

The WDOPR structure starts with a union of several data types. Each WDOPR argument is set up to pass one of these data types at a time. In addition to passing a single short, long, double, or string value, you can also pass arrays of doubles or strings. If an array is passed, the WDOPR structure contains a pointer to the array and to a data structure that defines the dimensions of the array. For complete information about arrays in the Word operator, see "Specifics on Arrays" later in this section.

BufferSize

This field specifies the length of a string handled for input or output. If the argument is set for input, the BufferSize field can be set to one of two ways:

  • If BufferSize is set to 0 (zero), the string is passed as a null-terminated string.
  • If BufferSize is set to a nonzero value, that exact number of characters, including null characters, is passed from the string. If the WDOPR holds an array of strings, BufferSize indicates the length of each string in the array, which means that all array strings should have the same maximum length.

If the argument is set for output, the BufferSize field indicates the size of
the buffer allocated for the returned string. If the allocated buffer is not large
enough, or if you deliberately set BufferSize to 0 (zero), an error occurs, the BufferTooSmall bit field is set to 1, and BufferSize is set to the required size. For information about handling returned strings, see "Techniques for Successful Calling" later in this appendix.

The Bit Fields

The following bit fields in the WDOPR data structure convey important information about the argument.

Type

These 4 bits indicate the type of the WDOPR's data. The constants TypeVoid, TypeShort, TypeLong, TypeDouble, and TypeString are defined in WDCAPI.H for use in this field.

In Part 2, "WordBasic Reference," statement and function arguments and return types are specified as "number" (TypeShort, TypeLong, TypeDouble) or "text" (TypeString). To determine the appropriate WDOPR type for a "number" argument or return type, cross-reference the WordBasic topic with WBTYPE.TXT (Windows) or WBTYPE (Macintosh), a text file included in the CAPI folder on the Microsoft Word Developer's Kit disk; if the statement or function does not appear in the list of those that use TypeDouble or TypeLong, then the WDOPR type should be TypeShort.

IsArray

This bit should be set to 1 if the WDOPR is passing an array of the indicated data type. Note that it is the responsibility of the calling function to handle the allocation of memory for WDOPR arrays. For more information, see "Specifics on Arrays" later in this section.

ForInput

ForInput indicates that the contents of the WDOPR argument are intended as input to a dialog box's field settings. This bit is ignored if the command does not correspond to a dialog box.

ForOutput

ForOutput indicates that the WDOPR has been set up to return the value of one field of a dialog box. Set this bit if you are using the CommandDefaults constant for DlgOptions in your wdCommandDispatch function. This bit is ignored if the command does not correspond to a dialog box.

BufferTooSmall

If the allocated buffer space is too small to hold the field's data, wdCommandDispatch generates an error that sets BufferTooSmall to 1 (true) upon return from calling the command. It is important to clear this bit when making any call. The calling routine is responsible for checking this bit field and taking corrective action. Note that you can check this flag, reallocate the buffer (using the required size returned in BufferSize), and try the call again. If this occurs after calling a command that corresponds to a dialog box where the ForOutput bit was set before the call, this bit should be checked in all WDOPRs to determine which buffer was too small.

FieldID

FieldID is an identifier for the named field parameters passed in each WDOPR. Constants are provided in WDFID.H for this field, and they correspond closely to the parameters that can be passed in WordBasic, as described in Part 2, "WordBasic Reference." For example, in WordBasic the FormatFont statement takes the .Bold argument. The corresponding FieldID constant used to pass a short value of 1 in a WDOPR argument is fidBold. This WDOPR would, of course, be constructed and passed as part of a wdFormatFont command to the wdCommandDispatch function.

Specifics on Arrays

The WDOPR data structure is set up to facilitate the passing of either arrays of strings or arrays of doubles. These arrays can have one or more dimensions.

One of the data types in the union part of the WDOPR is a nested set of structures for passing arrays. Several pieces of information about each array are passed in the appropriate variables. The ARRAY_DEF structure passes information on the number of dimensions in the array and the size of each of those dimensions. Like the WDOPR structure, the ARRAY_DEF structure is also defined in WDCAPI.H, and is listed here for reference.

typedef struct
{
    short    cArrayDimensions;
    short    ArrayDimensions[];
} ARRAY_DEF;

The remaining part of the WDOPR's array-passing structure is a union of two pointers. In the first case, the pointer is to the first value in an array of double-precision floating-point values. In the second case, the pointer is to an area of memory containing a list of pointers to null-terminated strings.

Keep the following points in mind when building WDOPR arguments to pass arrays:

  • ARRAY_DEF must be loaded with data about each dimension of the array.
  • For doubles, DoubleArray must be loaded with a pointer to the array.
  • For strings, StringArray must be loaded with a pointer to a list of pointers
    to each string in the array.
  • You must set IsArray to 1.
  • When passing an array of strings on output, you must specify the length of the array; if the array length is 0 (zero), the Word API will assume that the buffer length is 0 (zero).
  • On output, the length of strings in an array is determined by BufferSize. If you pass a string longer than BufferSize, the Word API will write into at most the first BufferSize –1 locations.

Note

There is a subtle difference in the way WordBasic and C arrays are dimensioned. In WordBasic, an array has elements 0 (zero) through n, whereas
in C, an array has elements 0 (zero) through n–1, where n is the value given in the array's declaration. The following two arrays, for example, will be allocated the same amount of memory, with elements 0 (zero) through 5 in both cases:

' WordBasic array definition
Dim Array (5)

// C array definition
double Array[6];

Keep this in mind when working with WordBasic arrays in your Word API code.


Techniques for Successful Calling

It is important to make your Word API code robust because a problem in your Word API code can cause problems in Word. Any possible error conditions should be accounted for, and proper allocation and deallocation of memory should be verified, especially when passing strings.

Handling Errors

The wdCommandDispatch function returns an error code that should always be checked. Error constants are defined in WDERROR.H, and errors specific to the Word API are listed in "Word API Errors" later in this appendix. Any nonzero returned value indicates a problem, and your code should accommodate all cases.

In Windows, you should also be careful with function calls into other Windows DLLs, and take appropriate action for any unexpected conditions. A good working knowledge of Windows programming techniques will help make your Word API programming successful.

Allocating Memory

It is the responsibility of the WLL to allocate and deallocate required memory. This means you must declare or allocate appropriate memory space for all string buffers, arrays, and so on. For dynamically allocated variables you must also remember to deallocate the memory later on.

There are two general approaches to allocating enough space for strings returned by Word API commands:

Fixed size

In general, 256 bytes is sufficient for virtually all returned strings,
so you can declare or allocate character buffers of this length for most purposes.

Double calling

Another useful technique is to first set BufferSize to 0 (zero), which guarantees that the command will fail. Upon return, however, BufferSize contains the number of bytes required to successfully return the string. You can then allocate a buffer of the exact size required and repeat the call.

Deallocating Memory

It is important to correctly deallocate all memory dynamically allocated by your WLL. Sometimes you can deallocate immediately after a function call. In other cases the returned data will need to be passed back to Word, or kept for future reference by your WLL. In these cases, you are responsible for keeping track of and eventually deallocating these blocks of memory. For example, you might set
a flag that can be checked in wdAutoRemove to indicate that a specific buffer is
to be deallocated.

Working with Strings

When a string is passed from WordBasic to a WLL function, it is automatically lengthened to a minimum of 256 bytes (including the null character) by Word. The WLL can always safely write up to 256 bytes into a passed string. If you need to pass back a longer string, you must take special steps to prevent overwriting the wrong parts of memory. For example, you might add another parameter to your function and insist that WordBasic passes the actual string length. The following WordBasic instructions demonstrate how this might work:

strsize = 500
x$ = String$( strsize, "x" )
rtn = MyNewCAPIFunction( strsize, x$ )

It is the ultimate responsibility of your WLL code to make sure the string is long enough before overwriting its contents.


Using the CAPILIB Functions

CAPILIB provides a toolbox of functions to simplify your Word API programming tasks. This section takes a close look at these functions and how to use them to build Word operators, pass arrays, and customize Word.

The Word Command Buffer (WCB)

WCB is a data structure defined in WDCAPI.H. This structure is used by the various functions in CAPILIB to help build up the array of WDOPR parameters to be passed to the wdCommandDispatch function. The constant MaxArgs, found in WDCAPI.H, determines the maximum number of WDOPR parameters that can be built up. MaxArgs is safely set to 34, an argument count much greater than you'll probably ever need. cArgs is automatically incremented as WDOPR arguments are built up by the CAPILIB functions, and contains the actual count of the WDOPR arguments.

typedef struct
{
    short    cArgs;
    WDOPR    wdoprReturn;
    WDOPR    wdoprArgs[MaxArgs];
} WCB;

Functions in CAPILIB

There are eighteen functions in CAPILIB, which can be grouped into seven categories:

  • Initialize WCB
  • Add dialog fields
  • Add parameters
  • Define arrays
  • Call a Word command
  • Register functions in Word
  • Assign functions in Word

You should include the header file CAPILIB.H in modules that call these functions.

Initialize WCB

The first function initializes the WCB structure before building up the WDOPR arguments. The InitWCB function sets the cArgs count to 0 (zero) and sets up the return type. It is very important to call this function first; if cArgs is not initialized and set to the proper count, wdCommandDispatch will behave unpredictably.

// Windows
void InitWCB( WCB far *lpwcb, ushort retType, LPUCHAR lpBuffer,
    ushort cBufferSize );

// Macintosh
void InitWCB( WCB *lpwcb, ushort retType, StringPtr lpBuffer,
    ushort cBufferSize );

The parameters to InitWCB are as follows.

Parameter | Description
lpwcb | A pointer to the WCB to be initialized.
retType | The return type of the command. This lets the InitWCB function prepare the return WDOPR's contents.
lpBuffer | Pointer to the start of buffer. If the returned information will be a string buffer, the return WDOPR will only contain a pointer to a buffer.
cBufferSize | The return buffer's allocated length.

Add Dialog Fields

After InitWCB has been called, you build up WDOPR arguments one at a time by calling the other functions. Each of these functions increments the cArgs count and initializes the fields in a single WDOPR argument.

These four functions add field parameters for dialog commands:

// Windows
void AddShortDlgField( WCB far *lpwcb, short ShortVal, ushort FieldId,
    ushort fMode );
void AddLongDlgField( WCB far *lpwcb, long LongVal, ushort FieldId,
    ushort fMode );
void AddDoubleDlgField( WCB far *lpwcb, double DoubleVal,
    ushort FieldId, short fMode );
void AddStringDlgField( WCB far *lpwcb, LPUCHAR lpStr, ushort FieldId,
    ushort fMode, ushort cBufferSize );

// Macintosh
void AddShortDlgField( WCB *lpwcb, short ShortVal, ushort FieldId,
    ushort fMode );
void AddLongDlgField( WCB     *lpwcb, long LongVal, ushort FieldId,
    ushort fMode );
void AddDoubleDlgField( WCB *lpwcb, double DoubleVal, ushort FieldId,
    ushort fMode );
void AddStringDlgField( WCB *lpwcb, StringPtr lpStr, ushort FieldId,
    ushort fMode, ushort cBufferSize );

Here's a description of each of the parameters of these functions.

Parameter | Description
lpwcb | The address of the WCB structure.
ShortVal | The field's data, of the type indicated in the name of each function.
FieldId | The field's ID. A list of field ID constants is provided in WDFID.H, which should be included in modules calling the Word API functions. These constants have names that closely parallel the dialog command field names in WordBasic.
fMode | Indicates the input/output mode for the given dialog command field. Set this field using the constants INPUT, OUTPUT, or both.
cBufferSize | The allocated space for the string buffer.

Add Parameters

The next group of functions is called to build parameters for statements other than those that correspond to dialog boxes. The WDOPR argument in this case doesn't have field names, and the input/output information is irrelevant. For these reasons, only two parameters are passed to these functions: the WCB address, and the WDOPR argument data of the type indicated in the function's name.

// Windows
void AddShortParam( WCB far *lpwcb, short ShortVal );
void AddLongParam( WCB far *lpwcb, long LongVal );
void AddDoubleParam( WCB far *lpwcb, double DoubleVal );
void AddStringParam( WCB far *lpwcb, LPUCHAR lpStr );

// Macintosh
void AddShortParam( WCB *lpwcb, short ShortVal );
void AddLongParam( WCB *lpwcb, long LongVal );
void AddDoubleParam( WCB *lpwcb, double DoubleVal );
void AddStringParam( WCB *lpwcb, StringPtr lpStr );

Define Arrays

Three functions are provided to help you set up WDOPR arguments that pass arrays.

// Windows
ARRAY_DEF far * SetArrayDef( HANDLE *phArrDef, short cDimensions, ... );
void AddStringArray( WCB far *lpwcb, ARRAY_DEF far *ArrayDef,
    LPUCHAR far *lpStrArray, ushort cBufferSize );
void AddDoubleArray( WCB far *lpwcb, ARRAY_DEF far *ArrayDef,
    double far *lpdblArray );

// Macintosh
ARRAY_DEF * SetArrayDef( Handle *phArrDef, short cDimensions, ... );
void AddStringArray( WCB *lpwcb, ARRAY_DEF *ArrayDef, StringPtr
    *lpStrArray, ushort cBufferSize );
void AddDoubleArray( WCB *lpwcb, ARRAY_DEF *ArrayDef, double
    *lpdblArray );

The first function, SetArrayDef, builds the ArrayDef parameter required in the WDOPR when arrays are passed. ARRAY_DEF contains information on the number of dimensions and the size of each dimension for an array. The other two functions, AddStringArray and AddDoubleArray, build the WDOPR argument, filling in the data structure with pointers to an array and its associated ARRAY_DEF. When adding a string array, one additional parameter is passed to indicate the allocated size of each string in the array. Note that all strings in an array are allocated to the same maximum size, although the actual null-terminated strings may be of a shorter length.

Note

SetArrayDef allocates memory. After using an array, your WLL function needs to free that memory. For example, given the array hArrayDef, a function should deallocate memory as follows:

// Windows
GlobalUnlock( hArrayDef );
GlobalFree( hArrayDef );

// Macintosh
HUnlock( hArrayDef );
DisposHandle( hArrayDef );

The following stripped-down Windows code fragments demonstrate how SetArrayDef can be used to build the array definition table for an array of strings. Note that this code is extracted from the example code on the Microsoft Word Developer's Kit disk; you might want to study the example in its entirety.

HANDLE          hArrayDef;
ARRAY_DEF far * ArrayDef;
LPSTR           lpStrArray[ARRAYSIZE];
char            strArray[ARRAYSIZE][64];

ArrayDef = SetArrayDef( &hArrayDef, 1, ARRAYSIZE );

InitWCB( &wcb, TypeShort, NULL, 0 );
AddStringArray( &wcb, ArrayDef, lpStrArray, 64 );

Call a WordBasic Statement or Function

This function uses a subset of the other CAPILIB functions to fill a WCB for a WordBasic statement or function that does not correspond to a dialog box; it then dispatches the command to Word and returns the result. You can use this as an efficient way to dispatch WordBasic statements and functions in your WLL.

// Windows
short CallCapi( LPWCB far *wcb, short CommandID, ushort retType, LPSTR lpBuffer, ushort cBufferSize, LPSTR lpszFormat, ... );

//Macintosh
short CallCapi( WCB *wcb, short CommandID, ushort retType, StringPtr lpBuffer, ushort cBufferSize, StringPtr lpszFormat, ... );

Parameter | Description
*wcb | Pointer to the WCB structure.
CommandID | The WordBasic statement or function to be called; CommandID cannot correspond to a dialog box.
retType | The return type of the WordBasic statement or function.
lpBuffer | Buffer to store the return string, if any.
cBufferSize | Size of the buffer specified by lpBuffer.
lpszFormat | String describing the type of the arguments passed to CommandID. This list should be a string of characters that identify the type of each argument that follows. Use the following characters: i Integer l Long d Double s String For example, if the statement or function takes a string argument followed by an integer argument, lpszFormat would be "si"; the following argument list would be a string argument and an integer. CallCapi automatically parses this list and fills the WCB with the data in the specified order.
... | The list of arguments to dispatch with the statement, in the order specified by lpszFormat.

The following Macintosh example demonstrates how you can use CallCapi to dispatch the wdMsgBox statement in a single instruction.

CallCapi (&wcb, wdMsgBox, TypeVoid, NULL, 0, "ss", "Timer Hit!", "Examp WLL");

Register Functions in Word

The final group of functions provided in CAPILIB provides help with several common programming tasks in your WLL. These functions set up their WDOPR arguments and call wdCommandDispatch in the same way your code will. For this reason they provide excellent working examples of the use of the other CAPILIB functions.

To be callable from Word, functions must be registered with Word. The CAPIRegister function simplifies this task for you. The DocID parameter (passed in to wdAutoOpen), the name of your new function, and a description are the only parameters to this function.

// Windows
short CAPIRegister( short DocID, LPUCHAR lpszFunctionName, LPUCHAR
    lpszDescription );

// Macintosh
short CAPIRegister( short DocID, StringPtr lpszFunctionName, StringPtr
    lpszDescription );

DocID is a document identifier. It is used to register functions in Word and to customize Word to assign registered functions to toolbar buttons, menus, and shortcut keys.

Just as you choose the names for macros in Word templates, the name you choose for each registered add-in function should be unique to avoid naming conflicts during a Word session. If two or more add-in functions in two or more WLLs are registered under the same name, Word will run the function in the WLL listed first in the list of loaded global templates and add-ins in the Templates And Add-ins dialog box (Templates command, File menu).

A description is not required. If you specify a null value for lpszDescription, CAPIRegister ignores that parameter.

Assign Functions in Word

The final group of functions helps you assign registered functions to toolbar buttons, menus, or shortcut keys. Other than the DocID, the parameters all correspond closely to parameters for the equivalent WordBasic statements AddButton, NewToolbar, ToolsCustomizeMenu, ToolsCustomizeMenuBar, and ToolsCustomizeKeyboard.

// Windows
short CAPIAddButton( short DocID, LPUCHAR lpszToolbar, short cPosition,
    LPUCHAR lpszMacro, LPUCHAR lpszFace );
short CAPIAddToolbar( short DocID, LPUCHAR lpszToolbar )
short CAPIAddMenu( short DocID, LPUCHAR lpszMenuName, short Position,
    short MenuType );
short CAPIAddMenuItem( short DocID, LPUCHAR lpszMenu, LPUCHAR lpszName,
    LPUCHAR lpszMenuText, short Position, short MenuType );
short CAPIAddKey( short DocID, short KeyCode, LPUCHAR lpszName );

// Macintosh
short CAPIAddButton( short DocID, StringPtr lpszToolbar, short
    cPosition, StringPtr lpszMacro, StringPtr lpszFace );
short CAPIAddToolbar( short DocID, StringPtr lpszToolbar );
short CAPIAddMenu( short DocID, StringPtr lpszMenuName, short
    Position, short MenuType );
short CAPIAddMenuItem( short DocID, StringPtr lpszMenu, StringPtr
    lpszName, StringPtr lpszMenuText, short Position, short MenuType );
short CAPIAddKey( short DocID, short KeyCode, StringPtr lpszName );

When a WLL passes DocID as the context in which to customize Word, all customization is temporary; the template is not "dirtied" and all customization is removed automatically when the WLL is unloaded.

Note

If you want to make customization in Word permanent, pass the numeric value 0 (zero) to modify the Normal template or 1 to modify the active template (if other than the Normal template) instead of DocID. Note, however, that if you pass a context other than DocID, the template will be dirtied; you should include
a wdAutoRemove function in your WLL to deliberately clean up the Word environment when the WLL is unloaded.

For more information about these functions, see "Customizing Word with CAPILIB" later in this section.

Building Word Operators with CAPILIB

The following example code demonstrates the steps in building two WDOPR arguments for a call to wdCommandDispatch. The two WDOPR arguments pass the number of columns and the number of rows for a new table created by the WordBasic TableInsertTable statement. The WCB structure named wcb is first initialized by a call to InitWCB, the two WDOPR string field arguments are built up, and then wdCommandDispatch is called to perform the TableInsertTable statement. When activated, this block of code inserts a 4 by 12 table in the current document.

// Initialize the WCB - this zero's the WDOPR count
InitWCB( &wcb, TypeVoid, NULL, 0 );

// Build WDOPR arguments for number of columns and rows
AddStringDlgField( &wcb, "4", fidNumColumns, fMode, 0 );
AddStringDlgField( &wcb, "12", fidNumRows, fMode, 0 );

// Call into Word's TableInsertTable command
err = wdCommandDispatch ( wdTableInsertTable, CommandAction,
    wcb.cArgs, wcb.wdoprArgs, lpwdoprNil );

The last parameter to wdCommandDispatch is lpwdoprNil. Take a look in WDCAPI.H to see how the lpwdoprNil data type is defined as a WDOPR pointer to a zero. Use this when the Word API command doesn't return a WDOPR argument in the last parameter to wdCommandDispatch.

Passing Arrays with CAPILIB

To use the CAPILIB functions to build a WDOPR that passes an array, follow this general procedure:

  • Call SetArrayDef to set up the number and size of the array's dimensions.
  • For doubles, call AddDoubleArray, passing the ArrayDef and the double array.
  • For strings, call AddStringArray, passing the ArrayDef, the string array, and an array of pointers to each string in the array.

Example of Passing a Double Array

The following Windows code fragments demonstrate the passing of an array of doubles in a Word API function, using CAPILIB functions. Note that ArrayDef, in this case, is set up for a one-dimension array sized ARRAYSIZE. In the case of a multiple-dimensional array, you would pass different values to the SetArrayDef function.

// Related declarations
HANDLE            hArrayDef;
ARRAY_DEF far * ArrayDef;
double            array[ARRAYSIZE];

// Set the array definition
ArrayDef = SetArrayDef( &hArrayDef, 1, ARRAYSIZE );

// Build a double array WDOPR
InitWCB( &wcb, TypeVoid, NULL, 0 );
AddDoubleArray( &wcb, ArrayDef, array );

// Use wdCommandDispatch here

// Free allocated ArrayDef
GlobalUnlock( hArrayDef );
GlobalFree( hArrayDef );

Example of Passing a String Array

The following lines of Windows code illustrate the general procedure for handling string arrays using the CAPILIB module functions. The important concept to grasp here is the way the various parts of the WDOPR's data structure are loaded with the appropriate data. The string contents are contained in the character array strArray, pointers to each of these strings are loaded into lpStrArray, and the string array's dimensions and sizes are loaded into ArrayDef. Each of these
parts of the WDOPR data structure must be loaded correctly for passing
string array data.

// Related declarations
HANDLE            hArrayDef;
ARRAY_DEF far * ArrayDef;
LPSTR            lpStrArray[ARRAYSIZE];
char            strArray[ARRAYSIZE][MAXLENGTH];

// Set the array definition
ArrayDef = SetArrayDef( &hArrayDef, 1, ARRAYSIZE );

// Set the array of LPSTR to point to a buffer
for( i = 0; i < ARRAYSIZE; i++ )
    lpStrArray[i] = strArray[i];

// Build a string array WDOPR
InitWCB( &wcb, TypeShort, NULL, 0 );
AddStringArray( &wcb, ArrayDef, lpStrArray, MAXLENGTH );

// Use wdCommandDispatch here

// Free allocated ArrayDef
GlobalUnlock( hArrayDef );
GlobalFree( hArrayDef );

Customizing Word with CAPILIB

A WLL function registered in Word can be called from any WordBasic macro, just like any built-in statement. You also can assign a new Word API function to
a toolbar button, menu item, or shortcut key. The proper place to make such an assignment is in the wdAutoOpen function. This function runs automatically when the WLL is loaded, making your function associations automatic. There are several wdCommandDispatch commands that let you make these assignments in a manner analogous to the way WordBasic works. Specific CAPILIB functions simplify the process even further.

Adding a Command

An add-in function registered in Word extends WordBasic and is immediately available as a new command that can be included as an instruction in any macro. Use the CAPIRegister function in CAPILIB to register your add-in function.

Note

A WLL function that requires arguments from a WordBasic macro cannot be registered in Word. This kind of function must be declared in the WordBasic macro with the WordBasic Declare statement.

Adding a Toolbar Button

The following lines of code demonstrate how a toolbar button labeled "Table," assigned to the new function MyTable, can be added to the standard toolbar using the appropriate CAPILIB function. This line of code would normally go in the wdAutoOpen function of a WLL to create the button when the WLL is loaded.

err = CAPIAddButton( DocID, "Standard", cPosition, "MyTable",
    "Table" );

A related function in CAPILIB, CAPIAddToolbar, lets you add your own toolbar, to which you can then add buttons. For example:

err = CAPIAddToolbar( DocID, "MyToolbar" );

Adding a Menu Item

You can easily add a menu item and assign a registered function to it. The CAPIAddMenuItem function in CAPILIB simplifies the process. For example, the following line of code adds a new menu item labeled "String Array Test" to the end of the File menu and assigns the function StringArray to it:

err = CAPIAddMenuItem( DocID, "File", "StringArray", "String Array
    Test", -1, 0 );

A related function, CAPIAddMenu, lets you add a new menu to the main
menu bar and assign to it a name that can be used to further build the menu
with CAPIAddMenuItem.

Adding a Shortcut Key

A registered Word API function can also be assigned to a shortcut key using
the CAPIAddKey function provided in CAPILIB. For example:

err = CAPIAddKey( DocID, KeyCode, "MyNewFunction" );

This line of code assigns the Word API function MyNewFunction to the shortcut key indicated by KeyCode in the current document. For a complete description of the various KeyCode integers, see ToolsCustomizeKeyboard in Part 2, "WordBasic Reference."


Calling Word from Another Application

It is not possible to call a WLL from an application other than Word and then have the called WLL drive Word. The CAPI messaging interface (CMI) is a way to get around this problem.

Windows 3.x

To call wdCommandDispatch, a WLL must be called by Word; otherwise stack problems occur, resulting in a general protection fault. When making a Word API call, the calling application can send a message to Word (WM_WDCAPI) instead of calling wdCommandDispatch. As a result, Word calls wdCommandDispatch from its own stack (avoiding stack problems) when it processes the message.

To use the CAPI messaging interface, follow this general procedure.

1. Include the following in a header file:

#include "wdcapi.h"
#define WM_WDCAPI    (WM_USER + 0x0300)
typedef struct
{
    short    CommandID;
    short    DlgOptions;
    short    cArgs;
    LPWDOPR    lpwdoprArgs;
    LPWDOPR    lpwdoprReturn;
} CMI;
typedef CMI far *LPCMI;

2. Fill the CMI structure.

3. Call SendMessage in the following way:

err = (int)SendMessage( hWordWnd, WM_WDCAPI, 0, (LPARAM)(LPCMI)&cmi );

Windows 95 and Windows NT

To access the CMI from Windows 95 or Windows NT, you call cmiCommandDispatch instead of sending the WM_WORDCAPI message to Word (in Windows 95 and Windows NT, WM_WORDCAPI returns CAPIBadMessage). To call cmiCommandDispatch, you can either link your application with the WIN32CMI.LIB file, or load the WIN32CMI.DLL with LoadLibrary and then call GetProcAddress to get the address of the function.
The cmiCommandDispatch function has the same prototype as wdCommandDispatch; see the CMI header file (WIN32CMI.H) for this prototype.

The WIN32CMI.LIB and WIN32CMI.DLL files are located in the CAPI\WIN32CMI folder on the Microsoft Word Developer's Kit disk. The folder includes the source files required to build the LIB and DLL (a Microsoft Visual C++ version 2.0 project file is provided). If you are programming on a RISC platform, you will need to build the LIB and DLL for your platform using the source files provided.

Macintosh

On the Macintosh, you can use the CMI to drive Word from an application or code resource that is not directly called by Word. CMI on the Macintosh uses Apple Events to dispatch commands to Word instead of calling wdCommandDispatch directly from the Word API.

To make a CMI call on the Macintosh, you calling application or code resource needs to build an Apple Event that contains all the information normally passed by wdCommandDispatch. After it sends the event to Word, it needs to unpack the reply event.

To use the CMI on the Macintosh, use the CMILIB.C and CMILIB.H files included in the CMI folder in the CAPI folder on the Microsoft Word Developer's Kit disk instead of the CAPILIB.C and CAPILIB.H described earlier in this appendix. With these files added to your project, you can simply make calls to cmiCommandDispatch instead of wdCommandDispatch; all of the Apple Event construction is handled by the CMI files. Review the sample provided in the CMI:SAMPLE foler to see how the CMI is used.


Word API Functions

There are some functions in Word available to WLLs but not to WordBasic. These functions fill special needs of WLLs in Windows and on the Macintosh, as the following topics explain.

General Functions

Note that the following four WordBasic functions can only be called from a WLL.

wdAddCommand

Registers add-in functions in Word. It takes three arguments: the DocID (which is passed by Word to wdAutoOpen), the name of the function to be registered, and a description.

wdPrint

Same as the WordBasic Print statement; it prints a string in the status bar.

wdGetInst

Returns the handle (a long value) of the instance of Word (Windows only).

wdGetHwnd

Returns the handle (a long value) of the Word window (Windows only).

Timer Messages

On the Macintosh, the single function wdSetTimer supplies timer messages from Word for a WLL to use. When a timer message happens, the WLL gets called from Word with cacCallTimer. Here is the syntax:

short wdSetTimer( short DocID, long Timer);

Parameter | Description
DocID | Identifies which WLL the timer message should be sent to
Timer | The number of milliseconds to set the timer for

A WLL can have a single timer set at any time; calling wdSetTimer clears the old timer before setting a new one. Calling with a Timer value of 0 (zero) clears the old timer.

WLL Windows

On the Macintosh, the following group of functions should be used for WLLs that need windows created for them that Word will send messages to.

After a WLL window has been established, events are handled as follows:

  • MouseDown and mouseUp events are sent to all WLL windows.
  • Update events are sent to the appropriate WLL window.
  • KeyDown events are sent to the appropriate WLL window only if wdCaptureKeyDown has been done for that window.

wdOpenWindow

This function opens and displays a WLL window, and returns the window pointer in a long to use in the other WLL window functions. Here is the syntax:

long wdOpenWindow( short DocID, short x, short y, short dx,
    short dy, long lData, short fFloat);

Parameter | Description
DocID | Identifies which WLL to send messages to
x, y, dx, dy | Specifies the position and size of the window in pixels

Parameter | Description
lData | Contains user data
fFloat | If fTrue, uses altDBoxProc for the window type; otherwise, uses documentProc (does not actually cause the window to float or not float)

wdCloseWindow

Closes a CAPI window, and returns a short containing fTrue or fFalse to indicate success or failure. The function takes the window pointer as a long parameter. Here is the syntax:

short wdCloseWindow( long *Window);

wdCaptureKeyDown

Starts mode in which KeyDown messages are sent to the CAPI window, and returns a short containing fTrue or fFalse to indicate success or failure. This function takes the window pointer as a long parameter. Here is the syntax:

short wdCaptureKeyDown( long *Window);

wdReleaseKeyDown

Stops mode in which KeyDown messages are sent to the CAPI window, and returns a short containing fTrue or fFalse to indicate success or failure. This function takes the window pointer as a long parameter. Here is the syntax:

short wdReleaseKeyDown( long *Window);


Word API Errors

The following errors, shown here with their names and descriptions, are the Word-API–specific errors defined in WDERROR.H, where error 0 (zero) is CAPINoError.

Error | Name | Description
5001 | CAPIBadCommandId | Command ID is invalid
5002 | CAPIOddParamBlock | Parameter block has an odd number of bytes
5003 | CAPICmdNotAvailable | Command is not available
5004 | CAPIBadArgCount | Too many or too few arguments
5005 | CAPIInternalError | Internal data-handling error
5006 | CAPIByteCountMismatch | Parameter block doesn't have an acceptable number of bytes
5007 | CAPINotFunction | Non-function called as a function
5008 | CAPIBadType | Parameter type passed or expected is wrong

Error | Name | Description
5009 | CAPIStringTooLong | String is longer than 255 characters
5010 | CAPINullReturnBuffer | Pointer for output is nil
5011 | CAPICantLock | Can't lock global handle
5012 | CAPICantAllocate | Can't allocate global handle
5013 | CAPINoDialog | Commmand has no dialog box
5014 | CAPIOutOfMemory | Word API is out of memory
5015 | CAPIFieldIdOutOfRange | Too many parameters passed to function
5016 | CAPIBadFieldId | FieldID not in dialog box
5017 | CAPIBadHandle | Handle has not been allocated
5018 | CAPIArrayExpected | Parameter takes an array only
5019 | CAPITooManyDimensions | Too many dimensions for array
5020 | CAPIExpectedNumericType | Parameter passed was not a short, long, or numeric type
5021 | CAPIExpectedStringType | Parameter passed was not a string type
5022 | CAPIParameterOutOfRange | Parameter value was out of an acceptable range
5023 | CAPICantReturnString | String type requested for numeric-only field
5024 | CAPICantReturnNumeric | Numeric type requested for string-only field
5025 | CAPIReturnOverflow | Buffer for return string is too small
5026 | CAPIArrayOverflow | String array buffer is too small
5027 | CAPIDlgCommandOverflow | Dialog-box command string buffer is too small
5028 | CAPIOverflowNotHandled | BufferTooSmall bit set on input
5029 | CAPICantParse | String passed can't be parsed
5030 | CAPIBadMessage | Bad pointer in message
5031 | CAPICommandFailed | Word API command failed
5032 | CAPIBadDocRef | Document reference number (DocID) is invalid
5033 | CAPIInsufficientStack | Minimum stack not available
5034 | CAPIUninitializedString | 0 (zero) was passed as string pointer


AppleScript

Word supports AppleScript scripting on the Apple Macintosh. Word supports the Required, Core, Table, and Text suites of Apple Events, as defined by the Apple Event Registry. In addition, Word defines four objects, one event, and approximately 68 properties for use in AppleScript scripts that interact with Word.

To use AppleScript with Word, you must have the following:

  • Microsoft Word version 6.0
  • Apple Macintosh System 7 or later
  • AppleScript extension version 1.1
  • Apple Script Editor or another scripting application compatible with Open Scripting Architecture (OSA)

Note

This appendix assumes that you are using Script Editor, the application provided in the AppleScript Developer's Toolkit from Apple Computer, Inc. Any OSA-compatible script editing application can use the same information to create scripts for Microsoft Word version 6.0.

To use this appendix, you should already be familiar with AppleScript and scripting on the Macintosh. The reference section of this appendix describes only the new objects, events, and properties created for use with Word version 6.0. The remaining objects, events, and properties that Word shares with other scriptable applications are described in your scripting documentation. For more information about AppleScript, see Getting Started with AppleScript and AppleScript Language Guide, both included in the AppleScript Developer's Tookit version 1.1 from Apple Computer, Inc.


Supported Suites

With all of the objects and events listed in this section, users can create, format, change, and print Word documents from AppleScript.

Word recognizes the following standard objects, as defined by the Apple Event Registry.

Suite | Objects
Core | Application, Character, Document, File, Selection-Object, Text, Text Style Info, Window, Insertion Point
Text | Line, Paragraph, Text, Text Flow, Word
Table | Cell, Column, Row, Table

Word responds to the following standard events, as described in the Apple Event Registry.

Suite | Events
Required | Open, Print, Quit, Run
Core | Close, Count, Data Size, Delete, Duplicate, Exists, Get, Make, Move, Open, Print, Quit, Save, Set
Miscellaneous | Activate, Begin Transaction, Copy, Cut, Do Script, End Transaction, Paste, Redo, Revert, Undo

To determine the properties that Word supports for these standard objects, or to determine the arguments required by these supported events, refer to the AppleScript dictionary for Microsoft Word, accessible through the Open Dictionary command (File menu) in the Script Editor (or a comparable feature of your scripting application). For detailed information about supported objects and their properties, as well as supported events, see your scripting documentation.

In addition to the standard events and objects described above, Word defines four new objects and one new event.

Word Objects

Paragraph Style, Range, Section, Sentence

Word Event

Select

For detailed information about these objects and events, see "Extensions to Supported Suites" later in this appendix.


Object Hierarchy

The object hierarchy determines which objects are related to each other within a particular class of objects. The following table shows 16 object classes (the first column) and their corresponding elements (the second column). Within an object class, elements are grouped together by their valid reference forms (the third column). In other words, from an object in the first column, you can use a reference form in the third column to refer to an element in the second column.

An object that is the element of another object class may appear as its own object class later in the table. In some cases, an object can be an element of its own class; for example, a paragraph object is an element of the paragraph object class. In other cases, an object may appear as an element of an object class that would at first seem too small to contain the specified element; for example, because, technically, a word can be one character long, the word object is an element of the character object class.

Word supports the following reference forms:

  • Property
  • Index
  • Relative
  • Name
  • Middle/Arbitrary/Every Element
  • Range
  • Filter

Word does not support the ID reference form. For complete descriptions of these reference forms, refer to your AppleScript documentation.

Object Class | Element | Valid Reference Forms
Application | Window, Document | Index, Name, Filter
 | Character, Word, Sentence, Line, Paragraph, Section, Table | Index, Filter
 | Text Flow | Name
 | Paragraph Style | Name
Document | Window | Index, Name, Filter
 | Character, Word, Sentence, Line, Paragraph, Section, Table | Index, Filter
 | Text Flow | Name
 | Paragraph Style | Name

Object Class | Element | Valid Reference Forms
Window | Window | Relative
 | Character, Word, Sentence, Line, Paragraph, Section, Table | Index, Filter
 | Text Flow | Name
 | Paragraph Style | Name
Character, Word, Sentence, Line, Paragraph, Section, Table | Character, Word, Sentence, Line, Paragraph, Section, Table | Index, Filter, Relative
 | Text | Range
Text | Character, Word, Sentence, Line, Paragraph, Section, Table | Index, Filter, Relative
Table | Row, Column, Cell | Index, Filter
 | Range | Name
Row | Row | Relative
 | Cell, Column | Index, Filter
 | Range | Range
Column | Column | Relative
 | Cell, Row | Index, Filter
 | Range | Range
Cell | Character, Word, Sentence, Line, Paragraph, Section, Table | Index, Filter, Relative
 | Range | Range
Range | Cell, Row, Column | Index, Filter

The following paragraphs suggest some techniques you can use for handling and referencing objects in Word. These techniques will help you get the best performance out of your script applications.

Index through bigger objects

Word does not maintain internal indices to all text objects. To find the AppleScript object word 200, Word must scan through all the words in the document until it finds the two-hundredth word. Scanning through bigger objects is quicker, so scripts that reference larger objects first will execute more rapidly. For example, assuming the 1000th word is also the third word in the fifth paragraph of the third section, the reference word 1000 will execute much more slowly than the reference word 3 of paragraph 5 of section 3, even though each references the same word.

Use the filter reference form sparingly

To support the wide variety of filter reference cases supported by AppleScript, Word uses a set of operating system utilities that perform much of the bookkeeping involved with complex filter expressions. With this implementation, the operating system repeatedly asks for individual objects from Word during the processing of a filter reference. Then tests are performed on the objects to see if they meet the given filter criteria. This back-and-forth process of getting objects and then performing tests can be slow.

If you must use the filter reference form, use it in conjunction with a index reference qualifier (for example, the first word where character 1 is "w") to speed up the script. Avoid the qualifier "every"; it forces Word to filter all the text within a parent object.

Use bookmarks

As noted previously, using the index reference form can be slow. But even more problematic, as documents change, the indices of specific words or paragraphs will also change. If the document being accessed by a script is subject to change, the script cannot rely on fixed indices to locate particular text objects. The filter reference form can be used to find particular objects, but this method can be slow.

The best way to maintain persistent references to text and table objects in Word is to use bookmarks. Bookmarks are names that you can assign to any selected text. Even if the document is changed, the bookmark still refers to the original selection. For example, if a bookmark named "xref" is created for the third word of a document, and then a new word is inserted at the beginning of the document, the bookmark "xref" will refer to the fourth word.

Bookmarks are exposed to AppleScript through the Text Flow object, which is only accessible by name from a document. For example, the following reference refers to the text associated with the bookmark "xref":

set selection to text flow "xref"

Any valid text event can be performed on a Text Flow object. Text Flow objects can also reference Range objects if the bookmark for the range is contained in a Word table.


Extensions to Supported Suites

Word adds four objects, one event, and many properties that extend the standard suites that Word supports, identified earlier in this appendix and described in your AppleScript documentation. This section provides a reference to these Word-specific objects, events, and properties.

Word Objects

Word defines four new objects: Paragraph Style, Range, Section, and Sentence.

Paragraph Style

Paragraphs within Word documents all have an associated "style," which determines many of their default properties. This is different than the AppleScript notion of style, which only describes a few basic text properties (such as bold and italic). To avoid conflict with AppleScript's notion of style, Word defines the object Paragraph Style to be a named set of most text properties.

A Paragraph Style object has all the properties of any text object, but does not have any text elements. To change a property for all the paragraphs of a particular style, you can simply change that property of the appropriate paragraph style object.

tell app "Microsoft Word"
    set font of paragraph style "Heading 1" to "Helvetica"
end tell

Note that every paragraph has a Paragraph Style property, which is the name of that paragraph's Word style. A script can change any paragraph's style by setting this property:

tell app "Microsoft Word"
    set paragraph style of second paragraph to "Heading 2"
end tell

Range

Microsoft Excel defines a Range object to simplify access to Table objects. The standard Table, Row, and Column objects use complex records for returning their data. The Range object, however, returns a simple list of the cells of the given range.

Within word, a Range can be any contiguous part of a table: a row, a column, the whole table, or some rectangular part of the table. A Range object is referenced through the Name form.

tell app "Microsoft Word"
    get range "R2C3:R4C5" of table 1
end tell

Section

Word exposes the Section object as a simple extension to all the other standard text objects (for example, Word and Paragraph). In the text stream of a document, a section is bounded by section breaks or a section break and the beginning or end of the document. A document with no section breaks contains one section.

Sentence

Word exposes the Sentence object as simple extension to all the other standard text objects (for example, Word and Paragraph). In the text stream of a document, a sentence is usually bounded by terminating punctuation (period, exclamation point, question mark), excluding any leading white space. However, a paragraph composed of a stream of text and no punctuation (for example, a heading) is considered to contain one sentence (all of the text).

Word Event

Word defines one new event: Select.

Select

The Select event applies to any text object. The Select event is just a shorthand for setting the selection of the application to a particular AppleScript object.

The two instructions in the following script are equivalent:

tell app "Microsoft Word"
    set selection to second paragraph
    select second paragraph
end tell

Here is the syntax for the Select event:

select reference

The reference argument is a valid reference to the object to select.

The Select event is supported by Word because the usual purpose of WordBasic macros is to manipulate the current selection. The most efficient way to perform actions on text within Word is to select the text with the Select event, and then perform complex formatting using WordBasic through the Do Script event. With this scenario, a user can use AppleScript's expressive object references while also taking advantage of WordBasic's efficiency. For more information on using the Do Script event with WordBasic, see "Extending WordBasic with AppleScript" later in this appendix.

Word Properties

Virtually all text properties in Word are exposed to native AppleScript. These properties can be broken down into three categories: character, paragraph, and section. Character properties are generally those available in the Font dialog box (Format menu); paragraph properties are usually found in the Paragraph dialog box (Format menu); section properties are found scattered throughout other dialog boxes (such as Columns on the Format menu and Page Setup on the File Menu).

All of these properties can be accessed from any text object. That is, a paragraph property can be read from a word or sentence object. However, changing these properties often implies changing them for an entire parent object. For example, setting the Justification property of a word object actually changes the justification of the entire paragraph object that contains the word. Similarly, getting the Number Columns property of a paragraph actually returns the number of columns for the section that contains the paragraph. Character properties only affect the exact text object being referenced.

The following topics describe the character, paragraph, and section properties that are exposed by Word.

Note

You can set Word properties that take Boolean values with one of the following three values: true, false, or toggle. The toggle value reverses the current value of the property; for example, if the bold property of the specified text object is true, the following instruction sets it to false:

set bold of textobject to toggle

Character Properties

All of the properties described in the following table apply to each character of the referenced object in a Word document.

Property | Description | Data type
All Caps | Returns or sets a value that specifies whether the object is formatted with all capital letters. | Boolean
Bold | Returns or sets a value that specifies whether the object is formatted as bold. | Boolean
Character Position | Returns or sets the vertical position of characters for the object. | Points
Character Spacing | Returns or sets the amount of spacing between characters for an object. | Points

Property | Description | Data type
Hidden | Returns or sets a value specifying whether the text of the object is hidden. | Boolean
Italic | Returns or sets a value that specifies whether the text of the object is italic. | Boolean
Kerning Size | Returns or specifies the smallest font size to kern for the object. | Points
Language | Returns or specifies the language for the object. | String
Length | Returns the number of characters contained in the object | Integer
Outline | Returns or sets a value that specifies whether the object is formatted as outline. | Boolean
Plain | Returns or sets a value that specifies whether there are no character styles applied to the object. | Boolean
Shadow | Returns or sets a value that specifies whether the object is formatted with shadow. | Boolean
Small Caps | Returns or sets a value that specifies whether the object is formatted with small capital letters. | Boolean
Strikethrough | Returns or sets a value that specifies whether the object is formatted with strikethrough. | Boolean
Subscript | Returns or sets a value that specifies whether the object is formatted as subscript. | Boolean
Superscript | Returns or sets a value that specifies whether the object is formatted as superscript. | Boolean
Underline | Returns or specifies the type of underlining for the object. | One of the following values: none, single, words only, double, dotted, hidden

Paragraph Properties

All of the properties described in the following table apply to the paragraph or paragraphs related to the referenced object in a Word document.

Property | Description | Data type
After Spacing | Returns or sets the spacing after paragraphs for the object. | Points
Before Spacing | Returns or sets the spacing before paragraphs for the object. | Points
Top Border Color, Left Border Color, Bottom Border Color, Right Border Color, and Between Border Color | Return or set the color of a border of the object. | An RGB color
Top Border Distance, Left Border Distance, Bottom Border Distance, Right Border Distance, and Between Border Distance | Return or set the distance from text of a border of the object. | Points
Border Shadow | Returns or sets a value that specifies whether the object has shadowed borders. | Boolean
Top Border, Left Border, Bottom Border, Right Border, and Between Border | Return or set the type of a border for an object. | One of the following values: none, hair, thin, medium, thick, thicker, thickest, double, thick double, thicker double, dotted, dashed
Dont Hyphenate | Returns or sets a value that specifies whether automatic hyphenation is suppressed for the object. | Boolean
First Line Indent | Returns or sets the amount of indent for the first line of the paragraph (also known as the hanging indent) for the object. | Current application units (points, picas, centimeters, inches)
Justification | Returns or specifies the paragraph justification for the object. | One of the following values: left, right, center, full

Property | Description | Data type
Keep Lines Together | Returns or sets a value that specifies whether the lines in a paragraph or paragraphs of the object are kept together. | Boolean
Keep With Next | Returns or sets a value that specifies whether a paragraph or paragraphs of the object are kept on the same page with their following paragraphs. | Boolean
Left Indent | Returns or specifies the width of the left paragraph indent for the object. | Current application units (points, picas, centimeters, inches)
Line Spacing Amount | Returns or specifies the line spacing for the object (when Line Spacing Type is multiple). | Lines
Line Spacing Type | Returns or specifies the type of line spacing for the object. | One of the following values: single, lines1pt5, double, at least, exactly, multiple
Page Break Before | Returns or sets a value that specifies whether page breaks are made before paragraphs for the object. | Boolean
Right Indent | Returns or specifies the width of the right paragraph indent for the object. | Current application units (points, picas, centimeters, inches)
Shade Background Color | Returns or specifies the background color of paragraph shading for the object. | An RGB color
Shade Foreground Color | Returns or specifies the foreground color of paragraph shading for the object. | An RGB color

Property | Description | Data type
Shade Pattern | Returns or specifies the shading pattern for the object. | One of the following values: clear, solid, p5, p10, p20, p25, p30, p40, p50, p60, p70, p75, p80, p90, dark horizontal, dark vertical, dark down diagonal, dark up diagonal, dark grid, dark trellis, light horizontal, light vertical, light down diagonal, light up diagonal, light grid, light trellis
Suppress Line Numbers | Returns or sets a value that specifies whether line numbers are suppressed for the object. | Boolean
Tab Alignments | Returns or specifies the alignment of each nondefault tab stop for the object. | A list of the following values: left, center, right, decimal, bar
Tab Leaders | Returns or specifies the leader style of each nondefault tab stop for the object. | A list of the following values: none, dot, hyphen, single, heavy
Tab Positions | Returns or specifies the position of each nondefault tab stop for the object. | Current application units (points, picas, centimeters, inches)
Widow Orphan Control | Returns or sets a value that specifies whether widow and orphan control is active for the object. | Boolean

Section Properties

All of the properties described in the following table apply to the section or sections related to the referenced object in a Word document.

Property | Description | Data type
Bottom Margin | Returns or sets the width of the bottom margin for the object. | Current application units (points, picas, centimeters, or inches)
Column Spacings | Returns or sets the sizes of spaces between columns for an object. | Current application units (points, picas, centimeters, or inches)

Property | Description | Data type
Column Widths | Returns or sets the widths of columns for an object. | Current application units (points, picas, centimeters, or inches)
Equal Width Columns | Returns or sets a value that specifies whether the columns are the same width for the object. | Boolean
First Paper Source | Returns the paper source for the first page of the object. Read only. | One of the following values: none, upper, lower, middle, manual, envelope, envelope manual, auto, tractor, small format, large format, large capacity, cassette, manual PostScript
Gutter Margin | Returns or sets the width of the gutter margin for the object. | Current application units (points, picas, centimeters, inches)
Left Margin | Returns or specifies the width of the left margin for the object. | Current application units (points, picas, centimeters, inches)
Line Between Columns | Returns or sets a value that specifies whether there are lines between columns for the object. | Boolean
Number Columns | Returns or specifies the number of columns for the object. | Integer
Other Paper Source | Returns the paper source for pages other than the first page for the object. Read only. | One of the following values: none, upper, lower, middle, manual, envelope, envelope manual, auto, tractor, small format, large format, large capacity, cassette, manual PostScript
Page Height | Returns the height of the page for the object. Read only. | Current application units (points, picas, centimeters, inches)
Page Orientation | Returns the orientation of the page for the object. Read only. | One of the following values: none, portrait, landscape, mixed

Property | Description | Data type
Page Width | Returns the page width for the object. Read only. | Current application units (points, picas, centimeters, inches)
Right Margin | Returns or specifies the width of the right margin for the object. | Current application units (points, picas, centimeters, inches)
Top Margin | Returns or specifies the width of the top margin for the object. | Current application units (points, picas, centimeters, inches)


Extending WordBasic with AppleScript

When combined, AppleScript and WordBasic can be used to customize the Macintosh in many ways. A script can control Word and other scriptable applications, while WordBasic can run scripts that in turn do work and return data to Word. With AppleScript recording turned on, you can easily record scripts from within Word. You can also write simple macros and customize the Word interface to expose external scripts, so any user can take advantage of compiled script applications without leaving Word.

Recording Scripts

AppleScript can record Word. That is, Word will generate Apple Events for all user actions when recording has been turned on for an entire Macintosh. These events can then be recorded by AppleScript.

In Word, AppleScript recording is based on the internal WordBasic recording mechanism. Because of this, WordBasic macros and AppleScript scripts cannot be recorded at the same time. If Word is in the process of recording a WordBasic macro, it will ignore requests to record from AppleScript. Similarly, if Word is recording Apple Events, the user will not be able to start WordBasic macro recording.

Just as a subset of the functionality in Word is exposed to AppleScript, only a small segment of user actions are recorded as native AppleScript. That is, most simple editing, formatting, and file manipulation actions will be recorded as one of the basic events acting on an Apple Event object (for example, opening a file or setting the style of the selection to bold). All other actions are recorded as Do Script events with the appropriate WordBasic instructions, much as the actions would be recorded within a WordBasic macro.

Using the Do Script Event

Much of Word's functionality is not exposed directly to AppleScript because the standard suites are meant to be a common interface for objects across many applications. However, scripts can still control Word completely by using the Do Script event. With Do Script, a script can run the same WordBasic instructions that Word macros use to control the application. This effectively gives a script access to all the functionality of Word.

WordBasic is the native programming language of Word, and Word is optimized to use WordBasic. Therefore, to get the fastest performance from Word, AppleScript programmers should consider using Do Script events to control Word as much as possible.

Here is the syntax for the Do Script event:

do script WordBasic$

Note that WordBasic$ is either one instruction to execute or a list of instructions. The result of a Do Script event in a script is either one value, if Word was passed one WordBasic instruction, or a list of values, if Word was passed a list of instructions.

For example, here is a simple WordBasic macro:

Sub MAIN
    FileOpen "Hard Drive:Microsoft Word:Sample Document"
    EditFindStyle .Style = "Heading 2"
    EditReplaceStyle .Style = "Heading 3"
    EditReplace .Direction = 0, .ReplaceAll, .Format = 1, .Wrap = 1
    FileClose 1
End Sub

In AppleScript, scripting commands and objects could be used to duplicate the functionality of the original WordBasic macro, as follows:

tell application "Microsoft Word"
    open "Hard Drive:Microsoft Word:Sample Document"
    set countpara to count paragraphs of document "Sample Document"
    repeat with n from 1 to countpara
        if paragraph style of paragraph n = "Heading 2" then
            set paragraph style of paragraph n to "Heading 3"
        end if
    end repeat
    save document "Sample Document"
    close document "Sample Document"
end tell

However, an AppleScript script can use a single Do Script event to take the most advantage of the internal functionality of Word to duplicate the original macro:

tell application "Microsoft Word"
    Do Script Ø
        "FileOpen \"Hard Drive:Microsoft Word:Sample Document\"
        EditFindStyle .Style = \"Heading 2\"
        EditReplaceStyle .Style = \"Heading 3\"
        EditReplace .Direction = 0, .ReplaceAll, .Format = 1, .Wrap = 1
        FileClose 1"
end tell

Attaching Scripts

A limited form of AppleScript "attachability" within Word is provided through the WordBasic MacScript statement and MacScript$() function. With these, any interface element in Word that can be attached to a macro (for example, menu commands and toolbar buttons) can run a script.

Note that this does not provide arbitrary script object attachability. Word does not provide for attachment of scripts to any object. Thus, it is not possible to write a script which handles particular Apple Events for an attached object. For example, a script cannot be attached to a window so that the script can handle the Close event.

Here is the syntax for the MacScript statement:

MacScript Script$

MacScript accepts a string parameter which may be either a path to a file, or a portion of text in the default scripting language. If the string is a path to a compiled script file or standalone script application, that file is opened and the first script resource is run. Otherwise, the string itself is passed to the default scripting language for compilation and execution.

Here is the syntax for the MacScript$() function:

MacScript$(Script$)

MacScript$() performs exactly as MacScript, except that it returns a string value. If the executed script returns a value, it is coerced into a string and returned. If the executed script does not return a value, an empty string ("") is returned.

For more information, see MacScript in Part 2, "WordBasic Reference."


Microsoft Word Operating Limits

Some of the limits listed in the following tables are determined by the amount of memory available.


WordBasic Limits

Operating parameter | Limit
Macro size | Limited only by available memory
Length of variable, subroutine, and user-defined function names | 40 characters (Word version 6.0) 80 characters (Word version 7.0)
Length of string variables | 65,280 characters
Highest number | 1.7976931348623 x 10308
Number of arguments that can be passed to a subroutine or function | 20


Word Limits

Operating parameter | Limit
Number of open windows | Limited only by available memory
Maximum file size | 32 megabytes (not including graphics)
Number of words in custom dictionaries | 10,000
Length of bookmark names | 20 characters (Word version 6.0) 40 characters (Word version 7.0)
Number of bookmarks per document | 32,000
Length of AutoText entry names (including spaces) | 31 characters
Length of style names | 253 characters
Number of styles per document or template | 4,093
Number of fields per document | 32,000

Operating parameter | Limit
Number of general switches in a field | 10
Number of field-specific switches in a field | 10
Number of nesting levels for fields | 20
Number of subdocuments in a master document | Limited only by available memory
Number of columns in a table | 31
Number of newspaper-style columns | 100
Number of tabs set in a paragraph | 50
Minimum page height | 3 inches
Number of custom toolbars | Limited only by available memory
Number of custom toolbar buttons | Limited only by available memory
Number of characters per line | 768
Font size | 1,637 pt (22 inches)
Number of fonts per document | 32,767
Amount of space between characters | 1,637 pt
Distance text can be raised or lowered | 1,637 pt